WebTextView.java revision 243ea06d2bf67e8b54da51977687b08f49aeb093
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.Rect;
21import android.text.Editable;
22import android.text.InputFilter;
23import android.text.Selection;
24import android.text.Spannable;
25import android.text.TextUtils;
26import android.text.method.MovementMethod;
27import android.util.Log;
28import android.view.inputmethod.EditorInfo;
29import android.view.inputmethod.InputMethodManager;
30import android.view.KeyCharacterMap;
31import android.view.KeyEvent;
32import android.view.MotionEvent;
33import android.view.View;
34import android.view.ViewGroup;
35import android.widget.AbsoluteLayout.LayoutParams;
36import android.widget.ArrayAdapter;
37import android.widget.AutoCompleteTextView;
38import android.widget.TextView;
39
40import java.util.ArrayList;
41
42/**
43 * WebTextView is a specialized version of EditText used by WebView
44 * to overlay html textfields (and textareas) to use our standard
45 * text editing.
46 */
47/* package */ class WebTextView extends AutoCompleteTextView {
48
49    static final String LOGTAG = "webtextview";
50
51    private WebView         mWebView;
52    private boolean         mSingle;
53    private int             mWidthSpec;
54    private int             mHeightSpec;
55    private int             mNodePointer;
56    // FIXME: This is a hack for blocking unmatched key ups, in particular
57    // on the enter key.  The method for blocking unmatched key ups prevents
58    // the shift key from working properly.
59    private boolean         mGotEnterDown;
60    // mScrollToAccommodateCursor being set to false prevents us from scrolling
61    // the cursor on screen when using the trackball to select a textfield.
62    private boolean         mScrollToAccommodateCursor;
63    private int             mMaxLength;
64    // Keep track of the text before the change so we know whether we actually
65    // need to send down the DOM events.
66    private String          mPreChange;
67    // Array to store the final character added in onTextChanged, so that its
68    // KeyEvents may be determined.
69    private char[]          mCharacter = new char[1];
70    // This is used to reset the length filter when on a textfield
71    // with no max length.
72    // FIXME: This can be replaced with TextView.NO_FILTERS if that
73    // is made public/protected.
74    private static final InputFilter[] NO_FILTERS = new InputFilter[0];
75
76    /**
77     * Create a new WebTextView.
78     * @param   context The Context for this WebTextView.
79     * @param   webView The WebView that created this.
80     */
81    /* package */ WebTextView(Context context, WebView webView) {
82        super(context);
83        mWebView = webView;
84        mMaxLength = -1;
85        setImeOptions(EditorInfo.IME_ACTION_NONE);
86        // Allow webkit's drawing to show through
87        setWillNotDraw(true);
88        setCursorVisible(false);
89    }
90
91    @Override
92    public boolean dispatchKeyEvent(KeyEvent event) {
93        if (event.isSystem()) {
94            return super.dispatchKeyEvent(event);
95        }
96        // Treat ACTION_DOWN and ACTION MULTIPLE the same
97        boolean down = event.getAction() != KeyEvent.ACTION_UP;
98        int keyCode = event.getKeyCode();
99        Spannable text = (Spannable) getText();
100        int oldLength = text.length();
101        // Normally the delete key's dom events are sent via onTextChanged.
102        // However, if the length is zero, the text did not change, so we
103        // go ahead and pass the key down immediately.
104        if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) {
105            sendDomEvent(event);
106            return true;
107        }
108
109        if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) {
110            if (isPopupShowing()) {
111                return super.dispatchKeyEvent(event);
112            }
113            if (!down) {
114                // Hide the keyboard, since the user has just submitted this
115                // form.  The submission happens thanks to the two calls
116                // to sendDomEvent.
117                InputMethodManager.getInstance(mContext)
118                        .hideSoftInputFromWindow(getWindowToken(), 0);
119                sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
120                sendDomEvent(event);
121            }
122            return super.dispatchKeyEvent(event);
123        } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) {
124            // Note that this handles center key and trackball.
125            if (isPopupShowing()) {
126                return super.dispatchKeyEvent(event);
127            }
128            if (!mWebView.nativeCursorMatchesFocus()) {
129                return down ? mWebView.onKeyDown(keyCode, event) : mWebView
130                        .onKeyUp(keyCode, event);
131            }
132            // Center key should be passed to a potential onClick
133            if (!down) {
134                mWebView.shortPressOnTextField();
135            }
136            // Pass to super to handle longpress.
137            return super.dispatchKeyEvent(event);
138        }
139        boolean isArrowKey = false;
140        switch(keyCode) {
141            case KeyEvent.KEYCODE_DPAD_LEFT:
142            case KeyEvent.KEYCODE_DPAD_RIGHT:
143            case KeyEvent.KEYCODE_DPAD_UP:
144            case KeyEvent.KEYCODE_DPAD_DOWN:
145                if (!mWebView.nativeCursorMatchesFocus()) {
146                    return down ? mWebView.onKeyDown(keyCode, event) : mWebView
147                            .onKeyUp(keyCode, event);
148
149                }
150                isArrowKey = true;
151                break;
152        }
153
154        // Ensure there is a layout so arrow keys are handled properly.
155        if (getLayout() == null) {
156            measure(mWidthSpec, mHeightSpec);
157        }
158        int oldStart = Selection.getSelectionStart(text);
159        int oldEnd = Selection.getSelectionEnd(text);
160
161        boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength;
162        // If we are at max length, and there is a selection rather than a
163        // cursor, we need to store the text to compare later, since the key
164        // may have changed the string.
165        String oldText;
166        if (maxedOut && oldEnd != oldStart) {
167            oldText = text.toString();
168        } else {
169            oldText = "";
170        }
171        if (super.dispatchKeyEvent(event)) {
172            // If the WebTextView handled the key it was either an alphanumeric
173            // key, a delete, or a movement within the text. All of those are
174            // ok to pass to javascript.
175
176            // UNLESS there is a max length determined by the html.  In that
177            // case, if the string was already at the max length, an
178            // alphanumeric key will be erased by the LengthFilter,
179            // so do not pass down to javascript, and instead
180            // return true.  If it is an arrow key or a delete key, we can go
181            // ahead and pass it down.
182            if (KeyEvent.KEYCODE_ENTER == keyCode) {
183                // For multi-line text boxes, newlines will
184                // trigger onTextChanged for key down (which will send both
185                // key up and key down) but not key up.
186                mGotEnterDown = true;
187            }
188            if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) {
189                if (oldEnd == oldStart) {
190                    // Return true so the key gets dropped.
191                    mScrollToAccommodateCursor = true;
192                    return true;
193                } else if (!oldText.equals(getText().toString())) {
194                    // FIXME: This makes the text work properly, but it
195                    // does not pass down the key event, so it may not
196                    // work for a textfield that has the type of
197                    // behavior of GoogleSuggest.  That said, it is
198                    // unlikely that a site would combine the two in
199                    // one textfield.
200                    Spannable span = (Spannable) getText();
201                    int newStart = Selection.getSelectionStart(span);
202                    int newEnd = Selection.getSelectionEnd(span);
203                    mWebView.replaceTextfieldText(0, oldLength, span.toString(),
204                            newStart, newEnd);
205                    mScrollToAccommodateCursor = true;
206                    return true;
207                }
208            }
209            /* FIXME:
210             * In theory, we would like to send the events for the arrow keys.
211             * However, the TextView can arbitrarily change the selection (i.e.
212             * long press followed by using the trackball).  Therefore, we keep
213             * in sync with the TextView via onSelectionChanged.  If we also
214             * send the DOM event, we lose the correct selection.
215            if (isArrowKey) {
216                // Arrow key does not change the text, but we still want to send
217                // the DOM events.
218                sendDomEvent(event);
219            }
220             */
221            mScrollToAccommodateCursor = true;
222            return true;
223        }
224        // Ignore the key up event for newlines. This prevents
225        // multiple newlines in the native textarea.
226        if (mGotEnterDown && !down) {
227            return true;
228        }
229        // if it is a navigation key, pass it to WebView
230        if (isArrowKey) {
231            // WebView check the trackballtime in onKeyDown to avoid calling
232            // native from both trackball and key handling. As this is called
233            // from WebTextView, we always want WebView to check with native.
234            // Reset trackballtime to ensure it.
235            mWebView.resetTrackballTime();
236            return down ? mWebView.onKeyDown(keyCode, event) : mWebView
237                    .onKeyUp(keyCode, event);
238        }
239        return false;
240    }
241
242    /**
243     *  Create a fake touch up event at (x,y) with respect to this WebTextView.
244     *  This is used by WebView to act as though a touch event which happened
245     *  before we placed the WebTextView actually hit it, so that it can place
246     *  the cursor accordingly.
247     */
248    /* package */ void fakeTouchEvent(float x, float y) {
249        // We need to ensure that there is a Layout, since the Layout is used
250        // in determining where to place the cursor.
251        if (getLayout() == null) {
252            measure(mWidthSpec, mHeightSpec);
253        }
254        // Create a fake touch up, which is used to place the cursor.
255        MotionEvent ev = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP,
256                x, y, 0);
257        onTouchEvent(ev);
258        ev.recycle();
259    }
260
261    /**
262     *  Determine whether this WebTextView currently represents the node
263     *  represented by ptr.
264     *  @param  ptr Pointer to a node to compare to.
265     *  @return boolean Whether this WebTextView already represents the node
266     *          pointed to by ptr.
267     */
268    /* package */ boolean isSameTextField(int ptr) {
269        return ptr == mNodePointer;
270    }
271
272    @Override
273    protected void onSelectionChanged(int selStart, int selEnd) {
274        if (mWebView != null) {
275            if (DebugFlags.WEB_TEXT_VIEW) {
276                Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart
277                        + " selEnd=" + selEnd);
278            }
279            mWebView.setSelection(selStart, selEnd);
280        }
281    }
282
283    @Override
284    protected void onTextChanged(CharSequence s,int start,int before,int count){
285        super.onTextChanged(s, start, before, count);
286        String postChange = s.toString();
287        // Prevent calls to setText from invoking onTextChanged (since this will
288        // mean we are on a different textfield).  Also prevent the change when
289        // going from a textfield with a string of text to one with a smaller
290        // limit on text length from registering the onTextChanged event.
291        if (mPreChange == null || mPreChange.equals(postChange) ||
292                (mMaxLength > -1 && mPreChange.length() > mMaxLength &&
293                mPreChange.substring(0, mMaxLength).equals(postChange))) {
294            return;
295        }
296        mPreChange = postChange;
297        // This was simply a delete or a cut, so just delete the selection.
298        if (before > 0 && 0 == count) {
299            mWebView.deleteSelection(start, start + before);
300            // For this and all changes to the text, update our cache
301            updateCachedTextfield();
302            return;
303        }
304        // Find the last character being replaced.  If it can be represented by
305        // events, we will pass them to native (after replacing the beginning
306        // of the changed text), so we can see javascript events.
307        // Otherwise, replace the text being changed (including the last
308        // character) in the textfield.
309        TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0);
310        KeyCharacterMap kmap =
311                KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
312        KeyEvent[] events = kmap.getEvents(mCharacter);
313        boolean cannotUseKeyEvents = null == events;
314        int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1;
315        if (count > 1 || cannotUseKeyEvents) {
316            String replace = s.subSequence(start,
317                    start + count - charactersFromKeyEvents).toString();
318            mWebView.replaceTextfieldText(start, start + before, replace,
319                    start + count - charactersFromKeyEvents,
320                    start + count - charactersFromKeyEvents);
321        } else {
322            // This corrects the selection which may have been affected by the
323            // trackball or auto-correct.
324            if (DebugFlags.WEB_TEXT_VIEW) {
325                Log.v(LOGTAG, "onTextChanged start=" + start
326                        + " start + before=" + (start + before));
327            }
328            mWebView.setSelection(start, start + before);
329        }
330        if (!cannotUseKeyEvents) {
331            int length = events.length;
332            for (int i = 0; i < length; i++) {
333                // We never send modifier keys to native code so don't send them
334                // here either.
335                if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
336                    sendDomEvent(events[i]);
337                }
338            }
339        }
340        updateCachedTextfield();
341    }
342
343    @Override
344    public boolean onTrackballEvent(MotionEvent event) {
345        if (isPopupShowing()) {
346            return super.onTrackballEvent(event);
347        }
348        if (event.getAction() != MotionEvent.ACTION_MOVE) {
349            return false;
350        }
351        // If the Cursor is not on the text input, webview should handle the
352        // trackball
353        if (!mWebView.nativeCursorMatchesFocus()) {
354            return mWebView.onTrackballEvent(event);
355        }
356        Spannable text = (Spannable) getText();
357        MovementMethod move = getMovementMethod();
358        if (move != null && getLayout() != null &&
359            move.onTrackballEvent(this, text, event)) {
360            // Selection is changed in onSelectionChanged
361            return true;
362        }
363        // If the user is in a textfield, and the movement method is not
364        // handling the trackball events, it means they are at the end of the
365        // field and continuing to move the trackball.  In this case, we should
366        // not scroll the cursor on screen bc the user may be attempting to
367        // scroll the page, possibly in the opposite direction of the cursor.
368        mScrollToAccommodateCursor = false;
369        return false;
370    }
371
372    /**
373     * Remove this WebTextView from its host WebView, and return
374     * focus to the host.
375     */
376    /* package */ void remove() {
377        // hide the soft keyboard when the edit text is out of focus
378        InputMethodManager.getInstance(mContext).hideSoftInputFromWindow(
379                getWindowToken(), 0);
380        mWebView.removeView(this);
381        mWebView.requestFocus();
382        mScrollToAccommodateCursor = false;
383    }
384
385    /* package */ void enableScrollOnScreen(boolean enable) {
386        mScrollToAccommodateCursor = enable;
387    }
388
389    /* package */ void bringIntoView() {
390        if (getLayout() != null) {
391            bringPointIntoView(Selection.getSelectionEnd(getText()));
392        }
393    }
394
395    @Override
396    public boolean requestRectangleOnScreen(Rect rectangle) {
397        if (mScrollToAccommodateCursor) {
398            return super.requestRectangleOnScreen(rectangle);
399        }
400        return false;
401    }
402
403    /**
404     *  Send the DOM events for the specified event.
405     *  @param event    KeyEvent to be translated into a DOM event.
406     */
407    private void sendDomEvent(KeyEvent event) {
408        mWebView.passToJavaScript(getText().toString(), event);
409    }
410
411    /**
412     *  Always use this instead of setAdapter, as this has features specific to
413     *  the WebTextView.
414     */
415    public void setAdapterCustom(AutoCompleteAdapter adapter) {
416        if (adapter != null) {
417            setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
418            adapter.setTextView(this);
419        }
420        super.setAdapter(adapter);
421    }
422
423    /**
424     *  This is a special version of ArrayAdapter which changes its text size
425     *  to match the text size of its host TextView.
426     */
427    public static class AutoCompleteAdapter extends ArrayAdapter<String> {
428        private TextView mTextView;
429
430        public AutoCompleteAdapter(Context context, ArrayList<String> entries) {
431            super(context, com.android.internal.R.layout
432                    .search_dropdown_item_1line, entries);
433        }
434
435        /**
436         * {@inheritDoc}
437         */
438        public View getView(int position, View convertView, ViewGroup parent) {
439            TextView tv =
440                    (TextView) super.getView(position, convertView, parent);
441            if (tv != null && mTextView != null) {
442                tv.setTextSize(mTextView.getTextSize());
443            }
444            return tv;
445        }
446
447        /**
448         * Set the TextView so we can match its text size.
449         */
450        private void setTextView(TextView tv) {
451            mTextView = tv;
452        }
453    }
454
455    /**
456     * Determine whether to use the system-wide password disguising method,
457     * or to use none.
458     * @param   inPassword  True if the textfield is a password field.
459     */
460    /* package */ void setInPassword(boolean inPassword) {
461        if (inPassword) {
462            setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
463                    TYPE_TEXT_VARIATION_PASSWORD);
464        }
465    }
466
467    /* package */ void setMaxLength(int maxLength) {
468        mMaxLength = maxLength;
469        if (-1 == maxLength) {
470            setFilters(NO_FILTERS);
471        } else {
472            setFilters(new InputFilter[] {
473                new InputFilter.LengthFilter(maxLength) });
474        }
475    }
476
477    /**
478     *  Set the pointer for this node so it can be determined which node this
479     *  WebTextView represents.
480     *  @param  ptr Integer representing the pointer to the node which this
481     *          WebTextView represents.
482     */
483    /* package */ void setNodePointer(int ptr) {
484        mNodePointer = ptr;
485    }
486
487    /**
488     * Determine the position and size of WebTextView, and add it to the
489     * WebView's view heirarchy.  All parameters are presumed to be in
490     * view coordinates.  Also requests Focus and sets the cursor to not
491     * request to be in view.
492     * @param x         x-position of the textfield.
493     * @param y         y-position of the textfield.
494     * @param width     width of the textfield.
495     * @param height    height of the textfield.
496     */
497    /* package */ void setRect(int x, int y, int width, int height) {
498        LayoutParams lp = (LayoutParams) getLayoutParams();
499        if (null == lp) {
500            lp = new LayoutParams(width, height, x, y);
501        } else {
502            lp.x = x;
503            lp.y = y;
504            lp.width = width;
505            lp.height = height;
506        }
507        if (getParent() == null) {
508            mWebView.addView(this, lp);
509        } else {
510            setLayoutParams(lp);
511        }
512        // Set up a measure spec so a layout can always be recreated.
513        mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
514        mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
515        requestFocus();
516    }
517
518    /**
519     * Set whether this is a single-line textfield or a multi-line textarea.
520     * Textfields scroll horizontally, and do not handle the enter key.
521     * Textareas behave oppositely.
522     * Do NOT call this after calling setInPassword(true).  This will result in
523     * removing the password input type.
524     */
525    public void setSingleLine(boolean single) {
526        int inputType = EditorInfo.TYPE_CLASS_TEXT
527                | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT;
528        if (!single) {
529            inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
530                    | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
531                    | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT;
532        }
533        mSingle = single;
534        setHorizontallyScrolling(single);
535        setInputType(inputType);
536    }
537
538    /**
539     * Set the text for this WebTextView, and set the selection to (start, end)
540     * @param   text    Text to go into this WebTextView.
541     * @param   start   Beginning of the selection.
542     * @param   end     End of the selection.
543     */
544    /* package */ void setText(CharSequence text, int start, int end) {
545        mPreChange = text.toString();
546        setText(text);
547        Spannable span = (Spannable) getText();
548        int length = span.length();
549        if (end > length) {
550            end = length;
551        }
552        if (start < 0) {
553            start = 0;
554        } else if (start > length) {
555            start = length;
556        }
557        if (DebugFlags.WEB_TEXT_VIEW) {
558            Log.v(LOGTAG, "setText start=" + start
559                    + " end=" + end);
560        }
561        Selection.setSelection(span, start, end);
562    }
563
564    /**
565     * Set the text to the new string, but use the old selection, making sure
566     * to keep it within the new string.
567     * @param   text    The new text to place in the textfield.
568     */
569    /* package */ void setTextAndKeepSelection(String text) {
570        mPreChange = text.toString();
571        Editable edit = (Editable) getText();
572        edit.replace(0, edit.length(), text);
573        updateCachedTextfield();
574    }
575
576    /**
577     *  Update the cache to reflect the current text.
578     */
579    /* package */ void updateCachedTextfield() {
580        mWebView.updateCachedTextfield(getText().toString());
581    }
582}
583