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