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