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