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