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