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