WebTextView.java revision 9e3e2d3a6967301730fd383e8b04d53fdfd008e5
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(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
603            adapter.setTextView(this);
604        }
605        super.setAdapter(adapter);
606    }
607
608    /**
609     *  This is a special version of ArrayAdapter which changes its text size
610     *  to match the text size of its host TextView.
611     */
612    public static class AutoCompleteAdapter extends ArrayAdapter<String> {
613        private TextView mTextView;
614
615        public AutoCompleteAdapter(Context context, ArrayList<String> entries) {
616            super(context, com.android.internal.R.layout
617                    .search_dropdown_item_1line, entries);
618        }
619
620        /**
621         * {@inheritDoc}
622         */
623        public View getView(int position, View convertView, ViewGroup parent) {
624            TextView tv =
625                    (TextView) super.getView(position, convertView, parent);
626            if (tv != null && mTextView != null) {
627                tv.setTextSize(mTextView.getTextSize());
628            }
629            return tv;
630        }
631
632        /**
633         * Set the TextView so we can match its text size.
634         */
635        private void setTextView(TextView tv) {
636            mTextView = tv;
637        }
638    }
639
640    /**
641     * Sets the selection when the user clicks on a textfield or textarea with
642     * the trackball or center key, or starts typing into it without clicking on
643     * it.
644     */
645    /* package */ void setDefaultSelection() {
646        Spannable text = (Spannable) getText();
647        int selection = mSingle ? text.length() : 0;
648        if (Selection.getSelectionStart(text) == selection
649                && Selection.getSelectionEnd(text) == selection) {
650            // The selection of the UI copy is set correctly, but the
651            // WebTextView still needs to inform the webkit thread to set the
652            // selection.  Normally that is done in onSelectionChanged, but
653            // onSelectionChanged will not be called because the UI copy is not
654            // changing.  (This can happen when the WebTextView takes focus.
655            // That onSelectionChanged was blocked because the selection set
656            // when focusing is not necessarily the desirable selection for
657            // WebTextView.)
658            if (mWebView != null) {
659                mWebView.setSelection(selection, selection);
660            }
661        } else {
662            Selection.setSelection(text, selection, selection);
663        }
664    }
665
666    /**
667     * Determine whether to use the system-wide password disguising method,
668     * or to use none.
669     * @param   inPassword  True if the textfield is a password field.
670     */
671    /* package */ void setInPassword(boolean inPassword) {
672        if (inPassword) {
673            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
674                    TYPE_TEXT_VARIATION_PASSWORD);
675            createBackground();
676        }
677        // For password fields, draw the WebTextView.  For others, just show
678        // webkit's drawing.
679        setWillNotDraw(!inPassword);
680        setBackgroundDrawable(inPassword ? mBackground : null);
681        // For non-password fields, avoid the invals from TextView's blinking
682        // cursor
683        setCursorVisible(inPassword);
684    }
685
686    /**
687     * Private class used for the background of a password textfield.
688     */
689    private static class OutlineDrawable extends Drawable {
690        public void draw(Canvas canvas) {
691            Rect bounds = getBounds();
692            Paint paint = new Paint();
693            paint.setAntiAlias(true);
694            // Draw the background.
695            paint.setColor(Color.WHITE);
696            canvas.drawRect(bounds, paint);
697            // Draw the outline.
698            paint.setStyle(Paint.Style.STROKE);
699            paint.setColor(Color.BLACK);
700            canvas.drawRect(bounds, paint);
701        }
702        // Always want it to be opaque.
703        public int getOpacity() {
704            return PixelFormat.OPAQUE;
705        }
706        // These are needed because they are abstract in Drawable.
707        public void setAlpha(int alpha) { }
708        public void setColorFilter(ColorFilter cf) { }
709    }
710
711    /**
712     * Create a background for the WebTextView and set up the paint for drawing
713     * the text.  This way, we can see the password transformation of the
714     * system, which (optionally) shows the actual text before changing to dots.
715     * The background is necessary to hide the webkit-drawn text beneath.
716     */
717    private void createBackground() {
718        if (mBackground != null) {
719            return;
720        }
721        mBackground = new OutlineDrawable();
722
723        setGravity(Gravity.CENTER_VERTICAL);
724        // Turn on subpixel text, and turn off kerning, so it better matches
725        // the text in webkit.
726        TextPaint paint = getPaint();
727        int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG |
728                Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG;
729        paint.setFlags(flags);
730        // Set the text color to black, regardless of the theme.  This ensures
731        // that other applications that use embedded WebViews will properly
732        // display the text in password textfields.
733        setTextColor(Color.BLACK);
734    }
735
736    @Override
737    public void setInputType(int type) {
738        mFromSetInputType = true;
739        super.setInputType(type);
740        mFromSetInputType = false;
741    }
742
743    /* package */ void setMaxLength(int maxLength) {
744        mMaxLength = maxLength;
745        if (-1 == maxLength) {
746            setFilters(NO_FILTERS);
747        } else {
748            setFilters(new InputFilter[] {
749                new InputFilter.LengthFilter(maxLength) });
750        }
751    }
752
753    /**
754     *  Set the pointer for this node so it can be determined which node this
755     *  WebTextView represents.
756     *  @param  ptr Integer representing the pointer to the node which this
757     *          WebTextView represents.
758     */
759    /* package */ void setNodePointer(int ptr) {
760        mNodePointer = ptr;
761    }
762
763    /**
764     * Determine the position and size of WebTextView, and add it to the
765     * WebView's view heirarchy.  All parameters are presumed to be in
766     * view coordinates.  Also requests Focus and sets the cursor to not
767     * request to be in view.
768     * @param x         x-position of the textfield.
769     * @param y         y-position of the textfield.
770     * @param width     width of the textfield.
771     * @param height    height of the textfield.
772     */
773    /* package */ void setRect(int x, int y, int width, int height) {
774        LayoutParams lp = (LayoutParams) getLayoutParams();
775        if (null == lp) {
776            lp = new LayoutParams(width, height, x, y);
777        } else {
778            lp.x = x;
779            lp.y = y;
780            lp.width = width;
781            lp.height = height;
782        }
783        if (getParent() == null) {
784            mWebView.addView(this, lp);
785        } else {
786            setLayoutParams(lp);
787        }
788        // Set up a measure spec so a layout can always be recreated.
789        mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
790        mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
791        requestFocus();
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 whether this is a single-line textfield or a multi-line textarea.
809     * Textfields scroll horizontally, and do not handle the enter key.
810     * Textareas behave oppositely.
811     * Do NOT call this after calling setInPassword(true).  This will result in
812     * removing the password input type.
813     */
814    public void setSingleLine(boolean single) {
815        int inputType = EditorInfo.TYPE_CLASS_TEXT
816                | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
817        if (single) {
818            int action = mWebView.nativeTextFieldAction();
819            switch (action) {
820            // Keep in sync with CachedRoot::ImeAction
821            case 0: // NEXT
822                setImeOptions(EditorInfo.IME_ACTION_NEXT);
823                break;
824            case 1: // GO
825                setImeOptions(EditorInfo.IME_ACTION_GO);
826                break;
827            case -1: // FAILURE
828            case 2: // DONE
829                setImeOptions(EditorInfo.IME_ACTION_DONE);
830                break;
831            case 3: // SEARCH
832                setImeOptions(EditorInfo.IME_ACTION_SEARCH);
833                break;
834            }
835        } else {
836            inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
837                    | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
838                    | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT;
839            setImeOptions(EditorInfo.IME_ACTION_NONE);
840        }
841        mSingle = single;
842        setHorizontallyScrolling(single);
843        setInputType(inputType);
844    }
845
846    /**
847     * Set the text to the new string, but use the old selection, making sure
848     * to keep it within the new string.
849     * @param   text    The new text to place in the textfield.
850     */
851    /* package */ void setTextAndKeepSelection(String text) {
852        mPreChange = text.toString();
853        Editable edit = (Editable) getText();
854        mInSetTextAndKeepSelection = true;
855        edit.replace(0, edit.length(), text);
856        mInSetTextAndKeepSelection = false;
857        updateCachedTextfield();
858    }
859
860    /**
861     *  Update the cache to reflect the current text.
862     */
863    /* package */ void updateCachedTextfield() {
864        mWebView.updateCachedTextfield(getText().toString());
865    }
866
867    @Override
868    public boolean requestRectangleOnScreen(Rect rectangle) {
869        // don't scroll while in zoom animation. When it is done, we will adjust
870        // the WebTextView if it is in editing mode.
871        if (!mWebView.inAnimateZoom()) {
872            return super.requestRectangleOnScreen(rectangle);
873        }
874        return false;
875    }
876}
877