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