WebTextView.java revision 6679f2f70813eb93bf88297dc2de5e56bc7d7ca0
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 android.content.Context;
20import android.graphics.Canvas;
21import android.graphics.Color;
22import android.graphics.ColorFilter;
23import android.graphics.Paint;
24import android.graphics.PixelFormat;
25import android.graphics.Rect;
26import android.graphics.drawable.Drawable;
27import android.text.Editable;
28import android.text.InputFilter;
29import android.text.Selection;
30import android.text.Spannable;
31import android.text.TextPaint;
32import android.text.TextUtils;
33import android.text.method.MovementMethod;
34import android.text.method.Touch;
35import android.util.Log;
36import android.view.Gravity;
37import android.view.KeyCharacterMap;
38import android.view.KeyEvent;
39import android.view.MotionEvent;
40import android.view.View;
41import android.view.ViewGroup;
42import android.view.inputmethod.EditorInfo;
43import android.view.inputmethod.InputMethodManager;
44import android.view.inputmethod.InputConnection;
45import android.widget.AbsoluteLayout.LayoutParams;
46import android.widget.ArrayAdapter;
47import android.widget.AutoCompleteTextView;
48import android.widget.TextView;
49
50import java.util.ArrayList;
51
52/**
53 * WebTextView is a specialized version of EditText used by WebView
54 * to overlay html textfields (and textareas) to use our standard
55 * text editing.
56 */
57/* package */ class WebTextView extends AutoCompleteTextView {
58
59    static final String LOGTAG = "webtextview";
60
61    private WebView         mWebView;
62    private boolean         mSingle;
63    private int             mWidthSpec;
64    private int             mHeightSpec;
65    private int             mNodePointer;
66    // FIXME: This is a hack for blocking unmatched key ups, in particular
67    // on the enter key.  The method for blocking unmatched key ups prevents
68    // the shift key from working properly.
69    private boolean         mGotEnterDown;
70    private int             mMaxLength;
71    // Keep track of the text before the change so we know whether we actually
72    // need to send down the DOM events.
73    private String          mPreChange;
74    private Drawable        mBackground;
75    // Variables for keeping track of the touch down, to send to the WebView
76    // when a drag starts
77    private float           mDragStartX;
78    private float           mDragStartY;
79    private long            mDragStartTime;
80    private boolean         mDragSent;
81    // True if the most recent drag event has caused either the TextView to
82    // scroll or the web page to scroll.  Gets reset after a touch down.
83    private boolean         mScrolled;
84    // Gets set to true when the the IME jumps to the next textfield.  When this
85    // happens, the next time the user hits a key it is okay for the focus
86    // pointer to not match the WebTextView's node pointer
87    private boolean         mOkayForFocusNotToMatch;
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    private boolean         mGotTouchDown;
92    // Array to store the final character added in onTextChanged, so that its
93    // KeyEvents may be determined.
94    private char[]          mCharacter = new char[1];
95    // This is used to reset the length filter when on a textfield
96    // with no max length.
97    // FIXME: This can be replaced with TextView.NO_FILTERS if that
98    // is made public/protected.
99    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
100
101    /**
102     * Create a new WebTextView.
103     * @param   context The Context for this WebTextView.
104     * @param   webView The WebView that created this.
105     */
106    /* package */ WebTextView(Context context, WebView webView) {
107        super(context);
108        mWebView = webView;
109        mMaxLength = -1;
110    }
111
112    @Override
113    public boolean dispatchKeyEvent(KeyEvent event) {
114        if (event.isSystem()) {
115            return super.dispatchKeyEvent(event);
116        }
117        // Treat ACTION_DOWN and ACTION MULTIPLE the same
118        boolean down = event.getAction() != KeyEvent.ACTION_UP;
119        int keyCode = event.getKeyCode();
120
121        boolean isArrowKey = false;
122        switch(keyCode) {
123            case KeyEvent.KEYCODE_DPAD_LEFT:
124            case KeyEvent.KEYCODE_DPAD_RIGHT:
125            case KeyEvent.KEYCODE_DPAD_UP:
126            case KeyEvent.KEYCODE_DPAD_DOWN:
127                if (!mWebView.nativeCursorMatchesFocus()) {
128                    return down ? mWebView.onKeyDown(keyCode, event) : mWebView
129                            .onKeyUp(keyCode, event);
130
131                }
132                isArrowKey = true;
133                break;
134        }
135        if (!isArrowKey && !mOkayForFocusNotToMatch
136                && mWebView.nativeFocusNodePointer() != mNodePointer) {
137            mWebView.nativeClearCursor();
138            // Do not call remove() here, which hides the soft keyboard.  If
139            // the soft keyboard is being displayed, the user will still want
140            // it there.
141            mWebView.removeView(this);
142            mWebView.requestFocus();
143            return mWebView.dispatchKeyEvent(event);
144        }
145        // After a jump to next textfield and the first key press, the cursor
146        // and focus will once again match, so reset this value.
147        mOkayForFocusNotToMatch = false;
148
149        Spannable text = (Spannable) getText();
150        int oldLength = text.length();
151        // Normally the delete key's dom events are sent via onTextChanged.
152        // However, if the length is zero, the text did not change, so we
153        // go ahead and pass the key down immediately.
154        if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) {
155            sendDomEvent(event);
156            return true;
157        }
158
159        if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) {
160            if (isPopupShowing()) {
161                return super.dispatchKeyEvent(event);
162            }
163            if (!down) {
164                // Hide the keyboard, since the user has just submitted this
165                // form.  The submission happens thanks to the two calls
166                // to sendDomEvent.
167                InputMethodManager.getInstance(mContext)
168                        .hideSoftInputFromWindow(getWindowToken(), 0);
169                sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
170                sendDomEvent(event);
171            }
172            return super.dispatchKeyEvent(event);
173        } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) {
174            // Note that this handles center key and trackball.
175            if (isPopupShowing()) {
176                return super.dispatchKeyEvent(event);
177            }
178            if (!mWebView.nativeCursorMatchesFocus()) {
179                return down ? mWebView.onKeyDown(keyCode, event) : mWebView
180                        .onKeyUp(keyCode, event);
181            }
182            // Center key should be passed to a potential onClick
183            if (!down) {
184                mWebView.shortPressOnTextField();
185            }
186            // Pass to super to handle longpress.
187            return super.dispatchKeyEvent(event);
188        }
189
190        // Ensure there is a layout so arrow keys are handled properly.
191        if (getLayout() == null) {
192            measure(mWidthSpec, mHeightSpec);
193        }
194        int oldStart = Selection.getSelectionStart(text);
195        int oldEnd = Selection.getSelectionEnd(text);
196
197        boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength;
198        // If we are at max length, and there is a selection rather than a
199        // cursor, we need to store the text to compare later, since the key
200        // may have changed the string.
201        String oldText;
202        if (maxedOut && oldEnd != oldStart) {
203            oldText = text.toString();
204        } else {
205            oldText = "";
206        }
207        if (super.dispatchKeyEvent(event)) {
208            // If the WebTextView handled the key it was either an alphanumeric
209            // key, a delete, or a movement within the text. All of those are
210            // ok to pass to javascript.
211
212            // UNLESS there is a max length determined by the html.  In that
213            // case, if the string was already at the max length, an
214            // alphanumeric key will be erased by the LengthFilter,
215            // so do not pass down to javascript, and instead
216            // return true.  If it is an arrow key or a delete key, we can go
217            // ahead and pass it down.
218            if (KeyEvent.KEYCODE_ENTER == keyCode) {
219                // For multi-line text boxes, newlines will
220                // trigger onTextChanged for key down (which will send both
221                // key up and key down) but not key up.
222                mGotEnterDown = true;
223            }
224            if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) {
225                if (oldEnd == oldStart) {
226                    // Return true so the key gets dropped.
227                    return true;
228                } else if (!oldText.equals(getText().toString())) {
229                    // FIXME: This makes the text work properly, but it
230                    // does not pass down the key event, so it may not
231                    // work for a textfield that has the type of
232                    // behavior of GoogleSuggest.  That said, it is
233                    // unlikely that a site would combine the two in
234                    // one textfield.
235                    Spannable span = (Spannable) getText();
236                    int newStart = Selection.getSelectionStart(span);
237                    int newEnd = Selection.getSelectionEnd(span);
238                    mWebView.replaceTextfieldText(0, oldLength, span.toString(),
239                            newStart, newEnd);
240                    return true;
241                }
242            }
243            /* FIXME:
244             * In theory, we would like to send the events for the arrow keys.
245             * However, the TextView can arbitrarily change the selection (i.e.
246             * long press followed by using the trackball).  Therefore, we keep
247             * in sync with the TextView via onSelectionChanged.  If we also
248             * send the DOM event, we lose the correct selection.
249            if (isArrowKey) {
250                // Arrow key does not change the text, but we still want to send
251                // the DOM events.
252                sendDomEvent(event);
253            }
254             */
255            return true;
256        }
257        // Ignore the key up event for newlines. This prevents
258        // multiple newlines in the native textarea.
259        if (mGotEnterDown && !down) {
260            return true;
261        }
262        // if it is a navigation key, pass it to WebView
263        if (isArrowKey) {
264            // WebView check the trackballtime in onKeyDown to avoid calling
265            // native from both trackball and key handling. As this is called
266            // from WebTextView, we always want WebView to check with native.
267            // Reset trackballtime to ensure it.
268            mWebView.resetTrackballTime();
269            return down ? mWebView.onKeyDown(keyCode, event) : mWebView
270                    .onKeyUp(keyCode, event);
271        }
272        return false;
273    }
274
275    /**
276     *  Create a fake touch up event at (x,y) with respect to this WebTextView.
277     *  This is used by WebView to act as though a touch event which happened
278     *  before we placed the WebTextView actually hit it, so that it can place
279     *  the cursor accordingly.
280     */
281    /* package */ void fakeTouchEvent(float x, float y) {
282        // We need to ensure that there is a Layout, since the Layout is used
283        // in determining where to place the cursor.
284        if (getLayout() == null) {
285            measure(mWidthSpec, mHeightSpec);
286        }
287        // Create a fake touch up, which is used to place the cursor.
288        MotionEvent ev = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP,
289                x, y, 0);
290        onTouchEvent(ev);
291        ev.recycle();
292    }
293
294    /**
295     *  Determine whether this WebTextView currently represents the node
296     *  represented by ptr.
297     *  @param  ptr Pointer to a node to compare to.
298     *  @return boolean Whether this WebTextView already represents the node
299     *          pointed to by ptr.
300     */
301    /* package */ boolean isSameTextField(int ptr) {
302        return ptr == mNodePointer;
303    }
304
305    @Override public InputConnection onCreateInputConnection(
306            EditorInfo outAttrs) {
307        InputConnection connection = super.onCreateInputConnection(outAttrs);
308        if (mWebView != null) {
309            // Use the name of the textfield + the url.  Use backslash as an
310            // arbitrary separator.
311            outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\"
312                    + mWebView.getUrl();
313        }
314        return connection;
315    }
316
317    @Override
318    public void onEditorAction(int actionCode) {
319        switch (actionCode) {
320        case EditorInfo.IME_ACTION_NEXT:
321            mWebView.nativeMoveCursorToNextTextInput();
322            // Preemptively rebuild the WebTextView, so that the action will
323            // be set properly.
324            mWebView.rebuildWebTextView();
325            // Since the cursor will no longer be in the same place as the
326            // focus, set the focus controller back to inactive
327            mWebView.setFocusControllerInactive();
328            mOkayForFocusNotToMatch = true;
329            break;
330        case EditorInfo.IME_ACTION_DONE:
331            super.onEditorAction(actionCode);
332            break;
333        case EditorInfo.IME_ACTION_GO:
334            // Send an enter and hide the soft keyboard
335            InputMethodManager.getInstance(mContext)
336                    .hideSoftInputFromWindow(getWindowToken(), 0);
337            sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
338                    KeyEvent.KEYCODE_ENTER));
339            sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP,
340                    KeyEvent.KEYCODE_ENTER));
341
342        default:
343            break;
344        }
345    }
346
347    @Override
348    protected void onSelectionChanged(int selStart, int selEnd) {
349        if (!mFromWebKit && mWebView != null) {
350            if (DebugFlags.WEB_TEXT_VIEW) {
351                Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart
352                        + " selEnd=" + selEnd);
353            }
354            mWebView.setSelection(selStart, selEnd);
355        }
356    }
357
358    @Override
359    protected void onTextChanged(CharSequence s,int start,int before,int count){
360        super.onTextChanged(s, start, before, count);
361        String postChange = s.toString();
362        // Prevent calls to setText from invoking onTextChanged (since this will
363        // mean we are on a different textfield).  Also prevent the change when
364        // going from a textfield with a string of text to one with a smaller
365        // limit on text length from registering the onTextChanged event.
366        if (mPreChange == null || mPreChange.equals(postChange) ||
367                (mMaxLength > -1 && mPreChange.length() > mMaxLength &&
368                mPreChange.substring(0, mMaxLength).equals(postChange))) {
369            return;
370        }
371        mPreChange = postChange;
372        // This was simply a delete or a cut, so just delete the selection.
373        if (before > 0 && 0 == count) {
374            mWebView.deleteSelection(start, start + before);
375            // For this and all changes to the text, update our cache
376            updateCachedTextfield();
377            return;
378        }
379        // Find the last character being replaced.  If it can be represented by
380        // events, we will pass them to native (after replacing the beginning
381        // of the changed text), so we can see javascript events.
382        // Otherwise, replace the text being changed (including the last
383        // character) in the textfield.
384        TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0);
385        KeyCharacterMap kmap =
386                KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
387        KeyEvent[] events = kmap.getEvents(mCharacter);
388        boolean cannotUseKeyEvents = null == events;
389        int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1;
390        if (count > 1 || cannotUseKeyEvents) {
391            String replace = s.subSequence(start,
392                    start + count - charactersFromKeyEvents).toString();
393            mWebView.replaceTextfieldText(start, start + before, replace,
394                    start + count - charactersFromKeyEvents,
395                    start + count - charactersFromKeyEvents);
396        } else {
397            // This corrects the selection which may have been affected by the
398            // trackball or auto-correct.
399            if (DebugFlags.WEB_TEXT_VIEW) {
400                Log.v(LOGTAG, "onTextChanged start=" + start
401                        + " start + before=" + (start + before));
402            }
403            mWebView.setSelection(start, start + before);
404        }
405        if (!cannotUseKeyEvents) {
406            int length = events.length;
407            for (int i = 0; i < length; i++) {
408                // We never send modifier keys to native code so don't send them
409                // here either.
410                if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
411                    sendDomEvent(events[i]);
412                }
413            }
414        }
415        updateCachedTextfield();
416    }
417
418    @Override
419    public boolean onTouchEvent(MotionEvent event) {
420        switch (event.getAction()) {
421        case MotionEvent.ACTION_DOWN:
422            super.onTouchEvent(event);
423            // This event may be the start of a drag, so store it to pass to the
424            // WebView if it is.
425            mDragStartX = event.getX();
426            mDragStartY = event.getY();
427            mDragStartTime = event.getEventTime();
428            mDragSent = false;
429            mScrolled = false;
430            mGotTouchDown = true;
431            break;
432        case MotionEvent.ACTION_MOVE:
433            Spannable buffer = getText();
434            int initialScrollX = Touch.getInitialScrollX(this, buffer);
435            int initialScrollY = Touch.getInitialScrollY(this, buffer);
436            super.onTouchEvent(event);
437            if (mScrollX != initialScrollX
438                    || mScrollY != initialScrollY) {
439                if (mWebView != null) {
440                    mWebView.scrollFocusedTextInput(mScrollX, mScrollY);
441                }
442                mScrolled = true;
443                return true;
444            }
445            if (mWebView != null) {
446                // Only want to set the initial state once.
447                if (!mDragSent) {
448                    mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY,
449                            mDragStartTime);
450                    mDragSent = true;
451                }
452                boolean scrolled = mWebView.textFieldDrag(event);
453                if (scrolled) {
454                    mScrolled = true;
455                    cancelLongPress();
456                    return true;
457                }
458            }
459            return false;
460        case MotionEvent.ACTION_UP:
461        case MotionEvent.ACTION_CANCEL:
462            if (!mScrolled) {
463                // If the page scrolled, or the TextView scrolled, we do not
464                // want to change the selection
465                cancelLongPress();
466                if (mGotTouchDown && mWebView != null) {
467                    mWebView.touchUpOnTextField(event);
468                }
469            }
470            // Necessary for the WebView to reset its state
471            if (mWebView != null && mDragSent) {
472                mWebView.onTouchEvent(event);
473            }
474            mGotTouchDown = false;
475            break;
476        default:
477            break;
478        }
479        return true;
480    }
481
482    @Override
483    public boolean onTrackballEvent(MotionEvent event) {
484        if (isPopupShowing()) {
485            return super.onTrackballEvent(event);
486        }
487        if (event.getAction() != MotionEvent.ACTION_MOVE) {
488            return false;
489        }
490        // If the Cursor is not on the text input, webview should handle the
491        // trackball
492        if (!mWebView.nativeCursorMatchesFocus()) {
493            return mWebView.onTrackballEvent(event);
494        }
495        Spannable text = (Spannable) getText();
496        MovementMethod move = getMovementMethod();
497        if (move != null && getLayout() != null &&
498            move.onTrackballEvent(this, text, event)) {
499            // Selection is changed in onSelectionChanged
500            return true;
501        }
502        return false;
503    }
504
505    /**
506     * Remove this WebTextView from its host WebView, and return
507     * focus to the host.
508     */
509    /* package */ void remove() {
510        // hide the soft keyboard when the edit text is out of focus
511        InputMethodManager.getInstance(mContext).hideSoftInputFromWindow(
512                getWindowToken(), 0);
513        mWebView.removeView(this);
514        mWebView.requestFocus();
515    }
516
517    /* package */ void bringIntoView() {
518        if (getLayout() != null) {
519            bringPointIntoView(Selection.getSelectionEnd(getText()));
520        }
521    }
522
523    /**
524     *  Send the DOM events for the specified event.
525     *  @param event    KeyEvent to be translated into a DOM event.
526     */
527    private void sendDomEvent(KeyEvent event) {
528        mWebView.passToJavaScript(getText().toString(), event);
529    }
530
531    /**
532     *  Always use this instead of setAdapter, as this has features specific to
533     *  the WebTextView.
534     */
535    public void setAdapterCustom(AutoCompleteAdapter adapter) {
536        if (adapter != null) {
537            setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
538            adapter.setTextView(this);
539        }
540        super.setAdapter(adapter);
541    }
542
543    /**
544     *  This is a special version of ArrayAdapter which changes its text size
545     *  to match the text size of its host TextView.
546     */
547    public static class AutoCompleteAdapter extends ArrayAdapter<String> {
548        private TextView mTextView;
549
550        public AutoCompleteAdapter(Context context, ArrayList<String> entries) {
551            super(context, com.android.internal.R.layout
552                    .search_dropdown_item_1line, entries);
553        }
554
555        /**
556         * {@inheritDoc}
557         */
558        public View getView(int position, View convertView, ViewGroup parent) {
559            TextView tv =
560                    (TextView) super.getView(position, convertView, parent);
561            if (tv != null && mTextView != null) {
562                tv.setTextSize(mTextView.getTextSize());
563            }
564            return tv;
565        }
566
567        /**
568         * Set the TextView so we can match its text size.
569         */
570        private void setTextView(TextView tv) {
571            mTextView = tv;
572        }
573    }
574
575    /**
576     * Determine whether to use the system-wide password disguising method,
577     * or to use none.
578     * @param   inPassword  True if the textfield is a password field.
579     */
580    /* package */ void setInPassword(boolean inPassword) {
581        if (inPassword) {
582            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
583                    TYPE_TEXT_VARIATION_PASSWORD);
584            createBackground();
585        }
586        // For password fields, draw the WebTextView.  For others, just show
587        // webkit's drawing.
588        setWillNotDraw(!inPassword);
589        setBackgroundDrawable(inPassword ? mBackground : null);
590        // For non-password fields, avoid the invals from TextView's blinking
591        // cursor
592        setCursorVisible(inPassword);
593    }
594
595    /**
596     * Private class used for the background of a password textfield.
597     */
598    private static class OutlineDrawable extends Drawable {
599        public void draw(Canvas canvas) {
600            Rect bounds = getBounds();
601            Paint paint = new Paint();
602            paint.setAntiAlias(true);
603            // Draw the background.
604            paint.setColor(Color.WHITE);
605            canvas.drawRect(bounds, paint);
606            // Draw the outline.
607            paint.setStyle(Paint.Style.STROKE);
608            paint.setColor(Color.BLACK);
609            canvas.drawRect(bounds, paint);
610        }
611        // Always want it to be opaque.
612        public int getOpacity() {
613            return PixelFormat.OPAQUE;
614        }
615        // These are needed because they are abstract in Drawable.
616        public void setAlpha(int alpha) { }
617        public void setColorFilter(ColorFilter cf) { }
618    }
619
620    /**
621     * Create a background for the WebTextView and set up the paint for drawing
622     * the text.  This way, we can see the password transformation of the
623     * system, which (optionally) shows the actual text before changing to dots.
624     * The background is necessary to hide the webkit-drawn text beneath.
625     */
626    private void createBackground() {
627        if (mBackground != null) {
628            return;
629        }
630        mBackground = new OutlineDrawable();
631
632        setGravity(Gravity.CENTER_VERTICAL);
633        // Turn on subpixel text, and turn off kerning, so it better matches
634        // the text in webkit.
635        TextPaint paint = getPaint();
636        int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG |
637                Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG;
638        paint.setFlags(flags);
639        // Set the text color to black, regardless of the theme.  This ensures
640        // that other applications that use embedded WebViews will properly
641        // display the text in password textfields.
642        setTextColor(Color.BLACK);
643    }
644
645    /* package */ void setMaxLength(int maxLength) {
646        mMaxLength = maxLength;
647        if (-1 == maxLength) {
648            setFilters(NO_FILTERS);
649        } else {
650            setFilters(new InputFilter[] {
651                new InputFilter.LengthFilter(maxLength) });
652        }
653    }
654
655    /**
656     *  Set the pointer for this node so it can be determined which node this
657     *  WebTextView represents.
658     *  @param  ptr Integer representing the pointer to the node which this
659     *          WebTextView represents.
660     */
661    /* package */ void setNodePointer(int ptr) {
662        mNodePointer = ptr;
663    }
664
665    /**
666     * Determine the position and size of WebTextView, and add it to the
667     * WebView's view heirarchy.  All parameters are presumed to be in
668     * view coordinates.  Also requests Focus and sets the cursor to not
669     * request to be in view.
670     * @param x         x-position of the textfield.
671     * @param y         y-position of the textfield.
672     * @param width     width of the textfield.
673     * @param height    height of the textfield.
674     */
675    /* package */ void setRect(int x, int y, int width, int height) {
676        LayoutParams lp = (LayoutParams) getLayoutParams();
677        if (null == lp) {
678            lp = new LayoutParams(width, height, x, y);
679        } else {
680            lp.x = x;
681            lp.y = y;
682            lp.width = width;
683            lp.height = height;
684        }
685        if (getParent() == null) {
686            mWebView.addView(this, lp);
687        } else {
688            setLayoutParams(lp);
689        }
690        // Set up a measure spec so a layout can always be recreated.
691        mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
692        mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
693        requestFocus();
694    }
695
696    /**
697     * Set the selection, and disable our onSelectionChanged action.
698     */
699    /* package */ void setSelectionFromWebKit(int start, int end) {
700        mFromWebKit = true;
701        Selection.setSelection((Spannable) getText(), start, end);
702        mFromWebKit = false;
703    }
704
705    /**
706     * Set whether this is a single-line textfield or a multi-line textarea.
707     * Textfields scroll horizontally, and do not handle the enter key.
708     * Textareas behave oppositely.
709     * Do NOT call this after calling setInPassword(true).  This will result in
710     * removing the password input type.
711     */
712    public void setSingleLine(boolean single) {
713        int inputType = EditorInfo.TYPE_CLASS_TEXT
714                | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
715        if (single) {
716            int action = mWebView.nativeTextFieldAction();
717            switch (action) {
718            // Keep in sync with CachedRoot::ImeAction
719            case 0: // NEXT
720                setImeOptions(EditorInfo.IME_ACTION_NEXT);
721                break;
722            case 1: // GO
723                setImeOptions(EditorInfo.IME_ACTION_GO);
724                break;
725            case -1: // FAILURE
726            case 2: // DONE
727                setImeOptions(EditorInfo.IME_ACTION_DONE);
728                break;
729            }
730        } else {
731            inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
732                    | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
733                    | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT;
734            setImeOptions(EditorInfo.IME_ACTION_NONE);
735        }
736        mSingle = single;
737        setHorizontallyScrolling(single);
738        setInputType(inputType);
739    }
740
741    /**
742     * Set the text for this WebTextView, and set the selection to (start, end)
743     * @param   text    Text to go into this WebTextView.
744     * @param   start   Beginning of the selection.
745     * @param   end     End of the selection.
746     */
747    /* package */ void setText(CharSequence text, int start, int end) {
748        mPreChange = text.toString();
749        setText(text);
750        Spannable span = (Spannable) getText();
751        int length = span.length();
752        if (end > length) {
753            end = length;
754        }
755        if (start < 0) {
756            start = 0;
757        } else if (start > length) {
758            start = length;
759        }
760        if (DebugFlags.WEB_TEXT_VIEW) {
761            Log.v(LOGTAG, "setText start=" + start
762                    + " end=" + end);
763        }
764        Selection.setSelection(span, start, end);
765    }
766
767    /**
768     * Set the text to the new string, but use the old selection, making sure
769     * to keep it within the new string.
770     * @param   text    The new text to place in the textfield.
771     */
772    /* package */ void setTextAndKeepSelection(String text) {
773        mPreChange = text.toString();
774        Editable edit = (Editable) getText();
775        edit.replace(0, edit.length(), text);
776        updateCachedTextfield();
777    }
778
779    /**
780     *  Update the cache to reflect the current text.
781     */
782    /* package */ void updateCachedTextfield() {
783        mWebView.updateCachedTextfield(getText().toString());
784    }
785}
786