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