WebTextView.java revision 44d2c69ad30878521c6eff66a83893099b3d12ee
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    /**
293     * Ensure that the underlying textfield is lined up with the WebTextView.
294     */
295    private void lineUpScroll() {
296        Layout layout = getLayout();
297        if (mWebView != null && layout != null) {
298            float maxScrollX = Touch.getMaxScrollX(this, layout, mScrollY);
299            if (DebugFlags.WEB_TEXT_VIEW) {
300                Log.v(LOGTAG, "onTouchEvent x=" + mScrollX + " y="
301                        + mScrollY + " maxX=" + maxScrollX);
302            }
303            mWebView.scrollFocusedTextInput(maxScrollX > 0 ?
304                    mScrollX / maxScrollX : 0, mScrollY);
305        }
306    }
307
308    @Override public InputConnection onCreateInputConnection(
309            EditorInfo outAttrs) {
310        InputConnection connection = super.onCreateInputConnection(outAttrs);
311        if (mWebView != null) {
312            // Use the name of the textfield + the url.  Use backslash as an
313            // arbitrary separator.
314            outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\"
315                    + mWebView.getUrl();
316        }
317        return connection;
318    }
319
320    @Override
321    protected void onDraw(Canvas canvas) {
322        // onDraw should only be called for password fields.  If WebTextView is
323        // still drawing, but is no longer corresponding to a password field,
324        // remove it.
325        if (mWebView == null || !mWebView.nativeFocusCandidateIsPassword()
326                || !isSameTextField(mWebView.nativeFocusCandidatePointer())) {
327            // Although calling remove() would seem to make more sense here,
328            // changing it to not be a password field will make it not draw.
329            // Other code will make sure that it is removed completely, but this
330            // way the user will not see it.
331            setInPassword(false);
332        } else {
333            super.onDraw(canvas);
334        }
335    }
336
337    @Override
338    public void onEditorAction(int actionCode) {
339        switch (actionCode) {
340        case EditorInfo.IME_ACTION_NEXT:
341            if (mWebView.nativeMoveCursorToNextTextInput()) {
342                // Since the cursor will no longer be in the same place as the
343                // focus, set the focus controller back to inactive
344                mWebView.setFocusControllerInactive();
345                // Preemptively rebuild the WebTextView, so that the action will
346                // be set properly.
347                mWebView.rebuildWebTextView();
348                setDefaultSelection();
349                mWebView.invalidate();
350            }
351            break;
352        case EditorInfo.IME_ACTION_DONE:
353            super.onEditorAction(actionCode);
354            break;
355        case EditorInfo.IME_ACTION_GO:
356        case EditorInfo.IME_ACTION_SEARCH:
357            // Send an enter and hide the soft keyboard
358            InputMethodManager.getInstance(mContext)
359                    .hideSoftInputFromWindow(getWindowToken(), 0);
360            sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
361                    KeyEvent.KEYCODE_ENTER));
362            sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP,
363                    KeyEvent.KEYCODE_ENTER));
364
365        default:
366            break;
367        }
368    }
369
370    @Override
371    protected void onFocusChanged(boolean focused, int direction,
372            Rect previouslyFocusedRect) {
373        mFromFocusChange = true;
374        super.onFocusChanged(focused, direction, previouslyFocusedRect);
375        mFromFocusChange = false;
376    }
377
378    @Override
379    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
380        super.onScrollChanged(l, t, oldl, oldt);
381        lineUpScroll();
382    }
383
384    @Override
385    protected void onSelectionChanged(int selStart, int selEnd) {
386        if (mInSetTextAndKeepSelection) return;
387        // This code is copied from TextView.onDraw().  That code does not get
388        // executed, however, because the WebTextView does not draw, allowing
389        // webkit's drawing to show through.
390        InputMethodManager imm = InputMethodManager.peekInstance();
391        if (imm != null && imm.isActive(this)) {
392            Spannable sp = (Spannable) getText();
393            int candStart = EditableInputConnection.getComposingSpanStart(sp);
394            int candEnd = EditableInputConnection.getComposingSpanEnd(sp);
395            imm.updateSelection(this, selStart, selEnd, candStart, candEnd);
396        }
397        if (!mFromWebKit && !mFromFocusChange && !mFromSetInputType
398                && mWebView != null) {
399            if (DebugFlags.WEB_TEXT_VIEW) {
400                Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart
401                        + " selEnd=" + selEnd);
402            }
403            mWebView.setSelection(selStart, selEnd);
404            lineUpScroll();
405        }
406    }
407
408    @Override
409    protected void onTextChanged(CharSequence s,int start,int before,int count){
410        super.onTextChanged(s, start, before, count);
411        String postChange = s.toString();
412        // Prevent calls to setText from invoking onTextChanged (since this will
413        // mean we are on a different textfield).  Also prevent the change when
414        // going from a textfield with a string of text to one with a smaller
415        // limit on text length from registering the onTextChanged event.
416        if (mPreChange == null || mPreChange.equals(postChange) ||
417                (mMaxLength > -1 && mPreChange.length() > mMaxLength &&
418                mPreChange.substring(0, mMaxLength).equals(postChange))) {
419            return;
420        }
421        mPreChange = postChange;
422        if (0 == count) {
423            if (before > 0) {
424                // This was simply a delete or a cut, so just delete the
425                // selection.
426                mWebView.deleteSelection(start, start + before);
427                // For this and all changes to the text, update our cache
428                updateCachedTextfield();
429            }
430            // before should never be negative, so whether it was a cut
431            // (handled above), or before is 0, in which case nothing has
432            // changed, we should return.
433            return;
434        }
435        // Find the last character being replaced.  If it can be represented by
436        // events, we will pass them to native (after replacing the beginning
437        // of the changed text), so we can see javascript events.
438        // Otherwise, replace the text being changed (including the last
439        // character) in the textfield.
440        TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0);
441        KeyCharacterMap kmap =
442                KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
443        KeyEvent[] events = kmap.getEvents(mCharacter);
444        boolean cannotUseKeyEvents = null == events;
445        int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1;
446        if (count > 1 || cannotUseKeyEvents) {
447            String replace = s.subSequence(start,
448                    start + count - charactersFromKeyEvents).toString();
449            mWebView.replaceTextfieldText(start, start + before, replace,
450                    start + count - charactersFromKeyEvents,
451                    start + count - charactersFromKeyEvents);
452        } else {
453            // This corrects the selection which may have been affected by the
454            // trackball or auto-correct.
455            if (DebugFlags.WEB_TEXT_VIEW) {
456                Log.v(LOGTAG, "onTextChanged start=" + start
457                        + " start + before=" + (start + before));
458            }
459            if (!mInSetTextAndKeepSelection) {
460                mWebView.setSelection(start, start + before);
461            }
462        }
463        if (!cannotUseKeyEvents) {
464            int length = events.length;
465            for (int i = 0; i < length; i++) {
466                // We never send modifier keys to native code so don't send them
467                // here either.
468                if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
469                    sendDomEvent(events[i]);
470                }
471            }
472        }
473        updateCachedTextfield();
474    }
475
476    @Override
477    public boolean onTouchEvent(MotionEvent event) {
478        switch (event.getAction()) {
479        case MotionEvent.ACTION_DOWN:
480            super.onTouchEvent(event);
481            // This event may be the start of a drag, so store it to pass to the
482            // WebView if it is.
483            mDragStartX = event.getX();
484            mDragStartY = event.getY();
485            mDragStartTime = event.getEventTime();
486            mDragSent = false;
487            mScrolled = false;
488            mGotTouchDown = true;
489            mHasPerformedLongClick = false;
490            break;
491        case MotionEvent.ACTION_MOVE:
492            if (mHasPerformedLongClick) {
493                mGotTouchDown = false;
494                return false;
495            }
496            int slop = ViewConfiguration.get(mContext).getScaledTouchSlop();
497            Spannable buffer = getText();
498            int initialScrollX = Touch.getInitialScrollX(this, buffer);
499            int initialScrollY = Touch.getInitialScrollY(this, buffer);
500            super.onTouchEvent(event);
501            int dx = Math.abs(mScrollX - initialScrollX);
502            int dy = Math.abs(mScrollY - initialScrollY);
503            // Use a smaller slop when checking to see if we've moved far enough
504            // to scroll the text, because experimentally, slop has shown to be
505            // to big for the case of a small textfield.
506            int smallerSlop = slop/2;
507            if (dx > smallerSlop || dy > smallerSlop) {
508                // Scrolling is handled in onScrollChanged.
509                mScrolled = true;
510                cancelLongPress();
511                return true;
512            }
513            if (Math.abs((int) event.getX() - mDragStartX) < slop
514                    && Math.abs((int) event.getY() - mDragStartY) < slop) {
515                // If the user has not scrolled further than slop, we should not
516                // send the drag.  Instead, do nothing, and when the user lifts
517                // their finger, we will change the selection.
518                return true;
519            }
520            if (mWebView != null) {
521                // Only want to set the initial state once.
522                if (!mDragSent) {
523                    mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY,
524                            mDragStartTime);
525                    mDragSent = true;
526                }
527                boolean scrolled = mWebView.textFieldDrag(event);
528                if (scrolled) {
529                    mScrolled = true;
530                    cancelLongPress();
531                    return true;
532                }
533            }
534            return false;
535        case MotionEvent.ACTION_UP:
536        case MotionEvent.ACTION_CANCEL:
537            super.onTouchEvent(event);
538            if (mHasPerformedLongClick) {
539                mGotTouchDown = false;
540                return false;
541            }
542            if (!mScrolled) {
543                // If the page scrolled, or the TextView scrolled, we do not
544                // want to change the selection
545                cancelLongPress();
546                if (mGotTouchDown && mWebView != null) {
547                    mWebView.touchUpOnTextField(event);
548                }
549            }
550            // Necessary for the WebView to reset its state
551            if (mWebView != null && mDragSent) {
552                mWebView.onTouchEvent(event);
553            }
554            mGotTouchDown = false;
555            break;
556        default:
557            break;
558        }
559        return true;
560    }
561
562    @Override
563    public boolean onTrackballEvent(MotionEvent event) {
564        if (isPopupShowing()) {
565            return super.onTrackballEvent(event);
566        }
567        if (event.getAction() != MotionEvent.ACTION_MOVE) {
568            return false;
569        }
570        // If the Cursor is not on the text input, webview should handle the
571        // trackball
572        if (!mWebView.nativeCursorMatchesFocus()) {
573            return mWebView.onTrackballEvent(event);
574        }
575        Spannable text = (Spannable) getText();
576        MovementMethod move = getMovementMethod();
577        if (move != null && getLayout() != null &&
578            move.onTrackballEvent(this, text, event)) {
579            // Selection is changed in onSelectionChanged
580            return true;
581        }
582        return false;
583    }
584
585    @Override
586    public boolean performLongClick() {
587        mHasPerformedLongClick = true;
588        return super.performLongClick();
589    }
590
591    /**
592     * Remove this WebTextView from its host WebView, and return
593     * focus to the host.
594     */
595    /* package */ void remove() {
596        // hide the soft keyboard when the edit text is out of focus
597        InputMethodManager.getInstance(mContext).hideSoftInputFromWindow(
598                getWindowToken(), 0);
599        mWebView.removeView(this);
600        mWebView.requestFocus();
601    }
602
603    /* package */ void bringIntoView() {
604        if (getLayout() != null) {
605            bringPointIntoView(Selection.getSelectionEnd(getText()));
606        }
607    }
608
609    /**
610     *  Send the DOM events for the specified event.
611     *  @param event    KeyEvent to be translated into a DOM event.
612     */
613    private void sendDomEvent(KeyEvent event) {
614        mWebView.passToJavaScript(getText().toString(), event);
615    }
616
617    /**
618     *  Always use this instead of setAdapter, as this has features specific to
619     *  the WebTextView.
620     */
621    public void setAdapterCustom(AutoCompleteAdapter adapter) {
622        if (adapter != null) {
623            setInputType(getInputType()
624                    | EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
625            adapter.setTextView(this);
626        }
627        super.setAdapter(adapter);
628    }
629
630    /**
631     *  This is a special version of ArrayAdapter which changes its text size
632     *  to match the text size of its host TextView.
633     */
634    public static class AutoCompleteAdapter extends ArrayAdapter<String> {
635        private TextView mTextView;
636
637        public AutoCompleteAdapter(Context context, ArrayList<String> entries) {
638            super(context, com.android.internal.R.layout
639                    .search_dropdown_item_1line, entries);
640        }
641
642        /**
643         * {@inheritDoc}
644         */
645        public View getView(int position, View convertView, ViewGroup parent) {
646            TextView tv =
647                    (TextView) super.getView(position, convertView, parent);
648            if (tv != null && mTextView != null) {
649                tv.setTextSize(mTextView.getTextSize());
650            }
651            return tv;
652        }
653
654        /**
655         * Set the TextView so we can match its text size.
656         */
657        private void setTextView(TextView tv) {
658            mTextView = tv;
659        }
660    }
661
662    /**
663     * Sets the selection when the user clicks on a textfield or textarea with
664     * the trackball or center key, or starts typing into it without clicking on
665     * it.
666     */
667    /* package */ void setDefaultSelection() {
668        Spannable text = (Spannable) getText();
669        int selection = mSingle ? text.length() : 0;
670        if (Selection.getSelectionStart(text) == selection
671                && Selection.getSelectionEnd(text) == selection) {
672            // The selection of the UI copy is set correctly, but the
673            // WebTextView still needs to inform the webkit thread to set the
674            // selection.  Normally that is done in onSelectionChanged, but
675            // onSelectionChanged will not be called because the UI copy is not
676            // changing.  (This can happen when the WebTextView takes focus.
677            // That onSelectionChanged was blocked because the selection set
678            // when focusing is not necessarily the desirable selection for
679            // WebTextView.)
680            if (mWebView != null) {
681                mWebView.setSelection(selection, selection);
682            }
683        } else {
684            Selection.setSelection(text, selection, selection);
685        }
686    }
687
688    /**
689     * Determine whether to use the system-wide password disguising method,
690     * or to use none.
691     * @param   inPassword  True if the textfield is a password field.
692     */
693    /* package */ void setInPassword(boolean inPassword) {
694        if (inPassword) {
695            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
696                    TYPE_TEXT_VARIATION_PASSWORD);
697            createBackground();
698        }
699        // For password fields, draw the WebTextView.  For others, just show
700        // webkit's drawing.
701        setWillNotDraw(!inPassword);
702        setBackgroundDrawable(inPassword ? mBackground : null);
703    }
704
705    /**
706     * Private class used for the background of a password textfield.
707     */
708    private static class OutlineDrawable extends Drawable {
709        public void draw(Canvas canvas) {
710            Rect bounds = getBounds();
711            Paint paint = new Paint();
712            paint.setAntiAlias(true);
713            // Draw the background.
714            paint.setColor(Color.WHITE);
715            canvas.drawRect(bounds, paint);
716            // Draw the outline.
717            paint.setStyle(Paint.Style.STROKE);
718            paint.setColor(Color.BLACK);
719            canvas.drawRect(bounds, paint);
720        }
721        // Always want it to be opaque.
722        public int getOpacity() {
723            return PixelFormat.OPAQUE;
724        }
725        // These are needed because they are abstract in Drawable.
726        public void setAlpha(int alpha) { }
727        public void setColorFilter(ColorFilter cf) { }
728    }
729
730    /**
731     * Create a background for the WebTextView and set up the paint for drawing
732     * the text.  This way, we can see the password transformation of the
733     * system, which (optionally) shows the actual text before changing to dots.
734     * The background is necessary to hide the webkit-drawn text beneath.
735     */
736    private void createBackground() {
737        if (mBackground != null) {
738            return;
739        }
740        mBackground = new OutlineDrawable();
741
742        setGravity(Gravity.CENTER_VERTICAL);
743        // Turn on subpixel text, and turn off kerning, so it better matches
744        // the text in webkit.
745        TextPaint paint = getPaint();
746        int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG |
747                Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG;
748        paint.setFlags(flags);
749        // Set the text color to black, regardless of the theme.  This ensures
750        // that other applications that use embedded WebViews will properly
751        // display the text in password textfields.
752        setTextColor(Color.BLACK);
753    }
754
755    @Override
756    public void setInputType(int type) {
757        mFromSetInputType = true;
758        super.setInputType(type);
759        mFromSetInputType = false;
760    }
761
762    private void setMaxLength(int maxLength) {
763        mMaxLength = maxLength;
764        if (-1 == maxLength) {
765            setFilters(NO_FILTERS);
766        } else {
767            setFilters(new InputFilter[] {
768                new InputFilter.LengthFilter(maxLength) });
769        }
770    }
771
772    /**
773     *  Set the pointer for this node so it can be determined which node this
774     *  WebTextView represents.
775     *  @param  ptr Integer representing the pointer to the node which this
776     *          WebTextView represents.
777     */
778    /* package */ void setNodePointer(int ptr) {
779        mNodePointer = ptr;
780    }
781
782    /**
783     * Determine the position and size of WebTextView, and add it to the
784     * WebView's view heirarchy.  All parameters are presumed to be in
785     * view coordinates.  Also requests Focus and sets the cursor to not
786     * request to be in view.
787     * @param x         x-position of the textfield.
788     * @param y         y-position of the textfield.
789     * @param width     width of the textfield.
790     * @param height    height of the textfield.
791     */
792    /* package */ void setRect(int x, int y, int width, int height) {
793        LayoutParams lp = (LayoutParams) getLayoutParams();
794        if (null == lp) {
795            lp = new LayoutParams(width, height, x, y);
796        } else {
797            lp.x = x;
798            lp.y = y;
799            lp.width = width;
800            lp.height = height;
801        }
802        if (getParent() == null) {
803            mWebView.addView(this, lp);
804        } else {
805            setLayoutParams(lp);
806        }
807        // Set up a measure spec so a layout can always be recreated.
808        mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
809        mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
810    }
811
812    /**
813     * Set the selection, and disable our onSelectionChanged action.
814     */
815    /* package */ void setSelectionFromWebKit(int start, int end) {
816        if (start < 0 || end < 0) return;
817        Spannable text = (Spannable) getText();
818        int length = text.length();
819        if (start > length || end > length) return;
820        mFromWebKit = true;
821        Selection.setSelection(text, start, end);
822        mFromWebKit = false;
823    }
824
825    /**
826     * Set the text to the new string, but use the old selection, making sure
827     * to keep it within the new string.
828     * @param   text    The new text to place in the textfield.
829     */
830    /* package */ void setTextAndKeepSelection(String text) {
831        mPreChange = text.toString();
832        Editable edit = (Editable) getText();
833        int selStart = Selection.getSelectionStart(edit);
834        int selEnd = Selection.getSelectionEnd(edit);
835        mInSetTextAndKeepSelection = true;
836        edit.replace(0, edit.length(), text);
837        int newLength = edit.length();
838        if (selStart > newLength) selStart = newLength;
839        if (selEnd > newLength) selEnd = newLength;
840        Selection.setSelection(edit, selStart, selEnd);
841        mInSetTextAndKeepSelection = false;
842        updateCachedTextfield();
843    }
844
845    /**
846     * Called by WebView.rebuildWebTextView().  Based on the type of the <input>
847     * element, set up the WebTextView, its InputType, and IME Options properly.
848     * @param type int corresponding to enum "type" defined in WebView.cpp.
849     *              Does not correspond to HTMLInputElement::InputType so this
850     *              is unaffected if that changes, and also because that has no
851     *              type corresponding to textarea (which is its own tag).
852     */
853    /* package */ void setType(int type) {
854        if (mWebView == null) return;
855        boolean single = true;
856        boolean inPassword = false;
857        int maxLength = -1;
858        int inputType = EditorInfo.TYPE_CLASS_TEXT;
859        if (mWebView.nativeFocusCandidateHasNextTextfield()) {
860            inputType |= EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
861        }
862        int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
863                | EditorInfo.IME_FLAG_NO_FULLSCREEN;
864        switch (type) {
865            case 0: // NORMAL_TEXT_FIELD
866                imeOptions |= EditorInfo.IME_ACTION_GO;
867                break;
868            case 1: // TEXT_AREA
869                single = false;
870                inputType = EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
871                        | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
872                        | EditorInfo.TYPE_CLASS_TEXT
873                        | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT;
874                imeOptions |= EditorInfo.IME_ACTION_NONE;
875                break;
876            case 2: // PASSWORD
877                inPassword = true;
878                imeOptions |= EditorInfo.IME_ACTION_GO;
879                break;
880            case 3: // SEARCH
881                imeOptions |= EditorInfo.IME_ACTION_SEARCH;
882                break;
883            case 4: // EMAIL
884                // TYPE_TEXT_VARIATION_WEB_EDIT_TEXT prevents EMAIL_ADDRESS
885                // from working, so exclude it for now.
886                imeOptions |= EditorInfo.IME_ACTION_GO;
887                break;
888            case 5: // NUMBER
889                inputType |= EditorInfo.TYPE_CLASS_NUMBER;
890                // Number and telephone do not have both a Tab key and an
891                // action, so set the action to NEXT
892                imeOptions |= EditorInfo.IME_ACTION_NEXT;
893                break;
894            case 6: // TELEPHONE
895                inputType |= EditorInfo.TYPE_CLASS_PHONE;
896                imeOptions |= EditorInfo.IME_ACTION_NEXT;
897                break;
898            case 7: // URL
899                // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so
900                // exclude it for now.
901                imeOptions |= EditorInfo.IME_ACTION_GO;
902                break;
903            default:
904                imeOptions |= EditorInfo.IME_ACTION_GO;
905                break;
906        }
907        setHint(null);
908        if (single) {
909            mWebView.requestLabel(mWebView.nativeFocusCandidateFramePointer(),
910                    mNodePointer);
911            maxLength = mWebView.nativeFocusCandidateMaxLength();
912            if (type != 2 /* PASSWORD */) {
913                String name = mWebView.nativeFocusCandidateName();
914                if (name != null && name.length() > 0) {
915                    mWebView.requestFormData(name, mNodePointer);
916                }
917            }
918        }
919        mSingle = single;
920        setMaxLength(maxLength);
921        setHorizontallyScrolling(single);
922        setInputType(inputType);
923        setImeOptions(imeOptions);
924        setInPassword(inPassword);
925        AutoCompleteAdapter adapter = null;
926        setAdapterCustom(adapter);
927    }
928
929    /**
930     *  Update the cache to reflect the current text.
931     */
932    /* package */ void updateCachedTextfield() {
933        mWebView.updateCachedTextfield(getText().toString());
934    }
935
936    @Override
937    public boolean requestRectangleOnScreen(Rect rectangle) {
938        // don't scroll while in zoom animation. When it is done, we will adjust
939        // the WebTextView if it is in editing mode.
940        if (!mWebView.inAnimateZoom()) {
941            return super.requestRectangleOnScreen(rectangle);
942        }
943        return false;
944    }
945}
946