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