blob: 59d857c35afe1138c7fe1e00490bd7620959f50b [file] [log] [blame]
Gilles Debunned88876a2012-03-16 17:34:04 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.widget;
18
19import android.R;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +090020import android.annotation.IntDef;
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +090021import android.annotation.NonNull;
Yoshiki Iguchiee147722015-04-14 00:12:44 +090022import android.annotation.Nullable;
Luca Zanolin1b15ba52013-02-20 14:31:37 +000023import android.app.PendingIntent;
24import android.app.PendingIntent.CanceledException;
Gilles Debunned88876a2012-03-16 17:34:04 -070025import android.content.ClipData;
26import android.content.ClipData.Item;
27import android.content.Context;
28import android.content.Intent;
Raph Levien26d443a2015-03-30 14:18:32 -070029import android.content.UndoManager;
30import android.content.UndoOperation;
31import android.content.UndoOwner;
Gilles Debunned88876a2012-03-16 17:34:04 -070032import android.content.pm.PackageManager;
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +000033import android.content.pm.ResolveInfo;
Gilles Debunned88876a2012-03-16 17:34:04 -070034import android.content.res.TypedArray;
35import android.graphics.Canvas;
36import android.graphics.Color;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +090037import android.graphics.Matrix;
Gilles Debunned88876a2012-03-16 17:34:04 -070038import android.graphics.Paint;
39import android.graphics.Path;
40import android.graphics.Rect;
41import android.graphics.RectF;
Seigo Nonaka3ed1b392016-01-19 13:54:59 +090042import android.graphics.drawable.ColorDrawable;
Gilles Debunned88876a2012-03-16 17:34:04 -070043import android.graphics.drawable.Drawable;
Gilles Debunned88876a2012-03-16 17:34:04 -070044import android.os.Bundle;
Raph Levien26d443a2015-03-30 14:18:32 -070045import android.os.Parcel;
46import android.os.Parcelable;
James Cookf59152c2015-02-26 18:03:58 -080047import android.os.ParcelableParcel;
Gilles Debunned88876a2012-03-16 17:34:04 -070048import android.os.SystemClock;
49import android.provider.Settings;
50import android.text.DynamicLayout;
51import android.text.Editable;
Raph Levien26d443a2015-03-30 14:18:32 -070052import android.text.InputFilter;
Gilles Debunned88876a2012-03-16 17:34:04 -070053import android.text.InputType;
54import android.text.Layout;
55import android.text.ParcelableSpan;
56import android.text.Selection;
57import android.text.SpanWatcher;
58import android.text.Spannable;
59import android.text.SpannableStringBuilder;
60import android.text.Spanned;
61import android.text.StaticLayout;
62import android.text.TextUtils;
Gilles Debunned88876a2012-03-16 17:34:04 -070063import android.text.method.KeyListener;
64import android.text.method.MetaKeyKeyListener;
65import android.text.method.MovementMethod;
Gilles Debunned88876a2012-03-16 17:34:04 -070066import android.text.method.WordIterator;
67import android.text.style.EasyEditSpan;
68import android.text.style.SuggestionRangeSpan;
69import android.text.style.SuggestionSpan;
70import android.text.style.TextAppearanceSpan;
71import android.text.style.URLSpan;
72import android.util.DisplayMetrics;
Yohei Yukawad469f212016-01-21 12:38:09 -080073import android.util.LocaleList;
Gilles Debunned88876a2012-03-16 17:34:04 -070074import android.util.Log;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -070075import android.util.SparseArray;
Gilles Debunned88876a2012-03-16 17:34:04 -070076import android.view.ActionMode;
77import android.view.ActionMode.Callback;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +090078import android.view.ContextMenu;
Chris Craikf6829a02015-03-10 10:28:59 -070079import android.view.DisplayListCanvas;
Gilles Debunned88876a2012-03-16 17:34:04 -070080import android.view.DragEvent;
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -080081import android.view.DropPermissions;
Gilles Debunned88876a2012-03-16 17:34:04 -070082import android.view.Gravity;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -080083import android.view.InputDevice;
Gilles Debunned88876a2012-03-16 17:34:04 -070084import android.view.LayoutInflater;
85import android.view.Menu;
86import android.view.MenuItem;
87import android.view.MotionEvent;
Chris Craikf6829a02015-03-10 10:28:59 -070088import android.view.RenderNode;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +090089import android.view.SubMenu;
Gilles Debunned88876a2012-03-16 17:34:04 -070090import android.view.View;
Gilles Debunned88876a2012-03-16 17:34:04 -070091import android.view.View.DragShadowBuilder;
92import android.view.View.OnClickListener;
Adam Powell057a5852012-05-11 10:28:38 -070093import android.view.ViewConfiguration;
94import android.view.ViewGroup;
Gilles Debunned88876a2012-03-16 17:34:04 -070095import android.view.ViewGroup.LayoutParams;
96import android.view.ViewParent;
97import android.view.ViewTreeObserver;
98import android.view.WindowManager;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -070099import android.view.accessibility.AccessibilityNodeInfo;
Gilles Debunned88876a2012-03-16 17:34:04 -0700100import android.view.inputmethod.CorrectionInfo;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900101import android.view.inputmethod.CursorAnchorInfo;
Gilles Debunned88876a2012-03-16 17:34:04 -0700102import android.view.inputmethod.EditorInfo;
103import android.view.inputmethod.ExtractedText;
104import android.view.inputmethod.ExtractedTextRequest;
105import android.view.inputmethod.InputConnection;
106import android.view.inputmethod.InputMethodManager;
107import android.widget.AdapterView.OnItemClickListener;
108import android.widget.TextView.Drawables;
109import android.widget.TextView.OnEditorActionListener;
110
Seigo Nonakaa60160b2015-08-19 12:38:35 -0700111import com.android.internal.annotations.VisibleForTesting;
Raph Levien26d443a2015-03-30 14:18:32 -0700112import com.android.internal.util.ArrayUtils;
113import com.android.internal.util.GrowingArrayUtils;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700114import com.android.internal.util.Preconditions;
Raph Levien26d443a2015-03-30 14:18:32 -0700115import com.android.internal.widget.EditableInputConnection;
116
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +0900117import java.lang.annotation.Retention;
118import java.lang.annotation.RetentionPolicy;
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +0100119import java.text.BreakIterator;
120import java.util.Arrays;
121import java.util.Comparator;
122import java.util.HashMap;
123import java.util.List;
124
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700125
Gilles Debunned88876a2012-03-16 17:34:04 -0700126/**
127 * Helper class used by TextView to handle editable text views.
128 *
129 * @hide
130 */
131public class Editor {
Adam Powell057a5852012-05-11 10:28:38 -0700132 private static final String TAG = "Editor";
James Cookf59152c2015-02-26 18:03:58 -0800133 private static final boolean DEBUG_UNDO = false;
Adam Powell057a5852012-05-11 10:28:38 -0700134
Gilles Debunned88876a2012-03-16 17:34:04 -0700135 static final int BLINK = 500;
136 private static final float[] TEMP_POSITION = new float[2];
137 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
Mady Mellorcc65c372015-06-17 09:25:19 -0700138 private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f;
Mady Mellore264ac32015-06-22 16:46:29 -0700139 private static final int UNSET_X_VALUE = -1;
Mady Mellora6a0f782015-07-10 16:43:32 -0700140 private static final int UNSET_LINE = -1;
James Cookf59152c2015-02-26 18:03:58 -0800141 // Tag used when the Editor maintains its own separate UndoManager.
142 private static final String UNDO_OWNER_TAG = "Editor";
Gilles Debunned88876a2012-03-16 17:34:04 -0700143
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900144 // Ordering constants used to place the Action Mode or context menu items in their menu.
145 private static final int MENU_ITEM_ORDER_UNDO = 1;
146 private static final int MENU_ITEM_ORDER_REDO = 2;
147 private static final int MENU_ITEM_ORDER_CUT = 3;
148 private static final int MENU_ITEM_ORDER_COPY = 4;
149 private static final int MENU_ITEM_ORDER_PASTE = 5;
150 private static final int MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 6;
151 private static final int MENU_ITEM_ORDER_SHARE = 7;
152 private static final int MENU_ITEM_ORDER_SELECT_ALL = 8;
153 private static final int MENU_ITEM_ORDER_REPLACE = 9;
Clara Bayarri3b69fd82015-06-03 21:52:02 +0100154 private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 10;
155
James Cookf59152c2015-02-26 18:03:58 -0800156 // Each Editor manages its own undo stack.
157 private final UndoManager mUndoManager = new UndoManager();
158 private UndoOwner mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
James Cook48e0fac2015-02-25 15:44:51 -0800159 final UndoInputFilter mUndoInputFilter = new UndoInputFilter(this);
James Cookf1dad1e2015-02-27 11:00:01 -0800160 boolean mAllowUndo = true;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -0700161
Gilles Debunned88876a2012-03-16 17:34:04 -0700162 // Cursor Controllers.
163 InsertionPointCursorController mInsertionPointCursorController;
164 SelectionModifierCursorController mSelectionModifierCursorController;
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100165 // Action mode used when text is selected or when actions on an insertion cursor are triggered.
166 ActionMode mTextActionMode;
Gilles Debunned88876a2012-03-16 17:34:04 -0700167 boolean mInsertionControllerEnabled;
168 boolean mSelectionControllerEnabled;
169
170 // Used to highlight a word when it is corrected by the IME
171 CorrectionHighlighter mCorrectionHighlighter;
172
173 InputContentType mInputContentType;
174 InputMethodState mInputMethodState;
175
Chris Craik956f3402015-04-27 16:41:00 -0700176 private static class TextRenderNode {
177 RenderNode renderNode;
John Reck7558aa72014-03-05 14:59:59 -0800178 boolean isDirty;
Chris Craik956f3402015-04-27 16:41:00 -0700179 public TextRenderNode(String name) {
John Reck7558aa72014-03-05 14:59:59 -0800180 isDirty = true;
Chris Craik956f3402015-04-27 16:41:00 -0700181 renderNode = RenderNode.create(name, null);
John Reck7558aa72014-03-05 14:59:59 -0800182 }
Chris Craik956f3402015-04-27 16:41:00 -0700183 boolean needsRecord() { return isDirty || !renderNode.isValid(); }
John Reck7558aa72014-03-05 14:59:59 -0800184 }
Chris Craik956f3402015-04-27 16:41:00 -0700185 TextRenderNode[] mTextRenderNodes;
Gilles Debunned88876a2012-03-16 17:34:04 -0700186
187 boolean mFrozenWithFocus;
188 boolean mSelectionMoved;
189 boolean mTouchFocusSelected;
190
191 KeyListener mKeyListener;
192 int mInputType = EditorInfo.TYPE_NULL;
193
194 boolean mDiscardNextActionUp;
195 boolean mIgnoreActionUpEvent;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900196 private boolean mIgnoreNextMouseActionUpOrDown;
Gilles Debunned88876a2012-03-16 17:34:04 -0700197
198 long mShowCursor;
199 Blink mBlink;
200
201 boolean mCursorVisible = true;
202 boolean mSelectAllOnFocus;
203 boolean mTextIsSelectable;
204
205 CharSequence mError;
206 boolean mErrorWasChanged;
207 ErrorPopup mErrorPopup;
Fabrice Di Meglio1957d282012-10-25 17:42:39 -0700208
Gilles Debunned88876a2012-03-16 17:34:04 -0700209 /**
210 * This flag is set if the TextView tries to display an error before it
211 * is attached to the window (so its position is still unknown).
212 * It causes the error to be shown later, when onAttachedToWindow()
213 * is called.
214 */
215 boolean mShowErrorAfterAttach;
216
217 boolean mInBatchEditControllers;
Gilles Debunne3473b2b2012-04-20 16:21:10 -0700218 boolean mShowSoftInputOnFocus = true;
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -0800219 private boolean mPreserveSelection;
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +0900220 private boolean mRestartActionModeOnNextRefresh;
Adam Powell057a5852012-05-11 10:28:38 -0700221 boolean mTemporaryDetach;
Gilles Debunned88876a2012-03-16 17:34:04 -0700222
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900223 boolean mIsBeingLongClicked;
224
Gilles Debunned88876a2012-03-16 17:34:04 -0700225 SuggestionsPopupWindow mSuggestionsPopupWindow;
226 SuggestionRangeSpan mSuggestionRangeSpan;
227 Runnable mShowSuggestionRunnable;
228
229 final Drawable[] mCursorDrawable = new Drawable[2];
230 int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split)
231
232 private Drawable mSelectHandleLeft;
233 private Drawable mSelectHandleRight;
234 private Drawable mSelectHandleCenter;
235
236 // Global listener that detects changes in the global position of the TextView
237 private PositionListener mPositionListener;
238
239 float mLastDownPositionX, mLastDownPositionY;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900240 private float mContextMenuAnchorX, mContextMenuAnchorY;
Gilles Debunned88876a2012-03-16 17:34:04 -0700241 Callback mCustomSelectionActionModeCallback;
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100242 Callback mCustomInsertionActionModeCallback;
Gilles Debunned88876a2012-03-16 17:34:04 -0700243
244 // Set when this TextView gained focus with some text selected. Will start selection mode.
245 boolean mCreatedWithASelection;
246
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +0900247 // Indicates the current tap state (first tap, double tap, or triple click).
248 private int mTapState = TAP_STATE_INITIAL;
249 private long mLastTouchUpTime = 0;
250 private static final int TAP_STATE_INITIAL = 0;
251 private static final int TAP_STATE_FIRST_TAP = 1;
252 private static final int TAP_STATE_DOUBLE_TAP = 2;
253 // Only for mouse input.
254 private static final int TAP_STATE_TRIPLE_CLICK = 3;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100255
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900256 // The button state as of the last time #onTouchEvent is called.
257 private int mLastButtonState;
258
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100259 private Runnable mInsertionActionModeRunnable;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100260
Jean Chalardbaf30942013-02-28 16:01:51 -0800261 // The span controller helps monitoring the changes to which the Editor needs to react:
262 // - EasyEditSpans, for which we have some UI to display on attach and on hide
263 // - SelectionSpans, for which we need to call updateSelection if an IME is attached
264 private SpanController mSpanController;
Gilles Debunned88876a2012-03-16 17:34:04 -0700265
266 WordIterator mWordIterator;
267 SpellChecker mSpellChecker;
268
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800269 // This word iterator is set with text and used to determine word boundaries
270 // when a user is selecting text.
271 private WordIterator mWordIteratorWithText;
272 // Indicate that the text in the word iterator needs to be updated.
273 private boolean mUpdateWordIteratorText;
274
Gilles Debunned88876a2012-03-16 17:34:04 -0700275 private Rect mTempRect;
276
277 private TextView mTextView;
278
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700279 final ProcessTextIntentActionsHandler mProcessTextIntentActionsHandler;
280
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900281 final CursorAnchorInfoNotifier mCursorAnchorInfoNotifier = new CursorAnchorInfoNotifier();
282
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100283 private final Runnable mShowFloatingToolbar = new Runnable() {
284 @Override
285 public void run() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100286 if (mTextActionMode != null) {
Abodunrinwa Toki9e211282015-06-05 02:46:57 +0100287 mTextActionMode.hide(0); // hide off.
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100288 }
289 }
290 };
291
Clara Bayarrib71dddd2015-06-04 23:17:30 +0100292 boolean mIsInsertionActionModeStartPending = false;
293
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +0900294 private final SuggestionHelper mSuggestionHelper = new SuggestionHelper();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +0900295
Gilles Debunned88876a2012-03-16 17:34:04 -0700296 Editor(TextView textView) {
297 mTextView = textView;
James Cookf59152c2015-02-26 18:03:58 -0800298 // Synchronize the filter list, which places the undo input filter at the end.
299 mTextView.setFilters(mTextView.getFilters());
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700300 mProcessTextIntentActionsHandler = new ProcessTextIntentActionsHandler(this);
James Cookf59152c2015-02-26 18:03:58 -0800301 }
302
303 ParcelableParcel saveInstanceState() {
James Cookd2026682015-03-03 14:40:14 -0800304 ParcelableParcel state = new ParcelableParcel(getClass().getClassLoader());
305 Parcel parcel = state.getParcel();
306 mUndoManager.saveInstanceState(parcel);
307 mUndoInputFilter.saveInstanceState(parcel);
308 return state;
James Cookf59152c2015-02-26 18:03:58 -0800309 }
310
311 void restoreInstanceState(ParcelableParcel state) {
James Cookd2026682015-03-03 14:40:14 -0800312 Parcel parcel = state.getParcel();
313 mUndoManager.restoreInstanceState(parcel, state.getClassLoader());
314 mUndoInputFilter.restoreInstanceState(parcel);
James Cookf59152c2015-02-26 18:03:58 -0800315 // Re-associate this object as the owner of undo state.
316 mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
317 }
318
James Cook48e0fac2015-02-25 15:44:51 -0800319 /**
320 * Forgets all undo and redo operations for this Editor.
321 */
322 void forgetUndoRedo() {
323 UndoOwner[] owners = { mUndoOwner };
324 mUndoManager.forgetUndos(owners, -1 /* all */);
325 mUndoManager.forgetRedos(owners, -1 /* all */);
326 }
327
James Cookf59152c2015-02-26 18:03:58 -0800328 boolean canUndo() {
329 UndoOwner[] owners = { mUndoOwner };
James Cookf1dad1e2015-02-27 11:00:01 -0800330 return mAllowUndo && mUndoManager.countUndos(owners) > 0;
James Cookf59152c2015-02-26 18:03:58 -0800331 }
332
333 boolean canRedo() {
334 UndoOwner[] owners = { mUndoOwner };
James Cookf1dad1e2015-02-27 11:00:01 -0800335 return mAllowUndo && mUndoManager.countRedos(owners) > 0;
James Cookf59152c2015-02-26 18:03:58 -0800336 }
337
338 void undo() {
James Cookf1dad1e2015-02-27 11:00:01 -0800339 if (!mAllowUndo) {
340 return;
341 }
James Cookf59152c2015-02-26 18:03:58 -0800342 UndoOwner[] owners = { mUndoOwner };
343 mUndoManager.undo(owners, 1); // Undo 1 action.
344 }
345
346 void redo() {
James Cookf1dad1e2015-02-27 11:00:01 -0800347 if (!mAllowUndo) {
348 return;
349 }
James Cookf59152c2015-02-26 18:03:58 -0800350 UndoOwner[] owners = { mUndoOwner };
351 mUndoManager.redo(owners, 1); // Redo 1 action.
Gilles Debunned88876a2012-03-16 17:34:04 -0700352 }
353
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100354 void replace() {
Keisuke Kuroyanagi713be062016-02-29 16:07:54 -0800355 if (mSuggestionsPopupWindow == null) {
356 mSuggestionsPopupWindow = new SuggestionsPopupWindow();
357 }
358 hideCursorAndSpanControllers();
359 mSuggestionsPopupWindow.show();
360
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100361 int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100362 Selection.setSelection((Spannable) mTextView.getText(), middle);
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100363 }
364
Gilles Debunned88876a2012-03-16 17:34:04 -0700365 void onAttachedToWindow() {
366 if (mShowErrorAfterAttach) {
367 showError();
368 mShowErrorAfterAttach = false;
369 }
Adam Powell057a5852012-05-11 10:28:38 -0700370 mTemporaryDetach = false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700371
372 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
373 // No need to create the controller.
374 // The get method will add the listener on controller creation.
375 if (mInsertionPointCursorController != null) {
376 observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
377 }
378 if (mSelectionModifierCursorController != null) {
Adam Powell057a5852012-05-11 10:28:38 -0700379 mSelectionModifierCursorController.resetTouchOffsets();
Gilles Debunned88876a2012-03-16 17:34:04 -0700380 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
381 }
382 updateSpellCheckSpans(0, mTextView.getText().length(),
383 true /* create the spell checker if needed */);
Adam Powell057a5852012-05-11 10:28:38 -0700384
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +0900385 if (mTextView.hasSelection()) {
386 refreshTextActionMode();
Adam Powell057a5852012-05-11 10:28:38 -0700387 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900388
389 getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true);
Mikael Gullstrand5b734f22013-07-09 14:41:28 +0200390 resumeBlink();
Gilles Debunned88876a2012-03-16 17:34:04 -0700391 }
392
393 void onDetachedFromWindow() {
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900394 getPositionListener().removeSubscriber(mCursorAnchorInfoNotifier);
395
Gilles Debunned88876a2012-03-16 17:34:04 -0700396 if (mError != null) {
397 hideError();
398 }
399
Mikael Gullstrand5b734f22013-07-09 14:41:28 +0200400 suspendBlink();
Gilles Debunned88876a2012-03-16 17:34:04 -0700401
402 if (mInsertionPointCursorController != null) {
403 mInsertionPointCursorController.onDetached();
404 }
405
406 if (mSelectionModifierCursorController != null) {
407 mSelectionModifierCursorController.onDetached();
408 }
409
410 if (mShowSuggestionRunnable != null) {
411 mTextView.removeCallbacks(mShowSuggestionRunnable);
412 }
413
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100414 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100415 if (mInsertionActionModeRunnable != null) {
416 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100417 }
418
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100419 mTextView.removeCallbacks(mShowFloatingToolbar);
420
Chris Craik003cc3d2015-10-16 10:24:55 -0700421 discardTextDisplayLists();
Gilles Debunned88876a2012-03-16 17:34:04 -0700422
423 if (mSpellChecker != null) {
424 mSpellChecker.closeSession();
425 // Forces the creation of a new SpellChecker next time this window is created.
426 // Will handle the cases where the settings has been changed in the meantime.
427 mSpellChecker = null;
428 }
429
Mady Mellora2861452015-06-25 08:40:27 -0700430 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -0800431 stopTextActionModeWithPreservingSelection();
Adam Powell057a5852012-05-11 10:28:38 -0700432 mTemporaryDetach = false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700433 }
434
Chris Craik003cc3d2015-10-16 10:24:55 -0700435 private void discardTextDisplayLists() {
Chris Craik956f3402015-04-27 16:41:00 -0700436 if (mTextRenderNodes != null) {
437 for (int i = 0; i < mTextRenderNodes.length; i++) {
438 RenderNode displayList = mTextRenderNodes[i] != null
439 ? mTextRenderNodes[i].renderNode : null;
John Reck7558aa72014-03-05 14:59:59 -0800440 if (displayList != null && displayList.isValid()) {
Chris Craik003cc3d2015-10-16 10:24:55 -0700441 displayList.discardDisplayList();
John Reck7558aa72014-03-05 14:59:59 -0800442 }
443 }
444 }
445 }
446
Gilles Debunned88876a2012-03-16 17:34:04 -0700447 private void showError() {
448 if (mTextView.getWindowToken() == null) {
449 mShowErrorAfterAttach = true;
450 return;
451 }
452
453 if (mErrorPopup == null) {
454 LayoutInflater inflater = LayoutInflater.from(mTextView.getContext());
455 final TextView err = (TextView) inflater.inflate(
456 com.android.internal.R.layout.textview_hint, null);
457
458 final float scale = mTextView.getResources().getDisplayMetrics().density;
459 mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f));
460 mErrorPopup.setFocusable(false);
461 // The user is entering text, so the input method is needed. We
462 // don't want the popup to be displayed on top of it.
463 mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
464 }
465
466 TextView tv = (TextView) mErrorPopup.getContentView();
467 chooseSize(mErrorPopup, mError, tv);
468 tv.setText(mError);
469
470 mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY());
471 mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor());
472 }
473
474 public void setError(CharSequence error, Drawable icon) {
475 mError = TextUtils.stringOrSpannedString(error);
476 mErrorWasChanged = true;
Romain Guyd1cc1872012-11-05 17:43:25 -0800477
Gilles Debunned88876a2012-03-16 17:34:04 -0700478 if (mError == null) {
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800479 setErrorIcon(null);
Gilles Debunned88876a2012-03-16 17:34:04 -0700480 if (mErrorPopup != null) {
481 if (mErrorPopup.isShowing()) {
482 mErrorPopup.dismiss();
483 }
484
485 mErrorPopup = null;
486 }
Daniel 2 Olofssonf4ecc552013-08-13 10:30:26 +0200487 mShowErrorAfterAttach = false;
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800488 } else {
Romain Guyd1cc1872012-11-05 17:43:25 -0800489 setErrorIcon(icon);
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800490 if (mTextView.isFocused()) {
491 showError();
492 }
Romain Guyd1cc1872012-11-05 17:43:25 -0800493 }
494 }
495
496 private void setErrorIcon(Drawable icon) {
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800497 Drawables dr = mTextView.mDrawables;
498 if (dr == null) {
Fabrice Di Megliof7a5cdf2013-03-15 15:36:51 -0700499 mTextView.mDrawables = dr = new Drawables(mTextView.getContext());
Gilles Debunned88876a2012-03-16 17:34:04 -0700500 }
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800501 dr.setErrorDrawable(icon, mTextView);
502
503 mTextView.resetResolvedDrawables();
504 mTextView.invalidate();
505 mTextView.requestLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -0700506 }
507
508 private void hideError() {
509 if (mErrorPopup != null) {
510 if (mErrorPopup.isShowing()) {
511 mErrorPopup.dismiss();
512 }
513 }
514
515 mShowErrorAfterAttach = false;
516 }
517
518 /**
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800519 * Returns the X offset to make the pointy top of the error point
Gilles Debunned88876a2012-03-16 17:34:04 -0700520 * at the middle of the error icon.
521 */
522 private int getErrorX() {
523 /*
524 * The "25" is the distance between the point and the right edge
525 * of the background
526 */
527 final float scale = mTextView.getResources().getDisplayMetrics().density;
528
529 final Drawables dr = mTextView.mDrawables;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800530
531 final int layoutDirection = mTextView.getLayoutDirection();
532 int errorX;
533 int offset;
534 switch (layoutDirection) {
535 default:
536 case View.LAYOUT_DIRECTION_LTR:
537 offset = - (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
538 errorX = mTextView.getWidth() - mErrorPopup.getWidth() -
539 mTextView.getPaddingRight() + offset;
540 break;
541 case View.LAYOUT_DIRECTION_RTL:
542 offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f);
543 errorX = mTextView.getPaddingLeft() + offset;
544 break;
545 }
546 return errorX;
Gilles Debunned88876a2012-03-16 17:34:04 -0700547 }
548
549 /**
550 * Returns the Y offset to make the pointy top of the error point
551 * at the bottom of the error icon.
552 */
553 private int getErrorY() {
554 /*
555 * Compound, not extended, because the icon is not clipped
556 * if the text height is smaller.
557 */
558 final int compoundPaddingTop = mTextView.getCompoundPaddingTop();
559 int vspace = mTextView.getBottom() - mTextView.getTop() -
560 mTextView.getCompoundPaddingBottom() - compoundPaddingTop;
561
562 final Drawables dr = mTextView.mDrawables;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800563
564 final int layoutDirection = mTextView.getLayoutDirection();
565 int height;
566 switch (layoutDirection) {
567 default:
568 case View.LAYOUT_DIRECTION_LTR:
569 height = (dr != null ? dr.mDrawableHeightRight : 0);
570 break;
571 case View.LAYOUT_DIRECTION_RTL:
572 height = (dr != null ? dr.mDrawableHeightLeft : 0);
573 break;
574 }
575
576 int icontop = compoundPaddingTop + (vspace - height) / 2;
Gilles Debunned88876a2012-03-16 17:34:04 -0700577
578 /*
579 * The "2" is the distance between the point and the top edge
580 * of the background.
581 */
582 final float scale = mTextView.getResources().getDisplayMetrics().density;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800583 return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f);
Gilles Debunned88876a2012-03-16 17:34:04 -0700584 }
585
586 void createInputContentTypeIfNeeded() {
587 if (mInputContentType == null) {
588 mInputContentType = new InputContentType();
589 }
590 }
591
592 void createInputMethodStateIfNeeded() {
593 if (mInputMethodState == null) {
594 mInputMethodState = new InputMethodState();
595 }
596 }
597
598 boolean isCursorVisible() {
599 // The default value is true, even when there is no associated Editor
600 return mCursorVisible && mTextView.isTextEditable();
601 }
602
603 void prepareCursorControllers() {
604 boolean windowSupportsHandles = false;
605
606 ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams();
607 if (params instanceof WindowManager.LayoutParams) {
608 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
609 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
610 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
611 }
612
613 boolean enabled = windowSupportsHandles && mTextView.getLayout() != null;
614 mInsertionControllerEnabled = enabled && isCursorVisible();
615 mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected();
616
617 if (!mInsertionControllerEnabled) {
618 hideInsertionPointCursorController();
619 if (mInsertionPointCursorController != null) {
620 mInsertionPointCursorController.onDetached();
621 mInsertionPointCursorController = null;
622 }
623 }
624
625 if (!mSelectionControllerEnabled) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100626 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -0700627 if (mSelectionModifierCursorController != null) {
628 mSelectionModifierCursorController.onDetached();
629 mSelectionModifierCursorController = null;
630 }
631 }
632 }
633
Seigo Nonakabb6a62c2015-03-31 21:59:30 +0900634 void hideInsertionPointCursorController() {
Gilles Debunned88876a2012-03-16 17:34:04 -0700635 if (mInsertionPointCursorController != null) {
636 mInsertionPointCursorController.hide();
637 }
638 }
639
640 /**
Mady Mellora2861452015-06-25 08:40:27 -0700641 * Hides the insertion and span controllers.
Gilles Debunned88876a2012-03-16 17:34:04 -0700642 */
Mady Mellora2861452015-06-25 08:40:27 -0700643 void hideCursorAndSpanControllers() {
Gilles Debunned88876a2012-03-16 17:34:04 -0700644 hideCursorControllers();
645 hideSpanControllers();
646 }
647
648 private void hideSpanControllers() {
Jean Chalardbaf30942013-02-28 16:01:51 -0800649 if (mSpanController != null) {
650 mSpanController.hide();
Gilles Debunned88876a2012-03-16 17:34:04 -0700651 }
652 }
653
654 private void hideCursorControllers() {
Yohei Yukawa85d08f12015-04-29 20:12:37 -0700655 // When mTextView is not ExtractEditText, we need to distinguish two kinds of focus-lost.
656 // One is the true focus lost where suggestions pop-up (if any) should be dismissed, and the
657 // other is an side effect of showing the suggestions pop-up itself. We use isShowingUp()
658 // to distinguish one from the other.
Andrei Stingaceanub1891b32015-06-19 16:44:37 +0100659 if (mSuggestionsPopupWindow != null && ((mTextView.isInExtractedMode()) ||
Yohei Yukawa85d08f12015-04-29 20:12:37 -0700660 !mSuggestionsPopupWindow.isShowingUp())) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700661 // Should be done before hide insertion point controller since it triggers a show of it
662 mSuggestionsPopupWindow.hide();
663 }
664 hideInsertionPointCursorController();
Gilles Debunned88876a2012-03-16 17:34:04 -0700665 }
666
667 /**
668 * Create new SpellCheckSpans on the modified region.
669 */
670 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
Satoshi Kataokad7429c12013-06-05 16:30:23 +0900671 // Remove spans whose adjacent characters are text not punctuation
672 mTextView.removeAdjacentSuggestionSpans(start);
673 mTextView.removeAdjacentSuggestionSpans(end);
674
Gilles Debunned88876a2012-03-16 17:34:04 -0700675 if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() &&
Andrei Stingaceanub1891b32015-06-19 16:44:37 +0100676 !(mTextView.isInExtractedMode())) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700677 if (mSpellChecker == null && createSpellChecker) {
678 mSpellChecker = new SpellChecker(mTextView);
679 }
680 if (mSpellChecker != null) {
681 mSpellChecker.spellCheck(start, end);
682 }
683 }
684 }
685
686 void onScreenStateChanged(int screenState) {
687 switch (screenState) {
688 case View.SCREEN_STATE_ON:
689 resumeBlink();
690 break;
691 case View.SCREEN_STATE_OFF:
692 suspendBlink();
693 break;
694 }
695 }
696
697 private void suspendBlink() {
698 if (mBlink != null) {
699 mBlink.cancel();
700 }
701 }
702
703 private void resumeBlink() {
704 if (mBlink != null) {
705 mBlink.uncancel();
706 makeBlink();
707 }
708 }
709
710 void adjustInputType(boolean password, boolean passwordInputType,
711 boolean webPasswordInputType, boolean numberPasswordInputType) {
712 // mInputType has been set from inputType, possibly modified by mInputMethod.
713 // Specialize mInputType to [web]password if we have a text class and the original input
714 // type was a password.
715 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
716 if (password || passwordInputType) {
717 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
718 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
719 }
720 if (webPasswordInputType) {
721 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
722 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
723 }
724 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
725 if (numberPasswordInputType) {
726 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
727 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
728 }
729 }
730 }
731
732 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
733 int wid = tv.getPaddingLeft() + tv.getPaddingRight();
734 int ht = tv.getPaddingTop() + tv.getPaddingBottom();
735
736 int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize(
737 com.android.internal.R.dimen.textview_error_popup_default_width);
738 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
739 Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
740 float max = 0;
741 for (int i = 0; i < l.getLineCount(); i++) {
742 max = Math.max(max, l.getLineWidth(i));
743 }
744
745 /*
746 * Now set the popup size to be big enough for the text plus the border capped
747 * to DEFAULT_MAX_POPUP_WIDTH
748 */
749 pop.setWidth(wid + (int) Math.ceil(max));
750 pop.setHeight(ht + l.getHeight());
751 }
752
753 void setFrame() {
754 if (mErrorPopup != null) {
755 TextView tv = (TextView) mErrorPopup.getContentView();
756 chooseSize(mErrorPopup, mError, tv);
757 mErrorPopup.update(mTextView, getErrorX(), getErrorY(),
758 mErrorPopup.getWidth(), mErrorPopup.getHeight());
759 }
760 }
761
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800762 private int getWordStart(int offset) {
763 // FIXME - For this and similar methods we're not doing anything to check if there's
764 // a LocaleSpan in the text, this may be something we should try handling or checking for.
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700765 int retOffset = getWordIteratorWithText().prevBoundary(offset);
Mady Mellor58c90872015-05-12 11:09:37 -0700766 if (getWordIteratorWithText().isOnPunctuation(retOffset)) {
767 // On punctuation boundary or within group of punctuation, find punctuation start.
768 retOffset = getWordIteratorWithText().getPunctuationBeginning(offset);
769 } else {
770 // Not on a punctuation boundary, find the word start.
Mady Mellore264ac32015-06-22 16:46:29 -0700771 retOffset = getWordIteratorWithText().getPrevWordBeginningOnTwoWordsBoundary(offset);
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800772 }
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700773 if (retOffset == BreakIterator.DONE) {
774 return offset;
775 }
776 return retOffset;
777 }
778
779 private int getWordEnd(int offset) {
780 int retOffset = getWordIteratorWithText().nextBoundary(offset);
Mady Mellor58c90872015-05-12 11:09:37 -0700781 if (getWordIteratorWithText().isAfterPunctuation(retOffset)) {
782 // On punctuation boundary or within group of punctuation, find punctuation end.
783 retOffset = getWordIteratorWithText().getPunctuationEnd(offset);
784 } else {
785 // Not on a punctuation boundary, find the word end.
Mady Mellore264ac32015-06-22 16:46:29 -0700786 retOffset = getWordIteratorWithText().getNextWordEndOnTwoWordBoundary(offset);
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700787 }
788 if (retOffset == BreakIterator.DONE) {
789 return offset;
790 }
791 return retOffset;
792 }
793
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900794 private boolean needsToSelectAllToSelectWordOrParagraph() {
Andrei Stingaceanu47f82ae2015-04-28 17:43:54 +0100795 if (mTextView.hasPasswordTransformationMethod()) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700796 // Always select all on a password field.
797 // Cut/copy menu entries are not available for passwords, but being able to select all
798 // is however useful to delete or paste to replace the entire content.
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900799 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -0700800 }
801
802 int inputType = mTextView.getInputType();
803 int klass = inputType & InputType.TYPE_MASK_CLASS;
804 int variation = inputType & InputType.TYPE_MASK_VARIATION;
805
806 // Specific text field types: select the entire text for these
807 if (klass == InputType.TYPE_CLASS_NUMBER ||
808 klass == InputType.TYPE_CLASS_PHONE ||
809 klass == InputType.TYPE_CLASS_DATETIME ||
810 variation == InputType.TYPE_TEXT_VARIATION_URI ||
811 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
812 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
813 variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900814 return true;
815 }
816 return false;
817 }
818
819 /**
820 * Adjusts selection to the word under last touch offset. Return true if the operation was
821 * successfully performed.
822 */
823 private boolean selectCurrentWord() {
824 if (!mTextView.canSelectText()) {
825 return false;
826 }
827
828 if (needsToSelectAllToSelectWordOrParagraph()) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700829 return mTextView.selectAllText();
830 }
831
832 long lastTouchOffsets = getLastTouchOffsets();
833 final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
834 final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
835
836 // Safety check in case standard touch event handling has been bypassed
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -0800837 if (minOffset < 0 || minOffset > mTextView.getText().length()) return false;
838 if (maxOffset < 0 || maxOffset > mTextView.getText().length()) return false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700839
840 int selectionStart, selectionEnd;
841
842 // If a URLSpan (web address, email, phone...) is found at that position, select it.
843 URLSpan[] urlSpans = ((Spanned) mTextView.getText()).
844 getSpans(minOffset, maxOffset, URLSpan.class);
845 if (urlSpans.length >= 1) {
846 URLSpan urlSpan = urlSpans[0];
847 selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan);
848 selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan);
849 } else {
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800850 // FIXME - We should check if there's a LocaleSpan in the text, this may be
851 // something we should try handling or checking for.
Gilles Debunned88876a2012-03-16 17:34:04 -0700852 final WordIterator wordIterator = getWordIterator();
853 wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset);
854
855 selectionStart = wordIterator.getBeginning(minOffset);
856 selectionEnd = wordIterator.getEnd(maxOffset);
857
858 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
859 selectionStart == selectionEnd) {
860 // Possible when the word iterator does not properly handle the text's language
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900861 long range = getCharClusterRange(minOffset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700862 selectionStart = TextUtils.unpackRangeStartFromLong(range);
863 selectionEnd = TextUtils.unpackRangeEndFromLong(range);
864 }
865 }
866
867 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
868 return selectionEnd > selectionStart;
869 }
870
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900871 /**
872 * Adjusts selection to the paragraph under last touch offset. Return true if the operation was
873 * successfully performed.
874 */
875 private boolean selectCurrentParagraph() {
876 if (!mTextView.canSelectText()) {
877 return false;
878 }
879
880 if (needsToSelectAllToSelectWordOrParagraph()) {
881 return mTextView.selectAllText();
882 }
883
884 long lastTouchOffsets = getLastTouchOffsets();
885 final int minLastTouchOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
886 final int maxLastTouchOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
887
888 final long paragraphsRange = getParagraphsRange(minLastTouchOffset, maxLastTouchOffset);
889 final int start = TextUtils.unpackRangeStartFromLong(paragraphsRange);
890 final int end = TextUtils.unpackRangeEndFromLong(paragraphsRange);
891 if (start < end) {
892 Selection.setSelection((Spannable) mTextView.getText(), start, end);
893 return true;
894 }
895 return false;
896 }
897
898 /**
899 * Get the minimum range of paragraphs that contains startOffset and endOffset.
900 */
901 private long getParagraphsRange(int startOffset, int endOffset) {
902 final Layout layout = mTextView.getLayout();
903 if (layout == null) {
904 return TextUtils.packRangeInLong(-1, -1);
905 }
906 final CharSequence text = mTextView.getText();
907 int minLine = layout.getLineForOffset(startOffset);
908 // Search paragraph start.
909 while (minLine > 0) {
910 final int prevLineEndOffset = layout.getLineEnd(minLine - 1);
911 if (text.charAt(prevLineEndOffset - 1) == '\n') {
912 break;
913 }
914 minLine--;
915 }
916 int maxLine = layout.getLineForOffset(endOffset);
917 // Search paragraph end.
918 while (maxLine < layout.getLineCount() - 1) {
919 final int lineEndOffset = layout.getLineEnd(maxLine);
920 if (text.charAt(lineEndOffset - 1) == '\n') {
921 break;
922 }
923 maxLine++;
924 }
925 return TextUtils.packRangeInLong(layout.getLineStart(minLine), layout.getLineEnd(maxLine));
926 }
927
Gilles Debunned88876a2012-03-16 17:34:04 -0700928 void onLocaleChanged() {
Keisuke Kuroyanagie0ac5ac2016-03-09 15:33:30 +0900929 // Will be re-created on demand in getWordIterator and getWordIteratorWithText with the
930 // proper new locale
Gilles Debunned88876a2012-03-16 17:34:04 -0700931 mWordIterator = null;
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800932 mWordIteratorWithText = null;
Gilles Debunned88876a2012-03-16 17:34:04 -0700933 }
934
935 /**
936 * @hide
937 */
938 public WordIterator getWordIterator() {
939 if (mWordIterator == null) {
940 mWordIterator = new WordIterator(mTextView.getTextServicesLocale());
941 }
942 return mWordIterator;
943 }
944
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800945 private WordIterator getWordIteratorWithText() {
946 if (mWordIteratorWithText == null) {
947 mWordIteratorWithText = new WordIterator(mTextView.getTextServicesLocale());
948 mUpdateWordIteratorText = true;
949 }
950 if (mUpdateWordIteratorText) {
951 // FIXME - Shouldn't copy all of the text as only the area of the text relevant
952 // to the user's selection is needed. A possible solution would be to
953 // copy some number N of characters near the selection and then when the
954 // user approaches N then we'd do another copy of the next N characters.
955 CharSequence text = mTextView.getText();
956 mWordIteratorWithText.setCharSequence(text, 0, text.length());
957 mUpdateWordIteratorText = false;
958 }
959 return mWordIteratorWithText;
960 }
961
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900962 private int getNextCursorOffset(int offset, boolean findAfterGivenOffset) {
963 final Layout layout = mTextView.getLayout();
964 if (layout == null) return offset;
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -0800965 return findAfterGivenOffset == layout.isRtlCharAt(offset) ?
966 layout.getOffsetToLeftOf(offset) : layout.getOffsetToRightOf(offset);
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900967 }
968
969 private long getCharClusterRange(int offset) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700970 final int textLength = mTextView.getText().length();
Gilles Debunned88876a2012-03-16 17:34:04 -0700971 if (offset < textLength) {
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -0800972 final int clusterEndOffset = getNextCursorOffset(offset, true);
973 return TextUtils.packRangeInLong(
974 getNextCursorOffset(clusterEndOffset, false), clusterEndOffset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700975 }
976 if (offset - 1 >= 0) {
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -0800977 final int clusterStartOffset = getNextCursorOffset(offset, false);
978 return TextUtils.packRangeInLong(clusterStartOffset,
979 getNextCursorOffset(clusterStartOffset, true));
Gilles Debunned88876a2012-03-16 17:34:04 -0700980 }
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900981 return TextUtils.packRangeInLong(offset, offset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700982 }
983
984 private boolean touchPositionIsInSelection() {
985 int selectionStart = mTextView.getSelectionStart();
986 int selectionEnd = mTextView.getSelectionEnd();
987
988 if (selectionStart == selectionEnd) {
989 return false;
990 }
991
992 if (selectionStart > selectionEnd) {
993 int tmp = selectionStart;
994 selectionStart = selectionEnd;
995 selectionEnd = tmp;
996 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
997 }
998
999 SelectionModifierCursorController selectionController = getSelectionController();
1000 int minOffset = selectionController.getMinTouchOffset();
1001 int maxOffset = selectionController.getMaxTouchOffset();
1002
1003 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
1004 }
1005
1006 private PositionListener getPositionListener() {
1007 if (mPositionListener == null) {
1008 mPositionListener = new PositionListener();
1009 }
1010 return mPositionListener;
1011 }
1012
1013 private interface TextViewPositionListener {
1014 public void updatePosition(int parentPositionX, int parentPositionY,
1015 boolean parentPositionChanged, boolean parentScrolled);
1016 }
1017
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09001018 private boolean isPositionVisible(final float positionX, final float positionY) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001019 synchronized (TEMP_POSITION) {
1020 final float[] position = TEMP_POSITION;
1021 position[0] = positionX;
1022 position[1] = positionY;
1023 View view = mTextView;
1024
1025 while (view != null) {
1026 if (view != mTextView) {
1027 // Local scroll is already taken into account in positionX/Y
1028 position[0] -= view.getScrollX();
1029 position[1] -= view.getScrollY();
1030 }
1031
1032 if (position[0] < 0 || position[1] < 0 ||
1033 position[0] > view.getWidth() || position[1] > view.getHeight()) {
1034 return false;
1035 }
1036
1037 if (!view.getMatrix().isIdentity()) {
1038 view.getMatrix().mapPoints(position);
1039 }
1040
1041 position[0] += view.getLeft();
1042 position[1] += view.getTop();
1043
1044 final ViewParent parent = view.getParent();
1045 if (parent instanceof View) {
1046 view = (View) parent;
1047 } else {
1048 // We've reached the ViewRoot, stop iterating
1049 view = null;
1050 }
1051 }
1052 }
1053
1054 // We've been able to walk up the view hierarchy and the position was never clipped
1055 return true;
1056 }
1057
1058 private boolean isOffsetVisible(int offset) {
1059 Layout layout = mTextView.getLayout();
Victoria Leaseb9b77ae2013-10-13 15:12:52 -07001060 if (layout == null) return false;
1061
Gilles Debunned88876a2012-03-16 17:34:04 -07001062 final int line = layout.getLineForOffset(offset);
1063 final int lineBottom = layout.getLineBottom(line);
1064 final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset);
1065 return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(),
1066 lineBottom + mTextView.viewportToContentVerticalOffset());
1067 }
1068
1069 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
1070 * in the view. Returns false when the position is in the empty space of left/right of text.
1071 */
1072 private boolean isPositionOnText(float x, float y) {
1073 Layout layout = mTextView.getLayout();
1074 if (layout == null) return false;
1075
1076 final int line = mTextView.getLineAtCoordinate(y);
1077 x = mTextView.convertToLocalHorizontalCoordinate(x);
1078
1079 if (x < layout.getLineLeft(line)) return false;
1080 if (x > layout.getLineRight(line)) return false;
1081 return true;
1082 }
1083
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001084 private void startDragAndDrop() {
Keisuke Kuroyanagifdfc93d2016-03-15 14:47:08 +09001085 // TODO: Fix drag and drop in full screen extracted mode.
1086 if (mTextView.isInExtractedMode()) {
1087 return;
1088 }
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001089 final int start = mTextView.getSelectionStart();
1090 final int end = mTextView.getSelectionEnd();
1091 CharSequence selectedText = mTextView.getTransformedText(start, end);
1092 ClipData data = ClipData.newPlainText(null, selectedText);
1093 DragLocalState localState = new DragLocalState(mTextView, start, end);
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08001094 mTextView.startDragAndDrop(data, getTextThumbnailBuilder(start, end), localState,
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001095 View.DRAG_FLAG_GLOBAL);
1096 stopTextActionMode();
1097 if (hasSelectionController()) {
1098 getSelectionController().resetTouchOffsets();
1099 }
1100 }
1101
Gilles Debunned88876a2012-03-16 17:34:04 -07001102 public boolean performLongClick(boolean handled) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001103 // Long press in empty space moves cursor and starts the insertion action mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07001104 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
1105 mInsertionControllerEnabled) {
1106 final int offset = mTextView.getOffsetForPosition(mLastDownPositionX,
1107 mLastDownPositionY);
Gilles Debunned88876a2012-03-16 17:34:04 -07001108 Selection.setSelection((Spannable) mTextView.getText(), offset);
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001109 getInsertionController().show();
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001110 mIsInsertionActionModeStartPending = true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001111 handled = true;
1112 }
1113
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001114 if (!handled && mTextActionMode != null) {
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +01001115 if (touchPositionIsInSelection()) {
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001116 startDragAndDrop();
Gilles Debunned88876a2012-03-16 17:34:04 -07001117 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001118 stopTextActionMode();
Clara Bayarridfac4432015-05-15 12:18:24 +01001119 selectCurrentWordAndStartDrag();
Gilles Debunned88876a2012-03-16 17:34:04 -07001120 }
1121 handled = true;
1122 }
1123
1124 // Start a new selection
1125 if (!handled) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001126 handled = selectCurrentWordAndStartDrag();
Gilles Debunned88876a2012-03-16 17:34:04 -07001127 }
1128
1129 return handled;
1130 }
1131
1132 private long getLastTouchOffsets() {
1133 SelectionModifierCursorController selectionController = getSelectionController();
1134 final int minOffset = selectionController.getMinTouchOffset();
1135 final int maxOffset = selectionController.getMaxTouchOffset();
1136 return TextUtils.packRangeInLong(minOffset, maxOffset);
1137 }
1138
1139 void onFocusChanged(boolean focused, int direction) {
1140 mShowCursor = SystemClock.uptimeMillis();
1141 ensureEndedBatchEdit();
1142
1143 if (focused) {
1144 int selStart = mTextView.getSelectionStart();
1145 int selEnd = mTextView.getSelectionEnd();
1146
1147 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
1148 // mode for these, unless there was a specific selection already started.
1149 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
1150 selEnd == mTextView.getText().length();
1151
1152 mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() &&
1153 !isFocusHighlighted;
1154
1155 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
1156 // If a tap was used to give focus to that view, move cursor at tap position.
1157 // Has to be done before onTakeFocus, which can be overloaded.
1158 final int lastTapPosition = getLastTapPosition();
1159 if (lastTapPosition >= 0) {
1160 Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition);
1161 }
1162
1163 // Note this may have to be moved out of the Editor class
1164 MovementMethod mMovement = mTextView.getMovementMethod();
1165 if (mMovement != null) {
1166 mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction);
1167 }
1168
1169 // The DecorView does not have focus when the 'Done' ExtractEditText button is
1170 // pressed. Since it is the ViewAncestor's mView, it requests focus before
1171 // ExtractEditText clears focus, which gives focus to the ExtractEditText.
1172 // This special case ensure that we keep current selection in that case.
1173 // It would be better to know why the DecorView does not have focus at that time.
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001174 if (((mTextView.isInExtractedMode()) || mSelectionMoved) &&
Gilles Debunned88876a2012-03-16 17:34:04 -07001175 selStart >= 0 && selEnd >= 0) {
1176 /*
1177 * Someone intentionally set the selection, so let them
1178 * do whatever it is that they wanted to do instead of
1179 * the default on-focus behavior. We reset the selection
1180 * here instead of just skipping the onTakeFocus() call
1181 * because some movement methods do something other than
1182 * just setting the selection in theirs and we still
1183 * need to go through that path.
1184 */
1185 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
1186 }
1187
1188 if (mSelectAllOnFocus) {
1189 mTextView.selectAllText();
1190 }
1191
1192 mTouchFocusSelected = true;
1193 }
1194
1195 mFrozenWithFocus = false;
1196 mSelectionMoved = false;
1197
1198 if (mError != null) {
1199 showError();
1200 }
1201
1202 makeBlink();
1203 } else {
1204 if (mError != null) {
1205 hideError();
1206 }
1207 // Don't leave us in the middle of a batch edit.
1208 mTextView.onEndBatchEdit();
1209
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001210 if (mTextView.isInExtractedMode()) {
Mady Mellora2861452015-06-25 08:40:27 -07001211 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001212 stopTextActionModeWithPreservingSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001213 } else {
Mady Mellora2861452015-06-25 08:40:27 -07001214 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001215 if (mTemporaryDetach) {
1216 stopTextActionModeWithPreservingSelection();
1217 } else {
1218 stopTextActionMode();
1219 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001220 downgradeEasyCorrectionSpans();
1221 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001222 // No need to create the controller
1223 if (mSelectionModifierCursorController != null) {
1224 mSelectionModifierCursorController.resetTouchOffsets();
1225 }
1226 }
1227 }
1228
1229 /**
1230 * Downgrades to simple suggestions all the easy correction spans that are not a spell check
1231 * span.
1232 */
1233 private void downgradeEasyCorrectionSpans() {
1234 CharSequence text = mTextView.getText();
1235 if (text instanceof Spannable) {
1236 Spannable spannable = (Spannable) text;
1237 SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
1238 spannable.length(), SuggestionSpan.class);
1239 for (int i = 0; i < suggestionSpans.length; i++) {
1240 int flags = suggestionSpans[i].getFlags();
1241 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
1242 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
1243 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
1244 suggestionSpans[i].setFlags(flags);
1245 }
1246 }
1247 }
1248 }
1249
1250 void sendOnTextChanged(int start, int after) {
1251 updateSpellCheckSpans(start, start + after, false);
1252
Mady Mellor2ff2cd82015-03-02 10:37:01 -08001253 // Flip flag to indicate the word iterator needs to have the text reset.
1254 mUpdateWordIteratorText = true;
1255
Gilles Debunned88876a2012-03-16 17:34:04 -07001256 // Hide the controllers as soon as text is modified (typing, procedural...)
1257 // We do not hide the span controllers, since they can be added when a new text is
1258 // inserted into the text view (voice IME).
1259 hideCursorControllers();
Keisuke Kuroyanagif4e347d2015-06-11 17:41:00 +09001260 // Reset drag accelerator.
1261 if (mSelectionModifierCursorController != null) {
1262 mSelectionModifierCursorController.resetTouchOffsets();
1263 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001264 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07001265 }
1266
1267 private int getLastTapPosition() {
1268 // No need to create the controller at that point, no last tap position saved
1269 if (mSelectionModifierCursorController != null) {
1270 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
1271 if (lastTapPosition >= 0) {
1272 // Safety check, should not be possible.
1273 if (lastTapPosition > mTextView.getText().length()) {
1274 lastTapPosition = mTextView.getText().length();
1275 }
1276 return lastTapPosition;
1277 }
1278 }
1279
1280 return -1;
1281 }
1282
1283 void onWindowFocusChanged(boolean hasWindowFocus) {
1284 if (hasWindowFocus) {
1285 if (mBlink != null) {
1286 mBlink.uncancel();
1287 makeBlink();
1288 }
Mady Mellora2861452015-06-25 08:40:27 -07001289 final InputMethodManager imm = InputMethodManager.peekInstance();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001290 if (mTextView.hasSelection() && !extractedTextModeWillBeStarted()) {
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001291 refreshTextActionMode();
Mady Mellora2861452015-06-25 08:40:27 -07001292 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001293 } else {
1294 if (mBlink != null) {
1295 mBlink.cancel();
1296 }
1297 if (mInputContentType != null) {
1298 mInputContentType.enterDown = false;
1299 }
1300 // Order matters! Must be done before onParentLostFocus to rely on isShowingUp
Mady Mellora2861452015-06-25 08:40:27 -07001301 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001302 stopTextActionModeWithPreservingSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001303 if (mSuggestionsPopupWindow != null) {
1304 mSuggestionsPopupWindow.onParentLostFocus();
1305 }
1306
Gilles Debunnec72fba82012-06-26 14:47:07 -07001307 // Don't leave us in the middle of a batch edit. Same as in onFocusChanged
1308 ensureEndedBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001309 }
1310 }
1311
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09001312 private void updateTapState(MotionEvent event) {
1313 final int action = event.getActionMasked();
1314 if (action == MotionEvent.ACTION_DOWN) {
1315 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
1316 // Detect double tap and triple click.
1317 if (((mTapState == TAP_STATE_FIRST_TAP)
1318 || ((mTapState == TAP_STATE_DOUBLE_TAP) && isMouse))
1319 && (SystemClock.uptimeMillis() - mLastTouchUpTime) <=
1320 ViewConfiguration.getDoubleTapTimeout()) {
1321 if (mTapState == TAP_STATE_FIRST_TAP) {
1322 mTapState = TAP_STATE_DOUBLE_TAP;
1323 } else {
1324 mTapState = TAP_STATE_TRIPLE_CLICK;
1325 }
1326 } else {
1327 mTapState = TAP_STATE_FIRST_TAP;
1328 }
1329 }
1330 if (action == MotionEvent.ACTION_UP) {
1331 mLastTouchUpTime = SystemClock.uptimeMillis();
1332 }
1333 }
1334
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09001335 private boolean shouldFilterOutTouchEvent(MotionEvent event) {
1336 if (!event.isFromSource(InputDevice.SOURCE_MOUSE)) {
1337 return false;
1338 }
1339 final boolean primaryButtonStateChanged =
1340 ((mLastButtonState ^ event.getButtonState()) & MotionEvent.BUTTON_PRIMARY) != 0;
1341 final int action = event.getActionMasked();
1342 if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP)
1343 && !primaryButtonStateChanged) {
1344 return true;
1345 }
1346 if (action == MotionEvent.ACTION_MOVE
1347 && !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
1348 return true;
1349 }
1350 return false;
1351 }
1352
Gilles Debunned88876a2012-03-16 17:34:04 -07001353 void onTouchEvent(MotionEvent event) {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09001354 final boolean filterOutEvent = shouldFilterOutTouchEvent(event);
1355 mLastButtonState = event.getButtonState();
1356 if (filterOutEvent) {
1357 if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1358 mDiscardNextActionUp = true;
1359 }
1360 return;
1361 }
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09001362 updateTapState(event);
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001363 updateFloatingToolbarVisibility(event);
1364
Gilles Debunned88876a2012-03-16 17:34:04 -07001365 if (hasSelectionController()) {
1366 getSelectionController().onTouchEvent(event);
1367 }
1368
1369 if (mShowSuggestionRunnable != null) {
1370 mTextView.removeCallbacks(mShowSuggestionRunnable);
1371 mShowSuggestionRunnable = null;
1372 }
1373
1374 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1375 mLastDownPositionX = event.getX();
1376 mLastDownPositionY = event.getY();
1377
1378 // Reset this state; it will be re-set if super.onTouchEvent
1379 // causes focus to move to the view.
1380 mTouchFocusSelected = false;
1381 mIgnoreActionUpEvent = false;
1382 }
1383 }
1384
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001385 private void updateFloatingToolbarVisibility(MotionEvent event) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001386 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001387 switch (event.getActionMasked()) {
1388 case MotionEvent.ACTION_MOVE:
1389 hideFloatingToolbar();
1390 break;
1391 case MotionEvent.ACTION_UP: // fall through
1392 case MotionEvent.ACTION_CANCEL:
1393 showFloatingToolbar();
1394 }
1395 }
1396 }
1397
1398 private void hideFloatingToolbar() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001399 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001400 mTextView.removeCallbacks(mShowFloatingToolbar);
Abodunrinwa Tokif444b5c2015-06-16 15:47:04 +01001401 mTextActionMode.hide(ActionMode.DEFAULT_HIDE_DURATION);
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001402 }
1403 }
1404
1405 private void showFloatingToolbar() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001406 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001407 // Delay "show" so it doesn't interfere with click confirmations
1408 // or double-clicks that could "dismiss" the floating toolbar.
1409 int delay = ViewConfiguration.getDoubleTapTimeout();
1410 mTextView.postDelayed(mShowFloatingToolbar, delay);
1411 }
1412 }
1413
Gilles Debunned88876a2012-03-16 17:34:04 -07001414 public void beginBatchEdit() {
1415 mInBatchEditControllers = true;
1416 final InputMethodState ims = mInputMethodState;
1417 if (ims != null) {
1418 int nesting = ++ims.mBatchEditNesting;
1419 if (nesting == 1) {
1420 ims.mCursorChanged = false;
1421 ims.mChangedDelta = 0;
1422 if (ims.mContentChanged) {
1423 // We already have a pending change from somewhere else,
1424 // so turn this into a full update.
1425 ims.mChangedStart = 0;
1426 ims.mChangedEnd = mTextView.getText().length();
1427 } else {
1428 ims.mChangedStart = EXTRACT_UNKNOWN;
1429 ims.mChangedEnd = EXTRACT_UNKNOWN;
1430 ims.mContentChanged = false;
1431 }
James Cook48e0fac2015-02-25 15:44:51 -08001432 mUndoInputFilter.beginBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001433 mTextView.onBeginBatchEdit();
1434 }
1435 }
1436 }
1437
1438 public void endBatchEdit() {
1439 mInBatchEditControllers = false;
1440 final InputMethodState ims = mInputMethodState;
1441 if (ims != null) {
1442 int nesting = --ims.mBatchEditNesting;
1443 if (nesting == 0) {
1444 finishBatchEdit(ims);
1445 }
1446 }
1447 }
1448
1449 void ensureEndedBatchEdit() {
1450 final InputMethodState ims = mInputMethodState;
1451 if (ims != null && ims.mBatchEditNesting != 0) {
1452 ims.mBatchEditNesting = 0;
1453 finishBatchEdit(ims);
1454 }
1455 }
1456
1457 void finishBatchEdit(final InputMethodState ims) {
1458 mTextView.onEndBatchEdit();
James Cook48e0fac2015-02-25 15:44:51 -08001459 mUndoInputFilter.endBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001460
1461 if (ims.mContentChanged || ims.mSelectionModeChanged) {
1462 mTextView.updateAfterEdit();
1463 reportExtractedText();
1464 } else if (ims.mCursorChanged) {
Jean Chalardc99d33f2013-02-28 16:39:47 -08001465 // Cheesy way to get us to report the current cursor location.
Gilles Debunned88876a2012-03-16 17:34:04 -07001466 mTextView.invalidateCursor();
1467 }
Jean Chalardc99d33f2013-02-28 16:39:47 -08001468 // sendUpdateSelection knows to avoid sending if the selection did
1469 // not actually change.
1470 sendUpdateSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001471 }
1472
1473 static final int EXTRACT_NOTHING = -2;
1474 static final int EXTRACT_UNKNOWN = -1;
1475
1476 boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
1477 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
1478 EXTRACT_UNKNOWN, outText);
1479 }
1480
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001481 private boolean extractTextInternal(@Nullable ExtractedTextRequest request,
Gilles Debunned88876a2012-03-16 17:34:04 -07001482 int partialStartOffset, int partialEndOffset, int delta,
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001483 @Nullable ExtractedText outText) {
1484 if (request == null || outText == null) {
1485 return false;
Gilles Debunned88876a2012-03-16 17:34:04 -07001486 }
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001487
1488 final CharSequence content = mTextView.getText();
1489 if (content == null) {
1490 return false;
1491 }
1492
1493 if (partialStartOffset != EXTRACT_NOTHING) {
1494 final int N = content.length();
1495 if (partialStartOffset < 0) {
1496 outText.partialStartOffset = outText.partialEndOffset = -1;
1497 partialStartOffset = 0;
1498 partialEndOffset = N;
1499 } else {
1500 // Now use the delta to determine the actual amount of text
1501 // we need.
1502 partialEndOffset += delta;
1503 // Adjust offsets to ensure we contain full spans.
1504 if (content instanceof Spanned) {
1505 Spanned spanned = (Spanned)content;
1506 Object[] spans = spanned.getSpans(partialStartOffset,
1507 partialEndOffset, ParcelableSpan.class);
1508 int i = spans.length;
1509 while (i > 0) {
1510 i--;
1511 int j = spanned.getSpanStart(spans[i]);
1512 if (j < partialStartOffset) partialStartOffset = j;
1513 j = spanned.getSpanEnd(spans[i]);
1514 if (j > partialEndOffset) partialEndOffset = j;
1515 }
1516 }
1517 outText.partialStartOffset = partialStartOffset;
1518 outText.partialEndOffset = partialEndOffset - delta;
1519
1520 if (partialStartOffset > N) {
1521 partialStartOffset = N;
1522 } else if (partialStartOffset < 0) {
1523 partialStartOffset = 0;
1524 }
1525 if (partialEndOffset > N) {
1526 partialEndOffset = N;
1527 } else if (partialEndOffset < 0) {
1528 partialEndOffset = 0;
1529 }
1530 }
1531 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
1532 outText.text = content.subSequence(partialStartOffset,
1533 partialEndOffset);
1534 } else {
1535 outText.text = TextUtils.substring(content, partialStartOffset,
1536 partialEndOffset);
1537 }
1538 } else {
1539 outText.partialStartOffset = 0;
1540 outText.partialEndOffset = 0;
1541 outText.text = "";
1542 }
1543 outText.flags = 0;
1544 if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) {
1545 outText.flags |= ExtractedText.FLAG_SELECTING;
1546 }
1547 if (mTextView.isSingleLine()) {
1548 outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
1549 }
1550 outText.startOffset = 0;
1551 outText.selectionStart = mTextView.getSelectionStart();
1552 outText.selectionEnd = mTextView.getSelectionEnd();
1553 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001554 }
1555
1556 boolean reportExtractedText() {
1557 final Editor.InputMethodState ims = mInputMethodState;
1558 if (ims != null) {
1559 final boolean contentChanged = ims.mContentChanged;
1560 if (contentChanged || ims.mSelectionModeChanged) {
1561 ims.mContentChanged = false;
1562 ims.mSelectionModeChanged = false;
Gilles Debunnec62589c2012-04-12 14:50:23 -07001563 final ExtractedTextRequest req = ims.mExtractedTextRequest;
Gilles Debunned88876a2012-03-16 17:34:04 -07001564 if (req != null) {
1565 InputMethodManager imm = InputMethodManager.peekInstance();
1566 if (imm != null) {
1567 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1568 "Retrieving extracted start=" + ims.mChangedStart +
1569 " end=" + ims.mChangedEnd +
1570 " delta=" + ims.mChangedDelta);
1571 if (ims.mChangedStart < 0 && !contentChanged) {
1572 ims.mChangedStart = EXTRACT_NOTHING;
1573 }
1574 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
Gilles Debunnec62589c2012-04-12 14:50:23 -07001575 ims.mChangedDelta, ims.mExtractedText)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001576 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1577 "Reporting extracted start=" +
Gilles Debunnec62589c2012-04-12 14:50:23 -07001578 ims.mExtractedText.partialStartOffset +
1579 " end=" + ims.mExtractedText.partialEndOffset +
1580 ": " + ims.mExtractedText.text);
1581
1582 imm.updateExtractedText(mTextView, req.token, ims.mExtractedText);
Gilles Debunned88876a2012-03-16 17:34:04 -07001583 ims.mChangedStart = EXTRACT_UNKNOWN;
1584 ims.mChangedEnd = EXTRACT_UNKNOWN;
1585 ims.mChangedDelta = 0;
1586 ims.mContentChanged = false;
1587 return true;
1588 }
1589 }
1590 }
1591 }
1592 }
1593 return false;
1594 }
1595
Jean Chalarddf7c72f2013-02-28 15:28:54 -08001596 private void sendUpdateSelection() {
1597 if (null != mInputMethodState && mInputMethodState.mBatchEditNesting <= 0) {
1598 final InputMethodManager imm = InputMethodManager.peekInstance();
1599 if (null != imm) {
1600 final int selectionStart = mTextView.getSelectionStart();
1601 final int selectionEnd = mTextView.getSelectionEnd();
1602 int candStart = -1;
1603 int candEnd = -1;
1604 if (mTextView.getText() instanceof Spannable) {
1605 final Spannable sp = (Spannable) mTextView.getText();
1606 candStart = EditableInputConnection.getComposingSpanStart(sp);
1607 candEnd = EditableInputConnection.getComposingSpanEnd(sp);
1608 }
Jean Chalardc99d33f2013-02-28 16:39:47 -08001609 // InputMethodManager#updateSelection skips sending the message if
1610 // none of the parameters have changed since the last time we called it.
Jean Chalarddf7c72f2013-02-28 15:28:54 -08001611 imm.updateSelection(mTextView,
1612 selectionStart, selectionEnd, candStart, candEnd);
1613 }
1614 }
1615 }
1616
Gilles Debunned88876a2012-03-16 17:34:04 -07001617 void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint,
1618 int cursorOffsetVertical) {
1619 final int selectionStart = mTextView.getSelectionStart();
1620 final int selectionEnd = mTextView.getSelectionEnd();
1621
1622 final InputMethodState ims = mInputMethodState;
1623 if (ims != null && ims.mBatchEditNesting == 0) {
1624 InputMethodManager imm = InputMethodManager.peekInstance();
1625 if (imm != null) {
1626 if (imm.isActive(mTextView)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001627 if (ims.mContentChanged || ims.mSelectionModeChanged) {
1628 // We are in extract mode and the content has changed
1629 // in some way... just report complete new text to the
1630 // input method.
Yohei Yukawab6bec1a2015-05-01 16:18:25 -07001631 reportExtractedText();
Gilles Debunned88876a2012-03-16 17:34:04 -07001632 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001633 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001634 }
1635 }
1636
1637 if (mCorrectionHighlighter != null) {
1638 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
1639 }
1640
1641 if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) {
1642 drawCursor(canvas, cursorOffsetVertical);
1643 // Rely on the drawable entirely, do not draw the cursor line.
1644 // Has to be done after the IMM related code above which relies on the highlight.
1645 highlight = null;
1646 }
1647
1648 if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) {
1649 drawHardwareAccelerated(canvas, layout, highlight, highlightPaint,
1650 cursorOffsetVertical);
1651 } else {
1652 layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
1653 }
1654 }
1655
1656 private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight,
1657 Paint highlightPaint, int cursorOffsetVertical) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001658 final long lineRange = layout.getLineRangeForDraw(canvas);
1659 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
1660 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
1661 if (lastLine < 0) return;
1662
1663 layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
1664 firstLine, lastLine);
1665
1666 if (layout instanceof DynamicLayout) {
Chris Craik956f3402015-04-27 16:41:00 -07001667 if (mTextRenderNodes == null) {
1668 mTextRenderNodes = ArrayUtils.emptyArray(TextRenderNode.class);
Gilles Debunned88876a2012-03-16 17:34:04 -07001669 }
1670
1671 DynamicLayout dynamicLayout = (DynamicLayout) layout;
Gilles Debunne157aafc2012-04-19 17:21:57 -07001672 int[] blockEndLines = dynamicLayout.getBlockEndLines();
Gilles Debunned88876a2012-03-16 17:34:04 -07001673 int[] blockIndices = dynamicLayout.getBlockIndices();
1674 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
Sangkyu Lee955beb22012-12-10 15:47:00 +09001675 final int indexFirstChangedBlock = dynamicLayout.getIndexFirstChangedBlock();
Gilles Debunned88876a2012-03-16 17:34:04 -07001676
Gilles Debunned88876a2012-03-16 17:34:04 -07001677 int endOfPreviousBlock = -1;
1678 int searchStartIndex = 0;
1679 for (int i = 0; i < numberOfBlocks; i++) {
Gilles Debunne157aafc2012-04-19 17:21:57 -07001680 int blockEndLine = blockEndLines[i];
Gilles Debunned88876a2012-03-16 17:34:04 -07001681 int blockIndex = blockIndices[i];
1682
1683 final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX;
1684 if (blockIsInvalid) {
1685 blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks,
1686 searchStartIndex);
Gilles Debunne157aafc2012-04-19 17:21:57 -07001687 // Note how dynamic layout's internal block indices get updated from Editor
Gilles Debunned88876a2012-03-16 17:34:04 -07001688 blockIndices[i] = blockIndex;
Chris Craik956f3402015-04-27 16:41:00 -07001689 if (mTextRenderNodes[blockIndex] != null) {
1690 mTextRenderNodes[blockIndex].isDirty = true;
Raph Levienbb2397c2015-02-12 16:16:49 -08001691 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001692 searchStartIndex = blockIndex + 1;
1693 }
1694
Chris Craik956f3402015-04-27 16:41:00 -07001695 if (mTextRenderNodes[blockIndex] == null) {
1696 mTextRenderNodes[blockIndex] =
1697 new TextRenderNode("Text " + blockIndex);
Gilles Debunned88876a2012-03-16 17:34:04 -07001698 }
1699
Chris Craik956f3402015-04-27 16:41:00 -07001700 final boolean blockDisplayListIsInvalid = mTextRenderNodes[blockIndex].needsRecord();
1701 RenderNode blockDisplayList = mTextRenderNodes[blockIndex].renderNode;
Sangkyu Lee955beb22012-12-10 15:47:00 +09001702 if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) {
Gilles Debunne157aafc2012-04-19 17:21:57 -07001703 final int blockBeginLine = endOfPreviousBlock + 1;
1704 final int top = layout.getLineTop(blockBeginLine);
1705 final int bottom = layout.getLineBottom(blockEndLine);
Gilles Debunnefd5bc012012-04-23 16:21:35 -07001706 int left = 0;
1707 int right = mTextView.getWidth();
1708 if (mTextView.getHorizontallyScrolling()) {
1709 float min = Float.MAX_VALUE;
1710 float max = Float.MIN_VALUE;
1711 for (int line = blockBeginLine; line <= blockEndLine; line++) {
1712 min = Math.min(min, layout.getLineLeft(line));
1713 max = Math.max(max, layout.getLineRight(line));
1714 }
1715 left = (int) min;
1716 right = (int) (max + 0.5f);
1717 }
Gilles Debunne157aafc2012-04-19 17:21:57 -07001718
Sangkyu Lee955beb22012-12-10 15:47:00 +09001719 // Rebuild display list if it is invalid
1720 if (blockDisplayListIsInvalid) {
Chris Craikf6829a02015-03-10 10:28:59 -07001721 final DisplayListCanvas displayListCanvas = blockDisplayList.start(
Romain Guy52036b12013-02-14 18:03:37 -08001722 right - left, bottom - top);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001723 try {
Romain Guy52036b12013-02-14 18:03:37 -08001724 // drawText is always relative to TextView's origin, this translation
1725 // brings this range of text back to the top left corner of the viewport
Chris Craikf6829a02015-03-10 10:28:59 -07001726 displayListCanvas.translate(-left, -top);
1727 layout.drawText(displayListCanvas, blockBeginLine, blockEndLine);
Chris Craik956f3402015-04-27 16:41:00 -07001728 mTextRenderNodes[blockIndex].isDirty = false;
Romain Guy52036b12013-02-14 18:03:37 -08001729 // No need to untranslate, previous context is popped after
1730 // drawDisplayList
Sangkyu Lee955beb22012-12-10 15:47:00 +09001731 } finally {
Chris Craikf6829a02015-03-10 10:28:59 -07001732 blockDisplayList.end(displayListCanvas);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001733 // Same as drawDisplayList below, handled by our TextView's parent
Chet Haasedd671592013-04-19 14:54:34 -07001734 blockDisplayList.setClipToBounds(false);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001735 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001736 }
Sangkyu Lee955beb22012-12-10 15:47:00 +09001737
1738 // Valid disply list whose index is >= indexFirstChangedBlock
1739 // only needs to update its drawing location.
1740 blockDisplayList.setLeftTopRightBottom(left, top, right, bottom);
Gilles Debunned88876a2012-03-16 17:34:04 -07001741 }
1742
Chris Craik956f3402015-04-27 16:41:00 -07001743 ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList);
Gilles Debunnefd5bc012012-04-23 16:21:35 -07001744
Gilles Debunne157aafc2012-04-19 17:21:57 -07001745 endOfPreviousBlock = blockEndLine;
Gilles Debunned88876a2012-03-16 17:34:04 -07001746 }
Sangkyu Lee955beb22012-12-10 15:47:00 +09001747
1748 dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks);
Gilles Debunned88876a2012-03-16 17:34:04 -07001749 } else {
1750 // Boring layout is used for empty and hint text
1751 layout.drawText(canvas, firstLine, lastLine);
1752 }
1753 }
1754
1755 private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
1756 int searchStartIndex) {
Chris Craik956f3402015-04-27 16:41:00 -07001757 int length = mTextRenderNodes.length;
Gilles Debunned88876a2012-03-16 17:34:04 -07001758 for (int i = searchStartIndex; i < length; i++) {
1759 boolean blockIndexFound = false;
1760 for (int j = 0; j < numberOfBlocks; j++) {
1761 if (blockIndices[j] == i) {
1762 blockIndexFound = true;
1763 break;
1764 }
1765 }
1766 if (blockIndexFound) continue;
1767 return i;
1768 }
1769
1770 // No available index found, the pool has to grow
Chris Craik956f3402015-04-27 16:41:00 -07001771 mTextRenderNodes = GrowingArrayUtils.append(mTextRenderNodes, length, null);
Gilles Debunned88876a2012-03-16 17:34:04 -07001772 return length;
1773 }
1774
1775 private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
1776 final boolean translate = cursorOffsetVertical != 0;
1777 if (translate) canvas.translate(0, cursorOffsetVertical);
1778 for (int i = 0; i < mCursorCount; i++) {
1779 mCursorDrawable[i].draw(canvas);
1780 }
1781 if (translate) canvas.translate(0, -cursorOffsetVertical);
1782 }
1783
Gilles Debunneebc86af2012-04-20 15:10:47 -07001784 /**
1785 * Invalidates all the sub-display lists that overlap the specified character range
1786 */
1787 void invalidateTextDisplayList(Layout layout, int start, int end) {
Chris Craik956f3402015-04-27 16:41:00 -07001788 if (mTextRenderNodes != null && layout instanceof DynamicLayout) {
Gilles Debunneebc86af2012-04-20 15:10:47 -07001789 final int firstLine = layout.getLineForOffset(start);
1790 final int lastLine = layout.getLineForOffset(end);
1791
1792 DynamicLayout dynamicLayout = (DynamicLayout) layout;
1793 int[] blockEndLines = dynamicLayout.getBlockEndLines();
1794 int[] blockIndices = dynamicLayout.getBlockIndices();
1795 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1796
1797 int i = 0;
1798 // Skip the blocks before firstLine
1799 while (i < numberOfBlocks) {
1800 if (blockEndLines[i] >= firstLine) break;
1801 i++;
1802 }
1803
1804 // Invalidate all subsequent blocks until lastLine is passed
1805 while (i < numberOfBlocks) {
1806 final int blockIndex = blockIndices[i];
1807 if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
Chris Craik956f3402015-04-27 16:41:00 -07001808 mTextRenderNodes[blockIndex].isDirty = true;
Gilles Debunneebc86af2012-04-20 15:10:47 -07001809 }
1810 if (blockEndLines[i] >= lastLine) break;
1811 i++;
1812 }
1813 }
1814 }
1815
Gilles Debunned88876a2012-03-16 17:34:04 -07001816 void invalidateTextDisplayList() {
Chris Craik956f3402015-04-27 16:41:00 -07001817 if (mTextRenderNodes != null) {
1818 for (int i = 0; i < mTextRenderNodes.length; i++) {
1819 if (mTextRenderNodes[i] != null) mTextRenderNodes[i].isDirty = true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001820 }
1821 }
1822 }
1823
1824 void updateCursorsPositions() {
1825 if (mTextView.mCursorDrawableRes == 0) {
1826 mCursorCount = 0;
1827 return;
1828 }
1829
Siyamed Sinir987ec652016-02-17 19:44:41 -08001830 Layout layout = mTextView.getLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -07001831 final int offset = mTextView.getSelectionStart();
1832 final int line = layout.getLineForOffset(offset);
1833 final int top = layout.getLineTop(line);
1834 final int bottom = layout.getLineTop(line + 1);
1835
1836 mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1;
1837
1838 int middle = bottom;
1839 if (mCursorCount == 2) {
1840 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
1841 middle = (top + bottom) >> 1;
1842 }
1843
Raph Levienafe8e9b2012-12-19 16:09:32 -08001844 boolean clamped = layout.shouldClampCursor(line);
Mady Mellorff66ca52015-07-08 12:31:45 -07001845 updateCursorPosition(0, top, middle, layout.getPrimaryHorizontal(offset, clamped));
Gilles Debunned88876a2012-03-16 17:34:04 -07001846
1847 if (mCursorCount == 2) {
Siyamed Sinir217c0f72016-02-01 18:30:02 -08001848 updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset, clamped));
Gilles Debunned88876a2012-03-16 17:34:04 -07001849 }
1850 }
1851
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001852 void refreshTextActionMode() {
1853 if (extractedTextModeWillBeStarted()) {
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001854 mRestartActionModeOnNextRefresh = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001855 return;
1856 }
1857 final boolean hasSelection = mTextView.hasSelection();
1858 final SelectionModifierCursorController selectionController = getSelectionController();
1859 final InsertionPointCursorController insertionController = getInsertionController();
1860 if ((selectionController != null && selectionController.isCursorBeingModified())
1861 || (insertionController != null && insertionController.isCursorBeingModified())) {
1862 // ActionMode should be managed by the currently active cursor controller.
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001863 mRestartActionModeOnNextRefresh = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001864 return;
1865 }
1866 if (hasSelection) {
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001867 hideInsertionPointCursorController();
1868 if (mTextActionMode == null) {
1869 if (mRestartActionModeOnNextRefresh || mTextView.isInExtractedMode()) {
1870 // To avoid distraction, newly start action mode only when selection action
1871 // mode is being restarted or in full screen extracted mode.
1872 startSelectionActionMode();
1873 }
1874 } else if (selectionController == null || !selectionController.isActive()) {
1875 // Insertion action mode is active. Avoid dismissing the selection.
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001876 stopTextActionModeWithPreservingSelection();
1877 startSelectionActionMode();
1878 } else {
1879 mTextActionMode.invalidateContentRect();
1880 }
1881 } else {
1882 // Insertion action mode is started only when insertion controller is explicitly
1883 // activated.
1884 if (insertionController == null || !insertionController.isActive()) {
1885 stopTextActionMode();
1886 } else if (mTextActionMode != null) {
1887 mTextActionMode.invalidateContentRect();
1888 }
1889 }
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001890 mRestartActionModeOnNextRefresh = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001891 }
1892
Gilles Debunned88876a2012-03-16 17:34:04 -07001893 /**
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001894 * Start an Insertion action mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07001895 */
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001896 void startInsertionActionMode() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001897 if (mInsertionActionModeRunnable != null) {
1898 mTextView.removeCallbacks(mInsertionActionModeRunnable);
1899 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001900 if (extractedTextModeWillBeStarted()) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001901 return;
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001902 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001903 stopTextActionMode();
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001904
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001905 ActionMode.Callback actionModeCallback =
1906 new TextActionModeCallback(false /* hasSelection */);
1907 mTextActionMode = mTextView.startActionMode(
Clara Bayarrib8ed5b72015-04-09 15:26:41 +01001908 actionModeCallback, ActionMode.TYPE_FLOATING);
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001909 if (mTextActionMode != null && getInsertionController() != null) {
1910 getInsertionController().show();
1911 }
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001912 }
1913
1914 /**
Clara Bayarri578286f2015-04-10 15:35:31 +01001915 * Starts a Selection Action Mode with the current selection and ensures the selection handles
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001916 * are shown if there is a selection. This should be used when the mode is started from a
1917 * non-touch event.
Clara Bayarri578286f2015-04-10 15:35:31 +01001918 *
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001919 * @return true if the selection mode was actually started.
1920 */
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001921 boolean startSelectionActionMode() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001922 boolean selectionStarted = startSelectionActionModeInternal();
Clara Bayarri578286f2015-04-10 15:35:31 +01001923 if (selectionStarted) {
1924 getSelectionController().show();
1925 }
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09001926 mRestartActionModeOnNextRefresh = false;
Clara Bayarri578286f2015-04-10 15:35:31 +01001927 return selectionStarted;
1928 }
1929
Clara Bayarridfac4432015-05-15 12:18:24 +01001930 /**
1931 * If the TextView allows text selection, selects the current word when no existing selection
1932 * was available and starts a drag.
1933 *
1934 * @return true if the drag was started.
1935 */
1936 private boolean selectCurrentWordAndStartDrag() {
Clara Bayarri7184c8a2015-06-05 17:34:09 +01001937 if (mInsertionActionModeRunnable != null) {
1938 mTextView.removeCallbacks(mInsertionActionModeRunnable);
1939 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001940 if (extractedTextModeWillBeStarted()) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001941 return false;
1942 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001943 if (!checkField()) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001944 return false;
1945 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001946 if (!mTextView.hasSelection() && !selectCurrentWord()) {
1947 // No selection and cannot select a word.
1948 return false;
1949 }
1950 stopTextActionModeWithPreservingSelection();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08001951 getSelectionController().enterDrag(
1952 SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_WORD);
Clara Bayarridfac4432015-05-15 12:18:24 +01001953 return true;
1954 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001955
Clara Bayarridfac4432015-05-15 12:18:24 +01001956 /**
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001957 * Checks whether a selection can be performed on the current TextView.
Clara Bayarridfac4432015-05-15 12:18:24 +01001958 *
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001959 * @return true if a selection can be performed
Clara Bayarridfac4432015-05-15 12:18:24 +01001960 */
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001961 boolean checkField() {
Clara Bayarridfac4432015-05-15 12:18:24 +01001962 if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
1963 Log.w(TextView.LOG_TAG,
1964 "TextView does not support text selection. Selection cancelled.");
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001965 return false;
1966 }
Clara Bayarridfac4432015-05-15 12:18:24 +01001967 return true;
1968 }
1969
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001970 private boolean startSelectionActionModeInternal() {
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001971 if (extractedTextModeWillBeStarted()) {
1972 return false;
1973 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001974 if (mTextActionMode != null) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001975 // Text action mode is already started
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001976 mTextActionMode.invalidate();
Gilles Debunned88876a2012-03-16 17:34:04 -07001977 return false;
1978 }
1979
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001980 if (!checkField() || !mTextView.hasSelection()) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001981 return false;
1982 }
1983
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001984 ActionMode.Callback actionModeCallback =
1985 new TextActionModeCallback(true /* hasSelection */);
1986 mTextActionMode = mTextView.startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING);
Gilles Debunned88876a2012-03-16 17:34:04 -07001987
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001988 final boolean selectionStarted = mTextActionMode != null;
Gilles Debunne3473b2b2012-04-20 16:21:10 -07001989 if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001990 // Show the IME to be able to replace text, except when selecting non editable text.
1991 final InputMethodManager imm = InputMethodManager.peekInstance();
1992 if (imm != null) {
1993 imm.showSoftInput(mTextView, 0, null);
1994 }
1995 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001996 return selectionStarted;
1997 }
1998
Andrei Stingaceanu99d3bbd2015-06-30 16:57:03 +01001999 boolean extractedTextModeWillBeStarted() {
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01002000 if (!(mTextView.isInExtractedMode())) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002001 final InputMethodManager imm = InputMethodManager.peekInstance();
2002 return imm != null && imm.isFullscreenMode();
2003 }
2004 return false;
2005 }
2006
2007 /**
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002008 * @return <code>true</code> if it's reasonable to offer to show suggestions depending on
2009 * the current cursor position or selection range. This method is consistent with the
2010 * method to show suggestions {@link SuggestionsPopupWindow#updateSuggestions}.
Gilles Debunned88876a2012-03-16 17:34:04 -07002011 */
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002012 private boolean shouldOfferToShowSuggestions() {
Gilles Debunned88876a2012-03-16 17:34:04 -07002013 CharSequence text = mTextView.getText();
2014 if (!(text instanceof Spannable)) return false;
2015
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002016 final Spannable spannable = (Spannable) text;
2017 final int selectionStart = mTextView.getSelectionStart();
2018 final int selectionEnd = mTextView.getSelectionEnd();
2019 final SuggestionSpan[] suggestionSpans = spannable.getSpans(selectionStart, selectionEnd,
2020 SuggestionSpan.class);
2021 if (suggestionSpans.length == 0) {
2022 return false;
2023 }
2024 if (selectionStart == selectionEnd) {
2025 // Spans overlap the cursor.
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002026 for (int i = 0; i < suggestionSpans.length; i++) {
2027 if (suggestionSpans[i].getSuggestions().length > 0) {
2028 return true;
2029 }
2030 }
2031 return false;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002032 }
2033 int minSpanStart = mTextView.getText().length();
2034 int maxSpanEnd = 0;
2035 int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length();
2036 int unionOfSpansCoveringSelectionStartEnd = 0;
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002037 boolean hasValidSuggestions = false;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002038 for (int i = 0; i < suggestionSpans.length; i++) {
2039 final int spanStart = spannable.getSpanStart(suggestionSpans[i]);
2040 final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]);
2041 minSpanStart = Math.min(minSpanStart, spanStart);
2042 maxSpanEnd = Math.max(maxSpanEnd, spanEnd);
2043 if (selectionStart < spanStart || selectionStart > spanEnd) {
2044 // The span doesn't cover the current selection start point.
2045 continue;
2046 }
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002047 hasValidSuggestions =
2048 hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002049 unionOfSpansCoveringSelectionStartStart =
2050 Math.min(unionOfSpansCoveringSelectionStartStart, spanStart);
2051 unionOfSpansCoveringSelectionStartEnd =
2052 Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd);
2053 }
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002054 if (!hasValidSuggestions) {
2055 return false;
2056 }
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002057 if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) {
2058 // No spans cover the selection start point.
2059 return false;
2060 }
2061 if (minSpanStart < unionOfSpansCoveringSelectionStartStart
2062 || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) {
2063 // There is a span that is not covered by the union. In this case, we soouldn't offer
2064 // to show suggestions as it's confusing.
2065 return false;
2066 }
2067 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -07002068 }
2069
2070 /**
2071 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
2072 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
2073 */
2074 private boolean isCursorInsideEasyCorrectionSpan() {
2075 Spannable spannable = (Spannable) mTextView.getText();
2076 SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
2077 mTextView.getSelectionEnd(), SuggestionSpan.class);
2078 for (int i = 0; i < suggestionSpans.length; i++) {
2079 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
2080 return true;
2081 }
2082 }
2083 return false;
2084 }
2085
2086 void onTouchUpEvent(MotionEvent event) {
2087 boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
Mady Mellora2861452015-06-25 08:40:27 -07002088 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002089 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07002090 CharSequence text = mTextView.getText();
2091 if (!selectAllGotFocus && text.length() > 0) {
2092 // Move cursor
2093 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2094 Selection.setSelection((Spannable) text, offset);
2095 if (mSpellChecker != null) {
2096 // When the cursor moves, the word that was typed may need spell check
2097 mSpellChecker.onSelectionChanged();
2098 }
Andrei Stingaceanu35c550c2015-05-07 16:49:49 +01002099
Gilles Debunned88876a2012-03-16 17:34:04 -07002100 if (!extractedTextModeWillBeStarted()) {
2101 if (isCursorInsideEasyCorrectionSpan()) {
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01002102 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002103 if (mInsertionActionModeRunnable != null) {
2104 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01002105 }
2106
Gilles Debunned88876a2012-03-16 17:34:04 -07002107 mShowSuggestionRunnable = new Runnable() {
2108 public void run() {
Keisuke Kuroyanagi713be062016-02-29 16:07:54 -08002109 replace();
Gilles Debunned88876a2012-03-16 17:34:04 -07002110 }
2111 };
2112 // removeCallbacks is performed on every touch
2113 mTextView.postDelayed(mShowSuggestionRunnable,
2114 ViewConfiguration.getDoubleTapTimeout());
2115 } else if (hasInsertionController()) {
2116 getInsertionController().show();
2117 }
2118 }
2119 }
2120 }
2121
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002122 protected void stopTextActionMode() {
2123 if (mTextActionMode != null) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002124 // This will hide the mSelectionModifierCursorController
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002125 mTextActionMode.finish();
Gilles Debunned88876a2012-03-16 17:34:04 -07002126 }
2127 }
2128
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002129 private void stopTextActionModeWithPreservingSelection() {
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09002130 if (mTextActionMode != null) {
2131 mRestartActionModeOnNextRefresh = true;
2132 }
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08002133 mPreserveSelection = true;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002134 stopTextActionMode();
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08002135 mPreserveSelection = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002136 }
2137
Gilles Debunned88876a2012-03-16 17:34:04 -07002138 /**
2139 * @return True if this view supports insertion handles.
2140 */
2141 boolean hasInsertionController() {
2142 return mInsertionControllerEnabled;
2143 }
2144
2145 /**
2146 * @return True if this view supports selection handles.
2147 */
2148 boolean hasSelectionController() {
2149 return mSelectionControllerEnabled;
2150 }
2151
2152 InsertionPointCursorController getInsertionController() {
2153 if (!mInsertionControllerEnabled) {
2154 return null;
2155 }
2156
2157 if (mInsertionPointCursorController == null) {
2158 mInsertionPointCursorController = new InsertionPointCursorController();
2159
2160 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2161 observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
2162 }
2163
2164 return mInsertionPointCursorController;
2165 }
2166
2167 SelectionModifierCursorController getSelectionController() {
2168 if (!mSelectionControllerEnabled) {
2169 return null;
2170 }
2171
2172 if (mSelectionModifierCursorController == null) {
2173 mSelectionModifierCursorController = new SelectionModifierCursorController();
2174
2175 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2176 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
2177 }
2178
2179 return mSelectionModifierCursorController;
2180 }
2181
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002182 /**
2183 * @hide
2184 */
2185 @VisibleForTesting
2186 public Drawable[] getCursorDrawable() {
2187 return mCursorDrawable;
2188 }
2189
Gilles Debunned88876a2012-03-16 17:34:04 -07002190 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
2191 if (mCursorDrawable[cursorIndex] == null)
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002192 mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07002193 mTextView.mCursorDrawableRes);
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002194 final Drawable drawable = mCursorDrawable[cursorIndex];
Siyamed Sinir987ec652016-02-17 19:44:41 -08002195 final int left = clampHorizontalPosition(drawable, horizontal);
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002196 final int width = drawable.getIntrinsicWidth();
2197 drawable.setBounds(left, top - mTempRect.top, left + width,
Gilles Debunned88876a2012-03-16 17:34:04 -07002198 bottom + mTempRect.bottom);
2199 }
2200
2201 /**
Siyamed Sinir987ec652016-02-17 19:44:41 -08002202 * Return clamped position for the drawable. If the drawable is within the boundaries of the
2203 * view, then it is offset with the left padding of the cursor drawable. If the drawable is at
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002204 * the beginning or the end of the text then its drawable edge is aligned with left or right of
Siyamed Sinir987ec652016-02-17 19:44:41 -08002205 * the view boundary. If the drawable is null, horizontal parameter is aligned to left or right
2206 * of the view.
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002207 *
Siyamed Sinir987ec652016-02-17 19:44:41 -08002208 * @param drawable Drawable. Can be null.
2209 * @param horizontal Horizontal position for the drawable.
2210 * @return The clamped horizontal position for the drawable.
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002211 */
Siyamed Sinir987ec652016-02-17 19:44:41 -08002212 private int clampHorizontalPosition(@Nullable final Drawable drawable, float horizontal) {
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002213 horizontal = Math.max(0.5f, horizontal - 0.5f);
2214 if (mTempRect == null) mTempRect = new Rect();
Siyamed Sinir987ec652016-02-17 19:44:41 -08002215
2216 int drawableWidth = 0;
2217 if (drawable != null) {
2218 drawable.getPadding(mTempRect);
2219 drawableWidth = drawable.getIntrinsicWidth();
2220 } else {
2221 mTempRect.setEmpty();
2222 }
2223
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002224 int scrollX = mTextView.getScrollX();
2225 float horizontalDiff = horizontal - scrollX;
2226 int viewClippedWidth = mTextView.getWidth() - mTextView.getCompoundPaddingLeft()
2227 - mTextView.getCompoundPaddingRight();
2228
2229 final int left;
2230 if (horizontalDiff >= (viewClippedWidth - 1f)) {
2231 // at the rightmost position
Siyamed Sinir987ec652016-02-17 19:44:41 -08002232 left = viewClippedWidth + scrollX - (drawableWidth - mTempRect.right);
2233 } else if (Math.abs(horizontalDiff) <= 1f ||
2234 (TextUtils.isEmpty(mTextView.getText())
2235 && (TextView.VERY_WIDE - scrollX) <= (viewClippedWidth + 1f)
2236 && horizontal <= 1f)) {
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002237 // at the leftmost position
2238 left = scrollX - mTempRect.left;
2239 } else {
2240 left = (int) horizontal - mTempRect.left;
2241 }
2242 return left;
2243 }
2244
2245 /**
Gilles Debunned88876a2012-03-16 17:34:04 -07002246 * Called by the framework in response to a text auto-correction (such as fixing a typo using a
James Cookf59152c2015-02-26 18:03:58 -08002247 * a dictionary) from the current input method, provided by it calling
Gilles Debunned88876a2012-03-16 17:34:04 -07002248 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
2249 * implementation flashes the background of the corrected word to provide feedback to the user.
2250 *
2251 * @param info The auto correct info about the text that was corrected.
2252 */
2253 public void onCommitCorrection(CorrectionInfo info) {
2254 if (mCorrectionHighlighter == null) {
2255 mCorrectionHighlighter = new CorrectionHighlighter();
2256 } else {
2257 mCorrectionHighlighter.invalidate(false);
2258 }
2259
2260 mCorrectionHighlighter.highlight(info);
2261 }
2262
Gilles Debunned88876a2012-03-16 17:34:04 -07002263 void onScrollChanged() {
Gilles Debunne157aafc2012-04-19 17:21:57 -07002264 if (mPositionListener != null) {
2265 mPositionListener.onScrollChanged();
2266 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002267 if (mTextActionMode != null) {
2268 mTextActionMode.invalidateContentRect();
Abodunrinwa Toki56195db2015-04-22 06:46:54 +01002269 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002270 }
2271
2272 /**
2273 * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
2274 */
2275 private boolean shouldBlink() {
2276 if (!isCursorVisible() || !mTextView.isFocused()) return false;
2277
2278 final int start = mTextView.getSelectionStart();
2279 if (start < 0) return false;
2280
2281 final int end = mTextView.getSelectionEnd();
2282 if (end < 0) return false;
2283
2284 return start == end;
2285 }
2286
2287 void makeBlink() {
2288 if (shouldBlink()) {
2289 mShowCursor = SystemClock.uptimeMillis();
2290 if (mBlink == null) mBlink = new Blink();
John Reckd0374c62015-10-20 13:25:01 -07002291 mTextView.removeCallbacks(mBlink);
2292 mTextView.postDelayed(mBlink, BLINK);
Gilles Debunned88876a2012-03-16 17:34:04 -07002293 } else {
John Reckd0374c62015-10-20 13:25:01 -07002294 if (mBlink != null) mTextView.removeCallbacks(mBlink);
Gilles Debunned88876a2012-03-16 17:34:04 -07002295 }
2296 }
2297
John Reckd0374c62015-10-20 13:25:01 -07002298 private class Blink implements Runnable {
Gilles Debunned88876a2012-03-16 17:34:04 -07002299 private boolean mCancelled;
2300
2301 public void run() {
Gilles Debunned88876a2012-03-16 17:34:04 -07002302 if (mCancelled) {
2303 return;
2304 }
2305
John Reckd0374c62015-10-20 13:25:01 -07002306 mTextView.removeCallbacks(this);
Gilles Debunned88876a2012-03-16 17:34:04 -07002307
2308 if (shouldBlink()) {
2309 if (mTextView.getLayout() != null) {
2310 mTextView.invalidateCursorPath();
2311 }
2312
John Reckd0374c62015-10-20 13:25:01 -07002313 mTextView.postDelayed(this, BLINK);
Gilles Debunned88876a2012-03-16 17:34:04 -07002314 }
2315 }
2316
2317 void cancel() {
2318 if (!mCancelled) {
John Reckd0374c62015-10-20 13:25:01 -07002319 mTextView.removeCallbacks(this);
Gilles Debunned88876a2012-03-16 17:34:04 -07002320 mCancelled = true;
2321 }
2322 }
2323
2324 void uncancel() {
2325 mCancelled = false;
2326 }
2327 }
2328
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08002329 private DragShadowBuilder getTextThumbnailBuilder(int start, int end) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002330 TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
2331 com.android.internal.R.layout.text_drag_thumbnail, null);
2332
2333 if (shadowView == null) {
2334 throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
2335 }
2336
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08002337 if (end - start > DRAG_SHADOW_MAX_TEXT_LENGTH) {
2338 final long range = getCharClusterRange(start + DRAG_SHADOW_MAX_TEXT_LENGTH);
2339 end = TextUtils.unpackRangeEndFromLong(range);
Gilles Debunned88876a2012-03-16 17:34:04 -07002340 }
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08002341 final CharSequence text = mTextView.getTransformedText(start, end);
Gilles Debunned88876a2012-03-16 17:34:04 -07002342 shadowView.setText(text);
2343 shadowView.setTextColor(mTextView.getTextColors());
2344
Alan Viverettebb98ebd2015-05-08 17:17:44 -07002345 shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge);
Gilles Debunned88876a2012-03-16 17:34:04 -07002346 shadowView.setGravity(Gravity.CENTER);
2347
2348 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2349 ViewGroup.LayoutParams.WRAP_CONTENT));
2350
2351 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
2352 shadowView.measure(size, size);
2353
2354 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
2355 shadowView.invalidate();
2356 return new DragShadowBuilder(shadowView);
2357 }
2358
2359 private static class DragLocalState {
2360 public TextView sourceTextView;
2361 public int start, end;
2362
2363 public DragLocalState(TextView sourceTextView, int start, int end) {
2364 this.sourceTextView = sourceTextView;
2365 this.start = start;
2366 this.end = end;
2367 }
2368 }
2369
2370 void onDrop(DragEvent event) {
2371 StringBuilder content = new StringBuilder("");
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -08002372
2373 final DropPermissions dropPermissions = DropPermissions.obtain(event);
2374 if (dropPermissions != null) {
2375 dropPermissions.takeTransient();
2376 }
2377
2378 try {
2379 ClipData clipData = event.getClipData();
2380 final int itemCount = clipData.getItemCount();
2381 for (int i=0; i < itemCount; i++) {
2382 Item item = clipData.getItemAt(i);
2383 content.append(item.coerceToStyledText(mTextView.getContext()));
2384 }
2385 }
2386 finally {
2387 if (dropPermissions != null) {
2388 dropPermissions.release();
2389 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002390 }
2391
2392 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2393
2394 Object localState = event.getLocalState();
2395 DragLocalState dragLocalState = null;
2396 if (localState instanceof DragLocalState) {
2397 dragLocalState = (DragLocalState) localState;
2398 }
2399 boolean dragDropIntoItself = dragLocalState != null &&
2400 dragLocalState.sourceTextView == mTextView;
2401
2402 if (dragDropIntoItself) {
2403 if (offset >= dragLocalState.start && offset < dragLocalState.end) {
2404 // A drop inside the original selection discards the drop.
2405 return;
2406 }
2407 }
2408
2409 final int originalLength = mTextView.getText().length();
Raph Levien5a689ce2014-09-10 11:03:18 -07002410 int min = offset;
2411 int max = offset;
Gilles Debunned88876a2012-03-16 17:34:04 -07002412
2413 Selection.setSelection((Spannable) mTextView.getText(), max);
2414 mTextView.replaceText_internal(min, max, content);
2415
2416 if (dragDropIntoItself) {
2417 int dragSourceStart = dragLocalState.start;
2418 int dragSourceEnd = dragLocalState.end;
2419 if (max <= dragSourceStart) {
2420 // Inserting text before selection has shifted positions
2421 final int shift = mTextView.getText().length() - originalLength;
2422 dragSourceStart += shift;
2423 dragSourceEnd += shift;
2424 }
2425
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08002426 mUndoInputFilter.setForceMerge(true);
2427 try {
2428 // Delete original selection
2429 mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
Gilles Debunned88876a2012-03-16 17:34:04 -07002430
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08002431 // Make sure we do not leave two adjacent spaces.
2432 final int prevCharIdx = Math.max(0, dragSourceStart - 1);
2433 final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1);
2434 if (nextCharIdx > prevCharIdx + 1) {
2435 CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx);
2436 if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) {
2437 mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1);
2438 }
Victoria Lease91373202012-09-07 16:41:59 -07002439 }
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08002440 } finally {
2441 mUndoInputFilter.setForceMerge(false);
Gilles Debunned88876a2012-03-16 17:34:04 -07002442 }
2443 }
2444 }
2445
Gilles Debunnec62589c2012-04-12 14:50:23 -07002446 public void addSpanWatchers(Spannable text) {
2447 final int textLength = text.length();
2448
2449 if (mKeyListener != null) {
2450 text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2451 }
2452
Jean Chalardbaf30942013-02-28 16:01:51 -08002453 if (mSpanController == null) {
2454 mSpanController = new SpanController();
Gilles Debunnec62589c2012-04-12 14:50:23 -07002455 }
Jean Chalardbaf30942013-02-28 16:01:51 -08002456 text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002457 }
2458
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002459 void setContextMenuAnchor(float x, float y) {
2460 mContextMenuAnchorX = x;
2461 mContextMenuAnchorY = y;
2462 }
2463
2464 void onCreateContextMenu(ContextMenu menu) {
2465 if (mIsBeingLongClicked || Float.isNaN(mContextMenuAnchorX)
2466 || Float.isNaN(mContextMenuAnchorY)) {
2467 return;
2468 }
2469 final int offset = mTextView.getOffsetForPosition(mContextMenuAnchorX, mContextMenuAnchorY);
2470 if (offset == -1) {
2471 return;
2472 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002473 stopTextActionModeWithPreservingSelection();
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002474 final boolean isOnSelection = mTextView.hasSelection()
2475 && offset >= mTextView.getSelectionStart() && offset <= mTextView.getSelectionEnd();
2476 if (!isOnSelection) {
2477 // Right clicked position is not on the selection. Remove the selection and move the
2478 // cursor to the right clicked position.
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002479 Selection.setSelection((Spannable) mTextView.getText(), offset);
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002480 stopTextActionMode();
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002481 }
2482
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002483 if (shouldOfferToShowSuggestions()) {
Keisuke Kuroyanagi182f5fe2016-03-11 16:31:29 +09002484 final SuggestionInfo[] suggestionInfoArray =
2485 new SuggestionInfo[SuggestionSpan.SUGGESTIONS_MAX_SIZE];
2486 for (int i = 0; i < suggestionInfoArray.length; i++) {
2487 suggestionInfoArray[i] = new SuggestionInfo();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002488 }
2489 final SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, MENU_ITEM_ORDER_REPLACE,
2490 com.android.internal.R.string.replace);
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09002491 final int numItems = mSuggestionHelper.getSuggestionInfo(suggestionInfoArray, null);
Keisuke Kuroyanagi182f5fe2016-03-11 16:31:29 +09002492 for (int i = 0; i < numItems; i++) {
2493 final SuggestionInfo info = suggestionInfoArray[i];
2494 subMenu.add(Menu.NONE, Menu.NONE, i, info.mText)
2495 .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2496 @Override
2497 public boolean onMenuItemClick(MenuItem item) {
2498 replaceWithSuggestion(info);
2499 return true;
2500 }
2501 });
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002502 }
2503 }
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002504
2505 menu.add(Menu.NONE, TextView.ID_UNDO, MENU_ITEM_ORDER_UNDO,
2506 com.android.internal.R.string.undo)
2507 .setAlphabeticShortcut('z')
2508 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2509 .setEnabled(mTextView.canUndo());
2510 menu.add(Menu.NONE, TextView.ID_REDO, MENU_ITEM_ORDER_REDO,
2511 com.android.internal.R.string.redo)
2512 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2513 .setEnabled(mTextView.canRedo());
2514
2515 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
2516 com.android.internal.R.string.cut)
2517 .setAlphabeticShortcut('x')
2518 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2519 .setEnabled(mTextView.canCut());
2520 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
2521 com.android.internal.R.string.copy)
2522 .setAlphabeticShortcut('c')
2523 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2524 .setEnabled(mTextView.canCopy());
2525 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
2526 com.android.internal.R.string.paste)
2527 .setAlphabeticShortcut('v')
2528 .setEnabled(mTextView.canPaste())
2529 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2530 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT,
2531 com.android.internal.R.string.paste_as_plain_text)
2532 .setEnabled(mTextView.canPaste())
2533 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2534 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
2535 com.android.internal.R.string.share)
2536 .setEnabled(mTextView.canShare())
2537 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2538 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
2539 com.android.internal.R.string.selectAll)
2540 .setAlphabeticShortcut('a')
2541 .setEnabled(mTextView.canSelectAllText())
2542 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2543
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08002544 mPreserveSelection = true;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002545 }
2546
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09002547 @Nullable
2548 private SuggestionSpan findEquivalentSuggestionSpan(
2549 @NonNull SuggestionSpanInfo suggestionSpanInfo) {
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002550 final Editable editable = (Editable) mTextView.getText();
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09002551 if (editable.getSpanStart(suggestionSpanInfo.mSuggestionSpan) >= 0) {
2552 // Exactly same span is found.
2553 return suggestionSpanInfo.mSuggestionSpan;
2554 }
2555 // Suggestion span couldn't be found. Try to find a suggestion span that has the same
2556 // contents.
2557 final SuggestionSpan[] suggestionSpans = editable.getSpans(suggestionSpanInfo.mSpanStart,
2558 suggestionSpanInfo.mSpanEnd, SuggestionSpan.class);
2559 for (final SuggestionSpan suggestionSpan : suggestionSpans) {
2560 final int start = editable.getSpanStart(suggestionSpan);
2561 if (start != suggestionSpanInfo.mSpanStart) {
2562 continue;
2563 }
2564 final int end = editable.getSpanEnd(suggestionSpan);
2565 if (end != suggestionSpanInfo.mSpanEnd) {
2566 continue;
2567 }
2568 if (suggestionSpan.equals(suggestionSpanInfo.mSuggestionSpan)) {
2569 return suggestionSpan;
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08002570 }
2571 }
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09002572 return null;
2573 }
2574
2575 private void replaceWithSuggestion(@NonNull final SuggestionInfo suggestionInfo) {
2576 final SuggestionSpan targetSuggestionSpan = findEquivalentSuggestionSpan(
2577 suggestionInfo.mSuggestionSpanInfo);
2578 if (targetSuggestionSpan == null) {
2579 // Span has been removed
2580 return;
2581 }
2582 final Editable editable = (Editable) mTextView.getText();
2583 final int spanStart = editable.getSpanStart(targetSuggestionSpan);
2584 final int spanEnd = editable.getSpanEnd(targetSuggestionSpan);
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08002585 if (spanStart < 0 || spanEnd <= spanStart) {
2586 // Span has been removed
2587 return;
2588 }
2589
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002590 final String originalText = TextUtils.substring(editable, spanStart, spanEnd);
2591 // SuggestionSpans are removed by replace: save them before
2592 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
2593 SuggestionSpan.class);
2594 final int length = suggestionSpans.length;
2595 int[] suggestionSpansStarts = new int[length];
2596 int[] suggestionSpansEnds = new int[length];
2597 int[] suggestionSpansFlags = new int[length];
2598 for (int i = 0; i < length; i++) {
2599 final SuggestionSpan suggestionSpan = suggestionSpans[i];
2600 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
2601 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
2602 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
2603
2604 // Remove potential misspelled flags
2605 int suggestionSpanFlags = suggestionSpan.getFlags();
2606 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2607 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
2608 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
2609 suggestionSpan.setFlags(suggestionSpanFlags);
2610 }
2611 }
2612
2613 // Notify source IME of the suggestion pick. Do this before swapping texts.
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09002614 targetSuggestionSpan.notifySelection(
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002615 mTextView.getContext(), originalText, suggestionInfo.mSuggestionIndex);
2616
2617 // Swap text content between actual text and Suggestion span
2618 final int suggestionStart = suggestionInfo.mSuggestionStart;
2619 final int suggestionEnd = suggestionInfo.mSuggestionEnd;
2620 final String suggestion = suggestionInfo.mText.subSequence(
2621 suggestionStart, suggestionEnd).toString();
2622 mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
2623
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09002624 String[] suggestions = targetSuggestionSpan.getSuggestions();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002625 suggestions[suggestionInfo.mSuggestionIndex] = originalText;
2626
2627 // Restore previous SuggestionSpans
2628 final int lengthDelta = suggestion.length() - (spanEnd - spanStart);
2629 for (int i = 0; i < length; i++) {
2630 // Only spans that include the modified region make sense after replacement
2631 // Spans partially included in the replaced region are removed, there is no
2632 // way to assign them a valid range after replacement
2633 if (suggestionSpansStarts[i] <= spanStart && suggestionSpansEnds[i] >= spanEnd) {
2634 mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
2635 suggestionSpansEnds[i] + lengthDelta, suggestionSpansFlags[i]);
2636 }
2637 }
2638 // Move cursor at the end of the replaced word
2639 final int newCursorPosition = spanEnd + lengthDelta;
2640 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
2641 }
2642
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002643 private final MenuItem.OnMenuItemClickListener mOnContextMenuItemClickListener =
2644 new MenuItem.OnMenuItemClickListener() {
2645 @Override
2646 public boolean onMenuItemClick(MenuItem item) {
2647 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
2648 return true;
2649 }
2650 return mTextView.onTextContextMenuItem(item.getItemId());
2651 }
2652 };
2653
Gilles Debunned88876a2012-03-16 17:34:04 -07002654 /**
2655 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
2656 * pop-up should be displayed.
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07002657 * Also monitors {@link Selection} to call back to the attached input method.
Gilles Debunned88876a2012-03-16 17:34:04 -07002658 */
Jean Chalardbaf30942013-02-28 16:01:51 -08002659 class SpanController implements SpanWatcher {
Gilles Debunned88876a2012-03-16 17:34:04 -07002660
2661 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
2662
2663 private EasyEditPopupWindow mPopupWindow;
2664
Gilles Debunned88876a2012-03-16 17:34:04 -07002665 private Runnable mHidePopup;
2666
Jean Chalardbaf30942013-02-28 16:01:51 -08002667 // This function is pure but inner classes can't have static functions
2668 private boolean isNonIntermediateSelectionSpan(final Spannable text,
2669 final Object span) {
2670 return (Selection.SELECTION_START == span || Selection.SELECTION_END == span)
2671 && (text.getSpanFlags(span) & Spanned.SPAN_INTERMEDIATE) == 0;
2672 }
2673
Gilles Debunnec62589c2012-04-12 14:50:23 -07002674 @Override
2675 public void onSpanAdded(Spannable text, Object span, int start, int end) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002676 if (isNonIntermediateSelectionSpan(text, span)) {
2677 sendUpdateSelection();
2678 } else if (span instanceof EasyEditSpan) {
Gilles Debunnec62589c2012-04-12 14:50:23 -07002679 if (mPopupWindow == null) {
2680 mPopupWindow = new EasyEditPopupWindow();
2681 mHidePopup = new Runnable() {
2682 @Override
2683 public void run() {
2684 hide();
2685 }
2686 };
2687 }
2688
2689 // Make sure there is only at most one EasyEditSpan in the text
2690 if (mPopupWindow.mEasyEditSpan != null) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002691 mPopupWindow.mEasyEditSpan.setDeleteEnabled(false);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002692 }
2693
2694 mPopupWindow.setEasyEditSpan((EasyEditSpan) span);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002695 mPopupWindow.setOnDeleteListener(new EasyEditDeleteListener() {
2696 @Override
2697 public void onDeleteClick(EasyEditSpan span) {
2698 Editable editable = (Editable) mTextView.getText();
2699 int start = editable.getSpanStart(span);
2700 int end = editable.getSpanEnd(span);
2701 if (start >= 0 && end >= 0) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002702 sendEasySpanNotification(EasyEditSpan.TEXT_DELETED, span);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002703 mTextView.deleteText_internal(start, end);
2704 }
2705 editable.removeSpan(span);
2706 }
2707 });
Gilles Debunnec62589c2012-04-12 14:50:23 -07002708
2709 if (mTextView.getWindowVisibility() != View.VISIBLE) {
2710 // The window is not visible yet, ignore the text change.
2711 return;
2712 }
2713
2714 if (mTextView.getLayout() == null) {
2715 // The view has not been laid out yet, ignore the text change
2716 return;
2717 }
2718
2719 if (extractedTextModeWillBeStarted()) {
2720 // The input is in extract mode. Do not handle the easy edit in
2721 // the original TextView, as the ExtractEditText will do
2722 return;
2723 }
2724
2725 mPopupWindow.show();
2726 mTextView.removeCallbacks(mHidePopup);
2727 mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
2728 }
2729 }
2730
2731 @Override
2732 public void onSpanRemoved(Spannable text, Object span, int start, int end) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002733 if (isNonIntermediateSelectionSpan(text, span)) {
2734 sendUpdateSelection();
2735 } else if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) {
Gilles Debunnec62589c2012-04-12 14:50:23 -07002736 hide();
2737 }
2738 }
2739
2740 @Override
2741 public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd,
2742 int newStart, int newEnd) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002743 if (isNonIntermediateSelectionSpan(text, span)) {
2744 sendUpdateSelection();
2745 } else if (mPopupWindow != null && span instanceof EasyEditSpan) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002746 EasyEditSpan easyEditSpan = (EasyEditSpan) span;
Jean Chalardbaf30942013-02-28 16:01:51 -08002747 sendEasySpanNotification(EasyEditSpan.TEXT_MODIFIED, easyEditSpan);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002748 text.removeSpan(easyEditSpan);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002749 }
2750 }
2751
Gilles Debunned88876a2012-03-16 17:34:04 -07002752 public void hide() {
2753 if (mPopupWindow != null) {
2754 mPopupWindow.hide();
2755 mTextView.removeCallbacks(mHidePopup);
2756 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002757 }
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002758
Jean Chalardbaf30942013-02-28 16:01:51 -08002759 private void sendEasySpanNotification(int textChangedType, EasyEditSpan span) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002760 try {
2761 PendingIntent pendingIntent = span.getPendingIntent();
2762 if (pendingIntent != null) {
2763 Intent intent = new Intent();
2764 intent.putExtra(EasyEditSpan.EXTRA_TEXT_CHANGED_TYPE, textChangedType);
2765 pendingIntent.send(mTextView.getContext(), 0, intent);
2766 }
2767 } catch (CanceledException e) {
2768 // This should not happen, as we should try to send the intent only once.
2769 Log.w(TAG, "PendingIntent for notification cannot be sent", e);
2770 }
2771 }
2772 }
2773
2774 /**
2775 * Listens for the delete event triggered by {@link EasyEditPopupWindow}.
2776 */
2777 private interface EasyEditDeleteListener {
2778
2779 /**
2780 * Clicks the delete pop-up.
2781 */
2782 void onDeleteClick(EasyEditSpan span);
Gilles Debunned88876a2012-03-16 17:34:04 -07002783 }
2784
2785 /**
2786 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07002787 * by {@link SpanController}.
Gilles Debunned88876a2012-03-16 17:34:04 -07002788 */
2789 private class EasyEditPopupWindow extends PinnedPopupWindow
2790 implements OnClickListener {
2791 private static final int POPUP_TEXT_LAYOUT =
2792 com.android.internal.R.layout.text_edit_action_popup_text;
2793 private TextView mDeleteTextView;
2794 private EasyEditSpan mEasyEditSpan;
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002795 private EasyEditDeleteListener mOnDeleteListener;
Gilles Debunned88876a2012-03-16 17:34:04 -07002796
2797 @Override
2798 protected void createPopupWindow() {
2799 mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2800 com.android.internal.R.attr.textSelectHandleWindowStyle);
2801 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2802 mPopupWindow.setClippingEnabled(true);
2803 }
2804
2805 @Override
2806 protected void initContentView() {
2807 LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2808 linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2809 mContentView = linearLayout;
2810 mContentView.setBackgroundResource(
2811 com.android.internal.R.drawable.text_edit_side_paste_window);
2812
2813 LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
2814 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2815
2816 LayoutParams wrapContent = new LayoutParams(
2817 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2818
2819 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2820 mDeleteTextView.setLayoutParams(wrapContent);
2821 mDeleteTextView.setText(com.android.internal.R.string.delete);
2822 mDeleteTextView.setOnClickListener(this);
2823 mContentView.addView(mDeleteTextView);
2824 }
2825
Gilles Debunnec62589c2012-04-12 14:50:23 -07002826 public void setEasyEditSpan(EasyEditSpan easyEditSpan) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002827 mEasyEditSpan = easyEditSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07002828 }
2829
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002830 private void setOnDeleteListener(EasyEditDeleteListener listener) {
2831 mOnDeleteListener = listener;
2832 }
2833
Gilles Debunned88876a2012-03-16 17:34:04 -07002834 @Override
2835 public void onClick(View view) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002836 if (view == mDeleteTextView
2837 && mEasyEditSpan != null && mEasyEditSpan.isDeleteEnabled()
2838 && mOnDeleteListener != null) {
2839 mOnDeleteListener.onDeleteClick(mEasyEditSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07002840 }
2841 }
2842
2843 @Override
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002844 public void hide() {
2845 if (mEasyEditSpan != null) {
2846 mEasyEditSpan.setDeleteEnabled(false);
2847 }
2848 mOnDeleteListener = null;
2849 super.hide();
2850 }
2851
2852 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07002853 protected int getTextOffset() {
2854 // Place the pop-up at the end of the span
2855 Editable editable = (Editable) mTextView.getText();
2856 return editable.getSpanEnd(mEasyEditSpan);
2857 }
2858
2859 @Override
2860 protected int getVerticalLocalPosition(int line) {
2861 return mTextView.getLayout().getLineBottom(line);
2862 }
2863
2864 @Override
2865 protected int clipVertically(int positionY) {
2866 // As we display the pop-up below the span, no vertical clipping is required.
2867 return positionY;
2868 }
2869 }
2870
2871 private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
2872 // 3 handles
2873 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09002874 // 1 CursorAnchorInfoNotifier
2875 private final int MAXIMUM_NUMBER_OF_LISTENERS = 7;
Gilles Debunned88876a2012-03-16 17:34:04 -07002876 private TextViewPositionListener[] mPositionListeners =
2877 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
2878 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
2879 private boolean mPositionHasChanged = true;
2880 // Absolute position of the TextView with respect to its parent window
2881 private int mPositionX, mPositionY;
2882 private int mNumberOfListeners;
2883 private boolean mScrollHasChanged;
2884 final int[] mTempCoords = new int[2];
2885
2886 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2887 if (mNumberOfListeners == 0) {
2888 updatePosition();
2889 ViewTreeObserver vto = mTextView.getViewTreeObserver();
2890 vto.addOnPreDrawListener(this);
2891 }
2892
2893 int emptySlotIndex = -1;
2894 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2895 TextViewPositionListener listener = mPositionListeners[i];
2896 if (listener == positionListener) {
2897 return;
2898 } else if (emptySlotIndex < 0 && listener == null) {
2899 emptySlotIndex = i;
2900 }
2901 }
2902
2903 mPositionListeners[emptySlotIndex] = positionListener;
2904 mCanMove[emptySlotIndex] = canMove;
2905 mNumberOfListeners++;
2906 }
2907
2908 public void removeSubscriber(TextViewPositionListener positionListener) {
2909 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2910 if (mPositionListeners[i] == positionListener) {
2911 mPositionListeners[i] = null;
2912 mNumberOfListeners--;
2913 break;
2914 }
2915 }
2916
2917 if (mNumberOfListeners == 0) {
2918 ViewTreeObserver vto = mTextView.getViewTreeObserver();
2919 vto.removeOnPreDrawListener(this);
2920 }
2921 }
2922
2923 public int getPositionX() {
2924 return mPositionX;
2925 }
2926
2927 public int getPositionY() {
2928 return mPositionY;
2929 }
2930
2931 @Override
2932 public boolean onPreDraw() {
2933 updatePosition();
2934
2935 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2936 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2937 TextViewPositionListener positionListener = mPositionListeners[i];
2938 if (positionListener != null) {
2939 positionListener.updatePosition(mPositionX, mPositionY,
2940 mPositionHasChanged, mScrollHasChanged);
2941 }
2942 }
2943 }
2944
2945 mScrollHasChanged = false;
2946 return true;
2947 }
2948
2949 private void updatePosition() {
2950 mTextView.getLocationInWindow(mTempCoords);
2951
2952 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2953
2954 mPositionX = mTempCoords[0];
2955 mPositionY = mTempCoords[1];
2956 }
2957
2958 public void onScrollChanged() {
2959 mScrollHasChanged = true;
2960 }
2961 }
2962
2963 private abstract class PinnedPopupWindow implements TextViewPositionListener {
2964 protected PopupWindow mPopupWindow;
2965 protected ViewGroup mContentView;
2966 int mPositionX, mPositionY;
Seigo Nonaka60490d12016-01-28 17:25:18 +09002967 int mClippingLimitLeft, mClippingLimitRight;
Gilles Debunned88876a2012-03-16 17:34:04 -07002968
2969 protected abstract void createPopupWindow();
2970 protected abstract void initContentView();
2971 protected abstract int getTextOffset();
2972 protected abstract int getVerticalLocalPosition(int line);
2973 protected abstract int clipVertically(int positionY);
2974
2975 public PinnedPopupWindow() {
2976 createPopupWindow();
2977
Alan Viverette80ebe0d2015-04-30 15:53:11 -07002978 mPopupWindow.setWindowLayoutType(
2979 WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL);
Gilles Debunned88876a2012-03-16 17:34:04 -07002980 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2981 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2982
2983 initContentView();
2984
2985 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2986 ViewGroup.LayoutParams.WRAP_CONTENT);
2987 mContentView.setLayoutParams(wrapContent);
2988
2989 mPopupWindow.setContentView(mContentView);
2990 }
2991
2992 public void show() {
2993 getPositionListener().addSubscriber(this, false /* offset is fixed */);
2994
2995 computeLocalPosition();
2996
2997 final PositionListener positionListener = getPositionListener();
2998 updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2999 }
3000
3001 protected void measureContent() {
3002 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3003 mContentView.measure(
3004 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
3005 View.MeasureSpec.AT_MOST),
3006 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
3007 View.MeasureSpec.AT_MOST));
3008 }
3009
3010 /* The popup window will be horizontally centered on the getTextOffset() and vertically
3011 * positioned according to viewportToContentHorizontalOffset.
3012 *
3013 * This method assumes that mContentView has properly been measured from its content. */
3014 private void computeLocalPosition() {
3015 measureContent();
3016 final int width = mContentView.getMeasuredWidth();
3017 final int offset = getTextOffset();
3018 mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
3019 mPositionX += mTextView.viewportToContentHorizontalOffset();
3020
3021 final int line = mTextView.getLayout().getLineForOffset(offset);
3022 mPositionY = getVerticalLocalPosition(line);
3023 mPositionY += mTextView.viewportToContentVerticalOffset();
3024 }
3025
3026 private void updatePosition(int parentPositionX, int parentPositionY) {
3027 int positionX = parentPositionX + mPositionX;
3028 int positionY = parentPositionY + mPositionY;
3029
3030 positionY = clipVertically(positionY);
3031
3032 // Horizontal clipping
3033 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3034 final int width = mContentView.getMeasuredWidth();
Seigo Nonaka60490d12016-01-28 17:25:18 +09003035 positionX = Math.min(
3036 displayMetrics.widthPixels - width + mClippingLimitRight, positionX);
3037 positionX = Math.max(-mClippingLimitLeft, positionX);
Gilles Debunned88876a2012-03-16 17:34:04 -07003038
3039 if (isShowing()) {
3040 mPopupWindow.update(positionX, positionY, -1, -1);
3041 } else {
3042 mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3043 positionX, positionY);
3044 }
3045 }
3046
3047 public void hide() {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09003048 if (!isShowing()) {
3049 return;
3050 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003051 mPopupWindow.dismiss();
3052 getPositionListener().removeSubscriber(this);
3053 }
3054
3055 @Override
3056 public void updatePosition(int parentPositionX, int parentPositionY,
3057 boolean parentPositionChanged, boolean parentScrolled) {
3058 // Either parentPositionChanged or parentScrolled is true, check if still visible
3059 if (isShowing() && isOffsetVisible(getTextOffset())) {
3060 if (parentScrolled) computeLocalPosition();
3061 updatePosition(parentPositionX, parentPositionY);
3062 } else {
3063 hide();
3064 }
3065 }
3066
3067 public boolean isShowing() {
3068 return mPopupWindow.isShowing();
3069 }
3070 }
3071
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003072 private static final class SuggestionInfo {
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003073 // Range of actual suggestion within mText
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003074 int mSuggestionStart, mSuggestionEnd;
3075
3076 // The SuggestionSpan that this TextView represents
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003077 final SuggestionSpanInfo mSuggestionSpanInfo = new SuggestionSpanInfo();
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003078
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003079 // The index of this suggestion inside suggestionSpan
3080 int mSuggestionIndex;
3081
3082 final SpannableStringBuilder mText = new SpannableStringBuilder();
3083
3084 void clear() {
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003085 mSuggestionSpanInfo.clear();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003086 mText.clear();
3087 }
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003088
3089 // Utility method to set attributes about a SuggestionSpan.
3090 void setSpanInfo(SuggestionSpan span, int spanStart, int spanEnd) {
3091 mSuggestionSpanInfo.mSuggestionSpan = span;
3092 mSuggestionSpanInfo.mSpanStart = spanStart;
3093 mSuggestionSpanInfo.mSpanEnd = spanEnd;
3094 }
3095 }
3096
3097 private static final class SuggestionSpanInfo {
3098 // The SuggestionSpan;
3099 @Nullable
3100 SuggestionSpan mSuggestionSpan;
3101
3102 // The SuggestionSpan start position
3103 int mSpanStart;
3104
3105 // The SuggestionSpan end position
3106 int mSpanEnd;
3107
3108 void clear() {
3109 mSuggestionSpan = null;
3110 }
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003111 }
3112
3113 private class SuggestionHelper {
3114 private final Comparator<SuggestionSpan> mSuggestionSpanComparator =
3115 new SuggestionSpanComparator();
3116 private final HashMap<SuggestionSpan, Integer> mSpansLengths =
3117 new HashMap<SuggestionSpan, Integer>();
3118
3119 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
3120 public int compare(SuggestionSpan span1, SuggestionSpan span2) {
3121 final int flag1 = span1.getFlags();
3122 final int flag2 = span2.getFlags();
3123 if (flag1 != flag2) {
3124 // The order here should match what is used in updateDrawState
3125 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
3126 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
3127 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
3128 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
3129 if (easy1 && !misspelled1) return -1;
3130 if (easy2 && !misspelled2) return 1;
3131 if (misspelled1) return -1;
3132 if (misspelled2) return 1;
3133 }
3134
3135 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
3136 }
3137 }
3138
3139 /**
3140 * Returns the suggestion spans that cover the current cursor position. The suggestion
3141 * spans are sorted according to the length of text that they are attached to.
3142 */
3143 private SuggestionSpan[] getSortedSuggestionSpans() {
3144 int pos = mTextView.getSelectionStart();
3145 Spannable spannable = (Spannable) mTextView.getText();
3146 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
3147
3148 mSpansLengths.clear();
3149 for (SuggestionSpan suggestionSpan : suggestionSpans) {
3150 int start = spannable.getSpanStart(suggestionSpan);
3151 int end = spannable.getSpanEnd(suggestionSpan);
3152 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
3153 }
3154
3155 // The suggestions are sorted according to their types (easy correction first, then
3156 // misspelled) and to the length of the text that they cover (shorter first).
3157 Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
3158 mSpansLengths.clear();
3159
3160 return suggestionSpans;
3161 }
3162
3163 /**
3164 * Gets the SuggestionInfo list that contains suggestion information at the current cursor
3165 * position.
3166 *
3167 * @param suggestionInfos SuggestionInfo array the results will be set.
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003168 * @param misspelledSpanInfo a struct the misspelled SuggestionSpan info will be set.
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003169 * @return the number of suggestions actually fetched.
3170 */
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003171 public int getSuggestionInfo(SuggestionInfo[] suggestionInfos,
3172 @Nullable SuggestionSpanInfo misspelledSpanInfo) {
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003173 final Spannable spannable = (Spannable) mTextView.getText();
3174 final SuggestionSpan[] suggestionSpans = getSortedSuggestionSpans();
3175 final int nbSpans = suggestionSpans.length;
3176 if (nbSpans == 0) return 0;
3177
3178 int numberOfSuggestions = 0;
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003179 for (final SuggestionSpan suggestionSpan : suggestionSpans) {
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003180 final int spanStart = spannable.getSpanStart(suggestionSpan);
3181 final int spanEnd = spannable.getSpanEnd(suggestionSpan);
3182
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003183 if (misspelledSpanInfo != null
3184 && (suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
3185 misspelledSpanInfo.mSuggestionSpan = suggestionSpan;
3186 misspelledSpanInfo.mSpanStart = spanStart;
3187 misspelledSpanInfo.mSpanEnd = spanEnd;
3188 }
3189
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003190 final String[] suggestions = suggestionSpan.getSuggestions();
3191 final int nbSuggestions = suggestions.length;
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003192 suggestionLoop:
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003193 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
3194 final String suggestion = suggestions[suggestionIndex];
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003195 for (int i = 0; i < numberOfSuggestions; i++) {
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003196 final SuggestionInfo otherSuggestionInfo = suggestionInfos[i];
3197 if (otherSuggestionInfo.mText.toString().equals(suggestion)) {
3198 final int otherSpanStart =
3199 otherSuggestionInfo.mSuggestionSpanInfo.mSpanStart;
3200 final int otherSpanEnd =
3201 otherSuggestionInfo.mSuggestionSpanInfo.mSpanEnd;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003202 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003203 continue suggestionLoop;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003204 }
3205 }
3206 }
3207
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003208 SuggestionInfo suggestionInfo = suggestionInfos[numberOfSuggestions];
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003209 suggestionInfo.setSpanInfo(suggestionSpan, spanStart, spanEnd);
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003210 suggestionInfo.mSuggestionIndex = suggestionIndex;
3211 suggestionInfo.mSuggestionStart = 0;
3212 suggestionInfo.mSuggestionEnd = suggestion.length();
3213 suggestionInfo.mText.replace(0, suggestionInfo.mText.length(), suggestion);
3214 numberOfSuggestions++;
3215 if (numberOfSuggestions >= suggestionInfos.length) {
3216 return numberOfSuggestions;
3217 }
3218 }
3219 }
3220 return numberOfSuggestions;
3221 }
3222 }
3223
Seigo Nonakaa60160b2015-08-19 12:38:35 -07003224 @VisibleForTesting
3225 public class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
Gilles Debunned88876a2012-03-16 17:34:04 -07003226 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003227
3228 // Key of intent extras for inserting new word into user dictionary.
3229 private static final String USER_DICTIONARY_EXTRA_WORD = "word";
3230 private static final String USER_DICTIONARY_EXTRA_LOCALE = "locale";
3231
Gilles Debunned88876a2012-03-16 17:34:04 -07003232 private SuggestionInfo[] mSuggestionInfos;
3233 private int mNumberOfSuggestions;
3234 private boolean mCursorWasVisibleBeforeSuggestions;
3235 private boolean mIsShowingUp = false;
3236 private SuggestionAdapter mSuggestionsAdapter;
Seigo Nonakabffbd302015-08-18 18:27:56 -07003237 private final TextAppearanceSpan mHighlightSpan = new TextAppearanceSpan(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003238 mTextView.getContext(), mTextView.mTextEditSuggestionHighlightStyle);
3239 private TextView mAddToDictionaryButton;
3240 private TextView mDeleteButton;
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003241 private ListView mSuggestionListView;
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003242 private final SuggestionSpanInfo mMisspelledSpanInfo = new SuggestionSpanInfo();
Seigo Nonaka60490d12016-01-28 17:25:18 +09003243 private int mContainerMarginWidth;
3244 private int mContainerMarginTop;
Gilles Debunned88876a2012-03-16 17:34:04 -07003245
3246 private class CustomPopupWindow extends PopupWindow {
Gilles Debunned88876a2012-03-16 17:34:04 -07003247 @Override
3248 public void dismiss() {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09003249 if (!isShowing()) {
3250 return;
3251 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003252 super.dismiss();
Gilles Debunned88876a2012-03-16 17:34:04 -07003253 getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
3254
3255 // Safe cast since show() checks that mTextView.getText() is an Editable
3256 ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
3257
3258 mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
Keisuke Kuroyanagi4a696ac2016-02-23 11:02:07 -08003259 if (hasInsertionController() && !extractedTextModeWillBeStarted()) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003260 getInsertionController().show();
3261 }
3262 }
3263 }
3264
3265 public SuggestionsPopupWindow() {
3266 mCursorWasVisibleBeforeSuggestions = mCursorVisible;
Gilles Debunned88876a2012-03-16 17:34:04 -07003267 }
3268
3269 @Override
3270 protected void createPopupWindow() {
Seigo Nonaka3ed1b392016-01-19 13:54:59 +09003271 mPopupWindow = new CustomPopupWindow();
Gilles Debunned88876a2012-03-16 17:34:04 -07003272 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
Seigo Nonaka3ed1b392016-01-19 13:54:59 +09003273 mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Gilles Debunned88876a2012-03-16 17:34:04 -07003274 mPopupWindow.setFocusable(true);
3275 mPopupWindow.setClippingEnabled(false);
3276 }
3277
3278 @Override
3279 protected void initContentView() {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003280 final LayoutInflater inflater = (LayoutInflater) mTextView.getContext().
3281 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Seigo Nonaka60490d12016-01-28 17:25:18 +09003282 final ViewGroup relativeLayout = (ViewGroup) inflater.inflate(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003283 mTextView.mTextEditSuggestionContainerLayout, null);
Gilles Debunned88876a2012-03-16 17:34:04 -07003284
Seigo Nonaka60490d12016-01-28 17:25:18 +09003285 final LinearLayout suggestionWindowContainer =
3286 (LinearLayout) relativeLayout.findViewById(
3287 com.android.internal.R.id.suggestionWindowContainer);
3288 ViewGroup.MarginLayoutParams lp =
3289 (ViewGroup.MarginLayoutParams) suggestionWindowContainer.getLayoutParams();
3290 mContainerMarginWidth = lp.leftMargin + lp.rightMargin;
3291 mContainerMarginTop = lp.topMargin;
3292 mClippingLimitLeft = lp.leftMargin;
3293 mClippingLimitRight = lp.rightMargin;
3294
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003295 mSuggestionListView = (ListView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003296 com.android.internal.R.id.suggestionContainer);
3297
3298 mSuggestionsAdapter = new SuggestionAdapter();
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003299 mSuggestionListView.setAdapter(mSuggestionsAdapter);
3300 mSuggestionListView.setOnItemClickListener(this);
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003301
3302 // Inflate the suggestion items once and for all.
3303 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS];
Gilles Debunned88876a2012-03-16 17:34:04 -07003304 for (int i = 0; i < mSuggestionInfos.length; i++) {
3305 mSuggestionInfos[i] = new SuggestionInfo();
3306 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003307
Seigo Nonaka60490d12016-01-28 17:25:18 +09003308 mContentView = relativeLayout;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003309
Seigo Nonaka60490d12016-01-28 17:25:18 +09003310 mAddToDictionaryButton = (TextView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003311 com.android.internal.R.id.addToDictionaryButton);
3312 mAddToDictionaryButton.setOnClickListener(new View.OnClickListener() {
3313 public void onClick(View v) {
Keisuke Kuroyanagi6e0860d2016-03-15 15:40:43 +09003314 final SuggestionSpan misspelledSpan =
3315 findEquivalentSuggestionSpan(mMisspelledSpanInfo);
3316 if (misspelledSpan == null) {
3317 // Span has been removed.
3318 return;
3319 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003320 final Editable editable = (Editable) mTextView.getText();
Keisuke Kuroyanagi6e0860d2016-03-15 15:40:43 +09003321 final int spanStart = editable.getSpanStart(misspelledSpan);
3322 final int spanEnd = editable.getSpanEnd(misspelledSpan);
3323 if (spanStart < 0 || spanEnd <= spanStart) {
3324 return;
3325 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003326 final String originalText = TextUtils.substring(editable, spanStart, spanEnd);
3327
3328 final Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
3329 intent.putExtra(USER_DICTIONARY_EXTRA_WORD, originalText);
3330 intent.putExtra(USER_DICTIONARY_EXTRA_LOCALE,
3331 mTextView.getTextServicesLocale().toString());
3332 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3333 mTextView.getContext().startActivity(intent);
3334 // There is no way to know if the word was indeed added. Re-check.
3335 // TODO The ExtractEditText should remove the span in the original text instead
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003336 editable.removeSpan(mMisspelledSpanInfo.mSuggestionSpan);
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003337 Selection.setSelection(editable, spanEnd);
3338 updateSpellCheckSpans(spanStart, spanEnd, false);
3339 hideWithCleanUp();
3340 }
3341 });
3342
Seigo Nonaka60490d12016-01-28 17:25:18 +09003343 mDeleteButton = (TextView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003344 com.android.internal.R.id.deleteButton);
3345 mDeleteButton.setOnClickListener(new View.OnClickListener() {
3346 public void onClick(View v) {
3347 final Editable editable = (Editable) mTextView.getText();
3348
3349 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
3350 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
3351 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
3352 // Do not leave two adjacent spaces after deletion, or one at beginning of
3353 // text
3354 if (spanUnionEnd < editable.length() &&
3355 Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
3356 (spanUnionStart == 0 ||
3357 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
3358 spanUnionEnd = spanUnionEnd + 1;
3359 }
3360 mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
3361 }
3362 hideWithCleanUp();
3363 }
3364 });
3365
Gilles Debunned88876a2012-03-16 17:34:04 -07003366 }
3367
3368 public boolean isShowingUp() {
3369 return mIsShowingUp;
3370 }
3371
3372 public void onParentLostFocus() {
3373 mIsShowingUp = false;
3374 }
3375
Gilles Debunned88876a2012-03-16 17:34:04 -07003376 private class SuggestionAdapter extends BaseAdapter {
3377 private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
3378 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3379
3380 @Override
3381 public int getCount() {
3382 return mNumberOfSuggestions;
3383 }
3384
3385 @Override
3386 public Object getItem(int position) {
3387 return mSuggestionInfos[position];
3388 }
3389
3390 @Override
3391 public long getItemId(int position) {
3392 return position;
3393 }
3394
3395 @Override
3396 public View getView(int position, View convertView, ViewGroup parent) {
3397 TextView textView = (TextView) convertView;
3398
3399 if (textView == null) {
3400 textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
3401 parent, false);
3402 }
3403
3404 final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003405 textView.setText(suggestionInfo.mText);
Gilles Debunned88876a2012-03-16 17:34:04 -07003406 return textView;
3407 }
3408 }
3409
Seigo Nonakaa60160b2015-08-19 12:38:35 -07003410 @VisibleForTesting
3411 public ViewGroup getContentViewForTesting() {
3412 return mContentView;
3413 }
3414
Gilles Debunned88876a2012-03-16 17:34:04 -07003415 @Override
3416 public void show() {
3417 if (!(mTextView.getText() instanceof Editable)) return;
Keisuke Kuroyanagi4a696ac2016-02-23 11:02:07 -08003418 if (extractedTextModeWillBeStarted()) {
3419 return;
3420 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003421
3422 if (updateSuggestions()) {
3423 mCursorWasVisibleBeforeSuggestions = mCursorVisible;
3424 mTextView.setCursorVisible(false);
3425 mIsShowingUp = true;
3426 super.show();
3427 }
3428 }
3429
3430 @Override
3431 protected void measureContent() {
3432 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3433 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
3434 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
3435 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
3436 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
3437
3438 int width = 0;
3439 View view = null;
3440 for (int i = 0; i < mNumberOfSuggestions; i++) {
3441 view = mSuggestionsAdapter.getView(i, view, mContentView);
3442 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
3443 view.measure(horizontalMeasure, verticalMeasure);
3444 width = Math.max(width, view.getMeasuredWidth());
3445 }
3446
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003447 if (mAddToDictionaryButton.getVisibility() != View.GONE) {
3448 mAddToDictionaryButton.measure(horizontalMeasure, verticalMeasure);
3449 width = Math.max(width, mAddToDictionaryButton.getMeasuredWidth());
3450 }
3451
3452 mDeleteButton.measure(horizontalMeasure, verticalMeasure);
3453 width = Math.max(width, mDeleteButton.getMeasuredWidth());
3454
Seigo Nonaka60490d12016-01-28 17:25:18 +09003455 width += mContainerMarginWidth;
3456
Gilles Debunned88876a2012-03-16 17:34:04 -07003457 // Enforce the width based on actual text widths
3458 mContentView.measure(
3459 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
3460 verticalMeasure);
3461
3462 Drawable popupBackground = mPopupWindow.getBackground();
3463 if (popupBackground != null) {
3464 if (mTempRect == null) mTempRect = new Rect();
3465 popupBackground.getPadding(mTempRect);
3466 width += mTempRect.left + mTempRect.right;
3467 }
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003468 mSuggestionListView.getLayoutParams().width = width;
Gilles Debunned88876a2012-03-16 17:34:04 -07003469 mPopupWindow.setWidth(width);
3470 }
3471
3472 @Override
3473 protected int getTextOffset() {
Keisuke Kuroyanagi713be062016-02-29 16:07:54 -08003474 return (mTextView.getSelectionStart() + mTextView.getSelectionStart()) / 2;
Gilles Debunned88876a2012-03-16 17:34:04 -07003475 }
3476
3477 @Override
3478 protected int getVerticalLocalPosition(int line) {
Seigo Nonaka60490d12016-01-28 17:25:18 +09003479 return mTextView.getLayout().getLineBottom(line) - mContainerMarginTop;
Gilles Debunned88876a2012-03-16 17:34:04 -07003480 }
3481
3482 @Override
3483 protected int clipVertically(int positionY) {
3484 final int height = mContentView.getMeasuredHeight();
3485 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3486 return Math.min(positionY, displayMetrics.heightPixels - height);
3487 }
3488
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003489 private void hideWithCleanUp() {
3490 for (final SuggestionInfo info : mSuggestionInfos) {
3491 info.clear();
3492 }
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003493 mMisspelledSpanInfo.clear();
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003494 hide();
Gilles Debunned88876a2012-03-16 17:34:04 -07003495 }
3496
3497 private boolean updateSuggestions() {
3498 Spannable spannable = (Spannable) mTextView.getText();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003499 mNumberOfSuggestions =
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003500 mSuggestionHelper.getSuggestionInfo(mSuggestionInfos, mMisspelledSpanInfo);
3501 if (mNumberOfSuggestions == 0 && mMisspelledSpanInfo.mSuggestionSpan == null) {
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003502 return false;
3503 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003504
Gilles Debunned88876a2012-03-16 17:34:04 -07003505 int spanUnionStart = mTextView.getText().length();
3506 int spanUnionEnd = 0;
3507
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003508 for (int i = 0; i < mNumberOfSuggestions; i++) {
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003509 final SuggestionSpanInfo spanInfo = mSuggestionInfos[i].mSuggestionSpanInfo;
3510 spanUnionStart = Math.min(spanUnionStart, spanInfo.mSpanStart);
3511 spanUnionEnd = Math.max(spanUnionEnd, spanInfo.mSpanEnd);
3512 }
3513 if (mMisspelledSpanInfo.mSuggestionSpan != null) {
3514 spanUnionStart = Math.min(spanUnionStart, mMisspelledSpanInfo.mSpanStart);
3515 spanUnionEnd = Math.max(spanUnionEnd, mMisspelledSpanInfo.mSpanEnd);
Gilles Debunned88876a2012-03-16 17:34:04 -07003516 }
3517
3518 for (int i = 0; i < mNumberOfSuggestions; i++) {
3519 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
3520 }
3521
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003522 // Make "Add to dictionary" item visible if there is a span with the misspelled flag
3523 int addToDictionaryButtonVisibility = View.GONE;
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003524 if (mMisspelledSpanInfo.mSuggestionSpan != null) {
3525 if (mMisspelledSpanInfo.mSpanStart >= 0
3526 && mMisspelledSpanInfo.mSpanEnd > mMisspelledSpanInfo.mSpanStart) {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003527 addToDictionaryButtonVisibility = View.VISIBLE;
Gilles Debunned88876a2012-03-16 17:34:04 -07003528 }
3529 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003530 mAddToDictionaryButton.setVisibility(addToDictionaryButtonVisibility);
Gilles Debunned88876a2012-03-16 17:34:04 -07003531
3532 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003533 final int underlineColor;
3534 if (mNumberOfSuggestions != 0) {
3535 underlineColor =
3536 mSuggestionInfos[0].mSuggestionSpanInfo.mSuggestionSpan.getUnderlineColor();
3537 } else {
3538 underlineColor = mMisspelledSpanInfo.mSuggestionSpan.getUnderlineColor();
3539 }
3540
Gilles Debunned88876a2012-03-16 17:34:04 -07003541 if (underlineColor == 0) {
3542 // Fallback on the default highlight color when the first span does not provide one
3543 mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
3544 } else {
3545 final float BACKGROUND_TRANSPARENCY = 0.4f;
3546 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
3547 mSuggestionRangeSpan.setBackgroundColor(
3548 (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
3549 }
3550 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
3551 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
3552
3553 mSuggestionsAdapter.notifyDataSetChanged();
3554 return true;
3555 }
3556
3557 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
3558 int unionEnd) {
3559 final Spannable text = (Spannable) mTextView.getText();
Keisuke Kuroyanagif8e0da22016-03-14 15:10:57 +09003560 final int spanStart = suggestionInfo.mSuggestionSpanInfo.mSpanStart;
3561 final int spanEnd = suggestionInfo.mSuggestionSpanInfo.mSpanEnd;
Gilles Debunned88876a2012-03-16 17:34:04 -07003562
3563 // Adjust the start/end of the suggestion span
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003564 suggestionInfo.mSuggestionStart = spanStart - unionStart;
3565 suggestionInfo.mSuggestionEnd = suggestionInfo.mSuggestionStart
3566 + suggestionInfo.mText.length();
Gilles Debunned88876a2012-03-16 17:34:04 -07003567
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003568 suggestionInfo.mText.setSpan(mHighlightSpan, 0, suggestionInfo.mText.length(),
Seigo Nonakabffbd302015-08-18 18:27:56 -07003569 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Gilles Debunned88876a2012-03-16 17:34:04 -07003570
3571 // Add the text before and after the span.
3572 final String textAsString = text.toString();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003573 suggestionInfo.mText.insert(0, textAsString.substring(unionStart, spanStart));
3574 suggestionInfo.mText.append(textAsString.substring(spanEnd, unionEnd));
Gilles Debunned88876a2012-03-16 17:34:04 -07003575 }
3576
3577 @Override
3578 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003579 SuggestionInfo suggestionInfo = mSuggestionInfos[position];
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003580 replaceWithSuggestion(suggestionInfo);
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003581 hideWithCleanUp();
Gilles Debunned88876a2012-03-16 17:34:04 -07003582 }
3583 }
3584
3585 /**
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003586 * An ActionMode Callback class that is used to provide actions while in text insertion or
3587 * selection mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07003588 *
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003589 * The default callback provides a subset of Select All, Cut, Copy, Paste, Share and Replace
3590 * actions, depending on which of these this TextView supports and the current selection.
Gilles Debunned88876a2012-03-16 17:34:04 -07003591 */
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003592 private class TextActionModeCallback extends ActionMode.Callback2 {
Clara Bayarriea4f1502015-03-18 00:25:01 +00003593 private final Path mSelectionPath = new Path();
3594 private final RectF mSelectionBounds = new RectF();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003595 private final boolean mHasSelection;
Clara Bayarriea4f1502015-03-18 00:25:01 +00003596
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003597 private int mHandleHeight;
Clara Bayarriea4f1502015-03-18 00:25:01 +00003598
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003599 public TextActionModeCallback(boolean hasSelection) {
3600 mHasSelection = hasSelection;
3601 if (mHasSelection) {
3602 SelectionModifierCursorController selectionController = getSelectionController();
3603 if (selectionController.mStartHandle == null) {
3604 // As these are for initializing selectionController, hide() must be called.
3605 selectionController.initDrawables();
3606 selectionController.initHandles();
3607 selectionController.hide();
3608 }
3609 mHandleHeight = Math.max(
3610 mSelectHandleLeft.getMinimumHeight(),
3611 mSelectHandleRight.getMinimumHeight());
3612 } else {
3613 InsertionPointCursorController insertionController = getInsertionController();
3614 if (insertionController != null) {
3615 insertionController.getHandle();
3616 mHandleHeight = mSelectHandleCenter.getMinimumHeight();
3617 }
Clara Bayarri7fc946e2015-03-31 14:48:33 +01003618 }
Clara Bayarriea4f1502015-03-18 00:25:01 +00003619 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003620
3621 @Override
3622 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003623 mode.setTitle(null);
Clara Bayarri13152d12015-04-09 12:02:04 +01003624 mode.setSubtitle(null);
3625 mode.setTitleOptionalHint(true);
3626 populateMenuWithItems(menu);
3627
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003628 Callback customCallback = getCustomCallback();
3629 if (customCallback != null) {
3630 if (!customCallback.onCreateActionMode(mode, menu)) {
Clara Bayarri01243ac2015-06-03 00:46:29 +01003631 // The custom mode can choose to cancel the action mode, dismiss selection.
3632 Selection.setSelection((Spannable) mTextView.getText(),
3633 mTextView.getSelectionEnd());
Clara Bayarri13152d12015-04-09 12:02:04 +01003634 return false;
3635 }
3636 }
3637
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07003638 if (mTextView.canProcessText()) {
3639 mProcessTextIntentActionsHandler.onInitializeMenu(menu);
3640 }
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00003641
Clara Bayarri13152d12015-04-09 12:02:04 +01003642 if (menu.hasVisibleItems() || mode.getCustomView() != null) {
Clara Bayarri13152d12015-04-09 12:02:04 +01003643 return true;
3644 } else {
3645 return false;
3646 }
3647 }
3648
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003649 private Callback getCustomCallback() {
3650 return mHasSelection
3651 ? mCustomSelectionActionModeCallback
3652 : mCustomInsertionActionModeCallback;
3653 }
3654
Clara Bayarri13152d12015-04-09 12:02:04 +01003655 private void populateMenuWithItems(Menu menu) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003656 if (mTextView.canCut()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003657 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
3658 com.android.internal.R.string.cut).
Gilles Debunned88876a2012-03-16 17:34:04 -07003659 setAlphabeticShortcut('x').
Clara Bayarriaee243b2015-05-18 17:05:46 +01003660 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003661 }
3662
3663 if (mTextView.canCopy()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003664 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
3665 com.android.internal.R.string.copy).
Gilles Debunned88876a2012-03-16 17:34:04 -07003666 setAlphabeticShortcut('c').
Clara Bayarriaee243b2015-05-18 17:05:46 +01003667 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003668 }
3669
3670 if (mTextView.canPaste()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003671 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
3672 com.android.internal.R.string.paste).
3673 setAlphabeticShortcut('v').
3674 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003675 }
3676
Andrei Stingaceanu7f0c5bd2015-04-14 17:12:08 +01003677 if (mTextView.canShare()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003678 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
3679 com.android.internal.R.string.share).
3680 setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
Andrei Stingaceanu7f0c5bd2015-04-14 17:12:08 +01003681 }
3682
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003683 updateSelectAllItem(menu);
Clara Bayarri13152d12015-04-09 12:02:04 +01003684 updateReplaceItem(menu);
Gilles Debunned88876a2012-03-16 17:34:04 -07003685 }
3686
3687 @Override
3688 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003689 updateSelectAllItem(menu);
Clara Bayarri13152d12015-04-09 12:02:04 +01003690 updateReplaceItem(menu);
3691
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003692 Callback customCallback = getCustomCallback();
3693 if (customCallback != null) {
3694 return customCallback.onPrepareActionMode(mode, menu);
Gilles Debunned88876a2012-03-16 17:34:04 -07003695 }
3696 return true;
3697 }
3698
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003699 private void updateSelectAllItem(Menu menu) {
3700 boolean canSelectAll = mTextView.canSelectAllText();
3701 boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null;
3702 if (canSelectAll && !selectAllItemExists) {
3703 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
3704 com.android.internal.R.string.selectAll)
3705 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3706 } else if (!canSelectAll && selectAllItemExists) {
3707 menu.removeItem(TextView.ID_SELECT_ALL);
3708 }
3709 }
3710
Clara Bayarri13152d12015-04-09 12:02:04 +01003711 private void updateReplaceItem(Menu menu) {
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003712 boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
Clara Bayarri13152d12015-04-09 12:02:04 +01003713 boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3714 if (canReplace && !replaceItemExists) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003715 menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
3716 com.android.internal.R.string.replace)
3717 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
Clara Bayarri13152d12015-04-09 12:02:04 +01003718 } else if (!canReplace && replaceItemExists) {
3719 menu.removeItem(TextView.ID_REPLACE);
3720 }
3721 }
3722
Gilles Debunned88876a2012-03-16 17:34:04 -07003723 @Override
3724 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07003725 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00003726 return true;
3727 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003728 Callback customCallback = getCustomCallback();
3729 if (customCallback != null && customCallback.onActionItemClicked(mode, item)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003730 return true;
3731 }
3732 return mTextView.onTextContextMenuItem(item.getItemId());
3733 }
3734
3735 @Override
3736 public void onDestroyActionMode(ActionMode mode) {
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09003737 // Clear mTextActionMode not to recursively destroy action mode by clearing selection.
3738 mTextActionMode = null;
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003739 Callback customCallback = getCustomCallback();
3740 if (customCallback != null) {
3741 customCallback.onDestroyActionMode(mode);
Gilles Debunned88876a2012-03-16 17:34:04 -07003742 }
Adam Powell057a5852012-05-11 10:28:38 -07003743
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08003744 if (!mPreserveSelection) {
3745 /*
3746 * Leave current selection when we tentatively destroy action mode for the
3747 * selection. If we're detaching from a window, we'll bring back the selection
3748 * mode when (if) we get reattached.
3749 */
Adam Powell057a5852012-05-11 10:28:38 -07003750 Selection.setSelection((Spannable) mTextView.getText(),
3751 mTextView.getSelectionEnd());
Adam Powell057a5852012-05-11 10:28:38 -07003752 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003753
3754 if (mSelectionModifierCursorController != null) {
3755 mSelectionModifierCursorController.hide();
3756 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003757 }
Clara Bayarriea4f1502015-03-18 00:25:01 +00003758
3759 @Override
3760 public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
3761 if (!view.equals(mTextView) || mTextView.getLayout() == null) {
3762 super.onGetContentRect(mode, view, outRect);
3763 return;
3764 }
3765 if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
3766 // We have a selection.
3767 mSelectionPath.reset();
3768 mTextView.getLayout().getSelectionPath(
3769 mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
3770 mSelectionPath.computeBounds(mSelectionBounds, true);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003771 mSelectionBounds.bottom += mHandleHeight;
Clara Bayarrib7419dd2015-04-09 15:24:58 +01003772 } else if (mCursorCount == 2) {
3773 // We have a split cursor. In this case, we take the rectangle that includes both
3774 // parts of the cursor to ensure we don't obscure either of them.
3775 Rect firstCursorBounds = mCursorDrawable[0].getBounds();
3776 Rect secondCursorBounds = mCursorDrawable[1].getBounds();
3777 mSelectionBounds.set(
3778 Math.min(firstCursorBounds.left, secondCursorBounds.left),
3779 Math.min(firstCursorBounds.top, secondCursorBounds.top),
3780 Math.max(firstCursorBounds.right, secondCursorBounds.right),
3781 Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom)
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003782 + mHandleHeight);
Clara Bayarriea4f1502015-03-18 00:25:01 +00003783 } else {
3784 // We have a single cursor.
Siyamed Sinir987ec652016-02-17 19:44:41 -08003785 Layout layout = mTextView.getLayout();
Mady Mellorff66ca52015-07-08 12:31:45 -07003786 int line = layout.getLineForOffset(mTextView.getSelectionStart());
Siyamed Sinir987ec652016-02-17 19:44:41 -08003787 float primaryHorizontal = clampHorizontalPosition(null,
3788 layout.getPrimaryHorizontal(mTextView.getSelectionStart()));
Clara Bayarriea4f1502015-03-18 00:25:01 +00003789 mSelectionBounds.set(
3790 primaryHorizontal,
Mady Mellorff66ca52015-07-08 12:31:45 -07003791 layout.getLineTop(line),
Clara Bayarrif95ed102015-08-12 19:46:47 +01003792 primaryHorizontal,
Mady Mellorff66ca52015-07-08 12:31:45 -07003793 layout.getLineTop(line + 1) + mHandleHeight);
Clara Bayarriea4f1502015-03-18 00:25:01 +00003794 }
3795 // Take TextView's padding and scroll into account.
3796 int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
3797 int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
3798 outRect.set(
3799 (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
3800 (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
3801 (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
3802 (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
3803 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003804 }
3805
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003806 /**
3807 * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
3808 * while the input method is requesting the cursor/anchor position. Does nothing as long as
3809 * {@link InputMethodManager#isWatchingCursor(View)} returns false.
3810 */
3811 private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
Yohei Yukawac46b5f02014-06-10 12:26:34 +09003812 final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003813 final int[] mTmpIntOffset = new int[2];
3814 final Matrix mViewToScreenMatrix = new Matrix();
3815
3816 @Override
3817 public void updatePosition(int parentPositionX, int parentPositionY,
3818 boolean parentPositionChanged, boolean parentScrolled) {
3819 final InputMethodState ims = mInputMethodState;
3820 if (ims == null || ims.mBatchEditNesting > 0) {
3821 return;
3822 }
3823 final InputMethodManager imm = InputMethodManager.peekInstance();
3824 if (null == imm) {
3825 return;
3826 }
Yohei Yukawa0023d0e2014-07-11 04:13:03 +09003827 if (!imm.isActive(mTextView)) {
3828 return;
3829 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003830 // Skip if the IME has not requested the cursor/anchor position.
Yohei Yukawa0023d0e2014-07-11 04:13:03 +09003831 if (!imm.isCursorAnchorInfoEnabled()) {
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003832 return;
3833 }
3834 Layout layout = mTextView.getLayout();
3835 if (layout == null) {
3836 return;
3837 }
3838
Yohei Yukawac46b5f02014-06-10 12:26:34 +09003839 final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003840 builder.reset();
3841
3842 final int selectionStart = mTextView.getSelectionStart();
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003843 builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003844
3845 // Construct transformation matrix from view local coordinates to screen coordinates.
3846 mViewToScreenMatrix.set(mTextView.getMatrix());
3847 mTextView.getLocationOnScreen(mTmpIntOffset);
3848 mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
3849 builder.setMatrix(mViewToScreenMatrix);
3850
3851 final float viewportToContentHorizontalOffset =
3852 mTextView.viewportToContentHorizontalOffset();
3853 final float viewportToContentVerticalOffset =
3854 mTextView.viewportToContentVerticalOffset();
3855
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003856 final CharSequence text = mTextView.getText();
3857 if (text instanceof Spannable) {
3858 final Spannable sp = (Spannable) text;
3859 int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
3860 int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
3861 if (composingTextEnd < composingTextStart) {
3862 final int temp = composingTextEnd;
3863 composingTextEnd = composingTextStart;
3864 composingTextStart = temp;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003865 }
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003866 final boolean hasComposingText =
3867 (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
3868 if (hasComposingText) {
3869 final CharSequence composingText = text.subSequence(composingTextStart,
3870 composingTextEnd);
3871 builder.setComposingText(composingTextStart, composingText);
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003872
3873 final int minLine = layout.getLineForOffset(composingTextStart);
3874 final int maxLine = layout.getLineForOffset(composingTextEnd - 1);
3875 for (int line = minLine; line <= maxLine; ++line) {
3876 final int lineStart = layout.getLineStart(line);
3877 final int lineEnd = layout.getLineEnd(line);
3878 final int offsetStart = Math.max(lineStart, composingTextStart);
3879 final int offsetEnd = Math.min(lineEnd, composingTextEnd);
3880 final boolean ltrLine =
3881 layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT;
3882 final float[] widths = new float[offsetEnd - offsetStart];
3883 layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths);
3884 final float top = layout.getLineTop(line);
3885 final float bottom = layout.getLineBottom(line);
3886 for (int offset = offsetStart; offset < offsetEnd; ++offset) {
3887 final float charWidth = widths[offset - offsetStart];
3888 final boolean isRtl = layout.isRtlCharAt(offset);
3889 final float primary = layout.getPrimaryHorizontal(offset);
3890 final float secondary = layout.getSecondaryHorizontal(offset);
3891 // TODO: This doesn't work perfectly for text with custom styles and
3892 // TAB chars.
3893 final float left;
3894 final float right;
3895 if (ltrLine) {
3896 if (isRtl) {
3897 left = secondary - charWidth;
3898 right = secondary;
3899 } else {
3900 left = primary;
3901 right = primary + charWidth;
3902 }
3903 } else {
3904 if (!isRtl) {
3905 left = secondary;
3906 right = secondary + charWidth;
3907 } else {
3908 left = primary - charWidth;
3909 right = primary;
3910 }
3911 }
3912 // TODO: Check top-right and bottom-left as well.
3913 final float localLeft = left + viewportToContentHorizontalOffset;
3914 final float localRight = right + viewportToContentHorizontalOffset;
3915 final float localTop = top + viewportToContentVerticalOffset;
3916 final float localBottom = bottom + viewportToContentVerticalOffset;
3917 final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop);
3918 final boolean isBottomRightVisible =
3919 isPositionVisible(localRight, localBottom);
3920 int characterBoundsFlags = 0;
3921 if (isTopLeftVisible || isBottomRightVisible) {
3922 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3923 }
Andreas Gampe4976e2d2015-03-17 16:08:43 -07003924 if (!isTopLeftVisible || !isBottomRightVisible) {
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003925 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3926 }
3927 if (isRtl) {
3928 characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3929 }
3930 // Here offset is the index in Java chars.
3931 builder.addCharacterBounds(offset, localLeft, localTop, localRight,
3932 localBottom, characterBoundsFlags);
3933 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003934 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003935 }
3936 }
3937
3938 // Treat selectionStart as the insertion point.
3939 if (0 <= selectionStart) {
3940 final int offset = selectionStart;
3941 final int line = layout.getLineForOffset(offset);
3942 final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
3943 + viewportToContentHorizontalOffset;
3944 final float insertionMarkerTop = layout.getLineTop(line)
3945 + viewportToContentVerticalOffset;
3946 final float insertionMarkerBaseline = layout.getLineBaseline(line)
3947 + viewportToContentVerticalOffset;
3948 final float insertionMarkerBottom = layout.getLineBottom(line)
3949 + viewportToContentVerticalOffset;
Yohei Yukawacc24e2b2014-08-29 20:21:10 -07003950 final boolean isTopVisible =
3951 isPositionVisible(insertionMarkerX, insertionMarkerTop);
3952 final boolean isBottomVisible =
3953 isPositionVisible(insertionMarkerX, insertionMarkerBottom);
3954 int insertionMarkerFlags = 0;
3955 if (isTopVisible || isBottomVisible) {
3956 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3957 }
3958 if (!isTopVisible || !isBottomVisible) {
3959 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3960 }
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003961 if (layout.isRtlCharAt(offset)) {
3962 insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3963 }
Yohei Yukawa0b01e7f2014-07-08 15:29:51 +09003964 builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
Yohei Yukawacc24e2b2014-08-29 20:21:10 -07003965 insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003966 }
3967
3968 imm.updateCursorAnchorInfo(mTextView, builder.build());
3969 }
3970 }
3971
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003972 @VisibleForTesting
3973 public abstract class HandleView extends View implements TextViewPositionListener {
Gilles Debunned88876a2012-03-16 17:34:04 -07003974 protected Drawable mDrawable;
3975 protected Drawable mDrawableLtr;
3976 protected Drawable mDrawableRtl;
3977 private final PopupWindow mContainer;
3978 // Position with respect to the parent TextView
3979 private int mPositionX, mPositionY;
3980 private boolean mIsDragging;
3981 // Offset from touch position to mPosition
3982 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
3983 protected int mHotspotX;
Adam Powell3fceabd2014-08-19 18:28:04 -07003984 protected int mHorizontalGravity;
Gilles Debunned88876a2012-03-16 17:34:04 -07003985 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
3986 private float mTouchOffsetY;
3987 // Where the touch position should be on the handle to ensure a maximum cursor visibility
3988 private float mIdealVerticalOffset;
3989 // Parent's (TextView) previous position in window
3990 private int mLastParentX, mLastParentY;
Gilles Debunned88876a2012-03-16 17:34:04 -07003991 // Previous text character offset
Mady Mellorc2225b92015-04-01 15:59:20 -07003992 protected int mPreviousOffset = -1;
Gilles Debunned88876a2012-03-16 17:34:04 -07003993 // Previous text character offset
3994 private boolean mPositionHasChanged = true;
Adam Powell3fceabd2014-08-19 18:28:04 -07003995 // Minimum touch target size for handles
3996 private int mMinSize;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08003997 // Indicates the line of text that the handle is on.
Mady Mellora6a0f782015-07-10 16:43:32 -07003998 protected int mPrevLine = UNSET_LINE;
3999 // Indicates the line of text that the user was touching. This can differ from mPrevLine
4000 // when selecting text when the handles jump to the end / start of words which may be on
4001 // a different line.
4002 protected int mPreviousLineTouched = UNSET_LINE;
Gilles Debunned88876a2012-03-16 17:34:04 -07004003
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09004004 private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
Gilles Debunned88876a2012-03-16 17:34:04 -07004005 super(mTextView.getContext());
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09004006 setId(id);
Gilles Debunned88876a2012-03-16 17:34:04 -07004007 mContainer = new PopupWindow(mTextView.getContext(), null,
4008 com.android.internal.R.attr.textSelectHandleWindowStyle);
4009 mContainer.setSplitTouchEnabled(true);
4010 mContainer.setClippingEnabled(false);
4011 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
Keisuke Kuroyanagi7340be72015-02-27 17:57:49 +09004012 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
4013 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
Gilles Debunned88876a2012-03-16 17:34:04 -07004014 mContainer.setContentView(this);
4015
4016 mDrawableLtr = drawableLtr;
4017 mDrawableRtl = drawableRtl;
Adam Powell3fceabd2014-08-19 18:28:04 -07004018 mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
4019 com.android.internal.R.dimen.text_handle_min_size);
Gilles Debunned88876a2012-03-16 17:34:04 -07004020
4021 updateDrawable();
4022
Adam Powell3fceabd2014-08-19 18:28:04 -07004023 final int handleHeight = getPreferredHeight();
Gilles Debunned88876a2012-03-16 17:34:04 -07004024 mTouchOffsetY = -0.3f * handleHeight;
4025 mIdealVerticalOffset = 0.7f * handleHeight;
4026 }
4027
Mady Mellor7a936442015-05-20 10:05:52 -07004028 public float getIdealVerticalOffset() {
4029 return mIdealVerticalOffset;
4030 }
4031
Gilles Debunned88876a2012-03-16 17:34:04 -07004032 protected void updateDrawable() {
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004033 if (mIsDragging) {
4034 // Don't update drawable during dragging.
4035 return;
4036 }
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004037 final Layout layout = mTextView.getLayout();
4038 if (layout == null) {
4039 return;
4040 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004041 final int offset = getCurrentCursorOffset();
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004042 final boolean isRtlCharAtOffset = isAtRtlRun(layout, offset);
Keisuke Kuroyanagi33f81ac2015-05-14 20:10:57 +09004043 final Drawable oldDrawable = mDrawable;
Gilles Debunned88876a2012-03-16 17:34:04 -07004044 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
4045 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
Adam Powell3fceabd2014-08-19 18:28:04 -07004046 mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004047 if (oldDrawable != mDrawable && isShowing()) {
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004048 // Update popup window position.
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004049 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX -
4050 getHorizontalOffset() + getCursorOffset();
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004051 mPositionX += mTextView.viewportToContentHorizontalOffset();
4052 mPositionHasChanged = true;
4053 updatePosition(mLastParentX, mLastParentY, false, false);
Keisuke Kuroyanagi33f81ac2015-05-14 20:10:57 +09004054 postInvalidate();
4055 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004056 }
4057
4058 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
Adam Powell3fceabd2014-08-19 18:28:04 -07004059 protected abstract int getHorizontalGravity(boolean isRtlRun);
Gilles Debunned88876a2012-03-16 17:34:04 -07004060
4061 // Touch-up filter: number of previous positions remembered
4062 private static final int HISTORY_SIZE = 5;
4063 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
4064 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
4065 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
4066 private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
4067 private int mPreviousOffsetIndex = 0;
4068 private int mNumberPreviousOffsets = 0;
4069
4070 private void startTouchUpFilter(int offset) {
4071 mNumberPreviousOffsets = 0;
4072 addPositionToTouchUpFilter(offset);
4073 }
4074
4075 private void addPositionToTouchUpFilter(int offset) {
4076 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
4077 mPreviousOffsets[mPreviousOffsetIndex] = offset;
4078 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
4079 mNumberPreviousOffsets++;
4080 }
4081
4082 private void filterOnTouchUp() {
4083 final long now = SystemClock.uptimeMillis();
4084 int i = 0;
4085 int index = mPreviousOffsetIndex;
4086 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
4087 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
4088 i++;
4089 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
4090 }
4091
4092 if (i > 0 && i < iMax &&
4093 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
4094 positionAtCursorOffset(mPreviousOffsets[index], false);
4095 }
4096 }
4097
4098 public boolean offsetHasBeenChanged() {
4099 return mNumberPreviousOffsets > 1;
4100 }
4101
4102 @Override
4103 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Powell3fceabd2014-08-19 18:28:04 -07004104 setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
4105 }
4106
4107 private int getPreferredWidth() {
4108 return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
4109 }
4110
4111 private int getPreferredHeight() {
4112 return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
Gilles Debunned88876a2012-03-16 17:34:04 -07004113 }
4114
4115 public void show() {
4116 if (isShowing()) return;
4117
4118 getPositionListener().addSubscriber(this, true /* local position may change */);
4119
4120 // Make sure the offset is always considered new, even when focusing at same position
4121 mPreviousOffset = -1;
4122 positionAtCursorOffset(getCurrentCursorOffset(), false);
Gilles Debunned88876a2012-03-16 17:34:04 -07004123 }
4124
4125 protected void dismiss() {
4126 mIsDragging = false;
4127 mContainer.dismiss();
4128 onDetached();
4129 }
4130
4131 public void hide() {
4132 dismiss();
4133
4134 getPositionListener().removeSubscriber(this);
4135 }
4136
Gilles Debunned88876a2012-03-16 17:34:04 -07004137 public boolean isShowing() {
4138 return mContainer.isShowing();
4139 }
4140
4141 private boolean isVisible() {
4142 // Always show a dragging handle.
4143 if (mIsDragging) {
4144 return true;
4145 }
4146
4147 if (mTextView.isInBatchEditMode()) {
4148 return false;
4149 }
4150
Keisuke Kuroyanagi6cda1e22015-04-22 21:41:14 +09004151 return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
Gilles Debunned88876a2012-03-16 17:34:04 -07004152 }
4153
4154 public abstract int getCurrentCursorOffset();
4155
4156 protected abstract void updateSelection(int offset);
4157
4158 public abstract void updatePosition(float x, float y);
4159
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004160 protected boolean isAtRtlRun(@NonNull Layout layout, int offset) {
4161 return layout.isRtlCharAt(offset);
4162 }
4163
4164 @VisibleForTesting
4165 public float getHorizontal(@NonNull Layout layout, int offset) {
4166 return layout.getPrimaryHorizontal(offset);
4167 }
4168
4169 protected int getOffsetAtCoordinate(@NonNull Layout layout, int line, float x) {
4170 return mTextView.getOffsetAtCoordinate(line, x);
4171 }
4172
Gilles Debunned88876a2012-03-16 17:34:04 -07004173 protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4174 // A HandleView relies on the layout, which may be nulled by external methods
4175 Layout layout = mTextView.getLayout();
4176 if (layout == null) {
4177 // Will update controllers' state, hiding them and stopping selection mode if needed
4178 prepareCursorControllers();
4179 return;
4180 }
Siyamed Sinir987ec652016-02-17 19:44:41 -08004181 layout = mTextView.getLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -07004182
4183 boolean offsetChanged = offset != mPreviousOffset;
4184 if (offsetChanged || parentScrolled) {
4185 if (offsetChanged) {
4186 updateSelection(offset);
4187 addPositionToTouchUpFilter(offset);
4188 }
4189 final int line = layout.getLineForOffset(offset);
Mady Mellorb9bbbb12015-03-23 11:50:46 -07004190 mPrevLine = line;
Gilles Debunned88876a2012-03-16 17:34:04 -07004191
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004192 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX -
4193 getHorizontalOffset() + getCursorOffset();
Gilles Debunned88876a2012-03-16 17:34:04 -07004194 mPositionY = layout.getLineBottom(line);
4195
4196 // Take TextView's padding and scroll into account.
4197 mPositionX += mTextView.viewportToContentHorizontalOffset();
4198 mPositionY += mTextView.viewportToContentVerticalOffset();
4199
4200 mPreviousOffset = offset;
4201 mPositionHasChanged = true;
4202 }
4203 }
4204
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004205 /**
4206 * Return the clamped horizontal position for the first cursor.
4207 *
4208 * @param layout Text layout.
4209 * @param offset Character offset for the cursor.
4210 * @return The clamped horizontal position for the cursor.
4211 */
4212 int getCursorHorizontalPosition(Layout layout, int offset) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004213 return (int) (getHorizontal(layout, offset) - 0.5f);
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004214 }
4215
Gilles Debunned88876a2012-03-16 17:34:04 -07004216 public void updatePosition(int parentPositionX, int parentPositionY,
4217 boolean parentPositionChanged, boolean parentScrolled) {
4218 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
4219 if (parentPositionChanged || mPositionHasChanged) {
4220 if (mIsDragging) {
4221 // Update touchToWindow offset in case of parent scrolling while dragging
4222 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
4223 mTouchToWindowOffsetX += parentPositionX - mLastParentX;
4224 mTouchToWindowOffsetY += parentPositionY - mLastParentY;
4225 mLastParentX = parentPositionX;
4226 mLastParentY = parentPositionY;
4227 }
4228
4229 onHandleMoved();
4230 }
4231
4232 if (isVisible()) {
Seigo Nonaka2f229ca2016-02-18 17:53:54 +09004233 // Transform to the window coordinates to follow the view tranformation.
4234 final int[] pts = { mPositionX + mHotspotX + getHorizontalOffset(), mPositionY};
4235 mTextView.transformFromViewToWindowSpace(pts);
4236 pts[0] -= mHotspotX + getHorizontalOffset();
4237
Gilles Debunned88876a2012-03-16 17:34:04 -07004238 if (isShowing()) {
Seigo Nonaka2f229ca2016-02-18 17:53:54 +09004239 mContainer.update(pts[0], pts[1], -1, -1);
Gilles Debunned88876a2012-03-16 17:34:04 -07004240 } else {
Seigo Nonaka2f229ca2016-02-18 17:53:54 +09004241 mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, pts[0], pts[1]);
Gilles Debunned88876a2012-03-16 17:34:04 -07004242 }
4243 } else {
4244 if (isShowing()) {
4245 dismiss();
4246 }
4247 }
4248
4249 mPositionHasChanged = false;
4250 }
4251 }
4252
4253 @Override
4254 protected void onDraw(Canvas c) {
Adam Powell3fceabd2014-08-19 18:28:04 -07004255 final int drawWidth = mDrawable.getIntrinsicWidth();
4256 final int left = getHorizontalOffset();
4257
4258 mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
Gilles Debunned88876a2012-03-16 17:34:04 -07004259 mDrawable.draw(c);
4260 }
4261
Adam Powell3fceabd2014-08-19 18:28:04 -07004262 private int getHorizontalOffset() {
4263 final int width = getPreferredWidth();
4264 final int drawWidth = mDrawable.getIntrinsicWidth();
4265 final int left;
4266 switch (mHorizontalGravity) {
4267 case Gravity.LEFT:
4268 left = 0;
4269 break;
4270 default:
4271 case Gravity.CENTER:
4272 left = (width - drawWidth) / 2;
4273 break;
4274 case Gravity.RIGHT:
4275 left = width - drawWidth;
4276 break;
4277 }
4278 return left;
4279 }
4280
4281 protected int getCursorOffset() {
4282 return 0;
4283 }
4284
Gilles Debunned88876a2012-03-16 17:34:04 -07004285 @Override
4286 public boolean onTouchEvent(MotionEvent ev) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01004287 updateFloatingToolbarVisibility(ev);
4288
Gilles Debunned88876a2012-03-16 17:34:04 -07004289 switch (ev.getActionMasked()) {
4290 case MotionEvent.ACTION_DOWN: {
4291 startTouchUpFilter(getCurrentCursorOffset());
4292 mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
4293 mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
4294
4295 final PositionListener positionListener = getPositionListener();
4296 mLastParentX = positionListener.getPositionX();
4297 mLastParentY = positionListener.getPositionY();
4298 mIsDragging = true;
Mady Mellora6a0f782015-07-10 16:43:32 -07004299 mPreviousLineTouched = UNSET_LINE;
Gilles Debunned88876a2012-03-16 17:34:04 -07004300 break;
4301 }
4302
4303 case MotionEvent.ACTION_MOVE: {
4304 final float rawX = ev.getRawX();
4305 final float rawY = ev.getRawY();
4306
4307 // Vertical hysteresis: vertical down movement tends to snap to ideal offset
4308 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
4309 final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
4310 float newVerticalOffset;
4311 if (previousVerticalOffset < mIdealVerticalOffset) {
4312 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
4313 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
4314 } else {
4315 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
4316 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
4317 }
4318 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
4319
Keisuke Kuroyanagibc89a5c2015-05-18 14:49:29 +09004320 final float newPosX =
4321 rawX - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
Gilles Debunned88876a2012-03-16 17:34:04 -07004322 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
4323
4324 updatePosition(newPosX, newPosY);
4325 break;
4326 }
4327
4328 case MotionEvent.ACTION_UP:
4329 filterOnTouchUp();
4330 mIsDragging = false;
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004331 updateDrawable();
Gilles Debunned88876a2012-03-16 17:34:04 -07004332 break;
4333
4334 case MotionEvent.ACTION_CANCEL:
4335 mIsDragging = false;
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004336 updateDrawable();
Gilles Debunned88876a2012-03-16 17:34:04 -07004337 break;
4338 }
4339 return true;
4340 }
4341
4342 public boolean isDragging() {
4343 return mIsDragging;
4344 }
4345
Clara Bayarri6351e662015-03-16 23:17:59 +00004346 void onHandleMoved() {}
Gilles Debunned88876a2012-03-16 17:34:04 -07004347
Clara Bayarri6351e662015-03-16 23:17:59 +00004348 public void onDetached() {}
Gilles Debunned88876a2012-03-16 17:34:04 -07004349 }
4350
4351 private class InsertionHandleView extends HandleView {
4352 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
4353 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
4354
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004355 // Used to detect taps on the insertion handle, which will affect the insertion action mode
Gilles Debunned88876a2012-03-16 17:34:04 -07004356 private float mDownPositionX, mDownPositionY;
4357 private Runnable mHider;
4358
4359 public InsertionHandleView(Drawable drawable) {
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09004360 super(drawable, drawable, com.android.internal.R.id.insertion_handle);
Gilles Debunned88876a2012-03-16 17:34:04 -07004361 }
4362
4363 @Override
4364 public void show() {
4365 super.show();
4366
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004367 final long durationSinceCutOrCopy =
Andrei Stingaceanu77b9c382015-05-06 13:25:19 +01004368 SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004369
4370 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004371 if (mInsertionActionModeRunnable != null
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004372 && ((mTapState == TAP_STATE_DOUBLE_TAP)
4373 || (mTapState == TAP_STATE_TRIPLE_CLICK)
4374 || isCursorInsideEasyCorrectionSpan())) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004375 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004376 }
4377
4378 // Prepare and schedule the single tap runnable to run exactly after the double tap
4379 // timeout has passed.
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004380 if ((mTapState != TAP_STATE_DOUBLE_TAP) && (mTapState != TAP_STATE_TRIPLE_CLICK)
4381 && !isCursorInsideEasyCorrectionSpan()
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01004382 && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004383 if (mTextActionMode == null) {
4384 if (mInsertionActionModeRunnable == null) {
4385 mInsertionActionModeRunnable = new Runnable() {
4386 @Override
4387 public void run() {
4388 startInsertionActionMode();
4389 }
4390 };
4391 }
4392 mTextView.postDelayed(
4393 mInsertionActionModeRunnable,
4394 ViewConfiguration.getDoubleTapTimeout() + 1);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004395 }
4396
Gilles Debunned88876a2012-03-16 17:34:04 -07004397 }
4398
4399 hideAfterDelay();
4400 }
4401
Gilles Debunned88876a2012-03-16 17:34:04 -07004402 private void hideAfterDelay() {
4403 if (mHider == null) {
4404 mHider = new Runnable() {
4405 public void run() {
4406 hide();
4407 }
4408 };
4409 } else {
4410 removeHiderCallback();
4411 }
4412 mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
4413 }
4414
4415 private void removeHiderCallback() {
4416 if (mHider != null) {
4417 mTextView.removeCallbacks(mHider);
4418 }
4419 }
4420
4421 @Override
4422 protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4423 return drawable.getIntrinsicWidth() / 2;
4424 }
4425
4426 @Override
Adam Powell3fceabd2014-08-19 18:28:04 -07004427 protected int getHorizontalGravity(boolean isRtlRun) {
4428 return Gravity.CENTER_HORIZONTAL;
4429 }
4430
4431 @Override
4432 protected int getCursorOffset() {
4433 int offset = super.getCursorOffset();
4434 final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
4435 if (cursor != null) {
4436 cursor.getPadding(mTempRect);
4437 offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
4438 }
4439 return offset;
4440 }
4441
4442 @Override
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004443 int getCursorHorizontalPosition(Layout layout, int offset) {
4444 final Drawable drawable = mCursorCount > 0 ? mCursorDrawable[0] : null;
4445 if (drawable != null) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004446 final float horizontal = getHorizontal(layout, offset);
Siyamed Sinir987ec652016-02-17 19:44:41 -08004447 return clampHorizontalPosition(drawable, horizontal) + mTempRect.left;
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004448 }
4449 return super.getCursorHorizontalPosition(layout, offset);
4450 }
4451
4452 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07004453 public boolean onTouchEvent(MotionEvent ev) {
4454 final boolean result = super.onTouchEvent(ev);
4455
4456 switch (ev.getActionMasked()) {
4457 case MotionEvent.ACTION_DOWN:
4458 mDownPositionX = ev.getRawX();
4459 mDownPositionY = ev.getRawY();
4460 break;
4461
4462 case MotionEvent.ACTION_UP:
4463 if (!offsetHasBeenChanged()) {
4464 final float deltaX = mDownPositionX - ev.getRawX();
4465 final float deltaY = mDownPositionY - ev.getRawY();
4466 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4467
4468 final ViewConfiguration viewConfiguration = ViewConfiguration.get(
4469 mTextView.getContext());
4470 final int touchSlop = viewConfiguration.getScaledTouchSlop();
4471
4472 if (distanceSquared < touchSlop * touchSlop) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004473 // Tapping on the handle toggles the insertion action mode.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004474 if (mTextActionMode != null) {
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08004475 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07004476 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004477 startInsertionActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07004478 }
4479 }
Abodunrinwa Tokibcdf0ab2015-04-25 00:11:25 +01004480 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004481 if (mTextActionMode != null) {
4482 mTextActionMode.invalidateContentRect();
Abodunrinwa Tokibcdf0ab2015-04-25 00:11:25 +01004483 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004484 }
4485 hideAfterDelay();
4486 break;
4487
4488 case MotionEvent.ACTION_CANCEL:
4489 hideAfterDelay();
4490 break;
4491
4492 default:
4493 break;
4494 }
4495
4496 return result;
4497 }
4498
4499 @Override
4500 public int getCurrentCursorOffset() {
4501 return mTextView.getSelectionStart();
4502 }
4503
4504 @Override
4505 public void updateSelection(int offset) {
4506 Selection.setSelection((Spannable) mTextView.getText(), offset);
4507 }
4508
4509 @Override
4510 public void updatePosition(float x, float y) {
Mady Melloree3821e2015-06-05 11:12:01 -07004511 Layout layout = mTextView.getLayout();
4512 int offset;
4513 if (layout != null) {
Mady Mellora6a0f782015-07-10 16:43:32 -07004514 if (mPreviousLineTouched == UNSET_LINE) {
4515 mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4516 }
4517 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004518 offset = getOffsetAtCoordinate(layout, currLine, x);
Mady Mellora6a0f782015-07-10 16:43:32 -07004519 mPreviousLineTouched = currLine;
Mady Melloree3821e2015-06-05 11:12:01 -07004520 } else {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004521 offset = -1;
Mady Melloree3821e2015-06-05 11:12:01 -07004522 }
4523 positionAtCursorOffset(offset, false);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004524 if (mTextActionMode != null) {
4525 mTextActionMode.invalidate();
Clara Bayarri1baed512015-05-11 15:29:16 +01004526 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004527 }
4528
4529 @Override
4530 void onHandleMoved() {
4531 super.onHandleMoved();
4532 removeHiderCallback();
4533 }
4534
4535 @Override
4536 public void onDetached() {
4537 super.onDetached();
4538 removeHiderCallback();
4539 }
4540 }
4541
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004542 @Retention(RetentionPolicy.SOURCE)
4543 @IntDef({HANDLE_TYPE_SELECTION_START, HANDLE_TYPE_SELECTION_END})
4544 public @interface HandleType {}
4545 public static final int HANDLE_TYPE_SELECTION_START = 0;
4546 public static final int HANDLE_TYPE_SELECTION_END = 1;
4547
4548 private class SelectionHandleView extends HandleView {
4549 // Indicates the handle type, selection start (HANDLE_TYPE_SELECTION_START) or selection
4550 // end (HANDLE_TYPE_SELECTION_END).
4551 @HandleType
4552 private final int mHandleType;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004553 // Indicates whether the cursor is making adjustments within a word.
4554 private boolean mInWord = false;
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004555 // Difference between touch position and word boundary position.
4556 private float mTouchWordDelta;
Mady Mellore264ac32015-06-22 16:46:29 -07004557 // X value of the previous updatePosition call.
4558 private float mPrevX;
4559 // Indicates if the handle has moved a boundary between LTR and RTL text.
4560 private boolean mLanguageDirectionChanged = false;
Mady Mellor42390aa2015-07-24 13:08:42 -07004561 // Distance from edge of horizontally scrolling text view
4562 // to use to switch to character mode.
4563 private final float mTextViewEdgeSlop;
4564 // Used to save text view location.
4565 private final int[] mTextViewLocation = new int[2];
Gilles Debunned88876a2012-03-16 17:34:04 -07004566
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004567 public SelectionHandleView(Drawable drawableLtr, Drawable drawableRtl, int id,
4568 @HandleType int handleType) {
4569 super(drawableLtr, drawableRtl, id);
4570 mHandleType = handleType;
4571 ViewConfiguration viewConfiguration = ViewConfiguration.get(mTextView.getContext());
Mady Mellor42390aa2015-07-24 13:08:42 -07004572 mTextViewEdgeSlop = viewConfiguration.getScaledTouchSlop() * 4;
Gilles Debunned88876a2012-03-16 17:34:04 -07004573 }
4574
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004575 private boolean isStartHandle() {
4576 return mHandleType == HANDLE_TYPE_SELECTION_START;
4577 }
4578
Gilles Debunned88876a2012-03-16 17:34:04 -07004579 @Override
4580 protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004581 if (isRtlRun == isStartHandle()) {
Mady Mellor709386f2015-05-14 12:41:18 -07004582 return drawable.getIntrinsicWidth() / 4;
4583 } else {
4584 return (drawable.getIntrinsicWidth() * 3) / 4;
4585 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004586 }
4587
4588 @Override
Adam Powell3fceabd2014-08-19 18:28:04 -07004589 protected int getHorizontalGravity(boolean isRtlRun) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004590 return (isRtlRun == isStartHandle()) ? Gravity.LEFT : Gravity.RIGHT;
Adam Powell3fceabd2014-08-19 18:28:04 -07004591 }
4592
4593 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07004594 public int getCurrentCursorOffset() {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004595 return isStartHandle() ? mTextView.getSelectionStart() : mTextView.getSelectionEnd();
Gilles Debunned88876a2012-03-16 17:34:04 -07004596 }
4597
4598 @Override
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004599 protected void updateSelection(int offset) {
4600 if (isStartHandle()) {
4601 Selection.setSelection((Spannable) mTextView.getText(), offset,
4602 mTextView.getSelectionEnd());
4603 } else {
4604 Selection.setSelection((Spannable) mTextView.getText(),
4605 mTextView.getSelectionStart(), offset);
4606 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004607 updateDrawable();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004608 if (mTextActionMode != null) {
4609 mTextActionMode.invalidate();
Clara Bayarri13152d12015-04-09 12:02:04 +01004610 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004611 }
4612
4613 @Override
4614 public void updatePosition(float x, float y) {
Mady Mellor81fa3e82015-05-14 09:17:41 -07004615 final Layout layout = mTextView.getLayout();
Mady Mellorcc65c372015-06-17 09:25:19 -07004616 if (layout == null) {
4617 // HandleView will deal appropriately in positionAtCursorOffset when
4618 // layout is null.
Mady Mellor42390aa2015-07-24 13:08:42 -07004619 positionAndAdjustForCrossingHandles(mTextView.getOffsetForPosition(x, y));
Mady Mellorcc65c372015-06-17 09:25:19 -07004620 return;
4621 }
4622
Mady Mellora6a0f782015-07-10 16:43:32 -07004623 if (mPreviousLineTouched == UNSET_LINE) {
4624 mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4625 }
4626
Mady Mellorb9bbbb12015-03-23 11:50:46 -07004627 boolean positionCursor = false;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004628 final int anotherHandleOffset =
4629 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
Mady Mellora6a0f782015-07-10 16:43:32 -07004630 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004631 int initialOffset = getOffsetAtCoordinate(layout, currLine, x);
Mady Mellor81fa3e82015-05-14 09:17:41 -07004632
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004633 if (isStartHandle() && initialOffset >= anotherHandleOffset
4634 || !isStartHandle() && initialOffset <= anotherHandleOffset) {
4635 // Handles have crossed, bound it to the first selected line and
Mady Mellor81fa3e82015-05-14 09:17:41 -07004636 // adjust by word / char as normal.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004637 currLine = layout.getLineForOffset(anotherHandleOffset);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004638 initialOffset = getOffsetAtCoordinate(layout, currLine, x);
Mady Mellor81fa3e82015-05-14 09:17:41 -07004639 }
4640
4641 int offset = initialOffset;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004642 final int wordEnd = getWordEnd(offset);
4643 final int wordStart = getWordStart(offset);
Gilles Debunned88876a2012-03-16 17:34:04 -07004644
Mady Mellore264ac32015-06-22 16:46:29 -07004645 if (mPrevX == UNSET_X_VALUE) {
4646 mPrevX = x;
4647 }
4648
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004649 final int currentOffset = getCurrentCursorOffset();
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004650 final boolean rtlAtCurrentOffset = isAtRtlRun(layout, currentOffset);
4651 final boolean atRtl = isAtRtlRun(layout, offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004652 final boolean isLvlBoundary = layout.isLevelBoundary(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004653
4654 // We can't determine if the user is expanding or shrinking the selection if they're
4655 // on a bi-di boundary, so until they've moved past the boundary we'll just place
4656 // the cursor at the current position.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004657 if (isLvlBoundary || (rtlAtCurrentOffset && !atRtl) || (!rtlAtCurrentOffset && atRtl)) {
Mady Mellore264ac32015-06-22 16:46:29 -07004658 // We're on a boundary or this is the first direction change -- just update
4659 // to the current position.
4660 mLanguageDirectionChanged = true;
4661 mTouchWordDelta = 0.0f;
Mady Mellor42390aa2015-07-24 13:08:42 -07004662 positionAndAdjustForCrossingHandles(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004663 return;
4664 } else if (mLanguageDirectionChanged && !isLvlBoundary) {
4665 // We've just moved past the boundary so update the position. After this we can
4666 // figure out if the user is expanding or shrinking to go by word or character.
Mady Mellor42390aa2015-07-24 13:08:42 -07004667 positionAndAdjustForCrossingHandles(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004668 mTouchWordDelta = 0.0f;
4669 mLanguageDirectionChanged = false;
4670 return;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004671 }
4672
4673 boolean isExpanding;
4674 final float xDiff = x - mPrevX;
Keisuke Kuroyanagi26454142015-12-02 15:04:57 -08004675 if (isStartHandle()) {
4676 isExpanding = currLine < mPreviousLineTouched;
Mady Mellore264ac32015-06-22 16:46:29 -07004677 } else {
Keisuke Kuroyanagi26454142015-12-02 15:04:57 -08004678 isExpanding = currLine > mPreviousLineTouched;
4679 }
4680 if (atRtl == isStartHandle()) {
4681 isExpanding |= xDiff > 0;
4682 } else {
4683 isExpanding |= xDiff < 0;
Mady Mellore264ac32015-06-22 16:46:29 -07004684 }
4685
Mady Mellor42390aa2015-07-24 13:08:42 -07004686 if (mTextView.getHorizontallyScrolling()) {
4687 if (positionNearEdgeOfScrollingView(x, atRtl)
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004688 && ((isStartHandle() && mTextView.getScrollX() != 0)
4689 || (!isStartHandle()
4690 && mTextView.canScrollHorizontally(atRtl ? -1 : 1)))
4691 && ((isExpanding && ((isStartHandle() && offset < currentOffset)
4692 || (!isStartHandle() && offset > currentOffset)))
4693 || !isExpanding)) {
4694 // If we're expanding ensure that the offset is actually expanding compared to
4695 // the current offset, if the handle snapped to the word, the finger position
Mady Mellor42390aa2015-07-24 13:08:42 -07004696 // may be out of sync and we don't want the selection to jump back.
4697 mTouchWordDelta = 0.0f;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004698 final int nextOffset = (atRtl == isStartHandle())
4699 ? layout.getOffsetToRightOf(mPreviousOffset)
Mady Mellor42390aa2015-07-24 13:08:42 -07004700 : layout.getOffsetToLeftOf(mPreviousOffset);
4701 positionAndAdjustForCrossingHandles(nextOffset);
4702 return;
4703 }
4704 }
4705
Mady Mellore264ac32015-06-22 16:46:29 -07004706 if (isExpanding) {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004707 // User is increasing the selection.
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004708 int wordBoundary = isStartHandle() ? wordStart : wordEnd;
4709 final boolean snapToWord = (!mInWord
4710 || (isStartHandle() ? currLine < mPrevLine : currLine > mPrevLine))
4711 && atRtl == isAtRtlRun(layout, wordBoundary);
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004712 if (snapToWord) {
Mady Mellora5266832015-06-26 14:28:12 -07004713 // Sometimes words can be broken across lines (Chinese, hyphenation).
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004714 // We still snap to the word boundary but we only use the letters on the
Mady Mellora5266832015-06-26 14:28:12 -07004715 // current line to determine if the user is far enough into the word to snap.
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004716 if (layout.getLineForOffset(wordBoundary) != currLine) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004717 wordBoundary = isStartHandle() ?
4718 layout.getLineStart(currLine) : layout.getLineEnd(currLine);
Mady Mellora5266832015-06-26 14:28:12 -07004719 }
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004720 final int offsetThresholdToSnap = isStartHandle()
4721 ? wordEnd - ((wordEnd - wordBoundary) / 2)
4722 : wordStart + ((wordBoundary - wordStart) / 2);
4723 if (isStartHandle()
4724 && (offset <= offsetThresholdToSnap || currLine < mPrevLine)) {
4725 // User is far enough into the word or on a different line so we expand by
4726 // word.
4727 offset = wordStart;
4728 } else if (!isStartHandle()
4729 && (offset >= offsetThresholdToSnap || currLine > mPrevLine)) {
4730 // User is far enough into the word or on a different line so we expand by
4731 // word.
4732 offset = wordEnd;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004733 } else {
Mady Mellorc2225b92015-04-01 15:59:20 -07004734 offset = mPreviousOffset;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004735 }
4736 }
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004737 if ((isStartHandle() && offset < initialOffset)
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004738 || (!isStartHandle() && offset > initialOffset)) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004739 final float adjustedX = getHorizontal(layout, offset);
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004740 mTouchWordDelta =
4741 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
Keisuke Kuroyanagi50a927c2015-05-07 17:34:21 +09004742 } else {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004743 mTouchWordDelta = 0.0f;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004744 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004745 positionCursor = true;
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004746 } else {
4747 final int adjustedOffset =
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004748 getOffsetAtCoordinate(layout, currLine, x - mTouchWordDelta);
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004749 final boolean shrinking = isStartHandle()
4750 ? adjustedOffset > mPreviousOffset || currLine > mPrevLine
4751 : adjustedOffset < mPreviousOffset || currLine < mPrevLine;
4752 if (shrinking) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004753 // User is shrinking the selection.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004754 if (currLine != mPrevLine) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004755 // We're on a different line, so we'll snap to word boundaries.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004756 offset = isStartHandle() ? wordStart : wordEnd;
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004757 if ((isStartHandle() && offset < initialOffset)
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004758 || (!isStartHandle() && offset > initialOffset)) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004759 final float adjustedX = getHorizontal(layout, offset);
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004760 mTouchWordDelta =
4761 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4762 } else {
4763 mTouchWordDelta = 0.0f;
4764 }
4765 } else {
4766 offset = adjustedOffset;
4767 }
4768 positionCursor = true;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004769 } else if ((isStartHandle() && adjustedOffset < mPreviousOffset)
4770 || (!isStartHandle() && adjustedOffset > mPreviousOffset)) {
4771 // Handle has jumped to the word boundary, and the user is moving
Mady Mellor43fd2f42015-06-08 14:03:34 -07004772 // their finger towards the handle, the delta should be updated.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004773 mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x) -
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004774 getHorizontal(layout, mPreviousOffset);
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004775 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004776 }
4777
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004778 if (positionCursor) {
Mady Mellora6a0f782015-07-10 16:43:32 -07004779 mPreviousLineTouched = currLine;
Mady Mellor42390aa2015-07-24 13:08:42 -07004780 positionAndAdjustForCrossingHandles(offset);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004781 }
Mady Mellore264ac32015-06-22 16:46:29 -07004782 mPrevX = x;
Gilles Debunned88876a2012-03-16 17:34:04 -07004783 }
4784
Yoshiki Iguchi9582e152015-10-15 13:34:41 +09004785 /**
4786 * @param offset Cursor offset. Must be in [-1, length].
4787 * @param parentScrolled If the parent has been scrolled or not.
4788 */
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004789 @Override
Mady Mellor36d5a7b2015-05-22 10:31:12 -07004790 protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4791 super.positionAtCursorOffset(offset, parentScrolled);
Yoshiki Iguchi9582e152015-10-15 13:34:41 +09004792 mInWord = (offset != -1) && !getWordIteratorWithText().isBoundary(offset);
Mady Mellor36d5a7b2015-05-22 10:31:12 -07004793 }
4794
4795 @Override
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004796 public boolean onTouchEvent(MotionEvent event) {
4797 boolean superResult = super.onTouchEvent(event);
Mady Mellora6a0f782015-07-10 16:43:32 -07004798 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
4799 // Reset the touch word offset and x value when the user
4800 // re-engages the handle.
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004801 mTouchWordDelta = 0.0f;
Mady Mellore264ac32015-06-22 16:46:29 -07004802 mPrevX = UNSET_X_VALUE;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004803 }
4804 return superResult;
4805 }
Mady Mellor42390aa2015-07-24 13:08:42 -07004806
Mady Mellor42390aa2015-07-24 13:08:42 -07004807 private void positionAndAdjustForCrossingHandles(int offset) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004808 final int anotherHandleOffset =
4809 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
4810 if ((isStartHandle() && offset >= anotherHandleOffset)
4811 || (!isStartHandle() && offset <= anotherHandleOffset)) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004812 mTouchWordDelta = 0.0f;
4813 final Layout layout = mTextView.getLayout();
4814 if (layout != null && offset != anotherHandleOffset) {
4815 final float horiz = getHorizontal(layout, offset);
4816 final float anotherHandleHoriz = getHorizontal(layout, anotherHandleOffset,
4817 !isStartHandle());
4818 final float currentHoriz = getHorizontal(layout, mPreviousOffset);
4819 if (currentHoriz < anotherHandleHoriz && horiz < anotherHandleHoriz
4820 || currentHoriz > anotherHandleHoriz && horiz > anotherHandleHoriz) {
4821 // This handle passes another one as it crossed a direction boundary.
4822 // Don't minimize the selection, but keep the handle at the run boundary.
4823 final int currentOffset = getCurrentCursorOffset();
4824 final int offsetToGetRunRange = isStartHandle() ?
4825 currentOffset : Math.max(currentOffset - 1, 0);
4826 final long range = layout.getRunRange(offsetToGetRunRange);
4827 if (isStartHandle()) {
4828 offset = TextUtils.unpackRangeStartFromLong(range);
4829 } else {
4830 offset = TextUtils.unpackRangeEndFromLong(range);
4831 }
4832 positionAtCursorOffset(offset, false);
4833 return;
4834 }
4835 }
Mady Mellor42390aa2015-07-24 13:08:42 -07004836 // Handles can not cross and selection is at least one character.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004837 offset = getNextCursorOffset(anotherHandleOffset, !isStartHandle());
Mady Mellor42390aa2015-07-24 13:08:42 -07004838 }
4839 positionAtCursorOffset(offset, false);
4840 }
4841
Mady Mellor42390aa2015-07-24 13:08:42 -07004842 private boolean positionNearEdgeOfScrollingView(float x, boolean atRtl) {
4843 mTextView.getLocationOnScreen(mTextViewLocation);
4844 boolean nearEdge;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004845 if (atRtl == isStartHandle()) {
Mady Mellor42390aa2015-07-24 13:08:42 -07004846 int rightEdge = mTextViewLocation[0] + mTextView.getWidth()
4847 - mTextView.getPaddingRight();
4848 nearEdge = x > rightEdge - mTextViewEdgeSlop;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004849 } else {
4850 int leftEdge = mTextViewLocation[0] + mTextView.getPaddingLeft();
4851 nearEdge = x < leftEdge + mTextViewEdgeSlop;
Mady Mellor42390aa2015-07-24 13:08:42 -07004852 }
4853 return nearEdge;
4854 }
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09004855
4856 @Override
4857 protected boolean isAtRtlRun(@NonNull Layout layout, int offset) {
4858 final int offsetToCheck = isStartHandle() ? offset : Math.max(offset - 1, 0);
4859 return layout.isRtlCharAt(offsetToCheck);
4860 }
4861
4862 @Override
4863 public float getHorizontal(@NonNull Layout layout, int offset) {
4864 return getHorizontal(layout, offset, isStartHandle());
4865 }
4866
4867 private float getHorizontal(@NonNull Layout layout, int offset, boolean startHandle) {
4868 final int line = layout.getLineForOffset(offset);
4869 final int offsetToCheck = startHandle ? offset : Math.max(offset - 1, 0);
4870 final boolean isRtlChar = layout.isRtlCharAt(offsetToCheck);
4871 final boolean isRtlParagraph = layout.getParagraphDirection(line) == -1;
4872 return (isRtlChar == isRtlParagraph) ?
4873 layout.getPrimaryHorizontal(offset) : layout.getSecondaryHorizontal(offset);
4874 }
4875
4876 @Override
4877 protected int getOffsetAtCoordinate(@NonNull Layout layout, int line, float x) {
4878 final int primaryOffset = layout.getOffsetForHorizontal(line, x, true);
4879 if (!layout.isLevelBoundary(primaryOffset)) {
4880 return primaryOffset;
4881 }
4882 final int secondaryOffset = layout.getOffsetForHorizontal(line, x, false);
4883 final int currentOffset = getCurrentCursorOffset();
4884 final int primaryDiff = Math.abs(primaryOffset - currentOffset);
4885 final int secondaryDiff = Math.abs(secondaryOffset - currentOffset);
4886 if (primaryDiff < secondaryDiff) {
4887 return primaryOffset;
4888 } else if (primaryDiff > secondaryDiff) {
4889 return secondaryOffset;
4890 } else {
4891 final int offsetToCheck = isStartHandle() ?
4892 currentOffset : Math.max(currentOffset - 1, 0);
4893 final boolean isRtlChar = layout.isRtlCharAt(offsetToCheck);
4894 final boolean isRtlParagraph = layout.getParagraphDirection(line) == -1;
4895 return isRtlChar == isRtlParagraph ? primaryOffset : secondaryOffset;
4896 }
4897 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004898 }
4899
Mady Mellorcc65c372015-06-17 09:25:19 -07004900 private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
Mady Mellor80679072015-07-09 16:05:36 -07004901 final int trueLine = mTextView.getLineAtCoordinate(y);
Mady Mellorcc65c372015-06-17 09:25:19 -07004902 if (layout == null || prevLine > layout.getLineCount()
4903 || layout.getLineCount() <= 0 || prevLine < 0) {
4904 // Invalid parameters, just return whatever line is at y.
Mady Mellor80679072015-07-09 16:05:36 -07004905 return trueLine;
4906 }
4907
4908 if (Math.abs(trueLine - prevLine) >= 2) {
4909 // Only stick to lines if we're within a line of the previous selection.
4910 return trueLine;
Mady Mellorcc65c372015-06-17 09:25:19 -07004911 }
4912
4913 final float verticalOffset = mTextView.viewportToContentVerticalOffset();
4914 final int lineCount = layout.getLineCount();
4915 final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
4916
4917 final float firstLineTop = layout.getLineTop(0) + verticalOffset;
4918 final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
4919 final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
4920
4921 final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
4922 final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
4923 final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
4924
4925 // Determine if we've moved lines based on y position and previous line.
4926 int currLine;
4927 if (y <= yTopBound) {
4928 currLine = Math.max(prevLine - 1, 0);
4929 } else if (y >= yBottomBound) {
4930 currLine = Math.min(prevLine + 1, lineCount - 1);
4931 } else {
4932 currLine = prevLine;
4933 }
4934 return currLine;
4935 }
4936
Gilles Debunned88876a2012-03-16 17:34:04 -07004937 /**
4938 * A CursorController instance can be used to control a cursor in the text.
4939 */
4940 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
4941 /**
4942 * Makes the cursor controller visible on screen.
4943 * See also {@link #hide()}.
4944 */
4945 public void show();
4946
4947 /**
4948 * Hide the cursor controller from screen.
4949 * See also {@link #show()}.
4950 */
4951 public void hide();
4952
4953 /**
4954 * Called when the view is detached from window. Perform house keeping task, such as
4955 * stopping Runnable thread that would otherwise keep a reference on the context, thus
4956 * preventing the activity from being recycled.
4957 */
4958 public void onDetached();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08004959
4960 public boolean isCursorBeingModified();
4961
4962 public boolean isActive();
Gilles Debunned88876a2012-03-16 17:34:04 -07004963 }
4964
4965 private class InsertionPointCursorController implements CursorController {
4966 private InsertionHandleView mHandle;
4967
4968 public void show() {
4969 getHandle().show();
Andrei Stingaceanu35c550c2015-05-07 16:49:49 +01004970
4971 if (mSelectionModifierCursorController != null) {
4972 mSelectionModifierCursorController.hide();
4973 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004974 }
4975
Gilles Debunned88876a2012-03-16 17:34:04 -07004976 public void hide() {
4977 if (mHandle != null) {
4978 mHandle.hide();
4979 }
4980 }
4981
4982 public void onTouchModeChanged(boolean isInTouchMode) {
4983 if (!isInTouchMode) {
4984 hide();
4985 }
4986 }
4987
4988 private InsertionHandleView getHandle() {
4989 if (mSelectHandleCenter == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004990 mSelectHandleCenter = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004991 mTextView.mTextSelectHandleRes);
4992 }
4993 if (mHandle == null) {
4994 mHandle = new InsertionHandleView(mSelectHandleCenter);
4995 }
4996 return mHandle;
4997 }
4998
4999 @Override
5000 public void onDetached() {
5001 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5002 observer.removeOnTouchModeChangeListener(this);
5003
5004 if (mHandle != null) mHandle.onDetached();
5005 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005006
5007 @Override
5008 public boolean isCursorBeingModified() {
5009 return mHandle != null && mHandle.isDragging();
5010 }
5011
5012 @Override
5013 public boolean isActive() {
5014 return mHandle != null && mHandle.isShowing();
5015 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005016 }
5017
5018 class SelectionModifierCursorController implements CursorController {
Gilles Debunned88876a2012-03-16 17:34:04 -07005019 // The cursor controller handles, lazily created when shown.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09005020 private SelectionHandleView mStartHandle;
5021 private SelectionHandleView mEndHandle;
Gilles Debunned88876a2012-03-16 17:34:04 -07005022 // The offsets of that last touch down event. Remembered to start selection there.
5023 private int mMinTouchOffset, mMaxTouchOffset;
5024
Gilles Debunned88876a2012-03-16 17:34:04 -07005025 private float mDownPositionX, mDownPositionY;
5026 private boolean mGestureStayedInTapRegion;
5027
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005028 // Where the user first starts the drag motion.
5029 private int mStartOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005030
Mady Mellor7a936442015-05-20 10:05:52 -07005031 private boolean mHaventMovedEnoughToStartDrag;
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07005032 // The line that a selection happened most recently with the drag accelerator.
5033 private int mLineSelectionIsOn = -1;
5034 // Whether the drag accelerator has selected past the initial line.
5035 private boolean mSwitchedLines = false;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005036
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005037 // Indicates the drag accelerator mode that the user is currently using.
5038 private int mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
5039 // Drag accelerator is inactive.
5040 private static final int DRAG_ACCELERATOR_MODE_INACTIVE = 0;
5041 // Character based selection by dragging. Only for mouse.
5042 private static final int DRAG_ACCELERATOR_MODE_CHARACTER = 1;
5043 // Word based selection by dragging. Enabled after long pressing or double tapping.
5044 private static final int DRAG_ACCELERATOR_MODE_WORD = 2;
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005045 // Paragraph based selection by dragging. Enabled after mouse triple click.
5046 private static final int DRAG_ACCELERATOR_MODE_PARAGRAPH = 3;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005047
Gilles Debunned88876a2012-03-16 17:34:04 -07005048 SelectionModifierCursorController() {
5049 resetTouchOffsets();
5050 }
5051
5052 public void show() {
5053 if (mTextView.isInBatchEditMode()) {
5054 return;
5055 }
5056 initDrawables();
5057 initHandles();
Gilles Debunned88876a2012-03-16 17:34:04 -07005058 }
5059
5060 private void initDrawables() {
5061 if (mSelectHandleLeft == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08005062 mSelectHandleLeft = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07005063 mTextView.mTextSelectHandleLeftRes);
5064 }
5065 if (mSelectHandleRight == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08005066 mSelectHandleRight = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07005067 mTextView.mTextSelectHandleRightRes);
5068 }
5069 }
5070
5071 private void initHandles() {
5072 // Lazy object creation has to be done before updatePosition() is called.
5073 if (mStartHandle == null) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09005074 mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight,
5075 com.android.internal.R.id.selection_start_handle,
5076 HANDLE_TYPE_SELECTION_START);
Gilles Debunned88876a2012-03-16 17:34:04 -07005077 }
5078 if (mEndHandle == null) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09005079 mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft,
5080 com.android.internal.R.id.selection_end_handle,
5081 HANDLE_TYPE_SELECTION_END);
Gilles Debunned88876a2012-03-16 17:34:04 -07005082 }
5083
5084 mStartHandle.show();
5085 mEndHandle.show();
5086
Gilles Debunned88876a2012-03-16 17:34:04 -07005087 hideInsertionPointCursorController();
5088 }
5089
5090 public void hide() {
5091 if (mStartHandle != null) mStartHandle.hide();
5092 if (mEndHandle != null) mEndHandle.hide();
5093 }
5094
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005095 public void enterDrag(int dragAcceleratorMode) {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005096 // Just need to init the handles / hide insertion cursor.
5097 show();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005098 mDragAcceleratorMode = dragAcceleratorMode;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005099 // Start location of selection.
5100 mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
5101 mLastDownPositionY);
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07005102 mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005103 // Don't show the handles until user has lifted finger.
5104 hide();
5105
5106 // This stops scrolling parents from intercepting the touch event, allowing
5107 // the user to continue dragging across the screen to select text; TextView will
5108 // scroll as necessary.
5109 mTextView.getParent().requestDisallowInterceptTouchEvent(true);
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005110 mTextView.cancelLongPress();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005111 }
5112
Gilles Debunned88876a2012-03-16 17:34:04 -07005113 public void onTouchEvent(MotionEvent event) {
5114 // This is done even when the View does not have focus, so that long presses can start
5115 // selection and tap can move cursor from this tap position.
Mady Mellor7a936442015-05-20 10:05:52 -07005116 final float eventX = event.getX();
5117 final float eventY = event.getY();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005118 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
Gilles Debunned88876a2012-03-16 17:34:04 -07005119 switch (event.getActionMasked()) {
5120 case MotionEvent.ACTION_DOWN:
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005121 if (extractedTextModeWillBeStarted()) {
5122 // Prevent duplicating the selection handles until the mode starts.
5123 hide();
5124 } else {
5125 // Remember finger down position, to be able to start selection from there.
5126 mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
5127 eventX, eventY);
Gilles Debunned88876a2012-03-16 17:34:04 -07005128
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005129 // Double tap detection
5130 if (mGestureStayedInTapRegion) {
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09005131 if (mTapState == TAP_STATE_DOUBLE_TAP
5132 || mTapState == TAP_STATE_TRIPLE_CLICK) {
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005133 final float deltaX = eventX - mDownPositionX;
5134 final float deltaY = eventY - mDownPositionY;
5135 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
Gilles Debunned88876a2012-03-16 17:34:04 -07005136
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005137 ViewConfiguration viewConfiguration = ViewConfiguration.get(
5138 mTextView.getContext());
5139 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
5140 boolean stayedInArea =
5141 distanceSquared < doubleTapSlop * doubleTapSlop;
Gilles Debunned88876a2012-03-16 17:34:04 -07005142
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005143 if (stayedInArea && (isMouse || isPositionOnText(eventX, eventY))) {
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09005144 if (mTapState == TAP_STATE_DOUBLE_TAP) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005145 selectCurrentWordAndStartDrag();
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09005146 } else if (mTapState == TAP_STATE_TRIPLE_CLICK) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005147 selectCurrentParagraphAndStartDrag();
5148 }
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005149 mDiscardNextActionUp = true;
5150 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005151 }
5152 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005153
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005154 mDownPositionX = eventX;
5155 mDownPositionY = eventY;
5156 mGestureStayedInTapRegion = true;
5157 mHaventMovedEnoughToStartDrag = true;
5158 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005159 break;
5160
5161 case MotionEvent.ACTION_POINTER_DOWN:
5162 case MotionEvent.ACTION_POINTER_UP:
5163 // Handle multi-point gestures. Keep min and max offset positions.
5164 // Only activated for devices that correctly handle multi-touch.
5165 if (mTextView.getContext().getPackageManager().hasSystemFeature(
5166 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
5167 updateMinAndMaxOffsets(event);
5168 }
5169 break;
5170
5171 case MotionEvent.ACTION_MOVE:
Mady Mellor7a936442015-05-20 10:05:52 -07005172 final ViewConfiguration viewConfig = ViewConfiguration.get(
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005173 mTextView.getContext());
Mady Mellor7a936442015-05-20 10:05:52 -07005174 final int touchSlop = viewConfig.getScaledTouchSlop();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005175
Mady Mellor7a936442015-05-20 10:05:52 -07005176 if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
5177 final float deltaX = eventX - mDownPositionX;
5178 final float deltaY = eventY - mDownPositionY;
Gilles Debunned88876a2012-03-16 17:34:04 -07005179 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5180
Mady Mellor7a936442015-05-20 10:05:52 -07005181 if (mGestureStayedInTapRegion) {
5182 int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
5183 mGestureStayedInTapRegion =
5184 distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
5185 }
5186 if (mHaventMovedEnoughToStartDrag) {
5187 // We don't start dragging until the user has moved enough.
5188 mHaventMovedEnoughToStartDrag =
5189 distanceSquared <= touchSlop * touchSlop;
Gilles Debunned88876a2012-03-16 17:34:04 -07005190 }
5191 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005192
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005193 if (isMouse && !isDragAcceleratorActive()) {
5194 final int offset = mTextView.getOffsetForPosition(eventX, eventY);
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09005195 if (mTextView.hasSelection()
5196 && (!mHaventMovedEnoughToStartDrag || mStartOffset != offset)
5197 && offset >= mTextView.getSelectionStart()
5198 && offset <= mTextView.getSelectionEnd()) {
5199 startDragAndDrop();
5200 break;
5201 }
5202
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005203 if (mStartOffset != offset) {
5204 // Start character based drag accelerator.
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005205 stopTextActionMode();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005206 enterDrag(DRAG_ACCELERATOR_MODE_CHARACTER);
5207 mDiscardNextActionUp = true;
5208 mHaventMovedEnoughToStartDrag = false;
5209 }
5210 }
5211
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005212 if (mStartHandle != null && mStartHandle.isShowing()) {
5213 // Don't do the drag if the handles are showing already.
5214 break;
5215 }
5216
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005217 updateSelection(event);
Gilles Debunned88876a2012-03-16 17:34:04 -07005218 break;
5219
5220 case MotionEvent.ACTION_UP:
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005221 if (!isDragAcceleratorActive()) {
5222 break;
5223 }
5224 updateSelection(event);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005225
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005226 // No longer dragging to select text, let the parent intercept events.
5227 mTextView.getParent().requestDisallowInterceptTouchEvent(false);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005228
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005229 // No longer the first dragging motion, reset.
5230 resetDragAcceleratorState();
Keisuke Kuroyanagic477b582016-03-15 15:38:40 +09005231
5232 if (mTextView.hasSelection()) {
5233 startSelectionActionMode();
5234 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005235 break;
5236 }
5237 }
5238
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005239 private void updateSelection(MotionEvent event) {
5240 if (mTextView.getLayout() != null) {
5241 switch (mDragAcceleratorMode) {
5242 case DRAG_ACCELERATOR_MODE_CHARACTER:
5243 updateCharacterBasedSelection(event);
5244 break;
5245 case DRAG_ACCELERATOR_MODE_WORD:
5246 updateWordBasedSelection(event);
5247 break;
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005248 case DRAG_ACCELERATOR_MODE_PARAGRAPH:
5249 updateParagraphBasedSelection(event);
5250 break;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005251 }
5252 }
5253 }
5254
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005255 /**
5256 * If the TextView allows text selection, selects the current paragraph and starts a drag.
5257 *
5258 * @return true if the drag was started.
5259 */
5260 private boolean selectCurrentParagraphAndStartDrag() {
5261 if (mInsertionActionModeRunnable != null) {
5262 mTextView.removeCallbacks(mInsertionActionModeRunnable);
5263 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005264 stopTextActionMode();
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005265 if (!selectCurrentParagraph()) {
5266 return false;
5267 }
5268 enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_PARAGRAPH);
5269 return true;
5270 }
5271
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005272 private void updateCharacterBasedSelection(MotionEvent event) {
5273 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5274 Selection.setSelection((Spannable) mTextView.getText(), mStartOffset, offset);
5275 }
5276
5277 private void updateWordBasedSelection(MotionEvent event) {
5278 if (mHaventMovedEnoughToStartDrag) {
5279 return;
5280 }
5281 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5282 final ViewConfiguration viewConfig = ViewConfiguration.get(
5283 mTextView.getContext());
5284 final float eventX = event.getX();
5285 final float eventY = event.getY();
5286 final int currLine;
5287 if (isMouse) {
5288 // No need to offset the y coordinate for mouse input.
5289 currLine = mTextView.getLineAtCoordinate(eventY);
5290 } else {
5291 float y = eventY;
5292 if (mSwitchedLines) {
5293 // Offset the finger by the same vertical offset as the handles.
5294 // This improves visibility of the content being selected by
5295 // shifting the finger below the content, this is applied once
5296 // the user has switched lines.
5297 final int touchSlop = viewConfig.getScaledTouchSlop();
5298 final float fingerOffset = (mStartHandle != null)
5299 ? mStartHandle.getIdealVerticalOffset()
5300 : touchSlop;
5301 y = eventY - fingerOffset;
5302 }
5303
5304 currLine = getCurrentLineAdjustedForSlop(mTextView.getLayout(), mLineSelectionIsOn,
5305 y);
5306 if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
5307 // Break early here, we want to offset the finger position from
5308 // the selection highlight, once the user moved their finger
5309 // to a different line we should apply the offset and *not* switch
5310 // lines until recomputing the position with the finger offset.
5311 mSwitchedLines = true;
5312 return;
5313 }
5314 }
5315
5316 int startOffset;
5317 int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
5318 // Snap to word boundaries.
5319 if (mStartOffset < offset) {
5320 // Expanding with end handle.
5321 offset = getWordEnd(offset);
5322 startOffset = getWordStart(mStartOffset);
5323 } else {
5324 // Expanding with start handle.
5325 offset = getWordStart(offset);
5326 startOffset = getWordEnd(mStartOffset);
5327 }
5328 mLineSelectionIsOn = currLine;
5329 Selection.setSelection((Spannable) mTextView.getText(),
5330 startOffset, offset);
5331 }
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005332
5333 private void updateParagraphBasedSelection(MotionEvent event) {
5334 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5335
5336 final int start = Math.min(offset, mStartOffset);
5337 final int end = Math.max(offset, mStartOffset);
5338 final long paragraphsRange = getParagraphsRange(start, end);
5339 final int selectionStart = TextUtils.unpackRangeStartFromLong(paragraphsRange);
5340 final int selectionEnd = TextUtils.unpackRangeEndFromLong(paragraphsRange);
5341 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
5342 }
5343
Gilles Debunned88876a2012-03-16 17:34:04 -07005344 /**
5345 * @param event
5346 */
5347 private void updateMinAndMaxOffsets(MotionEvent event) {
5348 int pointerCount = event.getPointerCount();
5349 for (int index = 0; index < pointerCount; index++) {
5350 int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
5351 if (offset < mMinTouchOffset) mMinTouchOffset = offset;
5352 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
5353 }
5354 }
5355
5356 public int getMinTouchOffset() {
5357 return mMinTouchOffset;
5358 }
5359
5360 public int getMaxTouchOffset() {
5361 return mMaxTouchOffset;
5362 }
5363
5364 public void resetTouchOffsets() {
5365 mMinTouchOffset = mMaxTouchOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005366 resetDragAcceleratorState();
5367 }
5368
5369 private void resetDragAcceleratorState() {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005370 mStartOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005371 mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07005372 mSwitchedLines = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005373 final int selectionStart = mTextView.getSelectionStart();
5374 final int selectionEnd = mTextView.getSelectionEnd();
5375 if (selectionStart > selectionEnd) {
5376 Selection.setSelection((Spannable) mTextView.getText(),
5377 selectionEnd, selectionStart);
5378 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005379 }
5380
5381 /**
5382 * @return true iff this controller is currently used to move the selection start.
5383 */
5384 public boolean isSelectionStartDragged() {
5385 return mStartHandle != null && mStartHandle.isDragging();
5386 }
5387
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005388 @Override
5389 public boolean isCursorBeingModified() {
5390 return isDragAcceleratorActive() || isSelectionStartDragged()
5391 || (mEndHandle != null && mEndHandle.isDragging());
5392 }
5393
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005394 /**
5395 * @return true if the user is selecting text using the drag accelerator.
5396 */
5397 public boolean isDragAcceleratorActive() {
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005398 return mDragAcceleratorMode != DRAG_ACCELERATOR_MODE_INACTIVE;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005399 }
5400
Gilles Debunned88876a2012-03-16 17:34:04 -07005401 public void onTouchModeChanged(boolean isInTouchMode) {
5402 if (!isInTouchMode) {
5403 hide();
5404 }
5405 }
5406
5407 @Override
5408 public void onDetached() {
5409 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5410 observer.removeOnTouchModeChangeListener(this);
5411
5412 if (mStartHandle != null) mStartHandle.onDetached();
5413 if (mEndHandle != null) mEndHandle.onDetached();
5414 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005415
5416 @Override
5417 public boolean isActive() {
5418 return mStartHandle != null && mStartHandle.isShowing();
5419 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005420 }
5421
5422 private class CorrectionHighlighter {
5423 private final Path mPath = new Path();
Chris Craik6a49dde2015-05-12 10:28:14 -07005424 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Gilles Debunned88876a2012-03-16 17:34:04 -07005425 private int mStart, mEnd;
5426 private long mFadingStartTime;
5427 private RectF mTempRectF;
5428 private final static int FADE_OUT_DURATION = 400;
5429
5430 public CorrectionHighlighter() {
5431 mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
5432 applicationScale);
5433 mPaint.setStyle(Paint.Style.FILL);
5434 }
5435
5436 public void highlight(CorrectionInfo info) {
5437 mStart = info.getOffset();
5438 mEnd = mStart + info.getNewText().length();
5439 mFadingStartTime = SystemClock.uptimeMillis();
5440
5441 if (mStart < 0 || mEnd < 0) {
5442 stopAnimation();
5443 }
5444 }
5445
5446 public void draw(Canvas canvas, int cursorOffsetVertical) {
5447 if (updatePath() && updatePaint()) {
5448 if (cursorOffsetVertical != 0) {
5449 canvas.translate(0, cursorOffsetVertical);
5450 }
5451
5452 canvas.drawPath(mPath, mPaint);
5453
5454 if (cursorOffsetVertical != 0) {
5455 canvas.translate(0, -cursorOffsetVertical);
5456 }
5457 invalidate(true); // TODO invalidate cursor region only
5458 } else {
5459 stopAnimation();
5460 invalidate(false); // TODO invalidate cursor region only
5461 }
5462 }
5463
5464 private boolean updatePaint() {
5465 final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5466 if (duration > FADE_OUT_DURATION) return false;
5467
5468 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5469 final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
5470 final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
5471 ((int) (highlightColorAlpha * coef) << 24);
5472 mPaint.setColor(color);
5473 return true;
5474 }
5475
5476 private boolean updatePath() {
5477 final Layout layout = mTextView.getLayout();
5478 if (layout == null) return false;
5479
5480 // Update in case text is edited while the animation is run
5481 final int length = mTextView.getText().length();
5482 int start = Math.min(length, mStart);
5483 int end = Math.min(length, mEnd);
5484
5485 mPath.reset();
5486 layout.getSelectionPath(start, end, mPath);
5487 return true;
5488 }
5489
5490 private void invalidate(boolean delayed) {
5491 if (mTextView.getLayout() == null) return;
5492
5493 if (mTempRectF == null) mTempRectF = new RectF();
5494 mPath.computeBounds(mTempRectF, false);
5495
5496 int left = mTextView.getCompoundPaddingLeft();
5497 int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
5498
5499 if (delayed) {
5500 mTextView.postInvalidateOnAnimation(
5501 left + (int) mTempRectF.left, top + (int) mTempRectF.top,
5502 left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
5503 } else {
5504 mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
5505 (int) mTempRectF.right, (int) mTempRectF.bottom);
5506 }
5507 }
5508
5509 private void stopAnimation() {
5510 Editor.this.mCorrectionHighlighter = null;
5511 }
5512 }
5513
5514 private static class ErrorPopup extends PopupWindow {
5515 private boolean mAbove = false;
5516 private final TextView mView;
5517 private int mPopupInlineErrorBackgroundId = 0;
5518 private int mPopupInlineErrorAboveBackgroundId = 0;
5519
5520 ErrorPopup(TextView v, int width, int height) {
5521 super(v, width, height);
5522 mView = v;
5523 // Make sure the TextView has a background set as it will be used the first time it is
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -08005524 // shown and positioned. Initialized with below background, which should have
Gilles Debunned88876a2012-03-16 17:34:04 -07005525 // dimensions identical to the above version for this to work (and is more likely).
5526 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5527 com.android.internal.R.styleable.Theme_errorMessageBackground);
5528 mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
5529 }
5530
5531 void fixDirection(boolean above) {
5532 mAbove = above;
5533
5534 if (above) {
5535 mPopupInlineErrorAboveBackgroundId =
5536 getResourceId(mPopupInlineErrorAboveBackgroundId,
5537 com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
5538 } else {
5539 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5540 com.android.internal.R.styleable.Theme_errorMessageBackground);
5541 }
5542
5543 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
5544 mPopupInlineErrorBackgroundId);
5545 }
5546
5547 private int getResourceId(int currentId, int index) {
5548 if (currentId == 0) {
5549 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
5550 R.styleable.Theme);
5551 currentId = styledAttributes.getResourceId(index, 0);
5552 styledAttributes.recycle();
5553 }
5554 return currentId;
5555 }
5556
5557 @Override
5558 public void update(int x, int y, int w, int h, boolean force) {
5559 super.update(x, y, w, h, force);
5560
5561 boolean above = isAboveAnchor();
5562 if (above != mAbove) {
5563 fixDirection(above);
5564 }
5565 }
5566 }
5567
5568 static class InputContentType {
5569 int imeOptions = EditorInfo.IME_NULL;
5570 String privateImeOptions;
5571 CharSequence imeActionLabel;
5572 int imeActionId;
5573 Bundle extras;
5574 OnEditorActionListener onEditorActionListener;
5575 boolean enterDown;
Yohei Yukawad469f212016-01-21 12:38:09 -08005576 LocaleList imeHintLocales;
Gilles Debunned88876a2012-03-16 17:34:04 -07005577 }
5578
5579 static class InputMethodState {
Gilles Debunnec62589c2012-04-12 14:50:23 -07005580 ExtractedTextRequest mExtractedTextRequest;
5581 final ExtractedText mExtractedText = new ExtractedText();
Gilles Debunned88876a2012-03-16 17:34:04 -07005582 int mBatchEditNesting;
5583 boolean mCursorChanged;
5584 boolean mSelectionModeChanged;
5585 boolean mContentChanged;
5586 int mChangedStart, mChangedEnd, mChangedDelta;
5587 }
Satoshi Kataoka0e3849a2012-12-13 14:37:19 +09005588
James Cookf59152c2015-02-26 18:03:58 -08005589 /**
James Cook471559f2015-02-27 10:31:20 -08005590 * @return True iff (start, end) is a valid range within the text.
5591 */
5592 private static boolean isValidRange(CharSequence text, int start, int end) {
5593 return 0 <= start && start <= end && end <= text.length();
5594 }
5595
Seigo Nonakaa60160b2015-08-19 12:38:35 -07005596 @VisibleForTesting
5597 public SuggestionsPopupWindow getSuggestionsPopupWindowForTesting() {
5598 return mSuggestionsPopupWindow;
5599 }
5600
James Cook471559f2015-02-27 10:31:20 -08005601 /**
James Cookf59152c2015-02-26 18:03:58 -08005602 * An InputFilter that monitors text input to maintain undo history. It does not modify the
5603 * text being typed (and hence always returns null from the filter() method).
5604 */
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005605 public static class UndoInputFilter implements InputFilter {
James Cookf59152c2015-02-26 18:03:58 -08005606 private final Editor mEditor;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005607
James Cook48e0fac2015-02-25 15:44:51 -08005608 // Whether the current filter pass is directly caused by an end-user text edit.
5609 private boolean mIsUserEdit;
5610
James Cookd2026682015-03-03 14:40:14 -08005611 // Whether the text field is handling an IME composition. Must be parceled in case the user
5612 // rotates the screen during composition.
5613 private boolean mHasComposition;
James Cook48e0fac2015-02-25 15:44:51 -08005614
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005615 // Whether to merge events into one operation.
5616 private boolean mForceMerge;
5617
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005618 public UndoInputFilter(Editor editor) {
5619 mEditor = editor;
5620 }
5621
James Cookd2026682015-03-03 14:40:14 -08005622 public void saveInstanceState(Parcel parcel) {
5623 parcel.writeInt(mIsUserEdit ? 1 : 0);
5624 parcel.writeInt(mHasComposition ? 1 : 0);
5625 }
5626
5627 public void restoreInstanceState(Parcel parcel) {
5628 mIsUserEdit = parcel.readInt() != 0;
5629 mHasComposition = parcel.readInt() != 0;
5630 }
5631
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005632 public void setForceMerge(boolean forceMerge) {
5633 mForceMerge = forceMerge;
5634 }
5635
James Cook48e0fac2015-02-25 15:44:51 -08005636 /**
5637 * Signals that a user-triggered edit is starting.
5638 */
5639 public void beginBatchEdit() {
5640 if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
5641 mIsUserEdit = true;
James Cook48e0fac2015-02-25 15:44:51 -08005642 }
5643
5644 public void endBatchEdit() {
5645 if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
5646 mIsUserEdit = false;
5647 }
5648
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005649 @Override
5650 public CharSequence filter(CharSequence source, int start, int end,
5651 Spanned dest, int dstart, int dend) {
5652 if (DEBUG_UNDO) {
James Cook471559f2015-02-27 10:31:20 -08005653 Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " +
5654 "dest=" + dest + " (" + dstart + "-" + dend + ")");
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005655 }
James Cookf1dad1e2015-02-27 11:00:01 -08005656
James Cook48e0fac2015-02-25 15:44:51 -08005657 // Check to see if this edit should be tracked for undo.
5658 if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
James Cookf1dad1e2015-02-27 11:00:01 -08005659 return null;
5660 }
5661
James Cookd2026682015-03-03 14:40:14 -08005662 // Check for and handle IME composition edits.
5663 if (handleCompositionEdit(source, start, end, dstart)) {
5664 return null;
5665 }
5666
5667 // Handle keyboard edits.
5668 handleKeyboardEdit(source, start, end, dest, dstart, dend);
5669 return null;
5670 }
5671
5672 /**
5673 * Returns true iff the edit was handled, either because it should be ignored or because
5674 * this function created an undo operation for it.
5675 */
5676 private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) {
5677 // Ignore edits while the user is composing.
5678 if (isComposition(source)) {
5679 mHasComposition = true;
5680 return true;
5681 }
5682 final boolean hadComposition = mHasComposition;
5683 mHasComposition = false;
5684
5685 // Check for the transition out of the composing state.
5686 if (hadComposition) {
5687 // If there was no text the user canceled composition. Ignore the edit.
5688 if (start == end) {
5689 return true;
5690 }
5691
5692 // Otherwise the user inserted the composition.
5693 String newText = TextUtils.substring(source, start, end);
James Cook22054252015-03-25 14:04:01 -07005694 EditOperation edit = new EditOperation(mEditor, "", dstart, newText);
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005695 recordEdit(edit, mForceMerge);
James Cookd2026682015-03-03 14:40:14 -08005696 return true;
5697 }
5698
5699 // This was neither a composition event nor a transition out of composing.
5700 return false;
5701 }
5702
5703 private void handleKeyboardEdit(CharSequence source, int start, int end,
5704 Spanned dest, int dstart, int dend) {
James Cook48e0fac2015-02-25 15:44:51 -08005705 // An application may install a TextWatcher to provide additional modifications after
5706 // the initial input filters run (e.g. a credit card formatter that adds spaces to a
5707 // string). This results in multiple filter() calls for what the user considers to be
5708 // a single operation. Always undo the whole set of changes in one step.
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005709 final boolean forceMerge = mForceMerge || isInTextWatcher();
James Cook471559f2015-02-27 10:31:20 -08005710
5711 // Build a new operation with all the information from this edit.
James Cookd2026682015-03-03 14:40:14 -08005712 String newText = TextUtils.substring(source, start, end);
5713 String oldText = TextUtils.substring(dest, dstart, dend);
James Cook22054252015-03-25 14:04:01 -07005714 EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText);
5715 recordEdit(edit, forceMerge);
James Cookd2026682015-03-03 14:40:14 -08005716 }
James Cook471559f2015-02-27 10:31:20 -08005717
James Cook22054252015-03-25 14:04:01 -07005718 /**
5719 * Fetches the last undo operation and checks to see if a new edit should be merged into it.
5720 * If forceMerge is true then the new edit is always merged.
5721 */
5722 private void recordEdit(EditOperation edit, boolean forceMerge) {
James Cook471559f2015-02-27 10:31:20 -08005723 // Fetch the last edit operation and attempt to merge in the new edit.
James Cook48e0fac2015-02-25 15:44:51 -08005724 final UndoManager um = mEditor.mUndoManager;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005725 um.beginUpdate("Edit text");
James Cook471559f2015-02-27 10:31:20 -08005726 EditOperation lastEdit = um.getLastOperation(
5727 EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
5728 if (lastEdit == null) {
5729 // Add this as the first edit.
5730 if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
5731 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook22054252015-03-25 14:04:01 -07005732 } else if (forceMerge) {
5733 // Forced merges take priority because they could be the result of a non-user-edit
5734 // change and this case should not create a new undo operation.
5735 if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
5736 lastEdit.forceMergeWith(edit);
James Cook48e0fac2015-02-25 15:44:51 -08005737 } else if (!mIsUserEdit) {
5738 // An application directly modified the Editable outside of a text edit. Treat this
5739 // as a new change and don't attempt to merge.
5740 if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
5741 um.commitState(mEditor.mUndoOwner);
5742 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook471559f2015-02-27 10:31:20 -08005743 } else if (lastEdit.mergeWith(edit)) {
5744 // Merge succeeded, nothing else to do.
5745 if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
James Cook3ac0bcb2015-02-26 10:53:41 -08005746 } else {
James Cook471559f2015-02-27 10:31:20 -08005747 // Could not merge with the last edit, so commit the last edit and add this edit.
5748 if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
5749 um.commitState(mEditor.mUndoOwner);
5750 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook3ac0bcb2015-02-26 10:53:41 -08005751 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005752 um.endUpdate();
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005753 }
James Cook48e0fac2015-02-25 15:44:51 -08005754
5755 private boolean canUndoEdit(CharSequence source, int start, int end,
5756 Spanned dest, int dstart, int dend) {
5757 if (!mEditor.mAllowUndo) {
5758 if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
5759 return false;
5760 }
5761
5762 if (mEditor.mUndoManager.isInUndo()) {
5763 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
5764 return false;
5765 }
5766
5767 // Text filters run before input operations are applied. However, some input operations
5768 // are invalid and will throw exceptions when applied. This is common in tests. Don't
5769 // attempt to undo invalid operations.
5770 if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
5771 if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
5772 return false;
5773 }
5774
5775 // Earlier filters can rewrite input to be a no-op, for example due to a length limit
5776 // on an input field. Skip no-op changes.
5777 if (start == end && dstart == dend) {
5778 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
5779 return false;
5780 }
5781
5782 return true;
5783 }
James Cookd2026682015-03-03 14:40:14 -08005784
5785 private boolean isComposition(CharSequence source) {
5786 if (!(source instanceof Spannable)) {
5787 return false;
5788 }
5789 // This is a composition edit if the source has a non-zero-length composing span.
5790 Spannable text = (Spannable) source;
5791 int composeBegin = EditableInputConnection.getComposingSpanStart(text);
5792 int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
5793 return composeBegin < composeEnd;
5794 }
5795
5796 private boolean isInTextWatcher() {
5797 CharSequence text = mEditor.mTextView.getText();
5798 return (text instanceof SpannableStringBuilder)
5799 && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
5800 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005801 }
5802
James Cookf59152c2015-02-26 18:03:58 -08005803 /**
5804 * An operation to undo a single "edit" to a text view.
5805 */
James Cook471559f2015-02-27 10:31:20 -08005806 public static class EditOperation extends UndoOperation<Editor> {
5807 private static final int TYPE_INSERT = 0;
5808 private static final int TYPE_DELETE = 1;
5809 private static final int TYPE_REPLACE = 2;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005810
James Cook471559f2015-02-27 10:31:20 -08005811 private int mType;
5812 private String mOldText;
5813 private int mOldTextStart;
5814 private String mNewText;
5815 private int mNewTextStart;
5816
5817 private int mOldCursorPos;
5818 private int mNewCursorPos;
5819
5820 /**
James Cookd2026682015-03-03 14:40:14 -08005821 * Constructs an edit operation from a text input operation on editor that replaces the
James Cook22054252015-03-25 14:04:01 -07005822 * oldText starting at dstart with newText.
James Cook471559f2015-02-27 10:31:20 -08005823 */
James Cook22054252015-03-25 14:04:01 -07005824 public EditOperation(Editor editor, String oldText, int dstart, String newText) {
James Cook471559f2015-02-27 10:31:20 -08005825 super(editor.mUndoOwner);
James Cookd2026682015-03-03 14:40:14 -08005826 mOldText = oldText;
5827 mNewText = newText;
James Cook471559f2015-02-27 10:31:20 -08005828
5829 // Determine the type of the edit and store where it occurred. Avoid storing
5830 // irrevelant data (e.g. mNewTextStart for a delete) because that makes the
5831 // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being
5832 // outside the bounds of the final text).
5833 if (mNewText.length() > 0 && mOldText.length() == 0) {
5834 mType = TYPE_INSERT;
5835 mNewTextStart = dstart;
5836 } else if (mNewText.length() == 0 && mOldText.length() > 0) {
5837 mType = TYPE_DELETE;
5838 mOldTextStart = dstart;
5839 } else {
5840 mType = TYPE_REPLACE;
5841 mOldTextStart = mNewTextStart = dstart;
5842 }
5843
5844 // Store cursor data.
5845 mOldCursorPos = editor.mTextView.getSelectionStart();
James Cookd2026682015-03-03 14:40:14 -08005846 mNewCursorPos = dstart + mNewText.length();
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005847 }
5848
James Cook471559f2015-02-27 10:31:20 -08005849 public EditOperation(Parcel src, ClassLoader loader) {
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005850 super(src, loader);
James Cook471559f2015-02-27 10:31:20 -08005851 mType = src.readInt();
5852 mOldText = src.readString();
5853 mOldTextStart = src.readInt();
5854 mNewText = src.readString();
5855 mNewTextStart = src.readInt();
5856 mOldCursorPos = src.readInt();
5857 mNewCursorPos = src.readInt();
5858 }
5859
5860 @Override
5861 public void writeToParcel(Parcel dest, int flags) {
5862 dest.writeInt(mType);
5863 dest.writeString(mOldText);
5864 dest.writeInt(mOldTextStart);
5865 dest.writeString(mNewText);
5866 dest.writeInt(mNewTextStart);
5867 dest.writeInt(mOldCursorPos);
5868 dest.writeInt(mNewCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005869 }
5870
James Cook48e0fac2015-02-25 15:44:51 -08005871 private int getNewTextEnd() {
5872 return mNewTextStart + mNewText.length();
5873 }
5874
5875 private int getOldTextEnd() {
5876 return mOldTextStart + mOldText.length();
5877 }
5878
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005879 @Override
5880 public void commit() {
5881 }
5882
5883 @Override
5884 public void undo() {
James Cook471559f2015-02-27 10:31:20 -08005885 if (DEBUG_UNDO) Log.d(TAG, "undo");
5886 // Remove the new text and insert the old.
James Cook48e0fac2015-02-25 15:44:51 -08005887 Editor editor = getOwnerData();
5888 Editable text = (Editable) editor.mTextView.getText();
5889 modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5890 mOldCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005891 }
5892
5893 @Override
5894 public void redo() {
James Cook471559f2015-02-27 10:31:20 -08005895 if (DEBUG_UNDO) Log.d(TAG, "redo");
5896 // Remove the old text and insert the new.
James Cook48e0fac2015-02-25 15:44:51 -08005897 Editor editor = getOwnerData();
5898 Editable text = (Editable) editor.mTextView.getText();
5899 modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart,
5900 mNewCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005901 }
5902
James Cook471559f2015-02-27 10:31:20 -08005903 /**
5904 * Attempts to merge this existing operation with a new edit.
5905 * @param edit The new edit operation.
5906 * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
5907 * object unchanged.
5908 */
5909 private boolean mergeWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005910 if (DEBUG_UNDO) {
5911 Log.d(TAG, "mergeWith old " + this);
5912 Log.d(TAG, "mergeWith new " + edit);
5913 }
James Cook471559f2015-02-27 10:31:20 -08005914 switch (mType) {
5915 case TYPE_INSERT:
5916 return mergeInsertWith(edit);
5917 case TYPE_DELETE:
5918 return mergeDeleteWith(edit);
5919 case TYPE_REPLACE:
5920 return mergeReplaceWith(edit);
5921 default:
5922 return false;
5923 }
5924 }
5925
5926 private boolean mergeInsertWith(EditOperation edit) {
James Cook471559f2015-02-27 10:31:20 -08005927 // Only merge continuous insertions.
5928 if (edit.mType != TYPE_INSERT) {
5929 return false;
5930 }
5931 // Only merge insertions that are contiguous.
5932 if (getNewTextEnd() != edit.mNewTextStart) {
5933 return false;
5934 }
5935 mNewText += edit.mNewText;
5936 mNewCursorPos = edit.mNewCursorPos;
5937 return true;
5938 }
5939
5940 // TODO: Support forward delete.
5941 private boolean mergeDeleteWith(EditOperation edit) {
James Cook471559f2015-02-27 10:31:20 -08005942 // Only merge continuous deletes.
5943 if (edit.mType != TYPE_DELETE) {
5944 return false;
5945 }
5946 // Only merge deletions that are contiguous.
5947 if (mOldTextStart != edit.getOldTextEnd()) {
5948 return false;
5949 }
5950 mOldTextStart = edit.mOldTextStart;
5951 mOldText = edit.mOldText + mOldText;
5952 mNewCursorPos = edit.mNewCursorPos;
5953 return true;
5954 }
5955
5956 private boolean mergeReplaceWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005957 // Replacements can merge only with adjacent inserts.
5958 if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) {
James Cook471559f2015-02-27 10:31:20 -08005959 return false;
5960 }
5961 mOldText += edit.mOldText;
5962 mNewText += edit.mNewText;
5963 mNewCursorPos = edit.mNewCursorPos;
5964 return true;
5965 }
5966
James Cook48e0fac2015-02-25 15:44:51 -08005967 /**
5968 * Forcibly creates a single merged edit operation by simulating the entire text
5969 * contents being replaced.
5970 */
James Cook22054252015-03-25 14:04:01 -07005971 public void forceMergeWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005972 if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
James Cookf59152c2015-02-26 18:03:58 -08005973 Editor editor = getOwnerData();
James Cook48e0fac2015-02-25 15:44:51 -08005974
5975 // Copy the text of the current field.
5976 // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
5977 // but would require two parallel implementations of modifyText() because Editable and
5978 // StringBuilder do not share an interface for replace/delete/insert.
5979 Editable editable = (Editable) editor.mTextView.getText();
5980 Editable originalText = new SpannableStringBuilder(editable.toString());
5981
5982 // Roll back the last operation.
5983 modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5984 mOldCursorPos);
5985
5986 // Clone the text again and apply the new operation.
5987 Editable finalText = new SpannableStringBuilder(editable.toString());
5988 modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText,
5989 edit.mNewTextStart, edit.mNewCursorPos);
5990
5991 // Convert this operation into a non-mergeable replacement of the entire string.
5992 mType = TYPE_REPLACE;
5993 mNewText = finalText.toString();
5994 mNewTextStart = 0;
5995 mOldText = originalText.toString();
5996 mOldTextStart = 0;
5997 mNewCursorPos = edit.mNewCursorPos;
5998 // mOldCursorPos is unchanged.
5999 }
6000
6001 private static void modifyText(Editable text, int deleteFrom, int deleteTo,
6002 CharSequence newText, int newTextInsertAt, int newCursorPos) {
James Cook471559f2015-02-27 10:31:20 -08006003 // Apply the edit if it is still valid.
6004 if (isValidRange(text, deleteFrom, deleteTo) &&
6005 newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
6006 if (deleteFrom != deleteTo) {
6007 text.delete(deleteFrom, deleteTo);
6008 }
6009 if (newText.length() != 0) {
6010 text.insert(newTextInsertAt, newText);
6011 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006012 }
James Cook900185d2015-03-10 09:48:11 -07006013 // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
6014 // don't explicitly set it and rely on SpannableStringBuilder to position it.
James Cook471559f2015-02-27 10:31:20 -08006015 // TODO: Select all the text that was undone.
James Cook900185d2015-03-10 09:48:11 -07006016 if (0 <= newCursorPos && newCursorPos <= text.length()) {
James Cook471559f2015-02-27 10:31:20 -08006017 Selection.setSelection(text, newCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006018 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006019 }
6020
James Cook48e0fac2015-02-25 15:44:51 -08006021 private String getTypeString() {
6022 switch (mType) {
6023 case TYPE_INSERT:
6024 return "insert";
6025 case TYPE_DELETE:
6026 return "delete";
6027 case TYPE_REPLACE:
6028 return "replace";
6029 default:
6030 return "";
6031 }
6032 }
6033
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006034 @Override
James Cook471559f2015-02-27 10:31:20 -08006035 public String toString() {
James Cook48e0fac2015-02-25 15:44:51 -08006036 return "[mType=" + getTypeString() + ", " +
James Cook471559f2015-02-27 10:31:20 -08006037 "mOldText=" + mOldText + ", " +
6038 "mOldTextStart=" + mOldTextStart + ", " +
6039 "mNewText=" + mNewText + ", " +
6040 "mNewTextStart=" + mNewTextStart + ", " +
6041 "mOldCursorPos=" + mOldCursorPos + ", " +
6042 "mNewCursorPos=" + mNewCursorPos + "]";
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006043 }
6044
James Cook471559f2015-02-27 10:31:20 -08006045 public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR
6046 = new Parcelable.ClassLoaderCreator<EditOperation>() {
James Cookf59152c2015-02-26 18:03:58 -08006047 @Override
James Cook471559f2015-02-27 10:31:20 -08006048 public EditOperation createFromParcel(Parcel in) {
6049 return new EditOperation(in, null);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006050 }
6051
James Cookf59152c2015-02-26 18:03:58 -08006052 @Override
James Cook471559f2015-02-27 10:31:20 -08006053 public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
6054 return new EditOperation(in, loader);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006055 }
6056
James Cookf59152c2015-02-26 18:03:58 -08006057 @Override
James Cook471559f2015-02-27 10:31:20 -08006058 public EditOperation[] newArray(int size) {
6059 return new EditOperation[size];
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07006060 }
6061 };
6062 }
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07006063
6064 /**
6065 * A helper for enabling and handling "PROCESS_TEXT" menu actions.
6066 * These allow external applications to plug into currently selected text.
6067 */
6068 static final class ProcessTextIntentActionsHandler {
6069
6070 private final Editor mEditor;
6071 private final TextView mTextView;
6072 private final PackageManager mPackageManager;
6073 private final SparseArray<Intent> mAccessibilityIntents = new SparseArray<Intent>();
6074 private final SparseArray<AccessibilityNodeInfo.AccessibilityAction> mAccessibilityActions
6075 = new SparseArray<AccessibilityNodeInfo.AccessibilityAction>();
6076
6077 private ProcessTextIntentActionsHandler(Editor editor) {
6078 mEditor = Preconditions.checkNotNull(editor);
6079 mTextView = Preconditions.checkNotNull(mEditor.mTextView);
6080 mPackageManager = Preconditions.checkNotNull(
6081 mTextView.getContext().getPackageManager());
6082 }
6083
6084 /**
6085 * Adds "PROCESS_TEXT" menu items to the specified menu.
6086 */
6087 public void onInitializeMenu(Menu menu) {
6088 int i = 0;
6089 for (ResolveInfo resolveInfo : getSupportedActivities()) {
6090 menu.add(Menu.NONE, Menu.NONE,
6091 Editor.MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i++,
6092 getLabel(resolveInfo))
6093 .setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
6094 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
6095 }
6096 }
6097
6098 /**
6099 * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6100 * menu item.
6101 *
6102 * @return True if the action was performed, false otherwise.
6103 */
6104 public boolean performMenuItemAction(MenuItem item) {
6105 return fireIntent(item.getIntent());
6106 }
6107
6108 /**
6109 * Initializes and caches "PROCESS_TEXT" accessibility actions.
6110 */
6111 public void initializeAccessibilityActions() {
6112 mAccessibilityIntents.clear();
6113 mAccessibilityActions.clear();
6114 int i = 0;
6115 for (ResolveInfo resolveInfo : getSupportedActivities()) {
6116 int actionId = TextView.ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID + i++;
6117 mAccessibilityActions.put(
6118 actionId,
6119 new AccessibilityNodeInfo.AccessibilityAction(
6120 actionId, getLabel(resolveInfo)));
6121 mAccessibilityIntents.put(
6122 actionId, createProcessTextIntentForResolveInfo(resolveInfo));
6123 }
6124 }
6125
6126 /**
6127 * Adds "PROCESS_TEXT" accessibility actions to the specified accessibility node info.
6128 * NOTE: This needs a prior call to {@link #initializeAccessibilityActions()} to make the
6129 * latest accessibility actions available for this call.
6130 */
6131 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo) {
6132 for (int i = 0; i < mAccessibilityActions.size(); i++) {
6133 nodeInfo.addAction(mAccessibilityActions.valueAt(i));
6134 }
6135 }
6136
6137 /**
6138 * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6139 * accessibility action id.
6140 *
6141 * @return True if the action was performed, false otherwise.
6142 */
6143 public boolean performAccessibilityAction(int actionId) {
6144 return fireIntent(mAccessibilityIntents.get(actionId));
6145 }
6146
6147 private boolean fireIntent(Intent intent) {
6148 if (intent != null && Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) {
6149 intent.putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText());
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08006150 mEditor.mPreserveSelection = true;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07006151 mTextView.startActivityForResult(intent, TextView.PROCESS_TEXT_REQUEST_CODE);
6152 return true;
6153 }
6154 return false;
6155 }
6156
6157 private List<ResolveInfo> getSupportedActivities() {
6158 PackageManager packageManager = mTextView.getContext().getPackageManager();
6159 return packageManager.queryIntentActivities(createProcessTextIntent(), 0);
6160 }
6161
6162 private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
6163 return createProcessTextIntent()
6164 .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
6165 .setClassName(info.activityInfo.packageName, info.activityInfo.name);
6166 }
6167
6168 private Intent createProcessTextIntent() {
6169 return new Intent()
6170 .setAction(Intent.ACTION_PROCESS_TEXT)
6171 .setType("text/plain");
6172 }
6173
6174 private CharSequence getLabel(ResolveInfo resolveInfo) {
6175 return resolveInfo.loadLabel(mPackageManager);
6176 }
6177 }
Gilles Debunned88876a2012-03-16 17:34:04 -07006178}