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