Editor.java revision e264ac392a886788ebfd1069e1d366e2b1edef72
12bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber/*
22bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * Copyright (C) 2012 The Android Open Source Project
32bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber *
42bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * Licensed under the Apache License, Version 2.0 (the "License");
52bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * you may not use this file except in compliance with the License.
62bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * You may obtain a copy of the License at
72bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber *
82bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber *      http://www.apache.org/licenses/LICENSE-2.0
92bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber *
102bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * Unless required by applicable law or agreed to in writing, software
112bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * distributed under the License is distributed on an "AS IS" BASIS,
122bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
132bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * See the License for the specific language governing permissions and
142bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber * limitations under the License.
152bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber */
162bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
172bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberpackage android.widget;
182bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
192bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.R;
202bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.annotation.Nullable;
212bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.app.PendingIntent;
222bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.app.PendingIntent.CanceledException;
232bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.ClipData;
242bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.ClipData.Item;
2581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport android.content.Context;
262bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.Intent;
271b86fe063badb5f28c467ade39be0f4008688947Andreas Huberimport android.content.UndoManager;
2849694688c82214f5fd9e969e177c9e126a240a26Andreas Huberimport android.content.UndoOperation;
292bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.UndoOwner;
302bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.pm.PackageManager;
312bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.pm.ResolveInfo;
322bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.content.res.TypedArray;
33cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönssonimport android.graphics.Canvas;
34cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönssonimport android.graphics.Color;
35641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.graphics.Matrix;
36641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.graphics.Paint;
37641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.graphics.Path;
38641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.graphics.Rect;
39641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.graphics.RectF;
40641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.graphics.drawable.Drawable;
412bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.inputmethodservice.ExtractEditText;
425ab368af38fefacc4009e3ab1c1bbd00e62b3bcfAndreas Huberimport android.os.Bundle;
431b86fe063badb5f28c467ade39be0f4008688947Andreas Huberimport android.os.Handler;
442bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.os.Parcel;
452bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.os.Parcelable;
462bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.os.ParcelableParcel;
4781dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport android.os.SystemClock;
4881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport android.provider.Settings;
495ab368af38fefacc4009e3ab1c1bbd00e62b3bcfAndreas Huberimport android.text.DynamicLayout;
501b86fe063badb5f28c467ade39be0f4008688947Andreas Huberimport android.text.Editable;
515ab368af38fefacc4009e3ab1c1bbd00e62b3bcfAndreas Huberimport android.text.InputFilter;
522bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.InputType;
532bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.Layout;
542bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.ParcelableSpan;
5581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport android.text.Selection;
562bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.SpanWatcher;
572bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.Spannable;
58ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huberimport android.text.SpannableStringBuilder;
59180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhangimport android.text.Spanned;
60641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shihimport android.text.StaticLayout;
61f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shihimport android.text.TextUtils;
62cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönssonimport android.text.method.KeyListener;
63cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönssonimport android.text.method.MetaKeyKeyListener;
64cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönssonimport android.text.method.MovementMethod;
652bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.method.WordIterator;
662bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.style.EasyEditSpan;
672bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.style.SuggestionRangeSpan;
682bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.style.SuggestionSpan;
692bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.style.TextAppearanceSpan;
702bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.text.style.URLSpan;
712bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.util.DisplayMetrics;
722bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.util.Log;
732bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.ActionMode;
742bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.ActionMode.Callback;
752bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.DisplayListCanvas;
762bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.DragEvent;
772bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.Gravity;
782bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.LayoutInflater;
792bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.Menu;
80602f5bbd7596ec3fe447fde4329d5d4f0b370835Andreas Huberimport android.view.MenuItem;
811228d6b175de8b21787cbe0c6c4bb5642f4d555eChong Zhangimport android.view.MotionEvent;
82602f5bbd7596ec3fe447fde4329d5d4f0b370835Andreas Huberimport android.view.RenderNode;
83602f5bbd7596ec3fe447fde4329d5d4f0b370835Andreas Huberimport android.view.View;
842bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.View.DragShadowBuilder;
852bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.View.OnClickListener;
8657cea553cb19235553463412db5ad04c99835411Andreas Huberimport android.view.ViewConfiguration;
87ce84b2240497cd0923e190ae115e319e4c17d303Wei Jiaimport android.view.ViewGroup;
88ce84b2240497cd0923e190ae115e319e4c17d303Wei Jiaimport android.view.ViewGroup.LayoutParams;
89ce84b2240497cd0923e190ae115e319e4c17d303Wei Jiaimport android.view.ViewParent;
90ce84b2240497cd0923e190ae115e319e4c17d303Wei Jiaimport android.view.ViewTreeObserver;
91ce84b2240497cd0923e190ae115e319e4c17d303Wei Jiaimport android.view.WindowManager;
922bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.inputmethod.CorrectionInfo;
932bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.inputmethod.CursorAnchorInfo;
942bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.inputmethod.EditorInfo;
952bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.inputmethod.ExtractedText;
962bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.inputmethod.ExtractedTextRequest;
971228d6b175de8b21787cbe0c6c4bb5642f4d555eChong Zhangimport android.view.inputmethod.InputConnection;
982bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.view.inputmethod.InputMethodManager;
992bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.widget.AdapterView.OnItemClickListener;
1002bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport android.widget.TextView.Drawables;
10181dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport android.widget.TextView.OnEditorActionListener;
1022bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
1031d15ab58bf8239069ef343de6cb21aabf3ef7d78Lajos Molnarimport com.android.internal.util.ArrayUtils;
1042bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport com.android.internal.util.GrowingArrayUtils;
1052bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport com.android.internal.widget.EditableInputConnection;
1062bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
1072bfdd428c56c7524d1a11979f200a1762866032dAndreas Huberimport java.text.BreakIterator;
10881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport java.util.Arrays;
10981dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport java.util.Comparator;
11081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhéimport java.util.HashMap;
11181e68448f3361eaf8618930471fdc3c21bdf5cbcAndreas Huberimport java.util.List;
11281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé
11357cea553cb19235553463412db5ad04c99835411Andreas Huber/**
11457cea553cb19235553463412db5ad04c99835411Andreas Huber * Helper class used by TextView to handle editable text views.
11581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé *
11681dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé * @hide
11781dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé */
11881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhépublic class Editor {
11981dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    private static final String TAG = "Editor";
12081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    private static final boolean DEBUG_UNDO = false;
121cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
122180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    static final int BLINK = 500;
12357cea553cb19235553463412db5ad04c99835411Andreas Huber    private static final float[] TEMP_POSITION = new float[2];
12457cea553cb19235553463412db5ad04c99835411Andreas Huber    private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
12557cea553cb19235553463412db5ad04c99835411Andreas Huber    private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f;
1262bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final int UNSET_X_VALUE = -1;
1272bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    // Tag used when the Editor maintains its own separate UndoManager.
1282bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final String UNDO_OWNER_TAG = "Editor";
1295834181d3f168acb8ff4bf3eff1fd1186afb0bd4James Dong
1305834181d3f168acb8ff4bf3eff1fd1186afb0bd4James Dong    // Ordering constants used to place the Action Mode items in their menu.
1315834181d3f168acb8ff4bf3eff1fd1186afb0bd4James Dong    private static final int MENU_ITEM_ORDER_CUT = 1;
1321d15ab58bf8239069ef343de6cb21aabf3ef7d78Lajos Molnar    private static final int MENU_ITEM_ORDER_COPY = 2;
1332bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final int MENU_ITEM_ORDER_PASTE = 3;
1342bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final int MENU_ITEM_ORDER_SHARE = 4;
1352bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final int MENU_ITEM_ORDER_SELECT_ALL = 5;
1362bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final int MENU_ITEM_ORDER_REPLACE = 6;
1372bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 10;
1382bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
139180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    // Each Editor manages its own undo stack.
1402bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private final UndoManager mUndoManager = new UndoManager();
1412bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private UndoOwner mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
1422bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    final UndoInputFilter mUndoInputFilter = new UndoInputFilter(this);
143840667883fd09d44015716d79bc3ac4d60edc0f0Andreas Huber    boolean mAllowUndo = true;
1442bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
1452bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    // Cursor Controllers.
1462bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    InsertionPointCursorController mInsertionPointCursorController;
1472bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    SelectionModifierCursorController mSelectionModifierCursorController;
1482bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    // Action mode used when text is selected or when actions on an insertion cursor are triggered.
1492bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    ActionMode mTextActionMode;
1502bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mInsertionControllerEnabled;
1512bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mSelectionControllerEnabled;
1522bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
153bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    // Used to highlight a word when it is corrected by the IME
154bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    CorrectionHighlighter mCorrectionHighlighter;
155bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
156bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    InputContentType mInputContentType;
157bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    InputMethodState mInputMethodState;
158bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
159cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    private static class TextRenderNode {
160cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson        RenderNode renderNode;
161cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson        boolean isDirty;
162cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson        public TextRenderNode(String name) {
163cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson            isDirty = true;
164cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson            renderNode = RenderNode.create(name, null);
165cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson        }
166bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber        boolean needsRecord() { return isDirty || !renderNode.isValid(); }
167bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    }
168bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    TextRenderNode[] mTextRenderNodes;
169bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
170bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mFrozenWithFocus;
171bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mSelectionMoved;
172bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mTouchFocusSelected;
173bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
174bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    KeyListener mKeyListener;
175bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    int mInputType = EditorInfo.TYPE_NULL;
176bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
177bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mDiscardNextActionUp;
178bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mIgnoreActionUpEvent;
179bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
180bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    long mShowCursor;
181bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    Blink mBlink;
182bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
183bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mCursorVisible = true;
184bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mSelectAllOnFocus;
185bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mTextIsSelectable;
186bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber
187bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    CharSequence mError;
188bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber    boolean mErrorWasChanged;
1892bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    ErrorPopup mErrorPopup;
1902bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
191180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    /**
192180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang     * This flag is set if the TextView tries to display an error before it
193bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber     * is attached to the window (so its position is still unknown).
194bfd4d0d9fe0033abf3f55b94f30f6a58846a875eAndreas Huber     * It causes the error to be shown later, when onAttachedToWindow()
1952bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber     * is called.
1962bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber     */
1972bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mShowErrorAfterAttach;
1982bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
1992bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mInBatchEditControllers;
2002bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mShowSoftInputOnFocus = true;
2012bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mPreserveDetachedSelection;
2022bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    boolean mTemporaryDetach;
203cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
204f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    SuggestionsPopupWindow mSuggestionsPopupWindow;
205f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    SuggestionRangeSpan mSuggestionRangeSpan;
206f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    Runnable mShowSuggestionRunnable;
207cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
208cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    final Drawable[] mCursorDrawable = new Drawable[2];
209cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split)
210cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
211f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    private Drawable mSelectHandleLeft;
212f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    private Drawable mSelectHandleRight;
213f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    private Drawable mSelectHandleCenter;
214cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
215cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    // Global listener that detects changes in the global position of the TextView
216cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    private PositionListener mPositionListener;
217cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
218cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    float mLastDownPositionX, mLastDownPositionY;
219cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    Callback mCustomSelectionActionModeCallback;
220cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    Callback mCustomInsertionActionModeCallback;
221cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
222cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    // Set when this TextView gained focus with some text selected. Will start selection mode.
223cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    boolean mCreatedWithASelection;
224cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
225f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    boolean mDoubleTap = false;
226cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
227cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    private Runnable mInsertionActionModeRunnable;
228180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang
229cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    // The span controller helps monitoring the changes to which the Editor needs to react:
230cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    // - EasyEditSpans, for which we have some UI to display on attach and on hide
231cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    // - SelectionSpans, for which we need to call updateSelection if an IME is attached
232cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    private SpanController mSpanController;
233cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
2342bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    WordIterator mWordIterator;
2352bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    SpellChecker mSpellChecker;
236cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
237cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    // This word iterator is set with text and used to determine word boundaries
2382bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    // when a user is selecting text.
2392bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private WordIterator mWordIteratorWithText;
2402bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    // Indicate that the text in the word iterator needs to be updated.
2412bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private boolean mUpdateWordIteratorText;
24249694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
24349694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    private Rect mTempRect;
24449694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
24549694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    private TextView mTextView;
24649694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
24749694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    final CursorAnchorInfoNotifier mCursorAnchorInfoNotifier = new CursorAnchorInfoNotifier();
24849694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
2492bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private final Runnable mShowFloatingToolbar = new Runnable() {
2502bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        @Override
2512bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        public void run() {
252cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson            if (mTextActionMode != null) {
253cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson                mTextActionMode.hide(0);  // hide off.
254cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson            }
255cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson        }
256cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    };
257cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
258cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson    boolean mIsInsertionActionModeStartPending = false;
259cfc3083927df14bf82403b20a45ae303a01c39f5Roger Jönsson
2602bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    Editor(TextView textView) {
2612bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mTextView = textView;
2622bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // Synchronize the filter list, which places the undo input filter at the end.
2632bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mTextView.setFilters(mTextView.getFilters());
2642bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
2652bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
2662bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    ParcelableParcel saveInstanceState() {
2672bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        ParcelableParcel state = new ParcelableParcel(getClass().getClassLoader());
2682bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        Parcel parcel = state.getParcel();
2692bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mUndoManager.saveInstanceState(parcel);
2702bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mUndoInputFilter.saveInstanceState(parcel);
2712bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        return state;
2722bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
2732bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
2742bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    void restoreInstanceState(ParcelableParcel state) {
2752bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        Parcel parcel = state.getParcel();
2762bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mUndoManager.restoreInstanceState(parcel, state.getClassLoader());
2772bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mUndoInputFilter.restoreInstanceState(parcel);
2782bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // Re-associate this object as the owner of undo state.
2792bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
2802bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
2812bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
2822bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    /**
2831d15ab58bf8239069ef343de6cb21aabf3ef7d78Lajos Molnar     * Forgets all undo and redo operations for this Editor.
284ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber     */
285ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber    void forgetUndoRedo() {
286ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber        UndoOwner[] owners = { mUndoOwner };
2878d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        mUndoManager.forgetUndos(owners, -1 /* all */);
2888d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        mUndoManager.forgetRedos(owners, -1 /* all */);
2898d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    }
2908d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih
2918d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    boolean canUndo() {
2928d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        UndoOwner[] owners = { mUndoOwner };
2938d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        return mAllowUndo && mUndoManager.countUndos(owners) > 0;
294ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber    }
295ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber
296ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber    boolean canRedo() {
2972bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        UndoOwner[] owners = { mUndoOwner };
2988d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        return mAllowUndo && mUndoManager.countRedos(owners) > 0;
299ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber    }
3002bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
3012bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    void undo() {
3022bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (!mAllowUndo) {
3032bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            return;
304f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        }
3052bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        UndoOwner[] owners = { mUndoOwner };
3062bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mUndoManager.undo(owners, 1);  // Undo 1 action.
307641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih    }
308641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
309641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih    void redo() {
310641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (!mAllowUndo) {
311641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            return;
312641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
313f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        UndoOwner[] owners = { mUndoOwner };
314641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        mUndoManager.redo(owners, 1);  // Redo 1 action.
315f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    }
316f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
317c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa    void replace() {
318c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa        int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
319c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa        stopTextActionMode();
320641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        Selection.setSelection((Spannable) mTextView.getText(), middle);
321641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        showSuggestions();
322641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih    }
323c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa
324c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa    void onAttachedToWindow() {
325c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa        if (mShowErrorAfterAttach) {
326c622c584ea0ffb807eb9f711aa30016eae069c92Takahiro Aizawa            showError();
327641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            mShowErrorAfterAttach = false;
328641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
329641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        mTemporaryDetach = false;
330641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
331641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        final ViewTreeObserver observer = mTextView.getViewTreeObserver();
332641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        // No need to create the controller.
333641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        // The get method will add the listener on controller creation.
334641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mInsertionPointCursorController != null) {
335641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
336f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        }
337641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mSelectionModifierCursorController != null) {
338641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            mSelectionModifierCursorController.resetTouchOffsets();
339641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
340641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
341641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        updateSpellCheckSpans(0, mTextView.getText().length(),
342641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih                true /* create the spell checker if needed */);
343641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
344641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mTextView.hasTransientState() &&
345641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih                mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
346641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            // Since transient state is reference counted make sure it stays matched
347641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            // with our own calls to it for managing selection.
348641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            // The action mode callback will set this back again when/if the action mode starts.
349641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            mTextView.setHasTransientState(false);
350641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
351641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            // We had an active selection from before, start the selection mode.
352641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            startSelectionActionMode();
353641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
354f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
355641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true);
356641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        resumeBlink();
357641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih    }
358f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
359f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    void onDetachedFromWindow() {
360641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        getPositionListener().removeSubscriber(mCursorAnchorInfoNotifier);
361641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
362641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mError != null) {
363641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            hideError();
364641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
365641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
366641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        suspendBlink();
367641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
368641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mInsertionPointCursorController != null) {
369641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            mInsertionPointCursorController.onDetached();
370641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
371641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
372641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mSelectionModifierCursorController != null) {
373641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            mSelectionModifierCursorController.onDetached();
374641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
375641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
376641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        if (mShowSuggestionRunnable != null) {
377641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih            mTextView.removeCallbacks(mShowSuggestionRunnable);
378641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
379f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
380f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        // Cancel the single tap delayed runnable.
381f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        if (mInsertionActionModeRunnable != null) {
382f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mTextView.removeCallbacks(mInsertionActionModeRunnable);
383641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        }
384641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
385641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        mTextView.removeCallbacks(mShowFloatingToolbar);
386f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
387f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        destroyDisplayListsData();
388f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
389f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        if (mSpellChecker != null) {
390f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mSpellChecker.closeSession();
391f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            // Forces the creation of a new SpellChecker next time this window is created.
392f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            // Will handle the cases where the settings has been changed in the meantime.
393f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mSpellChecker = null;
394f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        }
395f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
396f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mPreserveDetachedSelection = true;
397f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        hideControllers();
398f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        stopTextActionMode();
399f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mPreserveDetachedSelection = false;
400f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mTemporaryDetach = false;
401f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    }
402f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
403f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    private void destroyDisplayListsData() {
404f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        if (mTextRenderNodes != null) {
405f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            for (int i = 0; i < mTextRenderNodes.length; i++) {
406f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih                RenderNode displayList = mTextRenderNodes[i] != null
407f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih                        ? mTextRenderNodes[i].renderNode : null;
408f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih                if (displayList != null && displayList.isValid()) {
409f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih                    displayList.destroyDisplayListData();
410f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih                }
411f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            }
412f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        }
413f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    }
414f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
415f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    private void showError() {
416f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        if (mTextView.getWindowToken() == null) {
417f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mShowErrorAfterAttach = true;
418f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            return;
419f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        }
420f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
421f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        if (mErrorPopup == null) {
422f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            LayoutInflater inflater = LayoutInflater.from(mTextView.getContext());
423f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            final TextView err = (TextView) inflater.inflate(
424f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih                    com.android.internal.R.layout.textview_hint, null);
425f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
426f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            final float scale = mTextView.getResources().getDisplayMetrics().density;
427f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f));
428f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mErrorPopup.setFocusable(false);
429f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            // The user is entering text, so the input method is needed.  We
430f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            // don't want the popup to be displayed on top of it.
431f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
432f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        }
433f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
434f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        TextView tv = (TextView) mErrorPopup.getContentView();
435f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        chooseSize(mErrorPopup, mError, tv);
436f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        tv.setText(mError);
437f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
438f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY());
439f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor());
440f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    }
441f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
442f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    public void setError(CharSequence error, Drawable icon) {
443f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mError = TextUtils.stringOrSpannedString(error);
444f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mErrorWasChanged = true;
4452bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
4462bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mError == null) {
4473f27436a9346f043f52265da1e6a74cde2bffd4dLajos Molnar            setErrorIcon(null);
4482bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (mErrorPopup != null) {
4492bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                if (mErrorPopup.isShowing()) {
4502bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                    mErrorPopup.dismiss();
4512bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                }
4522bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
453ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber                mErrorPopup = null;
454ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber            }
455ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber            mShowErrorAfterAttach = false;
4568d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        } else {
457ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber            setErrorIcon(icon);
458ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber            if (mTextView.isFocused()) {
459ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber                showError();
4608d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih            }
461ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber        }
462ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber    }
463ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber
464ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber    private void setErrorIcon(Drawable icon) {
465ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber        Drawables dr = mTextView.mDrawables;
466ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber        if (dr == null) {
467ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber            mTextView.mDrawables = dr = new Drawables(mTextView.getContext());
468ee736e9e74c5368db8d63214513c85cb74bb0183Andreas Huber        }
469641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        dr.setErrorDrawable(icon, mTextView);
470641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih
471641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        mTextView.resetResolvedDrawables();
472f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mTextView.invalidate();
473f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        mTextView.requestLayout();
474f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih    }
4752bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
4762bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void hideError() {
4772bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mErrorPopup != null) {
4782bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (mErrorPopup.isShowing()) {
4792bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mErrorPopup.dismiss();
4802bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            }
4812bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
4822bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
4832bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mShowErrorAfterAttach = false;
4847f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber    }
4852bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
4867f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber    /**
487ced1c2f8f6c422063092f5cc5c675ccdebb2dc10Chong Zhang     * Returns the X offset to make the pointy top of the error point
4887f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber     * at the middle of the error icon.
4897f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber     */
4907f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber    private int getErrorX() {
4917f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        /*
4924b7069dac546ad21cf62ca6132d50ea41857d08eChong Zhang         * The "25" is the distance between the point and the right edge
4934b7069dac546ad21cf62ca6132d50ea41857d08eChong Zhang         * of the background
4944b7069dac546ad21cf62ca6132d50ea41857d08eChong Zhang         */
4954b7069dac546ad21cf62ca6132d50ea41857d08eChong Zhang        final float scale = mTextView.getResources().getDisplayMetrics().density;
4967f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber
4977f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        final Drawables dr = mTextView.mDrawables;
4987f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber
499641e0c718da1c58e5b89379f60465c4e564ebb73Robert Shih        final int layoutDirection = mTextView.getLayoutDirection();
5002bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        int errorX;
5017f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        int offset;
5022bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        switch (layoutDirection) {
5032bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            default:
5047f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber            case View.LAYOUT_DIRECTION_LTR:
5052bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                offset = - (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
5062bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                errorX = mTextView.getWidth() - mErrorPopup.getWidth() -
5077f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber                        mTextView.getPaddingRight() + offset;
5082bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                break;
5092bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            case View.LAYOUT_DIRECTION_RTL:
5102bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f);
5112bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                errorX = mTextView.getPaddingLeft() + offset;
5124ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia                break;
5134ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia        }
5148d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        return errorX;
5158d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    }
5168d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih
5178d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    /**
5188d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih     * Returns the Y offset to make the pointy top of the error point
5198d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih     * at the bottom of the error icon.
5208d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih     */
5218d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    private int getErrorY() {
5228d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        /*
5238d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih         * Compound, not extended, because the icon is not clipped
5248d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih         * if the text height is smaller.
5258d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih         */
5268d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        final int compoundPaddingTop = mTextView.getCompoundPaddingTop();
5278d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        int vspace = mTextView.getBottom() - mTextView.getTop() -
5288d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih                mTextView.getCompoundPaddingBottom() - compoundPaddingTop;
5298d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih
5308d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        final Drawables dr = mTextView.mDrawables;
5318d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih
5328d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        final int layoutDirection = mTextView.getLayoutDirection();
5338d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        int height;
5348d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        switch (layoutDirection) {
5358d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih            default:
5368d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih            case View.LAYOUT_DIRECTION_LTR:
5378d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih                height = (dr != null ? dr.mDrawableHeightRight : 0);
5388d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih                break;
5394ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia            case View.LAYOUT_DIRECTION_RTL:
5404ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia                height = (dr != null ? dr.mDrawableHeightLeft : 0);
5418d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih                break;
5422bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
5432bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
5442bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        int icontop = compoundPaddingTop + (vspace - height) / 2;
5452bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
5462bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        /*
5472bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber         * The "2" is the distance between the point and the top edge
5482bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber         * of the background.
54949694688c82214f5fd9e969e177c9e126a240a26Andreas Huber         */
55049694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        final float scale = mTextView.getResources().getDisplayMetrics().density;
55149694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f);
55249694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    }
55349694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
55449694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    void createInputContentTypeIfNeeded() {
5552bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mInputContentType == null) {
5562d8bedd05437b6fccdbc6bf70f673ffd86744d59Andreas Huber            mInputContentType = new InputContentType();
5572d8bedd05437b6fccdbc6bf70f673ffd86744d59Andreas Huber        }
5582bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
5592bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
5602bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    void createInputMethodStateIfNeeded() {
5612bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mInputMethodState == null) {
562df64d15042bbd5e0e4933ac49bf3c177dd94752cSteve Block            mInputMethodState = new InputMethodState();
5632bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
5642bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
5652bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
56649694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    boolean isCursorVisible() {
56749694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        // The default value is true, even when there is no associated Editor
56849694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        return mCursorVisible && mTextView.isTextEditable();
56949694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    }
57049694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
57149694688c82214f5fd9e969e177c9e126a240a26Andreas Huber    void prepareCursorControllers() {
57249694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        boolean windowSupportsHandles = false;
57349694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
57449694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams();
57549694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        if (params instanceof WindowManager.LayoutParams) {
57649694688c82214f5fd9e969e177c9e126a240a26Andreas Huber            WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
57749694688c82214f5fd9e969e177c9e126a240a26Andreas Huber            windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
57849694688c82214f5fd9e969e177c9e126a240a26Andreas Huber                    || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
57949694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        }
58049694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
58149694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        boolean enabled = windowSupportsHandles && mTextView.getLayout() != null;
58249694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        mInsertionControllerEnabled = enabled && isCursorVisible();
58349694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected();
584f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
58549694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        if (!mInsertionControllerEnabled) {
586f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            hideInsertionPointCursorController();
587f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih            if (mInsertionPointCursorController != null) {
58849694688c82214f5fd9e969e177c9e126a240a26Andreas Huber                mInsertionPointCursorController.onDetached();
58949694688c82214f5fd9e969e177c9e126a240a26Andreas Huber                mInsertionPointCursorController = null;
59049694688c82214f5fd9e969e177c9e126a240a26Andreas Huber            }
5911906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber        }
5921906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber
5931906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber        if (!mSelectionControllerEnabled) {
5942bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            stopTextActionMode();
5952bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (mSelectionModifierCursorController != null) {
5962bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mSelectionModifierCursorController.onDetached();
5972bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mSelectionModifierCursorController = null;
5981906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber            }
5991906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber        }
600c9d1696d214d2175327067ccc1991bcb36976404Andreas Huber    }
601c9d1696d214d2175327067ccc1991bcb36976404Andreas Huber
602c9d1696d214d2175327067ccc1991bcb36976404Andreas Huber    void hideInsertionPointCursorController() {
6031906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber        if (mInsertionPointCursorController != null) {
6041906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber            mInsertionPointCursorController.hide();
6052bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
6061906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber    }
6071906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber
6082bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    /**
6091906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber     * Hides the insertion controller and stops text selection mode, hiding the selection controller
6102bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber     */
6112bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    void hideControllers() {
6122bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        hideCursorControllers();
6132bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        hideSpanControllers();
6142bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
615f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih
6162bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void hideSpanControllers() {
6172bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mSpanController != null) {
6182bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            mSpanController.hide();
6192bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
6202bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
6212bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
6222bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void hideCursorControllers() {
6232bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // When mTextView is not ExtractEditText, we need to distinguish two kinds of focus-lost.
6242bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // One is the true focus lost where suggestions pop-up (if any) should be dismissed, and the
62549694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        // other is an side effect of showing the suggestions pop-up itself. We use isShowingUp()
626f1d261f1b5914ddc219a23b763ab19363eeedd85Robert Shih        // to distinguish one from the other.
62749694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        if (mSuggestionsPopupWindow != null && ((mTextView.isInExtractedMode()) ||
62849694688c82214f5fd9e969e177c9e126a240a26Andreas Huber                !mSuggestionsPopupWindow.isShowingUp())) {
62949694688c82214f5fd9e969e177c9e126a240a26Andreas Huber            // Should be done before hide insertion point controller since it triggers a show of it
63049694688c82214f5fd9e969e177c9e126a240a26Andreas Huber            mSuggestionsPopupWindow.hide();
63149694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        }
63249694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        hideInsertionPointCursorController();
6332bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
6342bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
6352bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    /**
6362bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber     * Create new SpellCheckSpans on the modified region.
6372bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber     */
6382bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
6392bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // Remove spans whose adjacent characters are text not punctuation
6402bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mTextView.removeAdjacentSuggestionSpans(start);
6412bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        mTextView.removeAdjacentSuggestionSpans(end);
6422bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
6432bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() &&
6442bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                !(mTextView.isInExtractedMode())) {
6452bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (mSpellChecker == null && createSpellChecker) {
6462bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mSpellChecker = new SpellChecker(mTextView);
6472bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            }
6482bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (mSpellChecker != null) {
6492bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mSpellChecker.spellCheck(start, end);
6502bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            }
651632740c58119a132ce19f6d498e39c5c3773971aChong Zhang        }
652fef808d42a9c94b0b5ef3c3d5fb0a090edbc42daWei Jia    }
653632740c58119a132ce19f6d498e39c5c3773971aChong Zhang
654632740c58119a132ce19f6d498e39c5c3773971aChong Zhang    void onScreenStateChanged(int screenState) {
6552bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        switch (screenState) {
6562bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            case View.SCREEN_STATE_ON:
6572bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                resumeBlink();
6582bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                break;
6592bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            case View.SCREEN_STATE_OFF:
6602bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                suspendBlink();
6612bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                break;
6622bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
6632bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
6642bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
6652bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void suspendBlink() {
6662bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mBlink != null) {
6672bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            mBlink.cancel();
6682bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
6692bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
6702bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
6712bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void resumeBlink() {
6722bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mBlink != null) {
6732bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            mBlink.uncancel();
6742bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            makeBlink();
6751906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber        }
6762bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
6772bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
6782bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    void adjustInputType(boolean password, boolean passwordInputType,
67981dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            boolean webPasswordInputType, boolean numberPasswordInputType) {
68081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        // mInputType has been set from inputType, possibly modified by mInputMethod.
68181dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        // Specialize mInputType to [web]password if we have a text class and the original input
68281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        // type was a password.
68381dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
68481dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            if (password || passwordInputType) {
6852bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
6862bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                        | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
6872bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            }
6882bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (webPasswordInputType) {
6892bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
6902bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                        | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
6912bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            }
6922bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
6932bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (numberPasswordInputType) {
6942bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
6952bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                        | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
6962bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            }
6972bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
6982bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
6992bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
7002bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
7012bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        int wid = tv.getPaddingLeft() + tv.getPaddingRight();
70249694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        int ht = tv.getPaddingTop() + tv.getPaddingBottom();
70349694688c82214f5fd9e969e177c9e126a240a26Andreas Huber
70449694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize(
70549694688c82214f5fd9e969e177c9e126a240a26Andreas Huber                com.android.internal.R.dimen.textview_error_popup_default_width);
70649694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
70749694688c82214f5fd9e969e177c9e126a240a26Andreas Huber                                    Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
70849694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        float max = 0;
70949694688c82214f5fd9e969e177c9e126a240a26Andreas Huber        for (int i = 0; i < l.getLineCount(); i++) {
7102bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            max = Math.max(max, l.getLineWidth(i));
7112bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
7122bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
7132bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        /*
7142bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber         * Now set the popup size to be big enough for the text plus the border capped
7152bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber         * to DEFAULT_MAX_POPUP_WIDTH
7162bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber         */
7171906e5c7492b9cbc88601365536a69e9a490c963Andreas Huber        pop.setWidth(wid + (int) Math.ceil(max));
7182bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        pop.setHeight(ht + l.getHeight());
7192bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
7202bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
7212bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    void setFrame() {
7222bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (mErrorPopup != null) {
7232bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            TextView tv = (TextView) mErrorPopup.getContentView();
7242bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            chooseSize(mErrorPopup, mError, tv);
7252bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            mErrorPopup.update(mTextView, getErrorX(), getErrorY(),
7262bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                    mErrorPopup.getWidth(), mErrorPopup.getHeight());
7272bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
7282bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    }
7292bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
7302bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber    private int getWordStart(int offset) {
7312bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // FIXME - For this and similar methods we're not doing anything to check if there's
7322bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        // a LocaleSpan in the text, this may be something we should try handling or checking for.
7332bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        int retOffset = getWordIteratorWithText().prevBoundary(offset);
7342bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (getWordIteratorWithText().isOnPunctuation(retOffset)) {
7352bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            // On punctuation boundary or within group of punctuation, find punctuation start.
7362bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            retOffset = getWordIteratorWithText().getPunctuationBeginning(offset);
7372bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        } else {
73881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            // Not on a punctuation boundary, find the word start.
73981dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            retOffset = getWordIteratorWithText().getPrevWordBeginningOnTwoWordsBoundary(offset);
74081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        }
74181dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        if (retOffset == BreakIterator.DONE) {
74281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            return offset;
74381dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        }
74481dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        return retOffset;
74581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    }
74681dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé
74781dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    private int getWordEnd(int offset) {
74881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        int retOffset = getWordIteratorWithText().nextBoundary(offset);
74981dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        if (getWordIteratorWithText().isAfterPunctuation(retOffset)) {
75081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            // On punctuation boundary or within group of punctuation, find punctuation end.
75181dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            retOffset = getWordIteratorWithText().getPunctuationEnd(offset);
75281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        } else {
75381dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            // Not on a punctuation boundary, find the word end.
75481dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            retOffset = getWordIteratorWithText().getNextWordEndOnTwoWordBoundary(offset);
75581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        }
75681dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        if (retOffset == BreakIterator.DONE) {
75781dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            return offset;
75881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        }
7591d15ab58bf8239069ef343de6cb21aabf3ef7d78Lajos Molnar        return retOffset;
76081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    }
76181dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé
76281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    /**
76381dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé     * Adjusts selection to the word under last touch offset. Return true if the operation was
76481dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé     * successfully performed.
76581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé     */
76681dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé    private boolean selectCurrentWord() {
76781dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        if (!mTextView.canSelectText()) {
76881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            return false;
7697f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        }
7707f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber
7717f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        if (mTextView.hasPasswordTransformationMethod()) {
7727f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber            // Always select all on a password field.
7737f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber            // Cut/copy menu entries are not available for passwords, but being able to select all
7747f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber            // is however useful to delete or paste to replace the entire content.
77581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            return mTextView.selectAllText();
776180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        }
77781dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé
77881dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        int inputType = mTextView.getInputType();
77981dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        int klass = inputType & InputType.TYPE_MASK_CLASS;
78081dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        int variation = inputType & InputType.TYPE_MASK_VARIATION;
78181dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé
78281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        // Specific text field types: select the entire text for these
78381dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé        if (klass == InputType.TYPE_CLASS_NUMBER ||
7842bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                klass == InputType.TYPE_CLASS_PHONE ||
7850ad03bc59d090a0455f858d2f629834c105f6f37Fredrik Rosin                klass == InputType.TYPE_CLASS_DATETIME ||
7860ad03bc59d090a0455f858d2f629834c105f6f37Fredrik Rosin                variation == InputType.TYPE_TEXT_VARIATION_URI ||
7870ad03bc59d090a0455f858d2f629834c105f6f37Fredrik Rosin                variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
7880ad03bc59d090a0455f858d2f629834c105f6f37Fredrik Rosin                variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
7892bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
7902bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            return mTextView.selectAllText();
7912bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        }
7922bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
7932bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        long lastTouchOffsets = getLastTouchOffsets();
7942bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
7952bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
7967f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber
7977f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        // Safety check in case standard touch event handling has been bypassed
7987f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        if (minOffset < 0 || minOffset >= mTextView.getText().length()) return false;
7997f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        if (maxOffset < 0 || maxOffset >= mTextView.getText().length()) return false;
8007f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber
8017f475c34ffc8e35345f2cceee2ef56a50bb5fea6Andreas Huber        int selectionStart, selectionEnd;
8022bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
803180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        // If a URLSpan (web address, email, phone...) is found at that position, select it.
8042bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        URLSpan[] urlSpans = ((Spanned) mTextView.getText()).
8052bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                getSpans(minOffset, maxOffset, URLSpan.class);
8062bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        if (urlSpans.length >= 1) {
8072bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            URLSpan urlSpan = urlSpans[0];
8082bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan);
8092bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan);
8102bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        } else {
8112bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            // FIXME - We should check if there's a LocaleSpan in the text, this may be
81281dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            // something we should try handling or checking for.
81381dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            final WordIterator wordIterator = getWordIterator();
81481dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset);
81581dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé
81681dd60e0340ddcf7f1d5fb80b6c30906fabf201aOscar Rydhé            selectionStart = wordIterator.getBeginning(minOffset);
8172bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            selectionEnd = wordIterator.getEnd(maxOffset);
8182bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber
8192bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber            if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
8202bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                    selectionStart == selectionEnd) {
8212bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                // Possible when the word iterator does not properly handle the text's language
8222bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                long range = getCharClusterRange(minOffset);
8232bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber                selectionStart = TextUtils.unpackRangeStartFromLong(range);
824180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang                selectionEnd = TextUtils.unpackRangeEndFromLong(range);
825180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            }
826180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        }
827180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang
828180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
829180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        return selectionEnd > selectionStart;
830180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    }
831180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang
832180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    void onLocaleChanged() {
833180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        // Will be re-created on demand in getWordIterator with the proper new locale
834180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        mWordIterator = null;
835180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        mWordIteratorWithText = null;
836c9ff2009a0a010eeaba80d76493fbf33fcb561c8Wei Jia    }
837180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang
838180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    /**
839180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang     * @hide
840180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang     */
841180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    public WordIterator getWordIterator() {
842180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        if (mWordIterator == null) {
843180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            mWordIterator = new WordIterator(mTextView.getTextServicesLocale());
844180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        }
845180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        return mWordIterator;
846180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    }
847180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang
848180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang    private WordIterator getWordIteratorWithText() {
849180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        if (mWordIteratorWithText == null) {
850180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            mWordIteratorWithText = new WordIterator(mTextView.getTextServicesLocale());
851180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            mUpdateWordIteratorText = true;
852c9ff2009a0a010eeaba80d76493fbf33fcb561c8Wei Jia        }
853180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        if (mUpdateWordIteratorText) {
854180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            // FIXME - Shouldn't copy all of the text as only the area of the text relevant
855180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            // to the user's selection is needed. A possible solution would be to
856180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            // copy some number N of characters near the selection and then when the
857180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            // user approaches N then we'd do another copy of the next N characters.
858180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang            CharSequence text = mTextView.getText();
8598d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih            mWordIteratorWithText.setCharSequence(text, 0, text.length());
8604ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia            mUpdateWordIteratorText = false;
8614ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia        }
8624ad74b2b4507c8b2714b7b7584578d2d43ae2633Wei Jia        return mWordIteratorWithText;
8638d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    }
8648d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih
8658d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih    private int getNextCursorOffset(int offset, boolean findAfterGivenOffset) {
8668d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        final Layout layout = mTextView.getLayout();
8678d237a5ce1e3c1dbc1d538f47e68cff2cc52d799Robert Shih        if (layout == null) return offset;
868180d1b96ee2312f1056a58e26884a89d25ab62c8Chong Zhang        final CharSequence text = mTextView.getText();
8692bfdd428c56c7524d1a11979f200a1762866032dAndreas Huber        final int nextOffset = layout.getPaint().getTextRunCursor(text, 0, text.length(),
870                layout.isRtlCharAt(offset) ? Paint.DIRECTION_RTL : Paint.DIRECTION_LTR,
871                offset, findAfterGivenOffset ? Paint.CURSOR_AFTER : Paint.CURSOR_BEFORE);
872        return nextOffset == -1 ? offset : nextOffset;
873    }
874
875    private long getCharClusterRange(int offset) {
876        final int textLength = mTextView.getText().length();
877        if (offset < textLength) {
878            return TextUtils.packRangeInLong(offset, getNextCursorOffset(offset, true));
879        }
880        if (offset - 1 >= 0) {
881            return TextUtils.packRangeInLong(getNextCursorOffset(offset, false), offset);
882        }
883        return TextUtils.packRangeInLong(offset, offset);
884    }
885
886    private boolean touchPositionIsInSelection() {
887        int selectionStart = mTextView.getSelectionStart();
888        int selectionEnd = mTextView.getSelectionEnd();
889
890        if (selectionStart == selectionEnd) {
891            return false;
892        }
893
894        if (selectionStart > selectionEnd) {
895            int tmp = selectionStart;
896            selectionStart = selectionEnd;
897            selectionEnd = tmp;
898            Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
899        }
900
901        SelectionModifierCursorController selectionController = getSelectionController();
902        int minOffset = selectionController.getMinTouchOffset();
903        int maxOffset = selectionController.getMaxTouchOffset();
904
905        return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
906    }
907
908    private PositionListener getPositionListener() {
909        if (mPositionListener == null) {
910            mPositionListener = new PositionListener();
911        }
912        return mPositionListener;
913    }
914
915    private interface TextViewPositionListener {
916        public void updatePosition(int parentPositionX, int parentPositionY,
917                boolean parentPositionChanged, boolean parentScrolled);
918    }
919
920    private boolean isPositionVisible(final float positionX, final float positionY) {
921        synchronized (TEMP_POSITION) {
922            final float[] position = TEMP_POSITION;
923            position[0] = positionX;
924            position[1] = positionY;
925            View view = mTextView;
926
927            while (view != null) {
928                if (view != mTextView) {
929                    // Local scroll is already taken into account in positionX/Y
930                    position[0] -= view.getScrollX();
931                    position[1] -= view.getScrollY();
932                }
933
934                if (position[0] < 0 || position[1] < 0 ||
935                        position[0] > view.getWidth() || position[1] > view.getHeight()) {
936                    return false;
937                }
938
939                if (!view.getMatrix().isIdentity()) {
940                    view.getMatrix().mapPoints(position);
941                }
942
943                position[0] += view.getLeft();
944                position[1] += view.getTop();
945
946                final ViewParent parent = view.getParent();
947                if (parent instanceof View) {
948                    view = (View) parent;
949                } else {
950                    // We've reached the ViewRoot, stop iterating
951                    view = null;
952                }
953            }
954        }
955
956        // We've been able to walk up the view hierarchy and the position was never clipped
957        return true;
958    }
959
960    private boolean isOffsetVisible(int offset) {
961        Layout layout = mTextView.getLayout();
962        if (layout == null) return false;
963
964        final int line = layout.getLineForOffset(offset);
965        final int lineBottom = layout.getLineBottom(line);
966        final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset);
967        return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(),
968                lineBottom + mTextView.viewportToContentVerticalOffset());
969    }
970
971    /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
972     * in the view. Returns false when the position is in the empty space of left/right of text.
973     */
974    private boolean isPositionOnText(float x, float y) {
975        Layout layout = mTextView.getLayout();
976        if (layout == null) return false;
977
978        final int line = mTextView.getLineAtCoordinate(y);
979        x = mTextView.convertToLocalHorizontalCoordinate(x);
980
981        if (x < layout.getLineLeft(line)) return false;
982        if (x > layout.getLineRight(line)) return false;
983        return true;
984    }
985
986    public boolean performLongClick(boolean handled) {
987        // Long press in empty space moves cursor and starts the insertion action mode.
988        if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
989                mInsertionControllerEnabled) {
990            final int offset = mTextView.getOffsetForPosition(mLastDownPositionX,
991                    mLastDownPositionY);
992            stopTextActionMode();
993            Selection.setSelection((Spannable) mTextView.getText(), offset);
994            getInsertionController().show();
995            mIsInsertionActionModeStartPending = true;
996            handled = true;
997        }
998
999        if (!handled && mTextActionMode != null) {
1000            if (touchPositionIsInSelection()) {
1001                // Start a drag
1002                final int start = mTextView.getSelectionStart();
1003                final int end = mTextView.getSelectionEnd();
1004                CharSequence selectedText = mTextView.getTransformedText(start, end);
1005                ClipData data = ClipData.newPlainText(null, selectedText);
1006                DragLocalState localState = new DragLocalState(mTextView, start, end);
1007                mTextView.startDrag(data, getTextThumbnailBuilder(selectedText), localState,
1008                        View.DRAG_FLAG_GLOBAL);
1009                stopTextActionMode();
1010            } else {
1011                stopTextActionMode();
1012                selectCurrentWordAndStartDrag();
1013            }
1014            handled = true;
1015        }
1016
1017        // Start a new selection
1018        if (!handled) {
1019            handled = selectCurrentWordAndStartDrag();
1020        }
1021
1022        return handled;
1023    }
1024
1025    private long getLastTouchOffsets() {
1026        SelectionModifierCursorController selectionController = getSelectionController();
1027        final int minOffset = selectionController.getMinTouchOffset();
1028        final int maxOffset = selectionController.getMaxTouchOffset();
1029        return TextUtils.packRangeInLong(minOffset, maxOffset);
1030    }
1031
1032    void onFocusChanged(boolean focused, int direction) {
1033        mShowCursor = SystemClock.uptimeMillis();
1034        ensureEndedBatchEdit();
1035
1036        if (focused) {
1037            int selStart = mTextView.getSelectionStart();
1038            int selEnd = mTextView.getSelectionEnd();
1039
1040            // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
1041            // mode for these, unless there was a specific selection already started.
1042            final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
1043                    selEnd == mTextView.getText().length();
1044
1045            mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() &&
1046                    !isFocusHighlighted;
1047
1048            if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
1049                // If a tap was used to give focus to that view, move cursor at tap position.
1050                // Has to be done before onTakeFocus, which can be overloaded.
1051                final int lastTapPosition = getLastTapPosition();
1052                if (lastTapPosition >= 0) {
1053                    Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition);
1054                }
1055
1056                // Note this may have to be moved out of the Editor class
1057                MovementMethod mMovement = mTextView.getMovementMethod();
1058                if (mMovement != null) {
1059                    mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction);
1060                }
1061
1062                // The DecorView does not have focus when the 'Done' ExtractEditText button is
1063                // pressed. Since it is the ViewAncestor's mView, it requests focus before
1064                // ExtractEditText clears focus, which gives focus to the ExtractEditText.
1065                // This special case ensure that we keep current selection in that case.
1066                // It would be better to know why the DecorView does not have focus at that time.
1067                if (((mTextView.isInExtractedMode()) || mSelectionMoved) &&
1068                        selStart >= 0 && selEnd >= 0) {
1069                    /*
1070                     * Someone intentionally set the selection, so let them
1071                     * do whatever it is that they wanted to do instead of
1072                     * the default on-focus behavior.  We reset the selection
1073                     * here instead of just skipping the onTakeFocus() call
1074                     * because some movement methods do something other than
1075                     * just setting the selection in theirs and we still
1076                     * need to go through that path.
1077                     */
1078                    Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
1079                }
1080
1081                if (mSelectAllOnFocus) {
1082                    mTextView.selectAllText();
1083                }
1084
1085                mTouchFocusSelected = true;
1086            }
1087
1088            mFrozenWithFocus = false;
1089            mSelectionMoved = false;
1090
1091            if (mError != null) {
1092                showError();
1093            }
1094
1095            makeBlink();
1096        } else {
1097            if (mError != null) {
1098                hideError();
1099            }
1100            // Don't leave us in the middle of a batch edit.
1101            mTextView.onEndBatchEdit();
1102
1103            if (mTextView.isInExtractedMode()) {
1104                // terminateTextSelectionMode removes selection, which we want to keep when
1105                // ExtractEditText goes out of focus.
1106                final int selStart = mTextView.getSelectionStart();
1107                final int selEnd = mTextView.getSelectionEnd();
1108                hideControllers();
1109                stopTextActionMode();
1110                Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
1111            } else {
1112                if (mTemporaryDetach) mPreserveDetachedSelection = true;
1113                hideControllers();
1114                stopTextActionMode();
1115                if (mTemporaryDetach) mPreserveDetachedSelection = false;
1116                downgradeEasyCorrectionSpans();
1117            }
1118
1119            // No need to create the controller
1120            if (mSelectionModifierCursorController != null) {
1121                mSelectionModifierCursorController.resetTouchOffsets();
1122            }
1123        }
1124    }
1125
1126    /**
1127     * Downgrades to simple suggestions all the easy correction spans that are not a spell check
1128     * span.
1129     */
1130    private void downgradeEasyCorrectionSpans() {
1131        CharSequence text = mTextView.getText();
1132        if (text instanceof Spannable) {
1133            Spannable spannable = (Spannable) text;
1134            SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
1135                    spannable.length(), SuggestionSpan.class);
1136            for (int i = 0; i < suggestionSpans.length; i++) {
1137                int flags = suggestionSpans[i].getFlags();
1138                if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
1139                        && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
1140                    flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
1141                    suggestionSpans[i].setFlags(flags);
1142                }
1143            }
1144        }
1145    }
1146
1147    void sendOnTextChanged(int start, int after) {
1148        updateSpellCheckSpans(start, start + after, false);
1149
1150        // Flip flag to indicate the word iterator needs to have the text reset.
1151        mUpdateWordIteratorText = true;
1152
1153        // Hide the controllers as soon as text is modified (typing, procedural...)
1154        // We do not hide the span controllers, since they can be added when a new text is
1155        // inserted into the text view (voice IME).
1156        hideCursorControllers();
1157        // Reset drag accelerator.
1158        if (mSelectionModifierCursorController != null) {
1159            mSelectionModifierCursorController.resetTouchOffsets();
1160        }
1161        stopTextActionMode();
1162    }
1163
1164    private int getLastTapPosition() {
1165        // No need to create the controller at that point, no last tap position saved
1166        if (mSelectionModifierCursorController != null) {
1167            int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
1168            if (lastTapPosition >= 0) {
1169                // Safety check, should not be possible.
1170                if (lastTapPosition > mTextView.getText().length()) {
1171                    lastTapPosition = mTextView.getText().length();
1172                }
1173                return lastTapPosition;
1174            }
1175        }
1176
1177        return -1;
1178    }
1179
1180    void onWindowFocusChanged(boolean hasWindowFocus) {
1181        if (hasWindowFocus) {
1182            if (mBlink != null) {
1183                mBlink.uncancel();
1184                makeBlink();
1185            }
1186        } else {
1187            if (mBlink != null) {
1188                mBlink.cancel();
1189            }
1190            if (mInputContentType != null) {
1191                mInputContentType.enterDown = false;
1192            }
1193            // Order matters! Must be done before onParentLostFocus to rely on isShowingUp
1194            hideControllers();
1195            if (mSuggestionsPopupWindow != null) {
1196                mSuggestionsPopupWindow.onParentLostFocus();
1197            }
1198
1199            // Don't leave us in the middle of a batch edit. Same as in onFocusChanged
1200            ensureEndedBatchEdit();
1201        }
1202    }
1203
1204    void onTouchEvent(MotionEvent event) {
1205        updateFloatingToolbarVisibility(event);
1206
1207        if (hasSelectionController()) {
1208            getSelectionController().onTouchEvent(event);
1209        }
1210
1211        if (mShowSuggestionRunnable != null) {
1212            mTextView.removeCallbacks(mShowSuggestionRunnable);
1213            mShowSuggestionRunnable = null;
1214        }
1215
1216        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1217            mLastDownPositionX = event.getX();
1218            mLastDownPositionY = event.getY();
1219
1220            // Reset this state; it will be re-set if super.onTouchEvent
1221            // causes focus to move to the view.
1222            mTouchFocusSelected = false;
1223            mIgnoreActionUpEvent = false;
1224        }
1225    }
1226
1227    private void updateFloatingToolbarVisibility(MotionEvent event) {
1228        if (mTextActionMode != null) {
1229            switch (event.getActionMasked()) {
1230                case MotionEvent.ACTION_MOVE:
1231                    hideFloatingToolbar();
1232                    break;
1233                case MotionEvent.ACTION_UP:  // fall through
1234                case MotionEvent.ACTION_CANCEL:
1235                    showFloatingToolbar();
1236            }
1237        }
1238    }
1239
1240    private void hideFloatingToolbar() {
1241        if (mTextActionMode != null) {
1242            mTextView.removeCallbacks(mShowFloatingToolbar);
1243            mTextActionMode.hide(ActionMode.DEFAULT_HIDE_DURATION);
1244        }
1245    }
1246
1247    private void showFloatingToolbar() {
1248        if (mTextActionMode != null) {
1249            // Delay "show" so it doesn't interfere with click confirmations
1250            // or double-clicks that could "dismiss" the floating toolbar.
1251            int delay = ViewConfiguration.getDoubleTapTimeout();
1252            mTextView.postDelayed(mShowFloatingToolbar, delay);
1253        }
1254    }
1255
1256    public void beginBatchEdit() {
1257        mInBatchEditControllers = true;
1258        final InputMethodState ims = mInputMethodState;
1259        if (ims != null) {
1260            int nesting = ++ims.mBatchEditNesting;
1261            if (nesting == 1) {
1262                ims.mCursorChanged = false;
1263                ims.mChangedDelta = 0;
1264                if (ims.mContentChanged) {
1265                    // We already have a pending change from somewhere else,
1266                    // so turn this into a full update.
1267                    ims.mChangedStart = 0;
1268                    ims.mChangedEnd = mTextView.getText().length();
1269                } else {
1270                    ims.mChangedStart = EXTRACT_UNKNOWN;
1271                    ims.mChangedEnd = EXTRACT_UNKNOWN;
1272                    ims.mContentChanged = false;
1273                }
1274                mUndoInputFilter.beginBatchEdit();
1275                mTextView.onBeginBatchEdit();
1276            }
1277        }
1278    }
1279
1280    public void endBatchEdit() {
1281        mInBatchEditControllers = false;
1282        final InputMethodState ims = mInputMethodState;
1283        if (ims != null) {
1284            int nesting = --ims.mBatchEditNesting;
1285            if (nesting == 0) {
1286                finishBatchEdit(ims);
1287            }
1288        }
1289    }
1290
1291    void ensureEndedBatchEdit() {
1292        final InputMethodState ims = mInputMethodState;
1293        if (ims != null && ims.mBatchEditNesting != 0) {
1294            ims.mBatchEditNesting = 0;
1295            finishBatchEdit(ims);
1296        }
1297    }
1298
1299    void finishBatchEdit(final InputMethodState ims) {
1300        mTextView.onEndBatchEdit();
1301        mUndoInputFilter.endBatchEdit();
1302
1303        if (ims.mContentChanged || ims.mSelectionModeChanged) {
1304            mTextView.updateAfterEdit();
1305            reportExtractedText();
1306        } else if (ims.mCursorChanged) {
1307            // Cheesy way to get us to report the current cursor location.
1308            mTextView.invalidateCursor();
1309        }
1310        // sendUpdateSelection knows to avoid sending if the selection did
1311        // not actually change.
1312        sendUpdateSelection();
1313    }
1314
1315    static final int EXTRACT_NOTHING = -2;
1316    static final int EXTRACT_UNKNOWN = -1;
1317
1318    boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
1319        return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
1320                EXTRACT_UNKNOWN, outText);
1321    }
1322
1323    private boolean extractTextInternal(@Nullable ExtractedTextRequest request,
1324            int partialStartOffset, int partialEndOffset, int delta,
1325            @Nullable ExtractedText outText) {
1326        if (request == null || outText == null) {
1327            return false;
1328        }
1329
1330        final CharSequence content = mTextView.getText();
1331        if (content == null) {
1332            return false;
1333        }
1334
1335        if (partialStartOffset != EXTRACT_NOTHING) {
1336            final int N = content.length();
1337            if (partialStartOffset < 0) {
1338                outText.partialStartOffset = outText.partialEndOffset = -1;
1339                partialStartOffset = 0;
1340                partialEndOffset = N;
1341            } else {
1342                // Now use the delta to determine the actual amount of text
1343                // we need.
1344                partialEndOffset += delta;
1345                // Adjust offsets to ensure we contain full spans.
1346                if (content instanceof Spanned) {
1347                    Spanned spanned = (Spanned)content;
1348                    Object[] spans = spanned.getSpans(partialStartOffset,
1349                            partialEndOffset, ParcelableSpan.class);
1350                    int i = spans.length;
1351                    while (i > 0) {
1352                        i--;
1353                        int j = spanned.getSpanStart(spans[i]);
1354                        if (j < partialStartOffset) partialStartOffset = j;
1355                        j = spanned.getSpanEnd(spans[i]);
1356                        if (j > partialEndOffset) partialEndOffset = j;
1357                    }
1358                }
1359                outText.partialStartOffset = partialStartOffset;
1360                outText.partialEndOffset = partialEndOffset - delta;
1361
1362                if (partialStartOffset > N) {
1363                    partialStartOffset = N;
1364                } else if (partialStartOffset < 0) {
1365                    partialStartOffset = 0;
1366                }
1367                if (partialEndOffset > N) {
1368                    partialEndOffset = N;
1369                } else if (partialEndOffset < 0) {
1370                    partialEndOffset = 0;
1371                }
1372            }
1373            if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
1374                outText.text = content.subSequence(partialStartOffset,
1375                        partialEndOffset);
1376            } else {
1377                outText.text = TextUtils.substring(content, partialStartOffset,
1378                        partialEndOffset);
1379            }
1380        } else {
1381            outText.partialStartOffset = 0;
1382            outText.partialEndOffset = 0;
1383            outText.text = "";
1384        }
1385        outText.flags = 0;
1386        if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) {
1387            outText.flags |= ExtractedText.FLAG_SELECTING;
1388        }
1389        if (mTextView.isSingleLine()) {
1390            outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
1391        }
1392        outText.startOffset = 0;
1393        outText.selectionStart = mTextView.getSelectionStart();
1394        outText.selectionEnd = mTextView.getSelectionEnd();
1395        return true;
1396    }
1397
1398    boolean reportExtractedText() {
1399        final Editor.InputMethodState ims = mInputMethodState;
1400        if (ims != null) {
1401            final boolean contentChanged = ims.mContentChanged;
1402            if (contentChanged || ims.mSelectionModeChanged) {
1403                ims.mContentChanged = false;
1404                ims.mSelectionModeChanged = false;
1405                final ExtractedTextRequest req = ims.mExtractedTextRequest;
1406                if (req != null) {
1407                    InputMethodManager imm = InputMethodManager.peekInstance();
1408                    if (imm != null) {
1409                        if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1410                                "Retrieving extracted start=" + ims.mChangedStart +
1411                                " end=" + ims.mChangedEnd +
1412                                " delta=" + ims.mChangedDelta);
1413                        if (ims.mChangedStart < 0 && !contentChanged) {
1414                            ims.mChangedStart = EXTRACT_NOTHING;
1415                        }
1416                        if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
1417                                ims.mChangedDelta, ims.mExtractedText)) {
1418                            if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1419                                    "Reporting extracted start=" +
1420                                    ims.mExtractedText.partialStartOffset +
1421                                    " end=" + ims.mExtractedText.partialEndOffset +
1422                                    ": " + ims.mExtractedText.text);
1423
1424                            imm.updateExtractedText(mTextView, req.token, ims.mExtractedText);
1425                            ims.mChangedStart = EXTRACT_UNKNOWN;
1426                            ims.mChangedEnd = EXTRACT_UNKNOWN;
1427                            ims.mChangedDelta = 0;
1428                            ims.mContentChanged = false;
1429                            return true;
1430                        }
1431                    }
1432                }
1433            }
1434        }
1435        return false;
1436    }
1437
1438    private void sendUpdateSelection() {
1439        if (null != mInputMethodState && mInputMethodState.mBatchEditNesting <= 0) {
1440            final InputMethodManager imm = InputMethodManager.peekInstance();
1441            if (null != imm) {
1442                final int selectionStart = mTextView.getSelectionStart();
1443                final int selectionEnd = mTextView.getSelectionEnd();
1444                int candStart = -1;
1445                int candEnd = -1;
1446                if (mTextView.getText() instanceof Spannable) {
1447                    final Spannable sp = (Spannable) mTextView.getText();
1448                    candStart = EditableInputConnection.getComposingSpanStart(sp);
1449                    candEnd = EditableInputConnection.getComposingSpanEnd(sp);
1450                }
1451                // InputMethodManager#updateSelection skips sending the message if
1452                // none of the parameters have changed since the last time we called it.
1453                imm.updateSelection(mTextView,
1454                        selectionStart, selectionEnd, candStart, candEnd);
1455            }
1456        }
1457    }
1458
1459    void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint,
1460            int cursorOffsetVertical) {
1461        final int selectionStart = mTextView.getSelectionStart();
1462        final int selectionEnd = mTextView.getSelectionEnd();
1463
1464        final InputMethodState ims = mInputMethodState;
1465        if (ims != null && ims.mBatchEditNesting == 0) {
1466            InputMethodManager imm = InputMethodManager.peekInstance();
1467            if (imm != null) {
1468                if (imm.isActive(mTextView)) {
1469                    if (ims.mContentChanged || ims.mSelectionModeChanged) {
1470                        // We are in extract mode and the content has changed
1471                        // in some way... just report complete new text to the
1472                        // input method.
1473                        reportExtractedText();
1474                    }
1475                }
1476            }
1477        }
1478
1479        if (mCorrectionHighlighter != null) {
1480            mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
1481        }
1482
1483        if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) {
1484            drawCursor(canvas, cursorOffsetVertical);
1485            // Rely on the drawable entirely, do not draw the cursor line.
1486            // Has to be done after the IMM related code above which relies on the highlight.
1487            highlight = null;
1488        }
1489
1490        if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) {
1491            drawHardwareAccelerated(canvas, layout, highlight, highlightPaint,
1492                    cursorOffsetVertical);
1493        } else {
1494            layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
1495        }
1496    }
1497
1498    private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight,
1499            Paint highlightPaint, int cursorOffsetVertical) {
1500        final long lineRange = layout.getLineRangeForDraw(canvas);
1501        int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
1502        int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
1503        if (lastLine < 0) return;
1504
1505        layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
1506                firstLine, lastLine);
1507
1508        if (layout instanceof DynamicLayout) {
1509            if (mTextRenderNodes == null) {
1510                mTextRenderNodes = ArrayUtils.emptyArray(TextRenderNode.class);
1511            }
1512
1513            DynamicLayout dynamicLayout = (DynamicLayout) layout;
1514            int[] blockEndLines = dynamicLayout.getBlockEndLines();
1515            int[] blockIndices = dynamicLayout.getBlockIndices();
1516            final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1517            final int indexFirstChangedBlock = dynamicLayout.getIndexFirstChangedBlock();
1518
1519            int endOfPreviousBlock = -1;
1520            int searchStartIndex = 0;
1521            for (int i = 0; i < numberOfBlocks; i++) {
1522                int blockEndLine = blockEndLines[i];
1523                int blockIndex = blockIndices[i];
1524
1525                final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX;
1526                if (blockIsInvalid) {
1527                    blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks,
1528                            searchStartIndex);
1529                    // Note how dynamic layout's internal block indices get updated from Editor
1530                    blockIndices[i] = blockIndex;
1531                    if (mTextRenderNodes[blockIndex] != null) {
1532                        mTextRenderNodes[blockIndex].isDirty = true;
1533                    }
1534                    searchStartIndex = blockIndex + 1;
1535                }
1536
1537                if (mTextRenderNodes[blockIndex] == null) {
1538                    mTextRenderNodes[blockIndex] =
1539                            new TextRenderNode("Text " + blockIndex);
1540                }
1541
1542                final boolean blockDisplayListIsInvalid = mTextRenderNodes[blockIndex].needsRecord();
1543                RenderNode blockDisplayList = mTextRenderNodes[blockIndex].renderNode;
1544                if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) {
1545                    final int blockBeginLine = endOfPreviousBlock + 1;
1546                    final int top = layout.getLineTop(blockBeginLine);
1547                    final int bottom = layout.getLineBottom(blockEndLine);
1548                    int left = 0;
1549                    int right = mTextView.getWidth();
1550                    if (mTextView.getHorizontallyScrolling()) {
1551                        float min = Float.MAX_VALUE;
1552                        float max = Float.MIN_VALUE;
1553                        for (int line = blockBeginLine; line <= blockEndLine; line++) {
1554                            min = Math.min(min, layout.getLineLeft(line));
1555                            max = Math.max(max, layout.getLineRight(line));
1556                        }
1557                        left = (int) min;
1558                        right = (int) (max + 0.5f);
1559                    }
1560
1561                    // Rebuild display list if it is invalid
1562                    if (blockDisplayListIsInvalid) {
1563                        final DisplayListCanvas displayListCanvas = blockDisplayList.start(
1564                                right - left, bottom - top);
1565                        try {
1566                            // drawText is always relative to TextView's origin, this translation
1567                            // brings this range of text back to the top left corner of the viewport
1568                            displayListCanvas.translate(-left, -top);
1569                            layout.drawText(displayListCanvas, blockBeginLine, blockEndLine);
1570                            mTextRenderNodes[blockIndex].isDirty = false;
1571                            // No need to untranslate, previous context is popped after
1572                            // drawDisplayList
1573                        } finally {
1574                            blockDisplayList.end(displayListCanvas);
1575                            // Same as drawDisplayList below, handled by our TextView's parent
1576                            blockDisplayList.setClipToBounds(false);
1577                        }
1578                    }
1579
1580                    // Valid disply list whose index is >= indexFirstChangedBlock
1581                    // only needs to update its drawing location.
1582                    blockDisplayList.setLeftTopRightBottom(left, top, right, bottom);
1583                }
1584
1585                ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList);
1586
1587                endOfPreviousBlock = blockEndLine;
1588            }
1589
1590            dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks);
1591        } else {
1592            // Boring layout is used for empty and hint text
1593            layout.drawText(canvas, firstLine, lastLine);
1594        }
1595    }
1596
1597    private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
1598            int searchStartIndex) {
1599        int length = mTextRenderNodes.length;
1600        for (int i = searchStartIndex; i < length; i++) {
1601            boolean blockIndexFound = false;
1602            for (int j = 0; j < numberOfBlocks; j++) {
1603                if (blockIndices[j] == i) {
1604                    blockIndexFound = true;
1605                    break;
1606                }
1607            }
1608            if (blockIndexFound) continue;
1609            return i;
1610        }
1611
1612        // No available index found, the pool has to grow
1613        mTextRenderNodes = GrowingArrayUtils.append(mTextRenderNodes, length, null);
1614        return length;
1615    }
1616
1617    private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
1618        final boolean translate = cursorOffsetVertical != 0;
1619        if (translate) canvas.translate(0, cursorOffsetVertical);
1620        for (int i = 0; i < mCursorCount; i++) {
1621            mCursorDrawable[i].draw(canvas);
1622        }
1623        if (translate) canvas.translate(0, -cursorOffsetVertical);
1624    }
1625
1626    /**
1627     * Invalidates all the sub-display lists that overlap the specified character range
1628     */
1629    void invalidateTextDisplayList(Layout layout, int start, int end) {
1630        if (mTextRenderNodes != null && layout instanceof DynamicLayout) {
1631            final int firstLine = layout.getLineForOffset(start);
1632            final int lastLine = layout.getLineForOffset(end);
1633
1634            DynamicLayout dynamicLayout = (DynamicLayout) layout;
1635            int[] blockEndLines = dynamicLayout.getBlockEndLines();
1636            int[] blockIndices = dynamicLayout.getBlockIndices();
1637            final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1638
1639            int i = 0;
1640            // Skip the blocks before firstLine
1641            while (i < numberOfBlocks) {
1642                if (blockEndLines[i] >= firstLine) break;
1643                i++;
1644            }
1645
1646            // Invalidate all subsequent blocks until lastLine is passed
1647            while (i < numberOfBlocks) {
1648                final int blockIndex = blockIndices[i];
1649                if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
1650                    mTextRenderNodes[blockIndex].isDirty = true;
1651                }
1652                if (blockEndLines[i] >= lastLine) break;
1653                i++;
1654            }
1655        }
1656    }
1657
1658    void invalidateTextDisplayList() {
1659        if (mTextRenderNodes != null) {
1660            for (int i = 0; i < mTextRenderNodes.length; i++) {
1661                if (mTextRenderNodes[i] != null) mTextRenderNodes[i].isDirty = true;
1662            }
1663        }
1664    }
1665
1666    void updateCursorsPositions() {
1667        if (mTextView.mCursorDrawableRes == 0) {
1668            mCursorCount = 0;
1669            return;
1670        }
1671
1672        Layout layout = mTextView.getLayout();
1673        Layout hintLayout = mTextView.getHintLayout();
1674        final int offset = mTextView.getSelectionStart();
1675        final int line = layout.getLineForOffset(offset);
1676        final int top = layout.getLineTop(line);
1677        final int bottom = layout.getLineTop(line + 1);
1678
1679        mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1;
1680
1681        int middle = bottom;
1682        if (mCursorCount == 2) {
1683            // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
1684            middle = (top + bottom) >> 1;
1685        }
1686
1687        boolean clamped = layout.shouldClampCursor(line);
1688        updateCursorPosition(0, top, middle,
1689                getPrimaryHorizontal(layout, hintLayout, offset, clamped));
1690
1691        if (mCursorCount == 2) {
1692            updateCursorPosition(1, middle, bottom,
1693                    layout.getSecondaryHorizontal(offset, clamped));
1694        }
1695    }
1696
1697    private float getPrimaryHorizontal(Layout layout, Layout hintLayout, int offset,
1698            boolean clamped) {
1699        if (TextUtils.isEmpty(layout.getText()) &&
1700                hintLayout != null &&
1701                !TextUtils.isEmpty(hintLayout.getText())) {
1702            return hintLayout.getPrimaryHorizontal(offset, clamped);
1703        } else {
1704            return layout.getPrimaryHorizontal(offset, clamped);
1705        }
1706    }
1707
1708    /**
1709     * Start an Insertion action mode.
1710     */
1711    void startInsertionActionMode() {
1712        if (mInsertionActionModeRunnable != null) {
1713            mTextView.removeCallbacks(mInsertionActionModeRunnable);
1714        }
1715        if (extractedTextModeWillBeStarted()) {
1716            return;
1717        }
1718        stopTextActionMode();
1719
1720        ActionMode.Callback actionModeCallback =
1721                new TextActionModeCallback(false /* hasSelection */);
1722        mTextActionMode = mTextView.startActionMode(
1723                actionModeCallback, ActionMode.TYPE_FLOATING);
1724        if (mTextActionMode != null && getInsertionController() != null) {
1725            getInsertionController().show();
1726        }
1727    }
1728
1729    /**
1730     * Starts a Selection Action Mode with the current selection and ensures the selection handles
1731     * are shown if there is a selection, otherwise the insertion handle is shown. This should be
1732     * used when the mode is started from a non-touch event.
1733     *
1734     * @return true if the selection mode was actually started.
1735     */
1736    boolean startSelectionActionMode() {
1737        boolean selectionStarted = startSelectionActionModeInternal();
1738        if (selectionStarted) {
1739            getSelectionController().show();
1740        } else if (getInsertionController() != null) {
1741            getInsertionController().show();
1742        }
1743        return selectionStarted;
1744    }
1745
1746    /**
1747     * If the TextView allows text selection, selects the current word when no existing selection
1748     * was available and starts a drag.
1749     *
1750     * @return true if the drag was started.
1751     */
1752    private boolean selectCurrentWordAndStartDrag() {
1753        if (mInsertionActionModeRunnable != null) {
1754            mTextView.removeCallbacks(mInsertionActionModeRunnable);
1755        }
1756        if (extractedTextModeWillBeStarted()) {
1757            return false;
1758        }
1759        if (mTextActionMode != null) {
1760            mTextActionMode.finish();
1761        }
1762        if (!checkFieldAndSelectCurrentWord()) {
1763            return false;
1764        }
1765
1766        // Avoid dismissing the selection if it exists.
1767        mPreserveDetachedSelection = true;
1768        stopTextActionMode();
1769        mPreserveDetachedSelection = false;
1770
1771        getSelectionController().enterDrag();
1772        return true;
1773    }
1774
1775    /**
1776     * Checks whether a selection can be performed on the current TextView and if so selects
1777     * the current word.
1778     *
1779     * @return true if there already was a selection or if the current word was selected.
1780     */
1781    private boolean checkFieldAndSelectCurrentWord() {
1782        if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
1783            Log.w(TextView.LOG_TAG,
1784                    "TextView does not support text selection. Selection cancelled.");
1785            return false;
1786        }
1787
1788        if (!mTextView.hasSelection()) {
1789            // There may already be a selection on device rotation
1790            return selectCurrentWord();
1791        }
1792        return true;
1793    }
1794
1795    private boolean startSelectionActionModeInternal() {
1796        if (mTextActionMode != null) {
1797            // Text action mode is already started
1798            mTextActionMode.invalidate();
1799            return false;
1800        }
1801
1802        if (!checkFieldAndSelectCurrentWord()) {
1803            return false;
1804        }
1805
1806        boolean willExtract = extractedTextModeWillBeStarted();
1807
1808        // Do not start the action mode when extracted text will show up full screen, which would
1809        // immediately hide the newly created action bar and would be visually distracting.
1810        if (!willExtract) {
1811            ActionMode.Callback actionModeCallback =
1812                    new TextActionModeCallback(true /* hasSelection */);
1813            mTextActionMode = mTextView.startActionMode(
1814                    actionModeCallback, ActionMode.TYPE_FLOATING);
1815        }
1816
1817        final boolean selectionStarted = mTextActionMode != null || willExtract;
1818        if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
1819            // Show the IME to be able to replace text, except when selecting non editable text.
1820            final InputMethodManager imm = InputMethodManager.peekInstance();
1821            if (imm != null) {
1822                imm.showSoftInput(mTextView, 0, null);
1823            }
1824        }
1825        return selectionStarted;
1826    }
1827
1828    private boolean extractedTextModeWillBeStarted() {
1829        if (!(mTextView.isInExtractedMode())) {
1830            final InputMethodManager imm = InputMethodManager.peekInstance();
1831            return  imm != null && imm.isFullscreenMode();
1832        }
1833        return false;
1834    }
1835
1836    /**
1837     * @return <code>true</code> if it's reasonable to offer to show suggestions depending on
1838     * the current cursor position or selection range. This method is consistent with the
1839     * method to show suggestions {@link SuggestionsPopupWindow#updateSuggestions}.
1840     */
1841    private boolean shouldOfferToShowSuggestions() {
1842        CharSequence text = mTextView.getText();
1843        if (!(text instanceof Spannable)) return false;
1844
1845        final Spannable spannable = (Spannable) text;
1846        final int selectionStart = mTextView.getSelectionStart();
1847        final int selectionEnd = mTextView.getSelectionEnd();
1848        final SuggestionSpan[] suggestionSpans = spannable.getSpans(selectionStart, selectionEnd,
1849                SuggestionSpan.class);
1850        if (suggestionSpans.length == 0) {
1851            return false;
1852        }
1853        if (selectionStart == selectionEnd) {
1854            // Spans overlap the cursor.
1855            for (int i = 0; i < suggestionSpans.length; i++) {
1856                if (suggestionSpans[i].getSuggestions().length > 0) {
1857                    return true;
1858                }
1859            }
1860            return false;
1861        }
1862        int minSpanStart = mTextView.getText().length();
1863        int maxSpanEnd = 0;
1864        int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length();
1865        int unionOfSpansCoveringSelectionStartEnd = 0;
1866        boolean hasValidSuggestions = false;
1867        for (int i = 0; i < suggestionSpans.length; i++) {
1868            final int spanStart = spannable.getSpanStart(suggestionSpans[i]);
1869            final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]);
1870            minSpanStart = Math.min(minSpanStart, spanStart);
1871            maxSpanEnd = Math.max(maxSpanEnd, spanEnd);
1872            if (selectionStart < spanStart || selectionStart > spanEnd) {
1873                // The span doesn't cover the current selection start point.
1874                continue;
1875            }
1876            hasValidSuggestions =
1877                    hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0;
1878            unionOfSpansCoveringSelectionStartStart =
1879                    Math.min(unionOfSpansCoveringSelectionStartStart, spanStart);
1880            unionOfSpansCoveringSelectionStartEnd =
1881                    Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd);
1882        }
1883        if (!hasValidSuggestions) {
1884            return false;
1885        }
1886        if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) {
1887            // No spans cover the selection start point.
1888            return false;
1889        }
1890        if (minSpanStart < unionOfSpansCoveringSelectionStartStart
1891                || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) {
1892            // There is a span that is not covered by the union. In this case, we soouldn't offer
1893            // to show suggestions as it's confusing.
1894            return false;
1895        }
1896        return true;
1897    }
1898
1899    /**
1900     * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
1901     * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
1902     */
1903    private boolean isCursorInsideEasyCorrectionSpan() {
1904        Spannable spannable = (Spannable) mTextView.getText();
1905        SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
1906                mTextView.getSelectionEnd(), SuggestionSpan.class);
1907        for (int i = 0; i < suggestionSpans.length; i++) {
1908            if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
1909                return true;
1910            }
1911        }
1912        return false;
1913    }
1914
1915    void onTouchUpEvent(MotionEvent event) {
1916        boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
1917        hideControllers();
1918        stopTextActionMode();
1919        CharSequence text = mTextView.getText();
1920        if (!selectAllGotFocus && text.length() > 0) {
1921            // Move cursor
1922            final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
1923            Selection.setSelection((Spannable) text, offset);
1924            if (mSpellChecker != null) {
1925                // When the cursor moves, the word that was typed may need spell check
1926                mSpellChecker.onSelectionChanged();
1927            }
1928
1929            if (!extractedTextModeWillBeStarted()) {
1930                if (isCursorInsideEasyCorrectionSpan()) {
1931                    // Cancel the single tap delayed runnable.
1932                    if (mInsertionActionModeRunnable != null) {
1933                        mTextView.removeCallbacks(mInsertionActionModeRunnable);
1934                    }
1935
1936                    mShowSuggestionRunnable = new Runnable() {
1937                        public void run() {
1938                            showSuggestions();
1939                        }
1940                    };
1941                    // removeCallbacks is performed on every touch
1942                    mTextView.postDelayed(mShowSuggestionRunnable,
1943                            ViewConfiguration.getDoubleTapTimeout());
1944                } else if (hasInsertionController()) {
1945                    getInsertionController().show();
1946                }
1947            }
1948        }
1949    }
1950
1951    protected void stopTextActionMode() {
1952        if (mTextActionMode != null) {
1953            // This will hide the mSelectionModifierCursorController
1954            mTextActionMode.finish();
1955        }
1956    }
1957
1958    /**
1959     * @return True if this view supports insertion handles.
1960     */
1961    boolean hasInsertionController() {
1962        return mInsertionControllerEnabled;
1963    }
1964
1965    /**
1966     * @return True if this view supports selection handles.
1967     */
1968    boolean hasSelectionController() {
1969        return mSelectionControllerEnabled;
1970    }
1971
1972    InsertionPointCursorController getInsertionController() {
1973        if (!mInsertionControllerEnabled) {
1974            return null;
1975        }
1976
1977        if (mInsertionPointCursorController == null) {
1978            mInsertionPointCursorController = new InsertionPointCursorController();
1979
1980            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1981            observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
1982        }
1983
1984        return mInsertionPointCursorController;
1985    }
1986
1987    SelectionModifierCursorController getSelectionController() {
1988        if (!mSelectionControllerEnabled) {
1989            return null;
1990        }
1991
1992        if (mSelectionModifierCursorController == null) {
1993            mSelectionModifierCursorController = new SelectionModifierCursorController();
1994
1995            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
1996            observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
1997        }
1998
1999        return mSelectionModifierCursorController;
2000    }
2001
2002    private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
2003        if (mCursorDrawable[cursorIndex] == null)
2004            mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable(
2005                    mTextView.mCursorDrawableRes);
2006
2007        if (mTempRect == null) mTempRect = new Rect();
2008        mCursorDrawable[cursorIndex].getPadding(mTempRect);
2009        final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth();
2010        horizontal = Math.max(0.5f, horizontal - 0.5f);
2011        final int left = (int) (horizontal) - mTempRect.left;
2012        mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width,
2013                bottom + mTempRect.bottom);
2014    }
2015
2016    /**
2017     * Called by the framework in response to a text auto-correction (such as fixing a typo using a
2018     * a dictionary) from the current input method, provided by it calling
2019     * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
2020     * implementation flashes the background of the corrected word to provide feedback to the user.
2021     *
2022     * @param info The auto correct info about the text that was corrected.
2023     */
2024    public void onCommitCorrection(CorrectionInfo info) {
2025        if (mCorrectionHighlighter == null) {
2026            mCorrectionHighlighter = new CorrectionHighlighter();
2027        } else {
2028            mCorrectionHighlighter.invalidate(false);
2029        }
2030
2031        mCorrectionHighlighter.highlight(info);
2032    }
2033
2034    void showSuggestions() {
2035        if (mSuggestionsPopupWindow == null) {
2036            mSuggestionsPopupWindow = new SuggestionsPopupWindow();
2037        }
2038        hideControllers();
2039        stopTextActionMode();
2040        mSuggestionsPopupWindow.show();
2041    }
2042
2043    void onScrollChanged() {
2044        if (mPositionListener != null) {
2045            mPositionListener.onScrollChanged();
2046        }
2047        if (mTextActionMode != null) {
2048            mTextActionMode.invalidateContentRect();
2049        }
2050    }
2051
2052    /**
2053     * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
2054     */
2055    private boolean shouldBlink() {
2056        if (!isCursorVisible() || !mTextView.isFocused()) return false;
2057
2058        final int start = mTextView.getSelectionStart();
2059        if (start < 0) return false;
2060
2061        final int end = mTextView.getSelectionEnd();
2062        if (end < 0) return false;
2063
2064        return start == end;
2065    }
2066
2067    void makeBlink() {
2068        if (shouldBlink()) {
2069            mShowCursor = SystemClock.uptimeMillis();
2070            if (mBlink == null) mBlink = new Blink();
2071            mBlink.removeCallbacks(mBlink);
2072            mBlink.postAtTime(mBlink, mShowCursor + BLINK);
2073        } else {
2074            if (mBlink != null) mBlink.removeCallbacks(mBlink);
2075        }
2076    }
2077
2078    private class Blink extends Handler implements Runnable {
2079        private boolean mCancelled;
2080
2081        public void run() {
2082            if (mCancelled) {
2083                return;
2084            }
2085
2086            removeCallbacks(Blink.this);
2087
2088            if (shouldBlink()) {
2089                if (mTextView.getLayout() != null) {
2090                    mTextView.invalidateCursorPath();
2091                }
2092
2093                postAtTime(this, SystemClock.uptimeMillis() + BLINK);
2094            }
2095        }
2096
2097        void cancel() {
2098            if (!mCancelled) {
2099                removeCallbacks(Blink.this);
2100                mCancelled = true;
2101            }
2102        }
2103
2104        void uncancel() {
2105            mCancelled = false;
2106        }
2107    }
2108
2109    private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
2110        TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
2111                com.android.internal.R.layout.text_drag_thumbnail, null);
2112
2113        if (shadowView == null) {
2114            throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
2115        }
2116
2117        if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
2118            text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
2119        }
2120        shadowView.setText(text);
2121        shadowView.setTextColor(mTextView.getTextColors());
2122
2123        shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge);
2124        shadowView.setGravity(Gravity.CENTER);
2125
2126        shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2127                ViewGroup.LayoutParams.WRAP_CONTENT));
2128
2129        final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
2130        shadowView.measure(size, size);
2131
2132        shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
2133        shadowView.invalidate();
2134        return new DragShadowBuilder(shadowView);
2135    }
2136
2137    private static class DragLocalState {
2138        public TextView sourceTextView;
2139        public int start, end;
2140
2141        public DragLocalState(TextView sourceTextView, int start, int end) {
2142            this.sourceTextView = sourceTextView;
2143            this.start = start;
2144            this.end = end;
2145        }
2146    }
2147
2148    void onDrop(DragEvent event) {
2149        StringBuilder content = new StringBuilder("");
2150        ClipData clipData = event.getClipData();
2151        final int itemCount = clipData.getItemCount();
2152        for (int i=0; i < itemCount; i++) {
2153            Item item = clipData.getItemAt(i);
2154            content.append(item.coerceToStyledText(mTextView.getContext()));
2155        }
2156
2157        final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2158
2159        Object localState = event.getLocalState();
2160        DragLocalState dragLocalState = null;
2161        if (localState instanceof DragLocalState) {
2162            dragLocalState = (DragLocalState) localState;
2163        }
2164        boolean dragDropIntoItself = dragLocalState != null &&
2165                dragLocalState.sourceTextView == mTextView;
2166
2167        if (dragDropIntoItself) {
2168            if (offset >= dragLocalState.start && offset < dragLocalState.end) {
2169                // A drop inside the original selection discards the drop.
2170                return;
2171            }
2172        }
2173
2174        final int originalLength = mTextView.getText().length();
2175        int min = offset;
2176        int max = offset;
2177
2178        Selection.setSelection((Spannable) mTextView.getText(), max);
2179        mTextView.replaceText_internal(min, max, content);
2180
2181        if (dragDropIntoItself) {
2182            int dragSourceStart = dragLocalState.start;
2183            int dragSourceEnd = dragLocalState.end;
2184            if (max <= dragSourceStart) {
2185                // Inserting text before selection has shifted positions
2186                final int shift = mTextView.getText().length() - originalLength;
2187                dragSourceStart += shift;
2188                dragSourceEnd += shift;
2189            }
2190
2191            // Delete original selection
2192            mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
2193
2194            // Make sure we do not leave two adjacent spaces.
2195            final int prevCharIdx = Math.max(0,  dragSourceStart - 1);
2196            final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1);
2197            if (nextCharIdx > prevCharIdx + 1) {
2198                CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx);
2199                if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) {
2200                    mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1);
2201                }
2202            }
2203        }
2204    }
2205
2206    public void addSpanWatchers(Spannable text) {
2207        final int textLength = text.length();
2208
2209        if (mKeyListener != null) {
2210            text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2211        }
2212
2213        if (mSpanController == null) {
2214            mSpanController = new SpanController();
2215        }
2216        text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2217    }
2218
2219    /**
2220     * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
2221     * pop-up should be displayed.
2222     * Also monitors {@link Selection} to call back to the attached input method.
2223     */
2224    class SpanController implements SpanWatcher {
2225
2226        private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
2227
2228        private EasyEditPopupWindow mPopupWindow;
2229
2230        private Runnable mHidePopup;
2231
2232        // This function is pure but inner classes can't have static functions
2233        private boolean isNonIntermediateSelectionSpan(final Spannable text,
2234                final Object span) {
2235            return (Selection.SELECTION_START == span || Selection.SELECTION_END == span)
2236                    && (text.getSpanFlags(span) & Spanned.SPAN_INTERMEDIATE) == 0;
2237        }
2238
2239        @Override
2240        public void onSpanAdded(Spannable text, Object span, int start, int end) {
2241            if (isNonIntermediateSelectionSpan(text, span)) {
2242                sendUpdateSelection();
2243            } else if (span instanceof EasyEditSpan) {
2244                if (mPopupWindow == null) {
2245                    mPopupWindow = new EasyEditPopupWindow();
2246                    mHidePopup = new Runnable() {
2247                        @Override
2248                        public void run() {
2249                            hide();
2250                        }
2251                    };
2252                }
2253
2254                // Make sure there is only at most one EasyEditSpan in the text
2255                if (mPopupWindow.mEasyEditSpan != null) {
2256                    mPopupWindow.mEasyEditSpan.setDeleteEnabled(false);
2257                }
2258
2259                mPopupWindow.setEasyEditSpan((EasyEditSpan) span);
2260                mPopupWindow.setOnDeleteListener(new EasyEditDeleteListener() {
2261                    @Override
2262                    public void onDeleteClick(EasyEditSpan span) {
2263                        Editable editable = (Editable) mTextView.getText();
2264                        int start = editable.getSpanStart(span);
2265                        int end = editable.getSpanEnd(span);
2266                        if (start >= 0 && end >= 0) {
2267                            sendEasySpanNotification(EasyEditSpan.TEXT_DELETED, span);
2268                            mTextView.deleteText_internal(start, end);
2269                        }
2270                        editable.removeSpan(span);
2271                    }
2272                });
2273
2274                if (mTextView.getWindowVisibility() != View.VISIBLE) {
2275                    // The window is not visible yet, ignore the text change.
2276                    return;
2277                }
2278
2279                if (mTextView.getLayout() == null) {
2280                    // The view has not been laid out yet, ignore the text change
2281                    return;
2282                }
2283
2284                if (extractedTextModeWillBeStarted()) {
2285                    // The input is in extract mode. Do not handle the easy edit in
2286                    // the original TextView, as the ExtractEditText will do
2287                    return;
2288                }
2289
2290                mPopupWindow.show();
2291                mTextView.removeCallbacks(mHidePopup);
2292                mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
2293            }
2294        }
2295
2296        @Override
2297        public void onSpanRemoved(Spannable text, Object span, int start, int end) {
2298            if (isNonIntermediateSelectionSpan(text, span)) {
2299                sendUpdateSelection();
2300            } else if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) {
2301                hide();
2302            }
2303        }
2304
2305        @Override
2306        public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd,
2307                int newStart, int newEnd) {
2308            if (isNonIntermediateSelectionSpan(text, span)) {
2309                sendUpdateSelection();
2310            } else if (mPopupWindow != null && span instanceof EasyEditSpan) {
2311                EasyEditSpan easyEditSpan = (EasyEditSpan) span;
2312                sendEasySpanNotification(EasyEditSpan.TEXT_MODIFIED, easyEditSpan);
2313                text.removeSpan(easyEditSpan);
2314            }
2315        }
2316
2317        public void hide() {
2318            if (mPopupWindow != null) {
2319                mPopupWindow.hide();
2320                mTextView.removeCallbacks(mHidePopup);
2321            }
2322        }
2323
2324        private void sendEasySpanNotification(int textChangedType, EasyEditSpan span) {
2325            try {
2326                PendingIntent pendingIntent = span.getPendingIntent();
2327                if (pendingIntent != null) {
2328                    Intent intent = new Intent();
2329                    intent.putExtra(EasyEditSpan.EXTRA_TEXT_CHANGED_TYPE, textChangedType);
2330                    pendingIntent.send(mTextView.getContext(), 0, intent);
2331                }
2332            } catch (CanceledException e) {
2333                // This should not happen, as we should try to send the intent only once.
2334                Log.w(TAG, "PendingIntent for notification cannot be sent", e);
2335            }
2336        }
2337    }
2338
2339    /**
2340     * Listens for the delete event triggered by {@link EasyEditPopupWindow}.
2341     */
2342    private interface EasyEditDeleteListener {
2343
2344        /**
2345         * Clicks the delete pop-up.
2346         */
2347        void onDeleteClick(EasyEditSpan span);
2348    }
2349
2350    /**
2351     * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
2352     * by {@link SpanController}.
2353     */
2354    private class EasyEditPopupWindow extends PinnedPopupWindow
2355            implements OnClickListener {
2356        private static final int POPUP_TEXT_LAYOUT =
2357                com.android.internal.R.layout.text_edit_action_popup_text;
2358        private TextView mDeleteTextView;
2359        private EasyEditSpan mEasyEditSpan;
2360        private EasyEditDeleteListener mOnDeleteListener;
2361
2362        @Override
2363        protected void createPopupWindow() {
2364            mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2365                    com.android.internal.R.attr.textSelectHandleWindowStyle);
2366            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2367            mPopupWindow.setClippingEnabled(true);
2368        }
2369
2370        @Override
2371        protected void initContentView() {
2372            LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2373            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2374            mContentView = linearLayout;
2375            mContentView.setBackgroundResource(
2376                    com.android.internal.R.drawable.text_edit_side_paste_window);
2377
2378            LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
2379                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2380
2381            LayoutParams wrapContent = new LayoutParams(
2382                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2383
2384            mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2385            mDeleteTextView.setLayoutParams(wrapContent);
2386            mDeleteTextView.setText(com.android.internal.R.string.delete);
2387            mDeleteTextView.setOnClickListener(this);
2388            mContentView.addView(mDeleteTextView);
2389        }
2390
2391        public void setEasyEditSpan(EasyEditSpan easyEditSpan) {
2392            mEasyEditSpan = easyEditSpan;
2393        }
2394
2395        private void setOnDeleteListener(EasyEditDeleteListener listener) {
2396            mOnDeleteListener = listener;
2397        }
2398
2399        @Override
2400        public void onClick(View view) {
2401            if (view == mDeleteTextView
2402                    && mEasyEditSpan != null && mEasyEditSpan.isDeleteEnabled()
2403                    && mOnDeleteListener != null) {
2404                mOnDeleteListener.onDeleteClick(mEasyEditSpan);
2405            }
2406        }
2407
2408        @Override
2409        public void hide() {
2410            if (mEasyEditSpan != null) {
2411                mEasyEditSpan.setDeleteEnabled(false);
2412            }
2413            mOnDeleteListener = null;
2414            super.hide();
2415        }
2416
2417        @Override
2418        protected int getTextOffset() {
2419            // Place the pop-up at the end of the span
2420            Editable editable = (Editable) mTextView.getText();
2421            return editable.getSpanEnd(mEasyEditSpan);
2422        }
2423
2424        @Override
2425        protected int getVerticalLocalPosition(int line) {
2426            return mTextView.getLayout().getLineBottom(line);
2427        }
2428
2429        @Override
2430        protected int clipVertically(int positionY) {
2431            // As we display the pop-up below the span, no vertical clipping is required.
2432            return positionY;
2433        }
2434    }
2435
2436    private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
2437        // 3 handles
2438        // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
2439        // 1 CursorAnchorInfoNotifier
2440        private final int MAXIMUM_NUMBER_OF_LISTENERS = 7;
2441        private TextViewPositionListener[] mPositionListeners =
2442                new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
2443        private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
2444        private boolean mPositionHasChanged = true;
2445        // Absolute position of the TextView with respect to its parent window
2446        private int mPositionX, mPositionY;
2447        private int mNumberOfListeners;
2448        private boolean mScrollHasChanged;
2449        final int[] mTempCoords = new int[2];
2450
2451        public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2452            if (mNumberOfListeners == 0) {
2453                updatePosition();
2454                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2455                vto.addOnPreDrawListener(this);
2456            }
2457
2458            int emptySlotIndex = -1;
2459            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2460                TextViewPositionListener listener = mPositionListeners[i];
2461                if (listener == positionListener) {
2462                    return;
2463                } else if (emptySlotIndex < 0 && listener == null) {
2464                    emptySlotIndex = i;
2465                }
2466            }
2467
2468            mPositionListeners[emptySlotIndex] = positionListener;
2469            mCanMove[emptySlotIndex] = canMove;
2470            mNumberOfListeners++;
2471        }
2472
2473        public void removeSubscriber(TextViewPositionListener positionListener) {
2474            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2475                if (mPositionListeners[i] == positionListener) {
2476                    mPositionListeners[i] = null;
2477                    mNumberOfListeners--;
2478                    break;
2479                }
2480            }
2481
2482            if (mNumberOfListeners == 0) {
2483                ViewTreeObserver vto = mTextView.getViewTreeObserver();
2484                vto.removeOnPreDrawListener(this);
2485            }
2486        }
2487
2488        public int getPositionX() {
2489            return mPositionX;
2490        }
2491
2492        public int getPositionY() {
2493            return mPositionY;
2494        }
2495
2496        @Override
2497        public boolean onPreDraw() {
2498            updatePosition();
2499
2500            for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2501                if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2502                    TextViewPositionListener positionListener = mPositionListeners[i];
2503                    if (positionListener != null) {
2504                        positionListener.updatePosition(mPositionX, mPositionY,
2505                                mPositionHasChanged, mScrollHasChanged);
2506                    }
2507                }
2508            }
2509
2510            mScrollHasChanged = false;
2511            return true;
2512        }
2513
2514        private void updatePosition() {
2515            mTextView.getLocationInWindow(mTempCoords);
2516
2517            mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2518
2519            mPositionX = mTempCoords[0];
2520            mPositionY = mTempCoords[1];
2521        }
2522
2523        public void onScrollChanged() {
2524            mScrollHasChanged = true;
2525        }
2526    }
2527
2528    private abstract class PinnedPopupWindow implements TextViewPositionListener {
2529        protected PopupWindow mPopupWindow;
2530        protected ViewGroup mContentView;
2531        int mPositionX, mPositionY;
2532
2533        protected abstract void createPopupWindow();
2534        protected abstract void initContentView();
2535        protected abstract int getTextOffset();
2536        protected abstract int getVerticalLocalPosition(int line);
2537        protected abstract int clipVertically(int positionY);
2538
2539        public PinnedPopupWindow() {
2540            createPopupWindow();
2541
2542            mPopupWindow.setWindowLayoutType(
2543                    WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL);
2544            mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2545            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2546
2547            initContentView();
2548
2549            LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2550                    ViewGroup.LayoutParams.WRAP_CONTENT);
2551            mContentView.setLayoutParams(wrapContent);
2552
2553            mPopupWindow.setContentView(mContentView);
2554        }
2555
2556        public void show() {
2557            getPositionListener().addSubscriber(this, false /* offset is fixed */);
2558
2559            computeLocalPosition();
2560
2561            final PositionListener positionListener = getPositionListener();
2562            updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2563        }
2564
2565        protected void measureContent() {
2566            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2567            mContentView.measure(
2568                    View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
2569                            View.MeasureSpec.AT_MOST),
2570                    View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
2571                            View.MeasureSpec.AT_MOST));
2572        }
2573
2574        /* The popup window will be horizontally centered on the getTextOffset() and vertically
2575         * positioned according to viewportToContentHorizontalOffset.
2576         *
2577         * This method assumes that mContentView has properly been measured from its content. */
2578        private void computeLocalPosition() {
2579            measureContent();
2580            final int width = mContentView.getMeasuredWidth();
2581            final int offset = getTextOffset();
2582            mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
2583            mPositionX += mTextView.viewportToContentHorizontalOffset();
2584
2585            final int line = mTextView.getLayout().getLineForOffset(offset);
2586            mPositionY = getVerticalLocalPosition(line);
2587            mPositionY += mTextView.viewportToContentVerticalOffset();
2588        }
2589
2590        private void updatePosition(int parentPositionX, int parentPositionY) {
2591            int positionX = parentPositionX + mPositionX;
2592            int positionY = parentPositionY + mPositionY;
2593
2594            positionY = clipVertically(positionY);
2595
2596            // Horizontal clipping
2597            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2598            final int width = mContentView.getMeasuredWidth();
2599            positionX = Math.min(displayMetrics.widthPixels - width, positionX);
2600            positionX = Math.max(0, positionX);
2601
2602            if (isShowing()) {
2603                mPopupWindow.update(positionX, positionY, -1, -1);
2604            } else {
2605                mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
2606                        positionX, positionY);
2607            }
2608        }
2609
2610        public void hide() {
2611            mPopupWindow.dismiss();
2612            getPositionListener().removeSubscriber(this);
2613        }
2614
2615        @Override
2616        public void updatePosition(int parentPositionX, int parentPositionY,
2617                boolean parentPositionChanged, boolean parentScrolled) {
2618            // Either parentPositionChanged or parentScrolled is true, check if still visible
2619            if (isShowing() && isOffsetVisible(getTextOffset())) {
2620                if (parentScrolled) computeLocalPosition();
2621                updatePosition(parentPositionX, parentPositionY);
2622            } else {
2623                hide();
2624            }
2625        }
2626
2627        public boolean isShowing() {
2628            return mPopupWindow.isShowing();
2629        }
2630    }
2631
2632    private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
2633        private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
2634        private static final int ADD_TO_DICTIONARY = -1;
2635        private static final int DELETE_TEXT = -2;
2636        private SuggestionInfo[] mSuggestionInfos;
2637        private int mNumberOfSuggestions;
2638        private boolean mCursorWasVisibleBeforeSuggestions;
2639        private boolean mIsShowingUp = false;
2640        private SuggestionAdapter mSuggestionsAdapter;
2641        private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
2642        private final HashMap<SuggestionSpan, Integer> mSpansLengths;
2643
2644        private class CustomPopupWindow extends PopupWindow {
2645            public CustomPopupWindow(Context context, int defStyleAttr) {
2646                super(context, null, defStyleAttr);
2647            }
2648
2649            @Override
2650            public void dismiss() {
2651                super.dismiss();
2652
2653                getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
2654
2655                // Safe cast since show() checks that mTextView.getText() is an Editable
2656                ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
2657
2658                mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
2659                if (hasInsertionController()) {
2660                    getInsertionController().show();
2661                }
2662            }
2663        }
2664
2665        public SuggestionsPopupWindow() {
2666            mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2667            mSuggestionSpanComparator = new SuggestionSpanComparator();
2668            mSpansLengths = new HashMap<SuggestionSpan, Integer>();
2669        }
2670
2671        @Override
2672        protected void createPopupWindow() {
2673            mPopupWindow = new CustomPopupWindow(mTextView.getContext(),
2674                com.android.internal.R.attr.textSuggestionsWindowStyle);
2675            mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2676            mPopupWindow.setFocusable(true);
2677            mPopupWindow.setClippingEnabled(false);
2678        }
2679
2680        @Override
2681        protected void initContentView() {
2682            ListView listView = new ListView(mTextView.getContext());
2683            mSuggestionsAdapter = new SuggestionAdapter();
2684            listView.setAdapter(mSuggestionsAdapter);
2685            listView.setOnItemClickListener(this);
2686            mContentView = listView;
2687
2688            // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete
2689            mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2];
2690            for (int i = 0; i < mSuggestionInfos.length; i++) {
2691                mSuggestionInfos[i] = new SuggestionInfo();
2692            }
2693        }
2694
2695        public boolean isShowingUp() {
2696            return mIsShowingUp;
2697        }
2698
2699        public void onParentLostFocus() {
2700            mIsShowingUp = false;
2701        }
2702
2703        private class SuggestionInfo {
2704            int suggestionStart, suggestionEnd; // range of actual suggestion within text
2705            SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
2706            int suggestionIndex; // the index of this suggestion inside suggestionSpan
2707            SpannableStringBuilder text = new SpannableStringBuilder();
2708            TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mTextView.getContext(),
2709                    android.R.style.TextAppearance_SuggestionHighlight);
2710        }
2711
2712        private class SuggestionAdapter extends BaseAdapter {
2713            private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
2714                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2715
2716            @Override
2717            public int getCount() {
2718                return mNumberOfSuggestions;
2719            }
2720
2721            @Override
2722            public Object getItem(int position) {
2723                return mSuggestionInfos[position];
2724            }
2725
2726            @Override
2727            public long getItemId(int position) {
2728                return position;
2729            }
2730
2731            @Override
2732            public View getView(int position, View convertView, ViewGroup parent) {
2733                TextView textView = (TextView) convertView;
2734
2735                if (textView == null) {
2736                    textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
2737                            parent, false);
2738                }
2739
2740                final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2741                textView.setText(suggestionInfo.text);
2742
2743                if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY ||
2744                suggestionInfo.suggestionIndex == DELETE_TEXT) {
2745                    textView.setBackgroundColor(Color.TRANSPARENT);
2746                } else {
2747                    textView.setBackgroundColor(Color.WHITE);
2748                }
2749
2750                return textView;
2751            }
2752        }
2753
2754        private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
2755            public int compare(SuggestionSpan span1, SuggestionSpan span2) {
2756                final int flag1 = span1.getFlags();
2757                final int flag2 = span2.getFlags();
2758                if (flag1 != flag2) {
2759                    // The order here should match what is used in updateDrawState
2760                    final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2761                    final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
2762                    final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2763                    final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
2764                    if (easy1 && !misspelled1) return -1;
2765                    if (easy2 && !misspelled2) return 1;
2766                    if (misspelled1) return -1;
2767                    if (misspelled2) return 1;
2768                }
2769
2770                return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
2771            }
2772        }
2773
2774        /**
2775         * Returns the suggestion spans that cover the current cursor position. The suggestion
2776         * spans are sorted according to the length of text that they are attached to.
2777         */
2778        private SuggestionSpan[] getSuggestionSpans() {
2779            int pos = mTextView.getSelectionStart();
2780            Spannable spannable = (Spannable) mTextView.getText();
2781            SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
2782
2783            mSpansLengths.clear();
2784            for (SuggestionSpan suggestionSpan : suggestionSpans) {
2785                int start = spannable.getSpanStart(suggestionSpan);
2786                int end = spannable.getSpanEnd(suggestionSpan);
2787                mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
2788            }
2789
2790            // The suggestions are sorted according to their types (easy correction first, then
2791            // misspelled) and to the length of the text that they cover (shorter first).
2792            Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
2793            return suggestionSpans;
2794        }
2795
2796        @Override
2797        public void show() {
2798            if (!(mTextView.getText() instanceof Editable)) return;
2799
2800            if (updateSuggestions()) {
2801                mCursorWasVisibleBeforeSuggestions = mCursorVisible;
2802                mTextView.setCursorVisible(false);
2803                mIsShowingUp = true;
2804                super.show();
2805            }
2806        }
2807
2808        @Override
2809        protected void measureContent() {
2810            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2811            final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
2812                    displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
2813            final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
2814                    displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
2815
2816            int width = 0;
2817            View view = null;
2818            for (int i = 0; i < mNumberOfSuggestions; i++) {
2819                view = mSuggestionsAdapter.getView(i, view, mContentView);
2820                view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
2821                view.measure(horizontalMeasure, verticalMeasure);
2822                width = Math.max(width, view.getMeasuredWidth());
2823            }
2824
2825            // Enforce the width based on actual text widths
2826            mContentView.measure(
2827                    View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
2828                    verticalMeasure);
2829
2830            Drawable popupBackground = mPopupWindow.getBackground();
2831            if (popupBackground != null) {
2832                if (mTempRect == null) mTempRect = new Rect();
2833                popupBackground.getPadding(mTempRect);
2834                width += mTempRect.left + mTempRect.right;
2835            }
2836            mPopupWindow.setWidth(width);
2837        }
2838
2839        @Override
2840        protected int getTextOffset() {
2841            return mTextView.getSelectionStart();
2842        }
2843
2844        @Override
2845        protected int getVerticalLocalPosition(int line) {
2846            return mTextView.getLayout().getLineBottom(line);
2847        }
2848
2849        @Override
2850        protected int clipVertically(int positionY) {
2851            final int height = mContentView.getMeasuredHeight();
2852            final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2853            return Math.min(positionY, displayMetrics.heightPixels - height);
2854        }
2855
2856        @Override
2857        public void hide() {
2858            super.hide();
2859        }
2860
2861        private boolean updateSuggestions() {
2862            Spannable spannable = (Spannable) mTextView.getText();
2863            SuggestionSpan[] suggestionSpans = getSuggestionSpans();
2864
2865            final int nbSpans = suggestionSpans.length;
2866            // Suggestions are shown after a delay: the underlying spans may have been removed
2867            if (nbSpans == 0) return false;
2868
2869            mNumberOfSuggestions = 0;
2870            int spanUnionStart = mTextView.getText().length();
2871            int spanUnionEnd = 0;
2872
2873            SuggestionSpan misspelledSpan = null;
2874            int underlineColor = 0;
2875
2876            for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
2877                SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
2878                final int spanStart = spannable.getSpanStart(suggestionSpan);
2879                final int spanEnd = spannable.getSpanEnd(suggestionSpan);
2880                spanUnionStart = Math.min(spanStart, spanUnionStart);
2881                spanUnionEnd = Math.max(spanEnd, spanUnionEnd);
2882
2883                if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2884                    misspelledSpan = suggestionSpan;
2885                }
2886
2887                // The first span dictates the background color of the highlighted text
2888                if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor();
2889
2890                String[] suggestions = suggestionSpan.getSuggestions();
2891                int nbSuggestions = suggestions.length;
2892                for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
2893                    String suggestion = suggestions[suggestionIndex];
2894
2895                    boolean suggestionIsDuplicate = false;
2896                    for (int i = 0; i < mNumberOfSuggestions; i++) {
2897                        if (mSuggestionInfos[i].text.toString().equals(suggestion)) {
2898                            SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan;
2899                            final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
2900                            final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
2901                            if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
2902                                suggestionIsDuplicate = true;
2903                                break;
2904                            }
2905                        }
2906                    }
2907
2908                    if (!suggestionIsDuplicate) {
2909                        SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2910                        suggestionInfo.suggestionSpan = suggestionSpan;
2911                        suggestionInfo.suggestionIndex = suggestionIndex;
2912                        suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion);
2913
2914                        mNumberOfSuggestions++;
2915
2916                        if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) {
2917                            // Also end outer for loop
2918                            spanIndex = nbSpans;
2919                            break;
2920                        }
2921                    }
2922                }
2923            }
2924
2925            for (int i = 0; i < mNumberOfSuggestions; i++) {
2926                highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
2927            }
2928
2929            // Add "Add to dictionary" item if there is a span with the misspelled flag
2930            if (misspelledSpan != null) {
2931                final int misspelledStart = spannable.getSpanStart(misspelledSpan);
2932                final int misspelledEnd = spannable.getSpanEnd(misspelledSpan);
2933                if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
2934                    SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2935                    suggestionInfo.suggestionSpan = misspelledSpan;
2936                    suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY;
2937                    suggestionInfo.text.replace(0, suggestionInfo.text.length(), mTextView.
2938                            getContext().getString(com.android.internal.R.string.addToDictionary));
2939                    suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2940                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2941
2942                    mNumberOfSuggestions++;
2943                }
2944            }
2945
2946            // Delete item
2947            SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions];
2948            suggestionInfo.suggestionSpan = null;
2949            suggestionInfo.suggestionIndex = DELETE_TEXT;
2950            suggestionInfo.text.replace(0, suggestionInfo.text.length(),
2951                    mTextView.getContext().getString(com.android.internal.R.string.deleteText));
2952            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0,
2953                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2954            mNumberOfSuggestions++;
2955
2956            if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
2957            if (underlineColor == 0) {
2958                // Fallback on the default highlight color when the first span does not provide one
2959                mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
2960            } else {
2961                final float BACKGROUND_TRANSPARENCY = 0.4f;
2962                final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
2963                mSuggestionRangeSpan.setBackgroundColor(
2964                        (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
2965            }
2966            spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
2967                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2968
2969            mSuggestionsAdapter.notifyDataSetChanged();
2970            return true;
2971        }
2972
2973        private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
2974                int unionEnd) {
2975            final Spannable text = (Spannable) mTextView.getText();
2976            final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan);
2977            final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan);
2978
2979            // Adjust the start/end of the suggestion span
2980            suggestionInfo.suggestionStart = spanStart - unionStart;
2981            suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart
2982                    + suggestionInfo.text.length();
2983
2984            suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0,
2985                    suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2986
2987            // Add the text before and after the span.
2988            final String textAsString = text.toString();
2989            suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart));
2990            suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd));
2991        }
2992
2993        @Override
2994        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2995            Editable editable = (Editable) mTextView.getText();
2996            SuggestionInfo suggestionInfo = mSuggestionInfos[position];
2997
2998            if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
2999                final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
3000                int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
3001                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
3002                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
3003                    if (spanUnionEnd < editable.length() &&
3004                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
3005                            (spanUnionStart == 0 ||
3006                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
3007                        spanUnionEnd = spanUnionEnd + 1;
3008                    }
3009                    mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
3010                }
3011                hide();
3012                return;
3013            }
3014
3015            final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan);
3016            final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan);
3017            if (spanStart < 0 || spanEnd <= spanStart) {
3018                // Span has been removed
3019                hide();
3020                return;
3021            }
3022
3023            final String originalText = editable.toString().substring(spanStart, spanEnd);
3024
3025            if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) {
3026                Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
3027                intent.putExtra("word", originalText);
3028                intent.putExtra("locale", mTextView.getTextServicesLocale().toString());
3029                // Put a listener to replace the original text with a word which the user
3030                // modified in a user dictionary dialog.
3031                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3032                mTextView.getContext().startActivity(intent);
3033                // There is no way to know if the word was indeed added. Re-check.
3034                // TODO The ExtractEditText should remove the span in the original text instead
3035                editable.removeSpan(suggestionInfo.suggestionSpan);
3036                Selection.setSelection(editable, spanEnd);
3037                updateSpellCheckSpans(spanStart, spanEnd, false);
3038            } else {
3039                // SuggestionSpans are removed by replace: save them before
3040                SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
3041                        SuggestionSpan.class);
3042                final int length = suggestionSpans.length;
3043                int[] suggestionSpansStarts = new int[length];
3044                int[] suggestionSpansEnds = new int[length];
3045                int[] suggestionSpansFlags = new int[length];
3046                for (int i = 0; i < length; i++) {
3047                    final SuggestionSpan suggestionSpan = suggestionSpans[i];
3048                    suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
3049                    suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
3050                    suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
3051
3052                    // Remove potential misspelled flags
3053                    int suggestionSpanFlags = suggestionSpan.getFlags();
3054                    if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) {
3055                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
3056                        suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
3057                        suggestionSpan.setFlags(suggestionSpanFlags);
3058                    }
3059                }
3060
3061                final int suggestionStart = suggestionInfo.suggestionStart;
3062                final int suggestionEnd = suggestionInfo.suggestionEnd;
3063                final String suggestion = suggestionInfo.text.subSequence(
3064                        suggestionStart, suggestionEnd).toString();
3065                mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
3066
3067                // Notify source IME of the suggestion pick. Do this before
3068                // swaping texts.
3069                suggestionInfo.suggestionSpan.notifySelection(
3070                        mTextView.getContext(), originalText, suggestionInfo.suggestionIndex);
3071
3072                // Swap text content between actual text and Suggestion span
3073                String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions();
3074                suggestions[suggestionInfo.suggestionIndex] = originalText;
3075
3076                // Restore previous SuggestionSpans
3077                final int lengthDifference = suggestion.length() - (spanEnd - spanStart);
3078                for (int i = 0; i < length; i++) {
3079                    // Only spans that include the modified region make sense after replacement
3080                    // Spans partially included in the replaced region are removed, there is no
3081                    // way to assign them a valid range after replacement
3082                    if (suggestionSpansStarts[i] <= spanStart &&
3083                            suggestionSpansEnds[i] >= spanEnd) {
3084                        mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
3085                                suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]);
3086                    }
3087                }
3088
3089                // Move cursor at the end of the replaced word
3090                final int newCursorPosition = spanEnd + lengthDifference;
3091                mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
3092            }
3093
3094            hide();
3095        }
3096    }
3097
3098    /**
3099     * An ActionMode Callback class that is used to provide actions while in text insertion or
3100     * selection mode.
3101     *
3102     * The default callback provides a subset of Select All, Cut, Copy, Paste, Share and Replace
3103     * actions, depending on which of these this TextView supports and the current selection.
3104     */
3105    private class TextActionModeCallback extends ActionMode.Callback2 {
3106        private final Path mSelectionPath = new Path();
3107        private final RectF mSelectionBounds = new RectF();
3108        private final boolean mHasSelection;
3109
3110        private int mHandleHeight;
3111
3112        public TextActionModeCallback(boolean hasSelection) {
3113            mHasSelection = hasSelection;
3114            if (mHasSelection) {
3115                SelectionModifierCursorController selectionController = getSelectionController();
3116                if (selectionController.mStartHandle == null) {
3117                    // As these are for initializing selectionController, hide() must be called.
3118                    selectionController.initDrawables();
3119                    selectionController.initHandles();
3120                    selectionController.hide();
3121                }
3122                mHandleHeight = Math.max(
3123                        mSelectHandleLeft.getMinimumHeight(),
3124                        mSelectHandleRight.getMinimumHeight());
3125            } else {
3126                InsertionPointCursorController insertionController = getInsertionController();
3127                if (insertionController != null) {
3128                    insertionController.getHandle();
3129                    mHandleHeight = mSelectHandleCenter.getMinimumHeight();
3130                }
3131            }
3132        }
3133
3134        @Override
3135        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
3136            mode.setTitle(null);
3137            mode.setSubtitle(null);
3138            mode.setTitleOptionalHint(true);
3139            populateMenuWithItems(menu);
3140
3141            Callback customCallback = getCustomCallback();
3142            if (customCallback != null) {
3143                if (!customCallback.onCreateActionMode(mode, menu)) {
3144                    // The custom mode can choose to cancel the action mode, dismiss selection.
3145                    Selection.setSelection((Spannable) mTextView.getText(),
3146                            mTextView.getSelectionEnd());
3147                    return false;
3148                }
3149            }
3150
3151            addIntentMenuItemsForTextProcessing(menu);
3152
3153            if (menu.hasVisibleItems() || mode.getCustomView() != null) {
3154                mTextView.setHasTransientState(true);
3155                return true;
3156            } else {
3157                return false;
3158            }
3159        }
3160
3161        private Callback getCustomCallback() {
3162            return mHasSelection
3163                    ? mCustomSelectionActionModeCallback
3164                    : mCustomInsertionActionModeCallback;
3165        }
3166
3167        private void populateMenuWithItems(Menu menu) {
3168            if (mTextView.canCut()) {
3169                menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
3170                        com.android.internal.R.string.cut).
3171                    setAlphabeticShortcut('x').
3172                    setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3173            }
3174
3175            if (mTextView.canCopy()) {
3176                menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
3177                        com.android.internal.R.string.copy).
3178                    setAlphabeticShortcut('c').
3179                    setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3180            }
3181
3182            if (mTextView.canPaste()) {
3183                menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
3184                        com.android.internal.R.string.paste).
3185                    setAlphabeticShortcut('v').
3186                    setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
3187            }
3188
3189            if (mTextView.canShare()) {
3190                menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
3191                        com.android.internal.R.string.share).
3192                    setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3193            }
3194
3195            updateSelectAllItem(menu);
3196            updateReplaceItem(menu);
3197        }
3198
3199        private void addIntentMenuItemsForTextProcessing(Menu menu) {
3200            if (mTextView.canProcessText()) {
3201                PackageManager packageManager = mTextView.getContext().getPackageManager();
3202                List<ResolveInfo> supportedActivities =
3203                        packageManager.queryIntentActivities(createProcessTextIntent(), 0);
3204                for (int i = 0; i < supportedActivities.size(); ++i) {
3205                    ResolveInfo info = supportedActivities.get(i);
3206                    menu.add(Menu.NONE, Menu.NONE,
3207                            MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i,
3208                            info.loadLabel(packageManager))
3209                        .setIntent(createProcessTextIntentForResolveInfo(info))
3210                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3211                }
3212            }
3213        }
3214
3215        private Intent createProcessTextIntent() {
3216            return new Intent()
3217                .setAction(Intent.ACTION_PROCESS_TEXT)
3218                .setType("text/plain");
3219        }
3220
3221        private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
3222            return createProcessTextIntent()
3223                    .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
3224                    .setClassName(info.activityInfo.packageName, info.activityInfo.name);
3225        }
3226
3227        @Override
3228        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
3229            updateSelectAllItem(menu);
3230            updateReplaceItem(menu);
3231
3232            Callback customCallback = getCustomCallback();
3233            if (customCallback != null) {
3234                return customCallback.onPrepareActionMode(mode, menu);
3235            }
3236            return true;
3237        }
3238
3239        private void updateSelectAllItem(Menu menu) {
3240            boolean canSelectAll = mTextView.canSelectAllText();
3241            boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null;
3242            if (canSelectAll && !selectAllItemExists) {
3243                menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
3244                        com.android.internal.R.string.selectAll)
3245                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3246            } else if (!canSelectAll && selectAllItemExists) {
3247                menu.removeItem(TextView.ID_SELECT_ALL);
3248            }
3249        }
3250
3251        private void updateReplaceItem(Menu menu) {
3252            boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
3253            boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3254            if (canReplace && !replaceItemExists) {
3255                menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
3256                        com.android.internal.R.string.replace)
3257                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3258            } else if (!canReplace && replaceItemExists) {
3259                menu.removeItem(TextView.ID_REPLACE);
3260            }
3261        }
3262
3263        @Override
3264        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
3265            if (item.getIntent() != null
3266                    && item.getIntent().getAction().equals(Intent.ACTION_PROCESS_TEXT)) {
3267                item.getIntent().putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText());
3268                mPreserveDetachedSelection = true;
3269                mTextView.startActivityForResult(
3270                        item.getIntent(), TextView.PROCESS_TEXT_REQUEST_CODE);
3271                return true;
3272            }
3273            Callback customCallback = getCustomCallback();
3274            if (customCallback != null && customCallback.onActionItemClicked(mode, item)) {
3275                return true;
3276            }
3277            return mTextView.onTextContextMenuItem(item.getItemId());
3278        }
3279
3280        @Override
3281        public void onDestroyActionMode(ActionMode mode) {
3282            Callback customCallback = getCustomCallback();
3283            if (customCallback != null) {
3284                customCallback.onDestroyActionMode(mode);
3285            }
3286
3287            /*
3288             * If we're ending this mode because we're detaching from a window,
3289             * we still have selection state to preserve. Don't clear it, we'll
3290             * bring back the selection mode when (if) we get reattached.
3291             */
3292            if (!mPreserveDetachedSelection) {
3293                Selection.setSelection((Spannable) mTextView.getText(),
3294                        mTextView.getSelectionEnd());
3295                mTextView.setHasTransientState(false);
3296            }
3297
3298            if (mSelectionModifierCursorController != null) {
3299                mSelectionModifierCursorController.hide();
3300            }
3301
3302            mTextActionMode = null;
3303        }
3304
3305        @Override
3306        public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
3307            if (!view.equals(mTextView) || mTextView.getLayout() == null) {
3308                super.onGetContentRect(mode, view, outRect);
3309                return;
3310            }
3311            if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
3312                // We have a selection.
3313                mSelectionPath.reset();
3314                mTextView.getLayout().getSelectionPath(
3315                        mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
3316                mSelectionPath.computeBounds(mSelectionBounds, true);
3317                mSelectionBounds.bottom += mHandleHeight;
3318            } else if (mCursorCount == 2) {
3319                // We have a split cursor. In this case, we take the rectangle that includes both
3320                // parts of the cursor to ensure we don't obscure either of them.
3321                Rect firstCursorBounds = mCursorDrawable[0].getBounds();
3322                Rect secondCursorBounds = mCursorDrawable[1].getBounds();
3323                mSelectionBounds.set(
3324                        Math.min(firstCursorBounds.left, secondCursorBounds.left),
3325                        Math.min(firstCursorBounds.top, secondCursorBounds.top),
3326                        Math.max(firstCursorBounds.right, secondCursorBounds.right),
3327                        Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom)
3328                                + mHandleHeight);
3329            } else {
3330                // We have a single cursor.
3331                int line = mTextView.getLayout().getLineForOffset(mTextView.getSelectionStart());
3332                float primaryHorizontal =
3333                        mTextView.getLayout().getPrimaryHorizontal(mTextView.getSelectionStart());
3334                mSelectionBounds.set(
3335                        primaryHorizontal,
3336                        mTextView.getLayout().getLineTop(line),
3337                        primaryHorizontal + 1,
3338                        mTextView.getLayout().getLineTop(line + 1) + mHandleHeight);
3339            }
3340            // Take TextView's padding and scroll into account.
3341            int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
3342            int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
3343            outRect.set(
3344                    (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
3345                    (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
3346                    (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
3347                    (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
3348        }
3349    }
3350
3351    /**
3352     * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
3353     * while the input method is requesting the cursor/anchor position. Does nothing as long as
3354     * {@link InputMethodManager#isWatchingCursor(View)} returns false.
3355     */
3356    private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
3357        final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
3358        final int[] mTmpIntOffset = new int[2];
3359        final Matrix mViewToScreenMatrix = new Matrix();
3360
3361        @Override
3362        public void updatePosition(int parentPositionX, int parentPositionY,
3363                boolean parentPositionChanged, boolean parentScrolled) {
3364            final InputMethodState ims = mInputMethodState;
3365            if (ims == null || ims.mBatchEditNesting > 0) {
3366                return;
3367            }
3368            final InputMethodManager imm = InputMethodManager.peekInstance();
3369            if (null == imm) {
3370                return;
3371            }
3372            if (!imm.isActive(mTextView)) {
3373                return;
3374            }
3375            // Skip if the IME has not requested the cursor/anchor position.
3376            if (!imm.isCursorAnchorInfoEnabled()) {
3377                return;
3378            }
3379            Layout layout = mTextView.getLayout();
3380            if (layout == null) {
3381                return;
3382            }
3383
3384            final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
3385            builder.reset();
3386
3387            final int selectionStart = mTextView.getSelectionStart();
3388            builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
3389
3390            // Construct transformation matrix from view local coordinates to screen coordinates.
3391            mViewToScreenMatrix.set(mTextView.getMatrix());
3392            mTextView.getLocationOnScreen(mTmpIntOffset);
3393            mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
3394            builder.setMatrix(mViewToScreenMatrix);
3395
3396            final float viewportToContentHorizontalOffset =
3397                    mTextView.viewportToContentHorizontalOffset();
3398            final float viewportToContentVerticalOffset =
3399                    mTextView.viewportToContentVerticalOffset();
3400
3401            final CharSequence text = mTextView.getText();
3402            if (text instanceof Spannable) {
3403                final Spannable sp = (Spannable) text;
3404                int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
3405                int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
3406                if (composingTextEnd < composingTextStart) {
3407                    final int temp = composingTextEnd;
3408                    composingTextEnd = composingTextStart;
3409                    composingTextStart = temp;
3410                }
3411                final boolean hasComposingText =
3412                        (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
3413                if (hasComposingText) {
3414                    final CharSequence composingText = text.subSequence(composingTextStart,
3415                            composingTextEnd);
3416                    builder.setComposingText(composingTextStart, composingText);
3417
3418                    final int minLine = layout.getLineForOffset(composingTextStart);
3419                    final int maxLine = layout.getLineForOffset(composingTextEnd - 1);
3420                    for (int line = minLine; line <= maxLine; ++line) {
3421                        final int lineStart = layout.getLineStart(line);
3422                        final int lineEnd = layout.getLineEnd(line);
3423                        final int offsetStart = Math.max(lineStart, composingTextStart);
3424                        final int offsetEnd = Math.min(lineEnd, composingTextEnd);
3425                        final boolean ltrLine =
3426                                layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT;
3427                        final float[] widths = new float[offsetEnd - offsetStart];
3428                        layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths);
3429                        final float top = layout.getLineTop(line);
3430                        final float bottom = layout.getLineBottom(line);
3431                        for (int offset = offsetStart; offset < offsetEnd; ++offset) {
3432                            final float charWidth = widths[offset - offsetStart];
3433                            final boolean isRtl = layout.isRtlCharAt(offset);
3434                            final float primary = layout.getPrimaryHorizontal(offset);
3435                            final float secondary = layout.getSecondaryHorizontal(offset);
3436                            // TODO: This doesn't work perfectly for text with custom styles and
3437                            // TAB chars.
3438                            final float left;
3439                            final float right;
3440                            if (ltrLine) {
3441                                if (isRtl) {
3442                                    left = secondary - charWidth;
3443                                    right = secondary;
3444                                } else {
3445                                    left = primary;
3446                                    right = primary + charWidth;
3447                                }
3448                            } else {
3449                                if (!isRtl) {
3450                                    left = secondary;
3451                                    right = secondary + charWidth;
3452                                } else {
3453                                    left = primary - charWidth;
3454                                    right = primary;
3455                                }
3456                            }
3457                            // TODO: Check top-right and bottom-left as well.
3458                            final float localLeft = left + viewportToContentHorizontalOffset;
3459                            final float localRight = right + viewportToContentHorizontalOffset;
3460                            final float localTop = top + viewportToContentVerticalOffset;
3461                            final float localBottom = bottom + viewportToContentVerticalOffset;
3462                            final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop);
3463                            final boolean isBottomRightVisible =
3464                                    isPositionVisible(localRight, localBottom);
3465                            int characterBoundsFlags = 0;
3466                            if (isTopLeftVisible || isBottomRightVisible) {
3467                                characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3468                            }
3469                            if (!isTopLeftVisible || !isBottomRightVisible) {
3470                                characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3471                            }
3472                            if (isRtl) {
3473                                characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3474                            }
3475                            // Here offset is the index in Java chars.
3476                            builder.addCharacterBounds(offset, localLeft, localTop, localRight,
3477                                    localBottom, characterBoundsFlags);
3478                        }
3479                    }
3480                }
3481            }
3482
3483            // Treat selectionStart as the insertion point.
3484            if (0 <= selectionStart) {
3485                final int offset = selectionStart;
3486                final int line = layout.getLineForOffset(offset);
3487                final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
3488                        + viewportToContentHorizontalOffset;
3489                final float insertionMarkerTop = layout.getLineTop(line)
3490                        + viewportToContentVerticalOffset;
3491                final float insertionMarkerBaseline = layout.getLineBaseline(line)
3492                        + viewportToContentVerticalOffset;
3493                final float insertionMarkerBottom = layout.getLineBottom(line)
3494                        + viewportToContentVerticalOffset;
3495                final boolean isTopVisible =
3496                        isPositionVisible(insertionMarkerX, insertionMarkerTop);
3497                final boolean isBottomVisible =
3498                        isPositionVisible(insertionMarkerX, insertionMarkerBottom);
3499                int insertionMarkerFlags = 0;
3500                if (isTopVisible || isBottomVisible) {
3501                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3502                }
3503                if (!isTopVisible || !isBottomVisible) {
3504                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3505                }
3506                if (layout.isRtlCharAt(offset)) {
3507                    insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3508                }
3509                builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
3510                        insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
3511            }
3512
3513            imm.updateCursorAnchorInfo(mTextView, builder.build());
3514        }
3515    }
3516
3517    private abstract class HandleView extends View implements TextViewPositionListener {
3518        protected Drawable mDrawable;
3519        protected Drawable mDrawableLtr;
3520        protected Drawable mDrawableRtl;
3521        private final PopupWindow mContainer;
3522        // Position with respect to the parent TextView
3523        private int mPositionX, mPositionY;
3524        private boolean mIsDragging;
3525        // Offset from touch position to mPosition
3526        private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
3527        protected int mHotspotX;
3528        protected int mHorizontalGravity;
3529        // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
3530        private float mTouchOffsetY;
3531        // Where the touch position should be on the handle to ensure a maximum cursor visibility
3532        private float mIdealVerticalOffset;
3533        // Parent's (TextView) previous position in window
3534        private int mLastParentX, mLastParentY;
3535        // Previous text character offset
3536        protected int mPreviousOffset = -1;
3537        // Previous text character offset
3538        private boolean mPositionHasChanged = true;
3539        // Minimum touch target size for handles
3540        private int mMinSize;
3541        // Indicates the line of text that the handle is on.
3542        protected int mPrevLine = -1;
3543
3544        public HandleView(Drawable drawableLtr, Drawable drawableRtl) {
3545            super(mTextView.getContext());
3546            mContainer = new PopupWindow(mTextView.getContext(), null,
3547                    com.android.internal.R.attr.textSelectHandleWindowStyle);
3548            mContainer.setSplitTouchEnabled(true);
3549            mContainer.setClippingEnabled(false);
3550            mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
3551            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
3552            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
3553            mContainer.setContentView(this);
3554
3555            mDrawableLtr = drawableLtr;
3556            mDrawableRtl = drawableRtl;
3557            mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
3558                    com.android.internal.R.dimen.text_handle_min_size);
3559
3560            updateDrawable();
3561
3562            final int handleHeight = getPreferredHeight();
3563            mTouchOffsetY = -0.3f * handleHeight;
3564            mIdealVerticalOffset = 0.7f * handleHeight;
3565        }
3566
3567        public float getIdealVerticalOffset() {
3568            return mIdealVerticalOffset;
3569        }
3570
3571        protected void updateDrawable() {
3572            if (mIsDragging) {
3573                // Don't update drawable during dragging.
3574                return;
3575            }
3576            final int offset = getCurrentCursorOffset();
3577            final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
3578            final Drawable oldDrawable = mDrawable;
3579            mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
3580            mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
3581            mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
3582            final Layout layout = mTextView.getLayout();
3583            if (layout != null && oldDrawable != mDrawable && isShowing()) {
3584                // Update popup window position.
3585                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX -
3586                        getHorizontalOffset() + getCursorOffset());
3587                mPositionX += mTextView.viewportToContentHorizontalOffset();
3588                mPositionHasChanged = true;
3589                updatePosition(mLastParentX, mLastParentY, false, false);
3590                postInvalidate();
3591            }
3592        }
3593
3594        protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
3595        protected abstract int getHorizontalGravity(boolean isRtlRun);
3596
3597        // Touch-up filter: number of previous positions remembered
3598        private static final int HISTORY_SIZE = 5;
3599        private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
3600        private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
3601        private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
3602        private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
3603        private int mPreviousOffsetIndex = 0;
3604        private int mNumberPreviousOffsets = 0;
3605
3606        private void startTouchUpFilter(int offset) {
3607            mNumberPreviousOffsets = 0;
3608            addPositionToTouchUpFilter(offset);
3609        }
3610
3611        private void addPositionToTouchUpFilter(int offset) {
3612            mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
3613            mPreviousOffsets[mPreviousOffsetIndex] = offset;
3614            mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
3615            mNumberPreviousOffsets++;
3616        }
3617
3618        private void filterOnTouchUp() {
3619            final long now = SystemClock.uptimeMillis();
3620            int i = 0;
3621            int index = mPreviousOffsetIndex;
3622            final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
3623            while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
3624                i++;
3625                index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
3626            }
3627
3628            if (i > 0 && i < iMax &&
3629                    (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
3630                positionAtCursorOffset(mPreviousOffsets[index], false);
3631            }
3632        }
3633
3634        public boolean offsetHasBeenChanged() {
3635            return mNumberPreviousOffsets > 1;
3636        }
3637
3638        @Override
3639        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
3640            setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
3641        }
3642
3643        private int getPreferredWidth() {
3644            return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
3645        }
3646
3647        private int getPreferredHeight() {
3648            return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
3649        }
3650
3651        public void show() {
3652            if (isShowing()) return;
3653
3654            getPositionListener().addSubscriber(this, true /* local position may change */);
3655
3656            // Make sure the offset is always considered new, even when focusing at same position
3657            mPreviousOffset = -1;
3658            positionAtCursorOffset(getCurrentCursorOffset(), false);
3659        }
3660
3661        protected void dismiss() {
3662            mIsDragging = false;
3663            mContainer.dismiss();
3664            onDetached();
3665        }
3666
3667        public void hide() {
3668            dismiss();
3669
3670            getPositionListener().removeSubscriber(this);
3671        }
3672
3673        public boolean isShowing() {
3674            return mContainer.isShowing();
3675        }
3676
3677        private boolean isVisible() {
3678            // Always show a dragging handle.
3679            if (mIsDragging) {
3680                return true;
3681            }
3682
3683            if (mTextView.isInBatchEditMode()) {
3684                return false;
3685            }
3686
3687            return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
3688        }
3689
3690        public abstract int getCurrentCursorOffset();
3691
3692        protected abstract void updateSelection(int offset);
3693
3694        public abstract void updatePosition(float x, float y);
3695
3696        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
3697            // A HandleView relies on the layout, which may be nulled by external methods
3698            Layout layout = mTextView.getLayout();
3699            if (layout == null) {
3700                // Will update controllers' state, hiding them and stopping selection mode if needed
3701                prepareCursorControllers();
3702                return;
3703            }
3704
3705            boolean offsetChanged = offset != mPreviousOffset;
3706            if (offsetChanged || parentScrolled) {
3707                if (offsetChanged) {
3708                    updateSelection(offset);
3709                    addPositionToTouchUpFilter(offset);
3710                }
3711                final int line = layout.getLineForOffset(offset);
3712                mPrevLine = line;
3713
3714                mPositionX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX -
3715                        getHorizontalOffset() + getCursorOffset());
3716                mPositionY = layout.getLineBottom(line);
3717
3718                // Take TextView's padding and scroll into account.
3719                mPositionX += mTextView.viewportToContentHorizontalOffset();
3720                mPositionY += mTextView.viewportToContentVerticalOffset();
3721
3722                mPreviousOffset = offset;
3723                mPositionHasChanged = true;
3724            }
3725        }
3726
3727        public void updatePosition(int parentPositionX, int parentPositionY,
3728                boolean parentPositionChanged, boolean parentScrolled) {
3729            positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
3730            if (parentPositionChanged || mPositionHasChanged) {
3731                if (mIsDragging) {
3732                    // Update touchToWindow offset in case of parent scrolling while dragging
3733                    if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
3734                        mTouchToWindowOffsetX += parentPositionX - mLastParentX;
3735                        mTouchToWindowOffsetY += parentPositionY - mLastParentY;
3736                        mLastParentX = parentPositionX;
3737                        mLastParentY = parentPositionY;
3738                    }
3739
3740                    onHandleMoved();
3741                }
3742
3743                if (isVisible()) {
3744                    final int positionX = parentPositionX + mPositionX;
3745                    final int positionY = parentPositionY + mPositionY;
3746                    if (isShowing()) {
3747                        mContainer.update(positionX, positionY, -1, -1);
3748                    } else {
3749                        mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3750                                positionX, positionY);
3751                    }
3752                } else {
3753                    if (isShowing()) {
3754                        dismiss();
3755                    }
3756                }
3757
3758                mPositionHasChanged = false;
3759            }
3760        }
3761
3762        public void showAtLocation(int offset) {
3763            // TODO - investigate if there's a better way to show the handles
3764            // after the drag accelerator has occured.
3765            int[] tmpCords = new int[2];
3766            mTextView.getLocationInWindow(tmpCords);
3767
3768            Layout layout = mTextView.getLayout();
3769            int posX = tmpCords[0];
3770            int posY = tmpCords[1];
3771
3772            final int line = layout.getLineForOffset(offset);
3773
3774            int startX = (int) (layout.getPrimaryHorizontal(offset) - 0.5f
3775                    - mHotspotX - getHorizontalOffset() + getCursorOffset());
3776            int startY = layout.getLineBottom(line);
3777
3778            // Take TextView's padding and scroll into account.
3779            startX += mTextView.viewportToContentHorizontalOffset();
3780            startY += mTextView.viewportToContentVerticalOffset();
3781
3782            mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3783                    startX + posX, startY + posY);
3784        }
3785
3786        @Override
3787        protected void onDraw(Canvas c) {
3788            final int drawWidth = mDrawable.getIntrinsicWidth();
3789            final int left = getHorizontalOffset();
3790
3791            mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
3792            mDrawable.draw(c);
3793        }
3794
3795        private int getHorizontalOffset() {
3796            final int width = getPreferredWidth();
3797            final int drawWidth = mDrawable.getIntrinsicWidth();
3798            final int left;
3799            switch (mHorizontalGravity) {
3800                case Gravity.LEFT:
3801                    left = 0;
3802                    break;
3803                default:
3804                case Gravity.CENTER:
3805                    left = (width - drawWidth) / 2;
3806                    break;
3807                case Gravity.RIGHT:
3808                    left = width - drawWidth;
3809                    break;
3810            }
3811            return left;
3812        }
3813
3814        protected int getCursorOffset() {
3815            return 0;
3816        }
3817
3818        @Override
3819        public boolean onTouchEvent(MotionEvent ev) {
3820            updateFloatingToolbarVisibility(ev);
3821
3822            switch (ev.getActionMasked()) {
3823                case MotionEvent.ACTION_DOWN: {
3824                    startTouchUpFilter(getCurrentCursorOffset());
3825                    mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
3826                    mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
3827
3828                    final PositionListener positionListener = getPositionListener();
3829                    mLastParentX = positionListener.getPositionX();
3830                    mLastParentY = positionListener.getPositionY();
3831                    mIsDragging = true;
3832                    break;
3833                }
3834
3835                case MotionEvent.ACTION_MOVE: {
3836                    final float rawX = ev.getRawX();
3837                    final float rawY = ev.getRawY();
3838
3839                    // Vertical hysteresis: vertical down movement tends to snap to ideal offset
3840                    final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
3841                    final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
3842                    float newVerticalOffset;
3843                    if (previousVerticalOffset < mIdealVerticalOffset) {
3844                        newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
3845                        newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
3846                    } else {
3847                        newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
3848                        newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
3849                    }
3850                    mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
3851
3852                    final float newPosX =
3853                            rawX - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
3854                    final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
3855
3856                    updatePosition(newPosX, newPosY);
3857                    break;
3858                }
3859
3860                case MotionEvent.ACTION_UP:
3861                    filterOnTouchUp();
3862                    mIsDragging = false;
3863                    updateDrawable();
3864                    break;
3865
3866                case MotionEvent.ACTION_CANCEL:
3867                    mIsDragging = false;
3868                    updateDrawable();
3869                    break;
3870            }
3871            return true;
3872        }
3873
3874        public boolean isDragging() {
3875            return mIsDragging;
3876        }
3877
3878        void onHandleMoved() {}
3879
3880        public void onDetached() {}
3881    }
3882
3883    private class InsertionHandleView extends HandleView {
3884        private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
3885        private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
3886
3887        // Used to detect taps on the insertion handle, which will affect the insertion action mode
3888        private float mDownPositionX, mDownPositionY;
3889        private Runnable mHider;
3890
3891        public InsertionHandleView(Drawable drawable) {
3892            super(drawable, drawable);
3893        }
3894
3895        @Override
3896        public void show() {
3897            super.show();
3898
3899            final long durationSinceCutOrCopy =
3900                    SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
3901
3902            // Cancel the single tap delayed runnable.
3903            if (mInsertionActionModeRunnable != null
3904                    && (mDoubleTap || isCursorInsideEasyCorrectionSpan())) {
3905                mTextView.removeCallbacks(mInsertionActionModeRunnable);
3906            }
3907
3908            // Prepare and schedule the single tap runnable to run exactly after the double tap
3909            // timeout has passed.
3910            if (!mDoubleTap && !isCursorInsideEasyCorrectionSpan()
3911                    && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
3912                if (mTextActionMode == null) {
3913                    if (mInsertionActionModeRunnable == null) {
3914                        mInsertionActionModeRunnable = new Runnable() {
3915                            @Override
3916                            public void run() {
3917                                startInsertionActionMode();
3918                            }
3919                        };
3920                    }
3921                    mTextView.postDelayed(
3922                            mInsertionActionModeRunnable,
3923                            ViewConfiguration.getDoubleTapTimeout() + 1);
3924                }
3925
3926            }
3927
3928            hideAfterDelay();
3929        }
3930
3931        private void hideAfterDelay() {
3932            if (mHider == null) {
3933                mHider = new Runnable() {
3934                    public void run() {
3935                        hide();
3936                    }
3937                };
3938            } else {
3939                removeHiderCallback();
3940            }
3941            mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
3942        }
3943
3944        private void removeHiderCallback() {
3945            if (mHider != null) {
3946                mTextView.removeCallbacks(mHider);
3947            }
3948        }
3949
3950        @Override
3951        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
3952            return drawable.getIntrinsicWidth() / 2;
3953        }
3954
3955        @Override
3956        protected int getHorizontalGravity(boolean isRtlRun) {
3957            return Gravity.CENTER_HORIZONTAL;
3958        }
3959
3960        @Override
3961        protected int getCursorOffset() {
3962            int offset = super.getCursorOffset();
3963            final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
3964            if (cursor != null) {
3965                cursor.getPadding(mTempRect);
3966                offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
3967            }
3968            return offset;
3969        }
3970
3971        @Override
3972        public boolean onTouchEvent(MotionEvent ev) {
3973            final boolean result = super.onTouchEvent(ev);
3974
3975            switch (ev.getActionMasked()) {
3976                case MotionEvent.ACTION_DOWN:
3977                    mDownPositionX = ev.getRawX();
3978                    mDownPositionY = ev.getRawY();
3979                    break;
3980
3981                case MotionEvent.ACTION_UP:
3982                    if (!offsetHasBeenChanged()) {
3983                        final float deltaX = mDownPositionX - ev.getRawX();
3984                        final float deltaY = mDownPositionY - ev.getRawY();
3985                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
3986
3987                        final ViewConfiguration viewConfiguration = ViewConfiguration.get(
3988                                mTextView.getContext());
3989                        final int touchSlop = viewConfiguration.getScaledTouchSlop();
3990
3991                        if (distanceSquared < touchSlop * touchSlop) {
3992                            // Tapping on the handle toggles the insertion action mode.
3993                            if (mTextActionMode != null) {
3994                                mTextActionMode.finish();
3995                            } else {
3996                                startInsertionActionMode();
3997                            }
3998                        }
3999                    } else {
4000                        if (mTextActionMode != null) {
4001                            mTextActionMode.invalidateContentRect();
4002                        }
4003                    }
4004                    hideAfterDelay();
4005                    break;
4006
4007                case MotionEvent.ACTION_CANCEL:
4008                    hideAfterDelay();
4009                    break;
4010
4011                default:
4012                    break;
4013            }
4014
4015            return result;
4016        }
4017
4018        @Override
4019        public int getCurrentCursorOffset() {
4020            return mTextView.getSelectionStart();
4021        }
4022
4023        @Override
4024        public void updateSelection(int offset) {
4025            Selection.setSelection((Spannable) mTextView.getText(), offset);
4026        }
4027
4028        @Override
4029        public void updatePosition(float x, float y) {
4030            Layout layout = mTextView.getLayout();
4031            int offset;
4032            if (layout != null) {
4033                int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
4034                offset = mTextView.getOffsetAtCoordinate(currLine, x);
4035            } else {
4036                offset = mTextView.getOffsetForPosition(x, y);
4037            }
4038            positionAtCursorOffset(offset, false);
4039            if (mTextActionMode != null) {
4040                mTextActionMode.invalidate();
4041            }
4042        }
4043
4044        @Override
4045        void onHandleMoved() {
4046            super.onHandleMoved();
4047            removeHiderCallback();
4048        }
4049
4050        @Override
4051        public void onDetached() {
4052            super.onDetached();
4053            removeHiderCallback();
4054        }
4055    }
4056
4057    private class SelectionStartHandleView extends HandleView {
4058        // Indicates whether the cursor is making adjustments within a word.
4059        private boolean mInWord = false;
4060        // Difference between touch position and word boundary position.
4061        private float mTouchWordDelta;
4062        // X value of the previous updatePosition call.
4063        private float mPrevX;
4064        // Indicates if the handle has moved a boundary between LTR and RTL text.
4065        private boolean mLanguageDirectionChanged = false;
4066
4067        public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) {
4068            super(drawableLtr, drawableRtl);
4069        }
4070
4071        @Override
4072        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4073            if (isRtlRun) {
4074                return drawable.getIntrinsicWidth() / 4;
4075            } else {
4076                return (drawable.getIntrinsicWidth() * 3) / 4;
4077            }
4078        }
4079
4080        @Override
4081        protected int getHorizontalGravity(boolean isRtlRun) {
4082            return isRtlRun ? Gravity.LEFT : Gravity.RIGHT;
4083        }
4084
4085        @Override
4086        public int getCurrentCursorOffset() {
4087            return mTextView.getSelectionStart();
4088        }
4089
4090        @Override
4091        public void updateSelection(int offset) {
4092            Selection.setSelection((Spannable) mTextView.getText(), offset,
4093                    mTextView.getSelectionEnd());
4094            updateDrawable();
4095            if (mTextActionMode != null) {
4096                mTextActionMode.invalidate();
4097            }
4098        }
4099
4100        @Override
4101        public void updatePosition(float x, float y) {
4102            final Layout layout = mTextView.getLayout();
4103            if (layout == null) {
4104                // HandleView will deal appropriately in positionAtCursorOffset when
4105                // layout is null.
4106                positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
4107                return;
4108            }
4109
4110            boolean positionCursor = false;
4111            final int selectionEnd = mTextView.getSelectionEnd();
4112            int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
4113            int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4114
4115            if (initialOffset >= selectionEnd) {
4116                // Handles have crossed, bound it to the last selected line and
4117                // adjust by word / char as normal.
4118                currLine = layout.getLineForOffset(selectionEnd);
4119                initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4120            }
4121
4122            int offset = initialOffset;
4123            int end = getWordEnd(offset);
4124            int start = getWordStart(offset);
4125
4126            if (mPrevX == UNSET_X_VALUE) {
4127                mPrevX = x;
4128            }
4129
4130            final int selectionStart = mTextView.getSelectionStart();
4131            final boolean selectionStartRtl = layout.isRtlCharAt(selectionStart);
4132            final boolean atRtl = layout.isRtlCharAt(offset);
4133            final boolean isLvlBoundary = layout.isLevelBoundary(offset);
4134            boolean isExpanding;
4135
4136            // We can't determine if the user is expanding or shrinking the selection if they're
4137            // on a bi-di boundary, so until they've moved past the boundary we'll just place
4138            // the cursor at the current position.
4139            if (isLvlBoundary || (selectionStartRtl && !atRtl) || (!selectionStartRtl && atRtl)) {
4140                // We're on a boundary or this is the first direction change -- just update
4141                // to the current position.
4142                mLanguageDirectionChanged = true;
4143                mTouchWordDelta = 0.0f;
4144                positionAtCursorOffset(offset, false);
4145                return;
4146            } else if (mLanguageDirectionChanged && !isLvlBoundary) {
4147                // We've just moved past the boundary so update the position. After this we can
4148                // figure out if the user is expanding or shrinking to go by word or character.
4149                positionAtCursorOffset(offset, false);
4150                mTouchWordDelta = 0.0f;
4151                mLanguageDirectionChanged = false;
4152                return;
4153            } else {
4154                final float xDiff = x - mPrevX;
4155                if (atRtl) {
4156                    isExpanding = xDiff > 0 || currLine > mPrevLine;
4157                } else {
4158                    isExpanding = xDiff < 0 || currLine < mPrevLine;
4159                }
4160            }
4161
4162            if (isExpanding) {
4163                // User is increasing the selection.
4164                if (!mInWord || currLine < mPrevLine) {
4165                    // We're not in a word, or we're on a different line so we'll expand by
4166                    // word. First ensure the user has at least entered the next word.
4167                    int offsetToWord = Math.min((end - start) / 2, 2);
4168                    if (offset <= end - offsetToWord || currLine < mPrevLine) {
4169                        offset = start;
4170                    } else {
4171                        offset = mPreviousOffset;
4172                    }
4173                }
4174                if (layout != null && offset < initialOffset) {
4175                    final float adjustedX = layout.getPrimaryHorizontal(offset);
4176                    mTouchWordDelta =
4177                            mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4178                } else {
4179                    mTouchWordDelta = 0.0f;
4180                }
4181                positionCursor = true;
4182            } else {
4183                final int adjustedOffset =
4184                        mTextView.getOffsetAtCoordinate(currLine, x - mTouchWordDelta);
4185                if (adjustedOffset > mPreviousOffset || currLine > mPrevLine) {
4186                    // User is shrinking the selection.
4187                    if (currLine > mPrevLine) {
4188                        // We're on a different line, so we'll snap to word boundaries.
4189                        offset = start;
4190                        if (layout != null && offset < initialOffset) {
4191                            final float adjustedX = layout.getPrimaryHorizontal(offset);
4192                            mTouchWordDelta =
4193                                    mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4194                        } else {
4195                            mTouchWordDelta = 0.0f;
4196                        }
4197                    } else {
4198                        offset = adjustedOffset;
4199                    }
4200                    positionCursor = true;
4201                } else if (adjustedOffset < mPreviousOffset) {
4202                    // Handle has jumped to the start of the word, and the user is moving
4203                    // their finger towards the handle, the delta should be updated.
4204                    mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x)
4205                            - layout.getPrimaryHorizontal(mPreviousOffset);
4206                }
4207            }
4208
4209            if (positionCursor) {
4210                // Handles can not cross and selection is at least one character.
4211                if (offset >= selectionEnd) {
4212                    offset = getNextCursorOffset(selectionEnd, false);
4213                    mTouchWordDelta = 0.0f;
4214                }
4215                positionAtCursorOffset(offset, false);
4216            }
4217            mPrevX = x;
4218        }
4219
4220        @Override
4221        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4222            super.positionAtCursorOffset(offset, parentScrolled);
4223            mInWord = !getWordIteratorWithText().isBoundary(offset);
4224        }
4225
4226        @Override
4227        public boolean onTouchEvent(MotionEvent event) {
4228            boolean superResult = super.onTouchEvent(event);
4229            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
4230                // Reset the touch word offset when the user has lifted their finger.
4231                mTouchWordDelta = 0.0f;
4232                mPrevX = UNSET_X_VALUE;
4233            }
4234            return superResult;
4235        }
4236    }
4237
4238    private class SelectionEndHandleView extends HandleView {
4239        // Indicates whether the cursor is making adjustments within a word.
4240        private boolean mInWord = false;
4241        // Difference between touch position and word boundary position.
4242        private float mTouchWordDelta;
4243        // X value of the previous updatePosition call.
4244        private float mPrevX;
4245        // Indicates if the handle has moved a boundary between LTR and RTL text.
4246        private boolean mLanguageDirectionChanged = false;
4247
4248        public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) {
4249            super(drawableLtr, drawableRtl);
4250        }
4251
4252        @Override
4253        protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4254            if (isRtlRun) {
4255                return (drawable.getIntrinsicWidth() * 3) / 4;
4256            } else {
4257                return drawable.getIntrinsicWidth() / 4;
4258            }
4259        }
4260
4261        @Override
4262        protected int getHorizontalGravity(boolean isRtlRun) {
4263            return isRtlRun ? Gravity.RIGHT : Gravity.LEFT;
4264        }
4265
4266        @Override
4267        public int getCurrentCursorOffset() {
4268            return mTextView.getSelectionEnd();
4269        }
4270
4271        @Override
4272        public void updateSelection(int offset) {
4273            Selection.setSelection((Spannable) mTextView.getText(),
4274                    mTextView.getSelectionStart(), offset);
4275            if (mTextActionMode != null) {
4276                mTextActionMode.invalidate();
4277            }
4278            updateDrawable();
4279        }
4280
4281        @Override
4282        public void updatePosition(float x, float y) {
4283            final Layout layout = mTextView.getLayout();
4284            if (layout == null) {
4285                // HandleView will deal appropriately in positionAtCursorOffset when
4286                // layout is null.
4287                positionAtCursorOffset(mTextView.getOffsetForPosition(x, y), false);
4288                return;
4289            }
4290
4291            boolean positionCursor = false;
4292            final int selectionStart = mTextView.getSelectionStart();
4293            int currLine = getCurrentLineAdjustedForSlop(layout, mPrevLine, y);
4294            int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4295
4296            if (initialOffset <= selectionStart) {
4297                // Handles have crossed, bound it to the first selected line and
4298                // adjust by word / char as normal.
4299                currLine = layout.getLineForOffset(selectionStart);
4300                initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4301            }
4302
4303            int offset = initialOffset;
4304            int end = getWordEnd(offset);
4305            int start = getWordStart(offset);
4306
4307            if (mPrevX == UNSET_X_VALUE) {
4308                mPrevX = x;
4309            }
4310
4311            final int selectionEnd = mTextView.getSelectionEnd();
4312            final boolean selectionEndRtl = layout.isRtlCharAt(selectionEnd);
4313            final boolean atRtl = layout.isRtlCharAt(offset);
4314            final boolean isLvlBoundary = layout.isLevelBoundary(offset);
4315            boolean isExpanding;
4316
4317            // We can't determine if the user is expanding or shrinking the selection if they're
4318            // on a bi-di boundary, so until they've moved past the boundary we'll just place
4319            // the cursor at the current position.
4320            if (isLvlBoundary || (selectionEndRtl && !atRtl) || (!selectionEndRtl && atRtl)) {
4321                // We're on a boundary or this is the first direction change -- just update
4322                // to the current position.
4323                mLanguageDirectionChanged = true;
4324                mTouchWordDelta = 0.0f;
4325                positionAtCursorOffset(offset, false);
4326                return;
4327            } else if (mLanguageDirectionChanged && !isLvlBoundary) {
4328                // We've just moved past the boundary so update the position. After this we can
4329                // figure out if the user is expanding or shrinking to go by word or character.
4330                positionAtCursorOffset(offset, false);
4331                mTouchWordDelta = 0.0f;
4332                mLanguageDirectionChanged = false;
4333                return;
4334            } else {
4335                final float xDiff = x - mPrevX;
4336                if (atRtl) {
4337                    isExpanding = xDiff < 0 || currLine < mPrevLine;
4338                } else {
4339                    isExpanding = xDiff > 0 || currLine > mPrevLine;
4340                }
4341            }
4342
4343            if (isExpanding) {
4344                // User is increasing the selection.
4345                if (!mInWord || currLine > mPrevLine) {
4346                    // We're not in a word, or we're on a different line so we'll expand by
4347                    // word. First ensure the user has at least entered the next word.
4348                    int midPoint = Math.min((end - start) / 2, 2);
4349                    if (offset >= start + midPoint || currLine > mPrevLine) {
4350                        offset = end;
4351                    } else {
4352                        offset = mPreviousOffset;
4353                    }
4354                }
4355                if (offset > initialOffset) {
4356                    final float adjustedX = layout.getPrimaryHorizontal(offset);
4357                    mTouchWordDelta =
4358                            adjustedX - mTextView.convertToLocalHorizontalCoordinate(x);
4359                } else {
4360                    mTouchWordDelta = 0.0f;
4361                }
4362                positionCursor = true;
4363            } else {
4364                final int adjustedOffset =
4365                        mTextView.getOffsetAtCoordinate(currLine, x + mTouchWordDelta);
4366                if (adjustedOffset < mPreviousOffset || currLine < mPrevLine) {
4367                    // User is shrinking the selection.
4368                    if (currLine < mPrevLine) {
4369                        // We're on a different line, so we'll snap to word boundaries.
4370                        offset = end;
4371                        if (offset > initialOffset) {
4372                            final float adjustedX = layout.getPrimaryHorizontal(offset);
4373                            mTouchWordDelta =
4374                                    adjustedX - mTextView.convertToLocalHorizontalCoordinate(x);
4375                        } else {
4376                            mTouchWordDelta = 0.0f;
4377                        }
4378                    } else {
4379                        offset = adjustedOffset;
4380                    }
4381                    positionCursor = true;
4382                } else if (adjustedOffset > mPreviousOffset) {
4383                    // Handle has jumped to the end of the word, and the user is moving
4384                    // their finger towards the handle, the delta should be updated.
4385                    mTouchWordDelta = layout.getPrimaryHorizontal(mPreviousOffset)
4386                            - mTextView.convertToLocalHorizontalCoordinate(x);
4387                }
4388            }
4389
4390            if (positionCursor) {
4391                // Handles can not cross and selection is at least one character.
4392                if (offset <= selectionStart) {
4393                    offset = getNextCursorOffset(selectionStart, true);
4394                    mTouchWordDelta = 0.0f;
4395                }
4396                positionAtCursorOffset(offset, false);
4397            }
4398            mPrevX = x;
4399        }
4400
4401        @Override
4402        protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4403            super.positionAtCursorOffset(offset, parentScrolled);
4404            mInWord = !getWordIteratorWithText().isBoundary(offset);
4405        }
4406
4407        @Override
4408        public boolean onTouchEvent(MotionEvent event) {
4409            boolean superResult = super.onTouchEvent(event);
4410            if (event.getActionMasked() == MotionEvent.ACTION_UP) {
4411                // Reset the touch word offset when the user has lifted their finger.
4412                mTouchWordDelta = 0.0f;
4413                mPrevX = UNSET_X_VALUE;
4414            }
4415            return superResult;
4416        }
4417    }
4418
4419    private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
4420        if (layout == null || prevLine > layout.getLineCount()
4421                || layout.getLineCount() <= 0 || prevLine < 0) {
4422            // Invalid parameters, just return whatever line is at y.
4423            return mTextView.getLineAtCoordinate(y);
4424        }
4425
4426        final float verticalOffset = mTextView.viewportToContentVerticalOffset();
4427        final int lineCount = layout.getLineCount();
4428        final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
4429
4430        final float firstLineTop = layout.getLineTop(0) + verticalOffset;
4431        final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
4432        final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
4433
4434        final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
4435        final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
4436        final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
4437
4438        // Determine if we've moved lines based on y position and previous line.
4439        int currLine;
4440        if (y <= yTopBound) {
4441            currLine = Math.max(prevLine - 1, 0);
4442        } else if (y >= yBottomBound) {
4443            currLine = Math.min(prevLine + 1, lineCount - 1);
4444        } else {
4445            currLine = prevLine;
4446        }
4447        return currLine;
4448    }
4449
4450    /**
4451     * A CursorController instance can be used to control a cursor in the text.
4452     */
4453    private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
4454        /**
4455         * Makes the cursor controller visible on screen.
4456         * See also {@link #hide()}.
4457         */
4458        public void show();
4459
4460        /**
4461         * Hide the cursor controller from screen.
4462         * See also {@link #show()}.
4463         */
4464        public void hide();
4465
4466        /**
4467         * Called when the view is detached from window. Perform house keeping task, such as
4468         * stopping Runnable thread that would otherwise keep a reference on the context, thus
4469         * preventing the activity from being recycled.
4470         */
4471        public void onDetached();
4472    }
4473
4474    private class InsertionPointCursorController implements CursorController {
4475        private InsertionHandleView mHandle;
4476
4477        public void show() {
4478            getHandle().show();
4479
4480            if (mSelectionModifierCursorController != null) {
4481                mSelectionModifierCursorController.hide();
4482            }
4483        }
4484
4485        public void hide() {
4486            if (mHandle != null) {
4487                mHandle.hide();
4488            }
4489        }
4490
4491        public void onTouchModeChanged(boolean isInTouchMode) {
4492            if (!isInTouchMode) {
4493                hide();
4494            }
4495        }
4496
4497        private InsertionHandleView getHandle() {
4498            if (mSelectHandleCenter == null) {
4499                mSelectHandleCenter = mTextView.getContext().getDrawable(
4500                        mTextView.mTextSelectHandleRes);
4501            }
4502            if (mHandle == null) {
4503                mHandle = new InsertionHandleView(mSelectHandleCenter);
4504            }
4505            return mHandle;
4506        }
4507
4508        @Override
4509        public void onDetached() {
4510            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4511            observer.removeOnTouchModeChangeListener(this);
4512
4513            if (mHandle != null) mHandle.onDetached();
4514        }
4515    }
4516
4517    class SelectionModifierCursorController implements CursorController {
4518        // The cursor controller handles, lazily created when shown.
4519        private SelectionStartHandleView mStartHandle;
4520        private SelectionEndHandleView mEndHandle;
4521        // The offsets of that last touch down event. Remembered to start selection there.
4522        private int mMinTouchOffset, mMaxTouchOffset;
4523
4524        private float mDownPositionX, mDownPositionY;
4525        private boolean mGestureStayedInTapRegion;
4526
4527        // Where the user first starts the drag motion.
4528        private int mStartOffset = -1;
4529        // Indicates whether the user is selecting text and using the drag accelerator.
4530        private boolean mDragAcceleratorActive;
4531        private boolean mHaventMovedEnoughToStartDrag;
4532        // The line that a selection happened most recently with the drag accelerator.
4533        private int mLineSelectionIsOn = -1;
4534        // Whether the drag accelerator has selected past the initial line.
4535        private boolean mSwitchedLines = false;
4536
4537        SelectionModifierCursorController() {
4538            resetTouchOffsets();
4539        }
4540
4541        public void show() {
4542            if (mTextView.isInBatchEditMode()) {
4543                return;
4544            }
4545            initDrawables();
4546            initHandles();
4547            hideInsertionPointCursorController();
4548        }
4549
4550        private void initDrawables() {
4551            if (mSelectHandleLeft == null) {
4552                mSelectHandleLeft = mTextView.getContext().getDrawable(
4553                        mTextView.mTextSelectHandleLeftRes);
4554            }
4555            if (mSelectHandleRight == null) {
4556                mSelectHandleRight = mTextView.getContext().getDrawable(
4557                        mTextView.mTextSelectHandleRightRes);
4558            }
4559        }
4560
4561        private void initHandles() {
4562            // Lazy object creation has to be done before updatePosition() is called.
4563            if (mStartHandle == null) {
4564                mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight);
4565            }
4566            if (mEndHandle == null) {
4567                mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft);
4568            }
4569
4570            mStartHandle.show();
4571            mEndHandle.show();
4572
4573            hideInsertionPointCursorController();
4574        }
4575
4576        public void hide() {
4577            if (mStartHandle != null) mStartHandle.hide();
4578            if (mEndHandle != null) mEndHandle.hide();
4579        }
4580
4581        public void enterDrag() {
4582            // Just need to init the handles / hide insertion cursor.
4583            show();
4584            mDragAcceleratorActive = true;
4585            // Start location of selection.
4586            mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
4587                    mLastDownPositionY);
4588            mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
4589            // Don't show the handles until user has lifted finger.
4590            hide();
4591
4592            // This stops scrolling parents from intercepting the touch event, allowing
4593            // the user to continue dragging across the screen to select text; TextView will
4594            // scroll as necessary.
4595            mTextView.getParent().requestDisallowInterceptTouchEvent(true);
4596        }
4597
4598        public void onTouchEvent(MotionEvent event) {
4599            // This is done even when the View does not have focus, so that long presses can start
4600            // selection and tap can move cursor from this tap position.
4601            final float eventX = event.getX();
4602            final float eventY = event.getY();
4603            switch (event.getActionMasked()) {
4604                case MotionEvent.ACTION_DOWN:
4605
4606                    // Remember finger down position, to be able to start selection from there.
4607                    mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
4608                            eventX, eventY);
4609
4610                    // Double tap detection
4611                    if (mGestureStayedInTapRegion) {
4612                        if (mDoubleTap) {
4613                            final float deltaX = eventX - mDownPositionX;
4614                            final float deltaY = eventY - mDownPositionY;
4615                            final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4616
4617                            ViewConfiguration viewConfiguration = ViewConfiguration.get(
4618                                    mTextView.getContext());
4619                            int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
4620                            boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop;
4621
4622                            if (stayedInArea && isPositionOnText(eventX, eventY)) {
4623                                selectCurrentWordAndStartDrag();
4624                                mDiscardNextActionUp = true;
4625                            }
4626                        }
4627                    }
4628
4629                    mDownPositionX = eventX;
4630                    mDownPositionY = eventY;
4631                    mGestureStayedInTapRegion = true;
4632                    mHaventMovedEnoughToStartDrag = true;
4633                    break;
4634
4635                case MotionEvent.ACTION_POINTER_DOWN:
4636                case MotionEvent.ACTION_POINTER_UP:
4637                    // Handle multi-point gestures. Keep min and max offset positions.
4638                    // Only activated for devices that correctly handle multi-touch.
4639                    if (mTextView.getContext().getPackageManager().hasSystemFeature(
4640                            PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
4641                        updateMinAndMaxOffsets(event);
4642                    }
4643                    break;
4644
4645                case MotionEvent.ACTION_MOVE:
4646                    final ViewConfiguration viewConfig = ViewConfiguration.get(
4647                            mTextView.getContext());
4648                    final int touchSlop = viewConfig.getScaledTouchSlop();
4649
4650                    if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
4651                        final float deltaX = eventX - mDownPositionX;
4652                        final float deltaY = eventY - mDownPositionY;
4653                        final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4654
4655                        if (mGestureStayedInTapRegion) {
4656                            int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
4657                            mGestureStayedInTapRegion =
4658                                    distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
4659                        }
4660                        if (mHaventMovedEnoughToStartDrag) {
4661                            // We don't start dragging until the user has moved enough.
4662                            mHaventMovedEnoughToStartDrag =
4663                                    distanceSquared <= touchSlop * touchSlop;
4664                        }
4665                    }
4666
4667                    if (mStartHandle != null && mStartHandle.isShowing()) {
4668                        // Don't do the drag if the handles are showing already.
4669                        break;
4670                    }
4671
4672                    if (mStartOffset != -1 && mTextView.getLayout() != null) {
4673                        if (!mHaventMovedEnoughToStartDrag) {
4674
4675                            float y = eventY;
4676                            if (mSwitchedLines) {
4677                                // Offset the finger by the same vertical offset as the handles.
4678                                // This improves visibility of the content being selected by
4679                                // shifting the finger below the content, this is applied once
4680                                // the user has switched lines.
4681                                final float fingerOffset = (mStartHandle != null)
4682                                        ? mStartHandle.getIdealVerticalOffset()
4683                                        : touchSlop;
4684                                y = eventY - fingerOffset;
4685                            }
4686
4687                            final int currLine = getCurrentLineAdjustedForSlop(
4688                                    mTextView.getLayout(),
4689                                    mLineSelectionIsOn, y);
4690                            if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
4691                                // Break early here, we want to offset the finger position from
4692                                // the selection highlight, once the user moved their finger
4693                                // to a different line we should apply the offset and *not* switch
4694                                // lines until recomputing the position with the finger offset.
4695                                mSwitchedLines = true;
4696                                break;
4697                            }
4698
4699                            int startOffset;
4700                            int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
4701                            // Snap to word boundaries.
4702                            if (mStartOffset < offset) {
4703                                // Expanding with end handle.
4704                                offset = getWordEnd(offset);
4705                                startOffset = getWordStart(mStartOffset);
4706                            } else {
4707                                // Expanding with start handle.
4708                                offset = getWordStart(offset);
4709                                startOffset = getWordEnd(mStartOffset);
4710                            }
4711                            mLineSelectionIsOn = currLine;
4712                            Selection.setSelection((Spannable) mTextView.getText(),
4713                                    startOffset, offset);
4714                        }
4715                    }
4716                    break;
4717
4718                case MotionEvent.ACTION_UP:
4719                    if (mDragAcceleratorActive) {
4720                        // No longer dragging to select text, let the parent intercept events.
4721                        mTextView.getParent().requestDisallowInterceptTouchEvent(false);
4722
4723                        show();
4724                        int startOffset = mTextView.getSelectionStart();
4725                        int endOffset = mTextView.getSelectionEnd();
4726
4727                        // Since we don't let drag handles pass once they're visible, we need to
4728                        // make sure the start / end locations are correct because the user *can*
4729                        // switch directions during the initial drag.
4730                        if (endOffset < startOffset) {
4731                            int tmp = endOffset;
4732                            endOffset = startOffset;
4733                            startOffset = tmp;
4734
4735                            // Also update the selection with the right offsets in this case.
4736                            Selection.setSelection((Spannable) mTextView.getText(),
4737                                    startOffset, endOffset);
4738                        }
4739
4740                        // Need to do this to display the handles.
4741                        mStartHandle.showAtLocation(startOffset);
4742                        mEndHandle.showAtLocation(endOffset);
4743
4744                        // No longer the first dragging motion, reset.
4745                        if (!(mTextView.isInExtractedMode())) {
4746                            startSelectionActionMode();
4747                        }
4748                        mDragAcceleratorActive = false;
4749                        mStartOffset = -1;
4750                        mSwitchedLines = false;
4751                    }
4752                    break;
4753            }
4754        }
4755
4756        /**
4757         * @param event
4758         */
4759        private void updateMinAndMaxOffsets(MotionEvent event) {
4760            int pointerCount = event.getPointerCount();
4761            for (int index = 0; index < pointerCount; index++) {
4762                int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
4763                if (offset < mMinTouchOffset) mMinTouchOffset = offset;
4764                if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
4765            }
4766        }
4767
4768        public int getMinTouchOffset() {
4769            return mMinTouchOffset;
4770        }
4771
4772        public int getMaxTouchOffset() {
4773            return mMaxTouchOffset;
4774        }
4775
4776        public void resetTouchOffsets() {
4777            mMinTouchOffset = mMaxTouchOffset = -1;
4778            mStartOffset = -1;
4779            mDragAcceleratorActive = false;
4780            mSwitchedLines = false;
4781        }
4782
4783        /**
4784         * @return true iff this controller is currently used to move the selection start.
4785         */
4786        public boolean isSelectionStartDragged() {
4787            return mStartHandle != null && mStartHandle.isDragging();
4788        }
4789
4790        /**
4791         * @return true if the user is selecting text using the drag accelerator.
4792         */
4793        public boolean isDragAcceleratorActive() {
4794            return mDragAcceleratorActive;
4795        }
4796
4797        public void onTouchModeChanged(boolean isInTouchMode) {
4798            if (!isInTouchMode) {
4799                hide();
4800            }
4801        }
4802
4803        @Override
4804        public void onDetached() {
4805            final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4806            observer.removeOnTouchModeChangeListener(this);
4807
4808            if (mStartHandle != null) mStartHandle.onDetached();
4809            if (mEndHandle != null) mEndHandle.onDetached();
4810        }
4811    }
4812
4813    private class CorrectionHighlighter {
4814        private final Path mPath = new Path();
4815        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
4816        private int mStart, mEnd;
4817        private long mFadingStartTime;
4818        private RectF mTempRectF;
4819        private final static int FADE_OUT_DURATION = 400;
4820
4821        public CorrectionHighlighter() {
4822            mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
4823                    applicationScale);
4824            mPaint.setStyle(Paint.Style.FILL);
4825        }
4826
4827        public void highlight(CorrectionInfo info) {
4828            mStart = info.getOffset();
4829            mEnd = mStart + info.getNewText().length();
4830            mFadingStartTime = SystemClock.uptimeMillis();
4831
4832            if (mStart < 0 || mEnd < 0) {
4833                stopAnimation();
4834            }
4835        }
4836
4837        public void draw(Canvas canvas, int cursorOffsetVertical) {
4838            if (updatePath() && updatePaint()) {
4839                if (cursorOffsetVertical != 0) {
4840                    canvas.translate(0, cursorOffsetVertical);
4841                }
4842
4843                canvas.drawPath(mPath, mPaint);
4844
4845                if (cursorOffsetVertical != 0) {
4846                    canvas.translate(0, -cursorOffsetVertical);
4847                }
4848                invalidate(true); // TODO invalidate cursor region only
4849            } else {
4850                stopAnimation();
4851                invalidate(false); // TODO invalidate cursor region only
4852            }
4853        }
4854
4855        private boolean updatePaint() {
4856            final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
4857            if (duration > FADE_OUT_DURATION) return false;
4858
4859            final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
4860            final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
4861            final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
4862                    ((int) (highlightColorAlpha * coef) << 24);
4863            mPaint.setColor(color);
4864            return true;
4865        }
4866
4867        private boolean updatePath() {
4868            final Layout layout = mTextView.getLayout();
4869            if (layout == null) return false;
4870
4871            // Update in case text is edited while the animation is run
4872            final int length = mTextView.getText().length();
4873            int start = Math.min(length, mStart);
4874            int end = Math.min(length, mEnd);
4875
4876            mPath.reset();
4877            layout.getSelectionPath(start, end, mPath);
4878            return true;
4879        }
4880
4881        private void invalidate(boolean delayed) {
4882            if (mTextView.getLayout() == null) return;
4883
4884            if (mTempRectF == null) mTempRectF = new RectF();
4885            mPath.computeBounds(mTempRectF, false);
4886
4887            int left = mTextView.getCompoundPaddingLeft();
4888            int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
4889
4890            if (delayed) {
4891                mTextView.postInvalidateOnAnimation(
4892                        left + (int) mTempRectF.left, top + (int) mTempRectF.top,
4893                        left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
4894            } else {
4895                mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
4896                        (int) mTempRectF.right, (int) mTempRectF.bottom);
4897            }
4898        }
4899
4900        private void stopAnimation() {
4901            Editor.this.mCorrectionHighlighter = null;
4902        }
4903    }
4904
4905    private static class ErrorPopup extends PopupWindow {
4906        private boolean mAbove = false;
4907        private final TextView mView;
4908        private int mPopupInlineErrorBackgroundId = 0;
4909        private int mPopupInlineErrorAboveBackgroundId = 0;
4910
4911        ErrorPopup(TextView v, int width, int height) {
4912            super(v, width, height);
4913            mView = v;
4914            // Make sure the TextView has a background set as it will be used the first time it is
4915            // shown and positioned. Initialized with below background, which should have
4916            // dimensions identical to the above version for this to work (and is more likely).
4917            mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
4918                    com.android.internal.R.styleable.Theme_errorMessageBackground);
4919            mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
4920        }
4921
4922        void fixDirection(boolean above) {
4923            mAbove = above;
4924
4925            if (above) {
4926                mPopupInlineErrorAboveBackgroundId =
4927                    getResourceId(mPopupInlineErrorAboveBackgroundId,
4928                            com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
4929            } else {
4930                mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
4931                        com.android.internal.R.styleable.Theme_errorMessageBackground);
4932            }
4933
4934            mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
4935                mPopupInlineErrorBackgroundId);
4936        }
4937
4938        private int getResourceId(int currentId, int index) {
4939            if (currentId == 0) {
4940                TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
4941                        R.styleable.Theme);
4942                currentId = styledAttributes.getResourceId(index, 0);
4943                styledAttributes.recycle();
4944            }
4945            return currentId;
4946        }
4947
4948        @Override
4949        public void update(int x, int y, int w, int h, boolean force) {
4950            super.update(x, y, w, h, force);
4951
4952            boolean above = isAboveAnchor();
4953            if (above != mAbove) {
4954                fixDirection(above);
4955            }
4956        }
4957    }
4958
4959    static class InputContentType {
4960        int imeOptions = EditorInfo.IME_NULL;
4961        String privateImeOptions;
4962        CharSequence imeActionLabel;
4963        int imeActionId;
4964        Bundle extras;
4965        OnEditorActionListener onEditorActionListener;
4966        boolean enterDown;
4967    }
4968
4969    static class InputMethodState {
4970        ExtractedTextRequest mExtractedTextRequest;
4971        final ExtractedText mExtractedText = new ExtractedText();
4972        int mBatchEditNesting;
4973        boolean mCursorChanged;
4974        boolean mSelectionModeChanged;
4975        boolean mContentChanged;
4976        int mChangedStart, mChangedEnd, mChangedDelta;
4977    }
4978
4979    /**
4980     * @return True iff (start, end) is a valid range within the text.
4981     */
4982    private static boolean isValidRange(CharSequence text, int start, int end) {
4983        return 0 <= start && start <= end && end <= text.length();
4984    }
4985
4986    /**
4987     * An InputFilter that monitors text input to maintain undo history. It does not modify the
4988     * text being typed (and hence always returns null from the filter() method).
4989     */
4990    public static class UndoInputFilter implements InputFilter {
4991        private final Editor mEditor;
4992
4993        // Whether the current filter pass is directly caused by an end-user text edit.
4994        private boolean mIsUserEdit;
4995
4996        // Whether the text field is handling an IME composition. Must be parceled in case the user
4997        // rotates the screen during composition.
4998        private boolean mHasComposition;
4999
5000        public UndoInputFilter(Editor editor) {
5001            mEditor = editor;
5002        }
5003
5004        public void saveInstanceState(Parcel parcel) {
5005            parcel.writeInt(mIsUserEdit ? 1 : 0);
5006            parcel.writeInt(mHasComposition ? 1 : 0);
5007        }
5008
5009        public void restoreInstanceState(Parcel parcel) {
5010            mIsUserEdit = parcel.readInt() != 0;
5011            mHasComposition = parcel.readInt() != 0;
5012        }
5013
5014        /**
5015         * Signals that a user-triggered edit is starting.
5016         */
5017        public void beginBatchEdit() {
5018            if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
5019            mIsUserEdit = true;
5020        }
5021
5022        public void endBatchEdit() {
5023            if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
5024            mIsUserEdit = false;
5025        }
5026
5027        @Override
5028        public CharSequence filter(CharSequence source, int start, int end,
5029                Spanned dest, int dstart, int dend) {
5030            if (DEBUG_UNDO) {
5031                Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " +
5032                        "dest=" + dest + " (" + dstart + "-" + dend + ")");
5033            }
5034
5035            // Check to see if this edit should be tracked for undo.
5036            if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
5037                return null;
5038            }
5039
5040            // Check for and handle IME composition edits.
5041            if (handleCompositionEdit(source, start, end, dstart)) {
5042                return null;
5043            }
5044
5045            // Handle keyboard edits.
5046            handleKeyboardEdit(source, start, end, dest, dstart, dend);
5047            return null;
5048        }
5049
5050        /**
5051         * Returns true iff the edit was handled, either because it should be ignored or because
5052         * this function created an undo operation for it.
5053         */
5054        private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) {
5055            // Ignore edits while the user is composing.
5056            if (isComposition(source)) {
5057                mHasComposition = true;
5058                return true;
5059            }
5060            final boolean hadComposition = mHasComposition;
5061            mHasComposition = false;
5062
5063            // Check for the transition out of the composing state.
5064            if (hadComposition) {
5065                // If there was no text the user canceled composition. Ignore the edit.
5066                if (start == end) {
5067                    return true;
5068                }
5069
5070                // Otherwise the user inserted the composition.
5071                String newText = TextUtils.substring(source, start, end);
5072                EditOperation edit = new EditOperation(mEditor, "", dstart, newText);
5073                recordEdit(edit, false /* forceMerge */);
5074                return true;
5075            }
5076
5077            // This was neither a composition event nor a transition out of composing.
5078            return false;
5079        }
5080
5081        private void handleKeyboardEdit(CharSequence source, int start, int end,
5082                Spanned dest, int dstart, int dend) {
5083            // An application may install a TextWatcher to provide additional modifications after
5084            // the initial input filters run (e.g. a credit card formatter that adds spaces to a
5085            // string). This results in multiple filter() calls for what the user considers to be
5086            // a single operation. Always undo the whole set of changes in one step.
5087            final boolean forceMerge = isInTextWatcher();
5088
5089            // Build a new operation with all the information from this edit.
5090            String newText = TextUtils.substring(source, start, end);
5091            String oldText = TextUtils.substring(dest, dstart, dend);
5092            EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText);
5093            recordEdit(edit, forceMerge);
5094        }
5095
5096        /**
5097         * Fetches the last undo operation and checks to see if a new edit should be merged into it.
5098         * If forceMerge is true then the new edit is always merged.
5099         */
5100        private void recordEdit(EditOperation edit, boolean forceMerge) {
5101            // Fetch the last edit operation and attempt to merge in the new edit.
5102            final UndoManager um = mEditor.mUndoManager;
5103            um.beginUpdate("Edit text");
5104            EditOperation lastEdit = um.getLastOperation(
5105                  EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
5106            if (lastEdit == null) {
5107                // Add this as the first edit.
5108                if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
5109                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5110            } else if (forceMerge) {
5111                // Forced merges take priority because they could be the result of a non-user-edit
5112                // change and this case should not create a new undo operation.
5113                if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
5114                lastEdit.forceMergeWith(edit);
5115            } else if (!mIsUserEdit) {
5116                // An application directly modified the Editable outside of a text edit. Treat this
5117                // as a new change and don't attempt to merge.
5118                if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
5119                um.commitState(mEditor.mUndoOwner);
5120                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5121            } else if (lastEdit.mergeWith(edit)) {
5122                // Merge succeeded, nothing else to do.
5123                if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
5124            } else {
5125                // Could not merge with the last edit, so commit the last edit and add this edit.
5126                if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
5127                um.commitState(mEditor.mUndoOwner);
5128                um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
5129            }
5130            um.endUpdate();
5131        }
5132
5133        private boolean canUndoEdit(CharSequence source, int start, int end,
5134                Spanned dest, int dstart, int dend) {
5135            if (!mEditor.mAllowUndo) {
5136                if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
5137                return false;
5138            }
5139
5140            if (mEditor.mUndoManager.isInUndo()) {
5141                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
5142                return false;
5143            }
5144
5145            // Text filters run before input operations are applied. However, some input operations
5146            // are invalid and will throw exceptions when applied. This is common in tests. Don't
5147            // attempt to undo invalid operations.
5148            if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
5149                if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
5150                return false;
5151            }
5152
5153            // Earlier filters can rewrite input to be a no-op, for example due to a length limit
5154            // on an input field. Skip no-op changes.
5155            if (start == end && dstart == dend) {
5156                if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
5157                return false;
5158            }
5159
5160            return true;
5161        }
5162
5163        private boolean isComposition(CharSequence source) {
5164            if (!(source instanceof Spannable)) {
5165                return false;
5166            }
5167            // This is a composition edit if the source has a non-zero-length composing span.
5168            Spannable text = (Spannable) source;
5169            int composeBegin = EditableInputConnection.getComposingSpanStart(text);
5170            int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
5171            return composeBegin < composeEnd;
5172        }
5173
5174        private boolean isInTextWatcher() {
5175            CharSequence text = mEditor.mTextView.getText();
5176            return (text instanceof SpannableStringBuilder)
5177                    && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
5178        }
5179    }
5180
5181    /**
5182     * An operation to undo a single "edit" to a text view.
5183     */
5184    public static class EditOperation extends UndoOperation<Editor> {
5185        private static final int TYPE_INSERT = 0;
5186        private static final int TYPE_DELETE = 1;
5187        private static final int TYPE_REPLACE = 2;
5188
5189        private int mType;
5190        private String mOldText;
5191        private int mOldTextStart;
5192        private String mNewText;
5193        private int mNewTextStart;
5194
5195        private int mOldCursorPos;
5196        private int mNewCursorPos;
5197
5198        /**
5199         * Constructs an edit operation from a text input operation on editor that replaces the
5200         * oldText starting at dstart with newText.
5201         */
5202        public EditOperation(Editor editor, String oldText, int dstart, String newText) {
5203            super(editor.mUndoOwner);
5204            mOldText = oldText;
5205            mNewText = newText;
5206
5207            // Determine the type of the edit and store where it occurred. Avoid storing
5208            // irrevelant data (e.g. mNewTextStart for a delete) because that makes the
5209            // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being
5210            // outside the bounds of the final text).
5211            if (mNewText.length() > 0 && mOldText.length() == 0) {
5212                mType = TYPE_INSERT;
5213                mNewTextStart = dstart;
5214            } else if (mNewText.length() == 0 && mOldText.length() > 0) {
5215                mType = TYPE_DELETE;
5216                mOldTextStart = dstart;
5217            } else {
5218                mType = TYPE_REPLACE;
5219                mOldTextStart = mNewTextStart = dstart;
5220            }
5221
5222            // Store cursor data.
5223            mOldCursorPos = editor.mTextView.getSelectionStart();
5224            mNewCursorPos = dstart + mNewText.length();
5225        }
5226
5227        public EditOperation(Parcel src, ClassLoader loader) {
5228            super(src, loader);
5229            mType = src.readInt();
5230            mOldText = src.readString();
5231            mOldTextStart = src.readInt();
5232            mNewText = src.readString();
5233            mNewTextStart = src.readInt();
5234            mOldCursorPos = src.readInt();
5235            mNewCursorPos = src.readInt();
5236        }
5237
5238        @Override
5239        public void writeToParcel(Parcel dest, int flags) {
5240            dest.writeInt(mType);
5241            dest.writeString(mOldText);
5242            dest.writeInt(mOldTextStart);
5243            dest.writeString(mNewText);
5244            dest.writeInt(mNewTextStart);
5245            dest.writeInt(mOldCursorPos);
5246            dest.writeInt(mNewCursorPos);
5247        }
5248
5249        private int getNewTextEnd() {
5250            return mNewTextStart + mNewText.length();
5251        }
5252
5253        private int getOldTextEnd() {
5254            return mOldTextStart + mOldText.length();
5255        }
5256
5257        @Override
5258        public void commit() {
5259        }
5260
5261        @Override
5262        public void undo() {
5263            if (DEBUG_UNDO) Log.d(TAG, "undo");
5264            // Remove the new text and insert the old.
5265            Editor editor = getOwnerData();
5266            Editable text = (Editable) editor.mTextView.getText();
5267            modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5268                    mOldCursorPos);
5269        }
5270
5271        @Override
5272        public void redo() {
5273            if (DEBUG_UNDO) Log.d(TAG, "redo");
5274            // Remove the old text and insert the new.
5275            Editor editor = getOwnerData();
5276            Editable text = (Editable) editor.mTextView.getText();
5277            modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart,
5278                    mNewCursorPos);
5279        }
5280
5281        /**
5282         * Attempts to merge this existing operation with a new edit.
5283         * @param edit The new edit operation.
5284         * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
5285         * object unchanged.
5286         */
5287        private boolean mergeWith(EditOperation edit) {
5288            if (DEBUG_UNDO) {
5289                Log.d(TAG, "mergeWith old " + this);
5290                Log.d(TAG, "mergeWith new " + edit);
5291            }
5292            switch (mType) {
5293                case TYPE_INSERT:
5294                    return mergeInsertWith(edit);
5295                case TYPE_DELETE:
5296                    return mergeDeleteWith(edit);
5297                case TYPE_REPLACE:
5298                    return mergeReplaceWith(edit);
5299                default:
5300                    return false;
5301            }
5302        }
5303
5304        private boolean mergeInsertWith(EditOperation edit) {
5305            // Only merge continuous insertions.
5306            if (edit.mType != TYPE_INSERT) {
5307                return false;
5308            }
5309            // Only merge insertions that are contiguous.
5310            if (getNewTextEnd() != edit.mNewTextStart) {
5311                return false;
5312            }
5313            mNewText += edit.mNewText;
5314            mNewCursorPos = edit.mNewCursorPos;
5315            return true;
5316        }
5317
5318        // TODO: Support forward delete.
5319        private boolean mergeDeleteWith(EditOperation edit) {
5320            // Only merge continuous deletes.
5321            if (edit.mType != TYPE_DELETE) {
5322                return false;
5323            }
5324            // Only merge deletions that are contiguous.
5325            if (mOldTextStart != edit.getOldTextEnd()) {
5326                return false;
5327            }
5328            mOldTextStart = edit.mOldTextStart;
5329            mOldText = edit.mOldText + mOldText;
5330            mNewCursorPos = edit.mNewCursorPos;
5331            return true;
5332        }
5333
5334        private boolean mergeReplaceWith(EditOperation edit) {
5335            // Replacements can merge only with adjacent inserts.
5336            if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) {
5337                return false;
5338            }
5339            mOldText += edit.mOldText;
5340            mNewText += edit.mNewText;
5341            mNewCursorPos = edit.mNewCursorPos;
5342            return true;
5343        }
5344
5345        /**
5346         * Forcibly creates a single merged edit operation by simulating the entire text
5347         * contents being replaced.
5348         */
5349        public void forceMergeWith(EditOperation edit) {
5350            if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
5351            Editor editor = getOwnerData();
5352
5353            // Copy the text of the current field.
5354            // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
5355            // but would require two parallel implementations of modifyText() because Editable and
5356            // StringBuilder do not share an interface for replace/delete/insert.
5357            Editable editable = (Editable) editor.mTextView.getText();
5358            Editable originalText = new SpannableStringBuilder(editable.toString());
5359
5360            // Roll back the last operation.
5361            modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5362                    mOldCursorPos);
5363
5364            // Clone the text again and apply the new operation.
5365            Editable finalText = new SpannableStringBuilder(editable.toString());
5366            modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText,
5367                    edit.mNewTextStart, edit.mNewCursorPos);
5368
5369            // Convert this operation into a non-mergeable replacement of the entire string.
5370            mType = TYPE_REPLACE;
5371            mNewText = finalText.toString();
5372            mNewTextStart = 0;
5373            mOldText = originalText.toString();
5374            mOldTextStart = 0;
5375            mNewCursorPos = edit.mNewCursorPos;
5376            // mOldCursorPos is unchanged.
5377        }
5378
5379        private static void modifyText(Editable text, int deleteFrom, int deleteTo,
5380                CharSequence newText, int newTextInsertAt, int newCursorPos) {
5381            // Apply the edit if it is still valid.
5382            if (isValidRange(text, deleteFrom, deleteTo) &&
5383                    newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
5384                if (deleteFrom != deleteTo) {
5385                    text.delete(deleteFrom, deleteTo);
5386                }
5387                if (newText.length() != 0) {
5388                    text.insert(newTextInsertAt, newText);
5389                }
5390            }
5391            // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
5392            // don't explicitly set it and rely on SpannableStringBuilder to position it.
5393            // TODO: Select all the text that was undone.
5394            if (0 <= newCursorPos && newCursorPos <= text.length()) {
5395                Selection.setSelection(text, newCursorPos);
5396            }
5397        }
5398
5399        private String getTypeString() {
5400            switch (mType) {
5401                case TYPE_INSERT:
5402                    return "insert";
5403                case TYPE_DELETE:
5404                    return "delete";
5405                case TYPE_REPLACE:
5406                    return "replace";
5407                default:
5408                    return "";
5409            }
5410        }
5411
5412        @Override
5413        public String toString() {
5414            return "[mType=" + getTypeString() + ", " +
5415                    "mOldText=" + mOldText + ", " +
5416                    "mOldTextStart=" + mOldTextStart + ", " +
5417                    "mNewText=" + mNewText + ", " +
5418                    "mNewTextStart=" + mNewTextStart + ", " +
5419                    "mOldCursorPos=" + mOldCursorPos + ", " +
5420                    "mNewCursorPos=" + mNewCursorPos + "]";
5421        }
5422
5423        public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR
5424                = new Parcelable.ClassLoaderCreator<EditOperation>() {
5425            @Override
5426            public EditOperation createFromParcel(Parcel in) {
5427                return new EditOperation(in, null);
5428            }
5429
5430            @Override
5431            public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
5432                return new EditOperation(in, loader);
5433            }
5434
5435            @Override
5436            public EditOperation[] newArray(int size) {
5437                return new EditOperation[size];
5438            }
5439        };
5440    }
5441}
5442