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