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