WebTextView.java revision 1d96ca06d83ef87544a7053ab6c19b3b8233ae4b
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import com.android.internal.widget.EditableInputConnection;
20
21import android.content.Context;
22import android.graphics.Canvas;
23import android.graphics.Color;
24import android.graphics.ColorFilter;
25import android.graphics.Paint;
26import android.graphics.PixelFormat;
27import android.graphics.Rect;
28import android.graphics.drawable.Drawable;
29import android.text.Editable;
30import android.text.InputFilter;
31import android.text.Selection;
32import android.text.Spannable;
33import android.text.TextPaint;
34import android.text.TextUtils;
35import android.text.method.MovementMethod;
36import android.text.method.Touch;
37import android.util.Log;
38import android.view.Gravity;
39import android.view.KeyCharacterMap;
40import android.view.KeyEvent;
41import android.view.MotionEvent;
42import android.view.View;
43import android.view.ViewConfiguration;
44import android.view.ViewGroup;
45import android.view.inputmethod.EditorInfo;
46import android.view.inputmethod.InputMethodManager;
47import android.view.inputmethod.InputConnection;
48import android.widget.AbsoluteLayout.LayoutParams;
49import android.widget.ArrayAdapter;
50import android.widget.AutoCompleteTextView;
51import android.widget.TextView;
52
53import java.util.ArrayList;
54
55/**
56 * WebTextView is a specialized version of EditText used by WebView
57 * to overlay html textfields (and textareas) to use our standard
58 * text editing.
59 */
60/* package */ class WebTextView extends AutoCompleteTextView {
61
62    static final String LOGTAG = "webtextview";
63
64    private WebView         mWebView;
65    private boolean         mSingle;
66    private int             mWidthSpec;
67    private int             mHeightSpec;
68    private int             mNodePointer;
69    // FIXME: This is a hack for blocking unmatched key ups, in particular
70    // on the enter key.  The method for blocking unmatched key ups prevents
71    // the shift key from working properly.
72    private boolean         mGotEnterDown;
73    private int             mMaxLength;
74    // Keep track of the text before the change so we know whether we actually
75    // need to send down the DOM events.
76    private String          mPreChange;
77    private Drawable        mBackground;
78    // Variables for keeping track of the touch down, to send to the WebView
79    // when a drag starts
80    private float           mDragStartX;
81    private float           mDragStartY;
82    private long            mDragStartTime;
83    private boolean         mDragSent;
84    // True if the most recent drag event has caused either the TextView to
85    // scroll or the web page to scroll.  Gets reset after a touch down.
86    private boolean         mScrolled;
87    // Gets set to true when the the IME jumps to the next textfield.  When this
88    // happens, the next time the user hits a key it is okay for the focus
89    // pointer to not match the WebTextView's node pointer
90    boolean                 mOkayForFocusNotToMatch;
91    boolean                 mResendKeyDown;
92    // Whether or not a selection change was generated from webkit.  If it was,
93    // we do not need to pass the selection back to webkit.
94    private boolean         mFromWebKit;
95    private boolean         mGotTouchDown;
96    private boolean         mInSetTextAndKeepSelection;
97    // Array to store the final character added in onTextChanged, so that its
98    // KeyEvents may be determined.
99    private char[]          mCharacter = new char[1];
100    // This is used to reset the length filter when on a textfield
101    // with no max length.
102    // FIXME: This can be replaced with TextView.NO_FILTERS if that
103    // is made public/protected.
104    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
105
106    /**
107     * Create a new WebTextView.
108     * @param   context The Context for this WebTextView.
109     * @param   webView The WebView that created this.
110     */
111    /* package */ WebTextView(Context context, WebView webView) {
112        super(context);
113        mWebView = webView;
114        mMaxLength = -1;
115    }
116
117    @Override
118    public boolean dispatchKeyEvent(KeyEvent event) {
119        if (event.isSystem()) {
120            return super.dispatchKeyEvent(event);
121        }
122        // Treat ACTION_DOWN and ACTION MULTIPLE the same
123        boolean down = event.getAction() != KeyEvent.ACTION_UP;
124        int keyCode = event.getKeyCode();
125
126        boolean isArrowKey = false;
127        switch(keyCode) {
128            case KeyEvent.KEYCODE_DPAD_LEFT:
129            case KeyEvent.KEYCODE_DPAD_RIGHT:
130            case KeyEvent.KEYCODE_DPAD_UP:
131            case KeyEvent.KEYCODE_DPAD_DOWN:
132                if (!mWebView.nativeCursorMatchesFocus()) {
133                    return down ? mWebView.onKeyDown(keyCode, event) : mWebView
134                            .onKeyUp(keyCode, event);
135
136                }
137                isArrowKey = true;
138                break;
139        }
140        if (!isArrowKey && !mOkayForFocusNotToMatch && !mResendKeyDown
141                && mWebView.nativeFocusNodePointer() != mNodePointer) {
142            if (mWebView.nativeFocusNodePointer() != 0) {
143                mWebView.nativeClearCursor();
144            }
145            // Do not call remove() here, which hides the soft keyboard.  If
146            // the soft keyboard is being displayed, the user will still want
147            // it there.
148            mWebView.removeView(this);
149            mWebView.requestFocus();
150            return mWebView.dispatchKeyEvent(event);
151        }
152        // After a jump to next textfield and the first key press, the cursor
153        // and focus will once again match, so reset this value.
154        mOkayForFocusNotToMatch = false;
155        mResendKeyDown = false;
156        Spannable text = (Spannable) getText();
157        int oldLength = text.length();
158        // Normally the delete key's dom events are sent via onTextChanged.
159        // However, if the length is zero, the text did not change, so we
160        // go ahead and pass the key down immediately.
161        if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) {
162            sendDomEvent(event);
163            return true;
164        }
165
166        if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) {
167            if (isPopupShowing()) {
168                return super.dispatchKeyEvent(event);
169            }
170            if (!down) {
171                // Hide the keyboard, since the user has just submitted this
172                // form.  The submission happens thanks to the two calls
173                // to sendDomEvent.
174                InputMethodManager.getInstance(mContext)
175                        .hideSoftInputFromWindow(getWindowToken(), 0);
176                sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
177                sendDomEvent(event);
178            }
179            return super.dispatchKeyEvent(event);
180        } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) {
181            // Note that this handles center key and trackball.
182            if (isPopupShowing()) {
183                return super.dispatchKeyEvent(event);
184            }
185            if (!mWebView.nativeCursorMatchesFocus()) {
186                return down ? mWebView.onKeyDown(keyCode, event) : mWebView
187                        .onKeyUp(keyCode, event);
188            }
189            // Center key should be passed to a potential onClick
190            if (!down) {
191                mWebView.centerKeyPressOnTextField();
192            }
193            // Pass to super to handle longpress.
194            return super.dispatchKeyEvent(event);
195        }
196
197        // Ensure there is a layout so arrow keys are handled properly.
198        if (getLayout() == null) {
199            measure(mWidthSpec, mHeightSpec);
200        }
201        int oldStart = Selection.getSelectionStart(text);
202        int oldEnd = Selection.getSelectionEnd(text);
203
204        boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength;
205        // If we are at max length, and there is a selection rather than a
206        // cursor, we need to store the text to compare later, since the key
207        // may have changed the string.
208        String oldText;
209        if (maxedOut && oldEnd != oldStart) {
210            oldText = text.toString();
211        } else {
212            oldText = "";
213        }
214        if (super.dispatchKeyEvent(event)) {
215            // If the WebTextView handled the key it was either an alphanumeric
216            // key, a delete, or a movement within the text. All of those are
217            // ok to pass to javascript.
218
219            // UNLESS there is a max length determined by the html.  In that
220            // case, if the string was already at the max length, an
221            // alphanumeric key will be erased by the LengthFilter,
222            // so do not pass down to javascript, and instead
223            // return true.  If it is an arrow key or a delete key, we can go
224            // ahead and pass it down.
225            if (KeyEvent.KEYCODE_ENTER == keyCode) {
226                // For multi-line text boxes, newlines will
227                // trigger onTextChanged for key down (which will send both
228                // key up and key down) but not key up.
229                mGotEnterDown = true;
230            }
231            if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) {
232                if (oldEnd == oldStart) {
233                    // Return true so the key gets dropped.
234                    return true;
235                } else if (!oldText.equals(getText().toString())) {
236                    // FIXME: This makes the text work properly, but it
237                    // does not pass down the key event, so it may not
238                    // work for a textfield that has the type of
239                    // behavior of GoogleSuggest.  That said, it is
240                    // unlikely that a site would combine the two in
241                    // one textfield.
242                    Spannable span = (Spannable) getText();
243                    int newStart = Selection.getSelectionStart(span);
244                    int newEnd = Selection.getSelectionEnd(span);
245                    mWebView.replaceTextfieldText(0, oldLength, span.toString(),
246                            newStart, newEnd);
247                    return true;
248                }
249            }
250            /* FIXME:
251             * In theory, we would like to send the events for the arrow keys.
252             * However, the TextView can arbitrarily change the selection (i.e.
253             * long press followed by using the trackball).  Therefore, we keep
254             * in sync with the TextView via onSelectionChanged.  If we also
255             * send the DOM event, we lose the correct selection.
256            if (isArrowKey) {
257                // Arrow key does not change the text, but we still want to send
258                // the DOM events.
259                sendDomEvent(event);
260            }
261             */
262            return true;
263        }
264        // Ignore the key up event for newlines. This prevents
265        // multiple newlines in the native textarea.
266        if (mGotEnterDown && !down) {
267            return true;
268        }
269        // if it is a navigation key, pass it to WebView
270        if (isArrowKey) {
271            // WebView check the trackballtime in onKeyDown to avoid calling
272            // native from both trackball and key handling. As this is called
273            // from WebTextView, we always want WebView to check with native.
274            // Reset trackballtime to ensure it.
275            mWebView.resetTrackballTime();
276            return down ? mWebView.onKeyDown(keyCode, event) : mWebView
277                    .onKeyUp(keyCode, event);
278        }
279        return false;
280    }
281
282    /**
283     *  Determine whether this WebTextView currently represents the node
284     *  represented by ptr.
285     *  @param  ptr Pointer to a node to compare to.
286     *  @return boolean Whether this WebTextView already represents the node
287     *          pointed to by ptr.
288     */
289    /* package */ boolean isSameTextField(int ptr) {
290        return ptr == mNodePointer;
291    }
292
293    @Override public InputConnection onCreateInputConnection(
294            EditorInfo outAttrs) {
295        InputConnection connection = super.onCreateInputConnection(outAttrs);
296        if (mWebView != null) {
297            // Use the name of the textfield + the url.  Use backslash as an
298            // arbitrary separator.
299            outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\"
300                    + mWebView.getUrl();
301        }
302        return connection;
303    }
304
305    @Override
306    public void onEditorAction(int actionCode) {
307        switch (actionCode) {
308        case EditorInfo.IME_ACTION_NEXT:
309            mWebView.nativeMoveCursorToNextTextInput();
310            // Preemptively rebuild the WebTextView, so that the action will
311            // be set properly.
312            mWebView.rebuildWebTextView();
313            // Since the cursor will no longer be in the same place as the
314            // focus, set the focus controller back to inactive
315            mWebView.setFocusControllerInactive();
316            mWebView.invalidate();
317            mOkayForFocusNotToMatch = true;
318            break;
319        case EditorInfo.IME_ACTION_DONE:
320            super.onEditorAction(actionCode);
321            break;
322        case EditorInfo.IME_ACTION_GO:
323            // Send an enter and hide the soft keyboard
324            InputMethodManager.getInstance(mContext)
325                    .hideSoftInputFromWindow(getWindowToken(), 0);
326            sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
327                    KeyEvent.KEYCODE_ENTER));
328            sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP,
329                    KeyEvent.KEYCODE_ENTER));
330
331        default:
332            break;
333        }
334    }
335
336    @Override
337    protected void onSelectionChanged(int selStart, int selEnd) {
338        // This code is copied from TextView.onDraw().  That code does not get
339        // executed, however, because the WebTextView does not draw, allowing
340        // webkit's drawing to show through.
341        InputMethodManager imm = InputMethodManager.peekInstance();
342        if (imm != null && imm.isActive(this)) {
343            Spannable sp = (Spannable) getText();
344            int candStart = EditableInputConnection.getComposingSpanStart(sp);
345            int candEnd = EditableInputConnection.getComposingSpanEnd(sp);
346            imm.updateSelection(this, selStart, selEnd, candStart, candEnd);
347        }
348        if (!mFromWebKit && mWebView != null) {
349            if (DebugFlags.WEB_TEXT_VIEW) {
350                Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart
351                        + " selEnd=" + selEnd);
352            }
353            mWebView.setSelection(selStart, selEnd);
354        }
355    }
356
357    @Override
358    protected void onTextChanged(CharSequence s,int start,int before,int count){
359        super.onTextChanged(s, start, before, count);
360        String postChange = s.toString();
361        // Prevent calls to setText from invoking onTextChanged (since this will
362        // mean we are on a different textfield).  Also prevent the change when
363        // going from a textfield with a string of text to one with a smaller
364        // limit on text length from registering the onTextChanged event.
365        if (mPreChange == null || mPreChange.equals(postChange) ||
366                (mMaxLength > -1 && mPreChange.length() > mMaxLength &&
367                mPreChange.substring(0, mMaxLength).equals(postChange))) {
368            return;
369        }
370        mPreChange = postChange;
371        // This was simply a delete or a cut, so just delete the selection.
372        if (before > 0 && 0 == count) {
373            mWebView.deleteSelection(start, start + before);
374            // For this and all changes to the text, update our cache
375            updateCachedTextfield();
376            return;
377        }
378        // Find the last character being replaced.  If it can be represented by
379        // events, we will pass them to native (after replacing the beginning
380        // of the changed text), so we can see javascript events.
381        // Otherwise, replace the text being changed (including the last
382        // character) in the textfield.
383        TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0);
384        KeyCharacterMap kmap =
385                KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
386        KeyEvent[] events = kmap.getEvents(mCharacter);
387        boolean cannotUseKeyEvents = null == events;
388        int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1;
389        if (count > 1 || cannotUseKeyEvents) {
390            String replace = s.subSequence(start,
391                    start + count - charactersFromKeyEvents).toString();
392            mWebView.replaceTextfieldText(start, start + before, replace,
393                    start + count - charactersFromKeyEvents,
394                    start + count - charactersFromKeyEvents);
395        } else {
396            // This corrects the selection which may have been affected by the
397            // trackball or auto-correct.
398            if (DebugFlags.WEB_TEXT_VIEW) {
399                Log.v(LOGTAG, "onTextChanged start=" + start
400                        + " start + before=" + (start + before));
401            }
402            if (!mInSetTextAndKeepSelection) {
403                mWebView.setSelection(start, start + before);
404            }
405        }
406        if (!cannotUseKeyEvents) {
407            int length = events.length;
408            for (int i = 0; i < length; i++) {
409                // We never send modifier keys to native code so don't send them
410                // here either.
411                if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
412                    sendDomEvent(events[i]);
413                }
414            }
415        }
416        updateCachedTextfield();
417    }
418
419    @Override
420    public boolean onTouchEvent(MotionEvent event) {
421        switch (event.getAction()) {
422        case MotionEvent.ACTION_DOWN:
423            super.onTouchEvent(event);
424            // This event may be the start of a drag, so store it to pass to the
425            // WebView if it is.
426            mDragStartX = event.getX();
427            mDragStartY = event.getY();
428            mDragStartTime = event.getEventTime();
429            mDragSent = false;
430            mScrolled = false;
431            mGotTouchDown = true;
432            break;
433        case MotionEvent.ACTION_MOVE:
434            int slop = ViewConfiguration.get(mContext).getScaledTouchSlop();
435            Spannable buffer = getText();
436            int initialScrollX = Touch.getInitialScrollX(this, buffer);
437            int initialScrollY = Touch.getInitialScrollY(this, buffer);
438            super.onTouchEvent(event);
439            int dx = Math.abs(mScrollX - initialScrollX);
440            int dy = Math.abs(mScrollY - initialScrollY);
441            // Use a smaller slop when checking to see if we've moved far enough
442            // to scroll the text, because experimentally, slop has shown to be
443            // to big for the case of a small textfield.
444            int smallerSlop = slop/2;
445            if (dx > smallerSlop || dy > smallerSlop) {
446                if (mWebView != null) {
447                    float maxScrollX = (float) Touch.getMaxScrollX(this,
448                                getLayout(), mScrollY);
449                    if (DebugFlags.WEB_TEXT_VIEW) {
450                        Log.v(LOGTAG, "onTouchEvent x=" + mScrollX + " y="
451                                + mScrollY + " maxX=" + maxScrollX);
452                    }
453                    mWebView.scrollFocusedTextInput(maxScrollX > 0 ?
454                            mScrollX / maxScrollX : 0, mScrollY);
455                }
456                mScrolled = true;
457                return true;
458            }
459            if (Math.abs((int) event.getX() - mDragStartX) < slop
460                    && Math.abs((int) event.getY() - mDragStartY) < slop) {
461                // If the user has not scrolled further than slop, we should not
462                // send the drag.  Instead, do nothing, and when the user lifts
463                // their finger, we will change the selection.
464                return true;
465            }
466            if (mWebView != null) {
467                // Only want to set the initial state once.
468                if (!mDragSent) {
469                    mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY,
470                            mDragStartTime);
471                    mDragSent = true;
472                }
473                boolean scrolled = mWebView.textFieldDrag(event);
474                if (scrolled) {
475                    mScrolled = true;
476                    cancelLongPress();
477                    return true;
478                }
479            }
480            return false;
481        case MotionEvent.ACTION_UP:
482        case MotionEvent.ACTION_CANCEL:
483            if (!mScrolled) {
484                // If the page scrolled, or the TextView scrolled, we do not
485                // want to change the selection
486                cancelLongPress();
487                if (mGotTouchDown && mWebView != null) {
488                    mWebView.touchUpOnTextField(event);
489                }
490            }
491            // Necessary for the WebView to reset its state
492            if (mWebView != null && mDragSent) {
493                mWebView.onTouchEvent(event);
494            }
495            mGotTouchDown = false;
496            break;
497        default:
498            break;
499        }
500        return true;
501    }
502
503    @Override
504    public boolean onTrackballEvent(MotionEvent event) {
505        if (isPopupShowing()) {
506            return super.onTrackballEvent(event);
507        }
508        if (event.getAction() != MotionEvent.ACTION_MOVE) {
509            return false;
510        }
511        // If the Cursor is not on the text input, webview should handle the
512        // trackball
513        if (!mWebView.nativeCursorMatchesFocus()) {
514            return mWebView.onTrackballEvent(event);
515        }
516        Spannable text = (Spannable) getText();
517        MovementMethod move = getMovementMethod();
518        if (move != null && getLayout() != null &&
519            move.onTrackballEvent(this, text, event)) {
520            // Selection is changed in onSelectionChanged
521            return true;
522        }
523        return false;
524    }
525
526    /**
527     * Remove this WebTextView from its host WebView, and return
528     * focus to the host.
529     */
530    /* package */ void remove() {
531        // hide the soft keyboard when the edit text is out of focus
532        InputMethodManager.getInstance(mContext).hideSoftInputFromWindow(
533                getWindowToken(), 0);
534        mWebView.removeView(this);
535        mWebView.requestFocus();
536    }
537
538    /* package */ void bringIntoView() {
539        if (getLayout() != null) {
540            bringPointIntoView(Selection.getSelectionEnd(getText()));
541        }
542    }
543
544    /**
545     *  Send the DOM events for the specified event.
546     *  @param event    KeyEvent to be translated into a DOM event.
547     */
548    private void sendDomEvent(KeyEvent event) {
549        mWebView.passToJavaScript(getText().toString(), event);
550    }
551
552    /**
553     *  Always use this instead of setAdapter, as this has features specific to
554     *  the WebTextView.
555     */
556    public void setAdapterCustom(AutoCompleteAdapter adapter) {
557        if (adapter != null) {
558            setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
559            adapter.setTextView(this);
560        }
561        super.setAdapter(adapter);
562    }
563
564    /**
565     *  This is a special version of ArrayAdapter which changes its text size
566     *  to match the text size of its host TextView.
567     */
568    public static class AutoCompleteAdapter extends ArrayAdapter<String> {
569        private TextView mTextView;
570
571        public AutoCompleteAdapter(Context context, ArrayList<String> entries) {
572            super(context, com.android.internal.R.layout
573                    .search_dropdown_item_1line, entries);
574        }
575
576        /**
577         * {@inheritDoc}
578         */
579        public View getView(int position, View convertView, ViewGroup parent) {
580            TextView tv =
581                    (TextView) super.getView(position, convertView, parent);
582            if (tv != null && mTextView != null) {
583                tv.setTextSize(mTextView.getTextSize());
584            }
585            return tv;
586        }
587
588        /**
589         * Set the TextView so we can match its text size.
590         */
591        private void setTextView(TextView tv) {
592            mTextView = tv;
593        }
594    }
595
596    /**
597     * Determine whether to use the system-wide password disguising method,
598     * or to use none.
599     * @param   inPassword  True if the textfield is a password field.
600     */
601    /* package */ void setInPassword(boolean inPassword) {
602        if (inPassword) {
603            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
604                    TYPE_TEXT_VARIATION_PASSWORD);
605            createBackground();
606        }
607        // For password fields, draw the WebTextView.  For others, just show
608        // webkit's drawing.
609        setWillNotDraw(!inPassword);
610        setBackgroundDrawable(inPassword ? mBackground : null);
611        // For non-password fields, avoid the invals from TextView's blinking
612        // cursor
613        setCursorVisible(inPassword);
614    }
615
616    /**
617     * Private class used for the background of a password textfield.
618     */
619    private static class OutlineDrawable extends Drawable {
620        public void draw(Canvas canvas) {
621            Rect bounds = getBounds();
622            Paint paint = new Paint();
623            paint.setAntiAlias(true);
624            // Draw the background.
625            paint.setColor(Color.WHITE);
626            canvas.drawRect(bounds, paint);
627            // Draw the outline.
628            paint.setStyle(Paint.Style.STROKE);
629            paint.setColor(Color.BLACK);
630            canvas.drawRect(bounds, paint);
631        }
632        // Always want it to be opaque.
633        public int getOpacity() {
634            return PixelFormat.OPAQUE;
635        }
636        // These are needed because they are abstract in Drawable.
637        public void setAlpha(int alpha) { }
638        public void setColorFilter(ColorFilter cf) { }
639    }
640
641    /**
642     * Create a background for the WebTextView and set up the paint for drawing
643     * the text.  This way, we can see the password transformation of the
644     * system, which (optionally) shows the actual text before changing to dots.
645     * The background is necessary to hide the webkit-drawn text beneath.
646     */
647    private void createBackground() {
648        if (mBackground != null) {
649            return;
650        }
651        mBackground = new OutlineDrawable();
652
653        setGravity(Gravity.CENTER_VERTICAL);
654        // Turn on subpixel text, and turn off kerning, so it better matches
655        // the text in webkit.
656        TextPaint paint = getPaint();
657        int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG |
658                Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG;
659        paint.setFlags(flags);
660        // Set the text color to black, regardless of the theme.  This ensures
661        // that other applications that use embedded WebViews will properly
662        // display the text in password textfields.
663        setTextColor(Color.BLACK);
664    }
665
666    /* package */ void setMaxLength(int maxLength) {
667        mMaxLength = maxLength;
668        if (-1 == maxLength) {
669            setFilters(NO_FILTERS);
670        } else {
671            setFilters(new InputFilter[] {
672                new InputFilter.LengthFilter(maxLength) });
673        }
674    }
675
676    /**
677     *  Set the pointer for this node so it can be determined which node this
678     *  WebTextView represents.
679     *  @param  ptr Integer representing the pointer to the node which this
680     *          WebTextView represents.
681     */
682    /* package */ void setNodePointer(int ptr) {
683        mNodePointer = ptr;
684    }
685
686    /**
687     * Determine the position and size of WebTextView, and add it to the
688     * WebView's view heirarchy.  All parameters are presumed to be in
689     * view coordinates.  Also requests Focus and sets the cursor to not
690     * request to be in view.
691     * @param x         x-position of the textfield.
692     * @param y         y-position of the textfield.
693     * @param width     width of the textfield.
694     * @param height    height of the textfield.
695     */
696    /* package */ void setRect(int x, int y, int width, int height) {
697        LayoutParams lp = (LayoutParams) getLayoutParams();
698        if (null == lp) {
699            lp = new LayoutParams(width, height, x, y);
700        } else {
701            lp.x = x;
702            lp.y = y;
703            lp.width = width;
704            lp.height = height;
705        }
706        if (getParent() == null) {
707            mWebView.addView(this, lp);
708        } else {
709            setLayoutParams(lp);
710        }
711        // Set up a measure spec so a layout can always be recreated.
712        mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
713        mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
714        requestFocus();
715    }
716
717    /**
718     * Set the selection, and disable our onSelectionChanged action.
719     */
720    /* package */ void setSelectionFromWebKit(int start, int end) {
721        if (start < 0 || end < 0) return;
722        Spannable text = (Spannable) getText();
723        int length = text.length();
724        if (start > length || end > length) return;
725        mFromWebKit = true;
726        Selection.setSelection(text, start, end);
727        mFromWebKit = false;
728    }
729
730    /**
731     * Set whether this is a single-line textfield or a multi-line textarea.
732     * Textfields scroll horizontally, and do not handle the enter key.
733     * Textareas behave oppositely.
734     * Do NOT call this after calling setInPassword(true).  This will result in
735     * removing the password input type.
736     */
737    public void setSingleLine(boolean single) {
738        int inputType = EditorInfo.TYPE_CLASS_TEXT
739                | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
740        if (single) {
741            int action = mWebView.nativeTextFieldAction();
742            switch (action) {
743            // Keep in sync with CachedRoot::ImeAction
744            case 0: // NEXT
745                setImeOptions(EditorInfo.IME_ACTION_NEXT);
746                break;
747            case 1: // GO
748                setImeOptions(EditorInfo.IME_ACTION_GO);
749                break;
750            case -1: // FAILURE
751            case 2: // DONE
752                setImeOptions(EditorInfo.IME_ACTION_DONE);
753                break;
754            }
755        } else {
756            inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
757                    | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
758                    | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT;
759            setImeOptions(EditorInfo.IME_ACTION_NONE);
760        }
761        mSingle = single;
762        setHorizontallyScrolling(single);
763        setInputType(inputType);
764    }
765
766    /**
767     * Set the text for this WebTextView, and set the selection to (start, end)
768     * @param   text    Text to go into this WebTextView.
769     * @param   start   Beginning of the selection.
770     * @param   end     End of the selection.
771     */
772    /* package */ void setText(CharSequence text, int start, int end) {
773        mPreChange = text.toString();
774        setText(text);
775        Spannable span = (Spannable) getText();
776        int length = span.length();
777        if (end > length) {
778            end = length;
779        }
780        if (start < 0) {
781            start = 0;
782        } else if (start > length) {
783            start = length;
784        }
785        if (DebugFlags.WEB_TEXT_VIEW) {
786            Log.v(LOGTAG, "setText start=" + start
787                    + " end=" + end);
788        }
789        Selection.setSelection(span, start, end);
790    }
791
792    /**
793     * Set the text to the new string, but use the old selection, making sure
794     * to keep it within the new string.
795     * @param   text    The new text to place in the textfield.
796     */
797    /* package */ void setTextAndKeepSelection(String text) {
798        mPreChange = text.toString();
799        Editable edit = (Editable) getText();
800        mInSetTextAndKeepSelection = true;
801        edit.replace(0, edit.length(), text);
802        mInSetTextAndKeepSelection = false;
803        updateCachedTextfield();
804    }
805
806    /**
807     *  Update the cache to reflect the current text.
808     */
809    /* package */ void updateCachedTextfield() {
810        mWebView.updateCachedTextfield(getText().toString());
811    }
812
813    @Override
814    public boolean requestRectangleOnScreen(Rect rectangle) {
815        // don't scroll while in zoom animation. When it is done, we will adjust
816        // the WebTextView if it is in editing mode.
817        if (!mWebView.inAnimateZoom()) {
818            return super.requestRectangleOnScreen(rectangle);
819        }
820        return false;
821    }
822}
823