blob: 3b6ba3a758a1b20e9c35a1ceeeb16f8cbf5e4424 [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;
Yoshiki Iguchiee147722015-04-14 00:12:44 +090021import android.annotation.Nullable;
Luca Zanolin1b15ba52013-02-20 14:31:37 +000022import android.app.PendingIntent;
23import android.app.PendingIntent.CanceledException;
Gilles Debunned88876a2012-03-16 17:34:04 -070024import android.content.ClipData;
25import android.content.ClipData.Item;
26import android.content.Context;
27import android.content.Intent;
Raph Levien26d443a2015-03-30 14:18:32 -070028import android.content.UndoManager;
29import android.content.UndoOperation;
30import android.content.UndoOwner;
Gilles Debunned88876a2012-03-16 17:34:04 -070031import android.content.pm.PackageManager;
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +000032import android.content.pm.ResolveInfo;
Gilles Debunned88876a2012-03-16 17:34:04 -070033import android.content.res.TypedArray;
34import android.graphics.Canvas;
35import android.graphics.Color;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +090036import android.graphics.Matrix;
Gilles Debunned88876a2012-03-16 17:34:04 -070037import android.graphics.Paint;
38import android.graphics.Path;
39import android.graphics.Rect;
40import android.graphics.RectF;
Seigo Nonaka3ed1b392016-01-19 13:54:59 +090041import android.graphics.drawable.ColorDrawable;
Gilles Debunned88876a2012-03-16 17:34:04 -070042import android.graphics.drawable.Drawable;
Gilles Debunned88876a2012-03-16 17:34:04 -070043import android.os.Bundle;
Raph Levien26d443a2015-03-30 14:18:32 -070044import android.os.Parcel;
45import android.os.Parcelable;
James Cookf59152c2015-02-26 18:03:58 -080046import android.os.ParcelableParcel;
Gilles Debunned88876a2012-03-16 17:34:04 -070047import android.os.SystemClock;
48import android.provider.Settings;
49import android.text.DynamicLayout;
50import android.text.Editable;
Raph Levien26d443a2015-03-30 14:18:32 -070051import android.text.InputFilter;
Gilles Debunned88876a2012-03-16 17:34:04 -070052import android.text.InputType;
53import android.text.Layout;
54import android.text.ParcelableSpan;
55import android.text.Selection;
56import android.text.SpanWatcher;
57import android.text.Spannable;
58import android.text.SpannableStringBuilder;
59import android.text.Spanned;
60import android.text.StaticLayout;
61import android.text.TextUtils;
Gilles Debunned88876a2012-03-16 17:34:04 -070062import android.text.method.KeyListener;
63import android.text.method.MetaKeyKeyListener;
64import android.text.method.MovementMethod;
Gilles Debunned88876a2012-03-16 17:34:04 -070065import android.text.method.WordIterator;
66import android.text.style.EasyEditSpan;
67import android.text.style.SuggestionRangeSpan;
68import android.text.style.SuggestionSpan;
69import android.text.style.TextAppearanceSpan;
70import android.text.style.URLSpan;
71import android.util.DisplayMetrics;
Yohei Yukawad469f212016-01-21 12:38:09 -080072import android.util.LocaleList;
Gilles Debunned88876a2012-03-16 17:34:04 -070073import android.util.Log;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -070074import android.util.SparseArray;
Gilles Debunned88876a2012-03-16 17:34:04 -070075import android.view.ActionMode;
76import android.view.ActionMode.Callback;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +090077import android.view.ContextMenu;
Chris Craikf6829a02015-03-10 10:28:59 -070078import android.view.DisplayListCanvas;
Gilles Debunned88876a2012-03-16 17:34:04 -070079import android.view.DragEvent;
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -080080import android.view.DropPermissions;
Gilles Debunned88876a2012-03-16 17:34:04 -070081import android.view.Gravity;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -080082import android.view.InputDevice;
Gilles Debunned88876a2012-03-16 17:34:04 -070083import android.view.LayoutInflater;
84import android.view.Menu;
85import android.view.MenuItem;
86import android.view.MotionEvent;
Chris Craikf6829a02015-03-10 10:28:59 -070087import android.view.RenderNode;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +090088import android.view.SubMenu;
Gilles Debunned88876a2012-03-16 17:34:04 -070089import android.view.View;
Gilles Debunned88876a2012-03-16 17:34:04 -070090import android.view.View.DragShadowBuilder;
91import android.view.View.OnClickListener;
Adam Powell057a5852012-05-11 10:28:38 -070092import android.view.ViewConfiguration;
93import android.view.ViewGroup;
Gilles Debunned88876a2012-03-16 17:34:04 -070094import android.view.ViewGroup.LayoutParams;
95import android.view.ViewParent;
96import android.view.ViewTreeObserver;
97import android.view.WindowManager;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -070098import android.view.accessibility.AccessibilityNodeInfo;
Gilles Debunned88876a2012-03-16 17:34:04 -070099import android.view.inputmethod.CorrectionInfo;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900100import android.view.inputmethod.CursorAnchorInfo;
Gilles Debunned88876a2012-03-16 17:34:04 -0700101import android.view.inputmethod.EditorInfo;
102import android.view.inputmethod.ExtractedText;
103import android.view.inputmethod.ExtractedTextRequest;
104import android.view.inputmethod.InputConnection;
105import android.view.inputmethod.InputMethodManager;
106import android.widget.AdapterView.OnItemClickListener;
107import android.widget.TextView.Drawables;
108import android.widget.TextView.OnEditorActionListener;
109
Seigo Nonakaa60160b2015-08-19 12:38:35 -0700110import com.android.internal.annotations.VisibleForTesting;
Raph Levien26d443a2015-03-30 14:18:32 -0700111import com.android.internal.util.ArrayUtils;
112import com.android.internal.util.GrowingArrayUtils;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700113import com.android.internal.util.Preconditions;
Raph Levien26d443a2015-03-30 14:18:32 -0700114import com.android.internal.widget.EditableInputConnection;
115
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +0900116import java.lang.annotation.Retention;
117import java.lang.annotation.RetentionPolicy;
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +0100118import java.text.BreakIterator;
119import java.util.Arrays;
120import java.util.Comparator;
121import java.util.HashMap;
122import java.util.List;
123
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700124
Gilles Debunned88876a2012-03-16 17:34:04 -0700125/**
126 * Helper class used by TextView to handle editable text views.
127 *
128 * @hide
129 */
130public class Editor {
Adam Powell057a5852012-05-11 10:28:38 -0700131 private static final String TAG = "Editor";
James Cookf59152c2015-02-26 18:03:58 -0800132 private static final boolean DEBUG_UNDO = false;
Adam Powell057a5852012-05-11 10:28:38 -0700133
Gilles Debunned88876a2012-03-16 17:34:04 -0700134 static final int BLINK = 500;
135 private static final float[] TEMP_POSITION = new float[2];
136 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
Mady Mellorcc65c372015-06-17 09:25:19 -0700137 private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f;
Mady Mellore264ac32015-06-22 16:46:29 -0700138 private static final int UNSET_X_VALUE = -1;
Mady Mellora6a0f782015-07-10 16:43:32 -0700139 private static final int UNSET_LINE = -1;
James Cookf59152c2015-02-26 18:03:58 -0800140 // Tag used when the Editor maintains its own separate UndoManager.
141 private static final String UNDO_OWNER_TAG = "Editor";
Gilles Debunned88876a2012-03-16 17:34:04 -0700142
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900143 // Ordering constants used to place the Action Mode or context menu items in their menu.
144 private static final int MENU_ITEM_ORDER_UNDO = 1;
145 private static final int MENU_ITEM_ORDER_REDO = 2;
146 private static final int MENU_ITEM_ORDER_CUT = 3;
147 private static final int MENU_ITEM_ORDER_COPY = 4;
148 private static final int MENU_ITEM_ORDER_PASTE = 5;
149 private static final int MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 6;
150 private static final int MENU_ITEM_ORDER_SHARE = 7;
151 private static final int MENU_ITEM_ORDER_SELECT_ALL = 8;
152 private static final int MENU_ITEM_ORDER_REPLACE = 9;
Clara Bayarri3b69fd82015-06-03 21:52:02 +0100153 private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 10;
154
James Cookf59152c2015-02-26 18:03:58 -0800155 // Each Editor manages its own undo stack.
156 private final UndoManager mUndoManager = new UndoManager();
157 private UndoOwner mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
James Cook48e0fac2015-02-25 15:44:51 -0800158 final UndoInputFilter mUndoInputFilter = new UndoInputFilter(this);
James Cookf1dad1e2015-02-27 11:00:01 -0800159 boolean mAllowUndo = true;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -0700160
Gilles Debunned88876a2012-03-16 17:34:04 -0700161 // Cursor Controllers.
162 InsertionPointCursorController mInsertionPointCursorController;
163 SelectionModifierCursorController mSelectionModifierCursorController;
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100164 // Action mode used when text is selected or when actions on an insertion cursor are triggered.
165 ActionMode mTextActionMode;
Gilles Debunned88876a2012-03-16 17:34:04 -0700166 boolean mInsertionControllerEnabled;
167 boolean mSelectionControllerEnabled;
168
169 // Used to highlight a word when it is corrected by the IME
170 CorrectionHighlighter mCorrectionHighlighter;
171
172 InputContentType mInputContentType;
173 InputMethodState mInputMethodState;
174
Chris Craik956f3402015-04-27 16:41:00 -0700175 private static class TextRenderNode {
176 RenderNode renderNode;
John Reck7558aa72014-03-05 14:59:59 -0800177 boolean isDirty;
Chris Craik956f3402015-04-27 16:41:00 -0700178 public TextRenderNode(String name) {
John Reck7558aa72014-03-05 14:59:59 -0800179 isDirty = true;
Chris Craik956f3402015-04-27 16:41:00 -0700180 renderNode = RenderNode.create(name, null);
John Reck7558aa72014-03-05 14:59:59 -0800181 }
Chris Craik956f3402015-04-27 16:41:00 -0700182 boolean needsRecord() { return isDirty || !renderNode.isValid(); }
John Reck7558aa72014-03-05 14:59:59 -0800183 }
Chris Craik956f3402015-04-27 16:41:00 -0700184 TextRenderNode[] mTextRenderNodes;
Gilles Debunned88876a2012-03-16 17:34:04 -0700185
186 boolean mFrozenWithFocus;
187 boolean mSelectionMoved;
188 boolean mTouchFocusSelected;
189
190 KeyListener mKeyListener;
191 int mInputType = EditorInfo.TYPE_NULL;
192
193 boolean mDiscardNextActionUp;
194 boolean mIgnoreActionUpEvent;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900195 private boolean mIgnoreNextMouseActionUpOrDown;
Gilles Debunned88876a2012-03-16 17:34:04 -0700196
197 long mShowCursor;
198 Blink mBlink;
199
200 boolean mCursorVisible = true;
201 boolean mSelectAllOnFocus;
202 boolean mTextIsSelectable;
203
204 CharSequence mError;
205 boolean mErrorWasChanged;
206 ErrorPopup mErrorPopup;
Fabrice Di Meglio1957d282012-10-25 17:42:39 -0700207
Gilles Debunned88876a2012-03-16 17:34:04 -0700208 /**
209 * This flag is set if the TextView tries to display an error before it
210 * is attached to the window (so its position is still unknown).
211 * It causes the error to be shown later, when onAttachedToWindow()
212 * is called.
213 */
214 boolean mShowErrorAfterAttach;
215
216 boolean mInBatchEditControllers;
Gilles Debunne3473b2b2012-04-20 16:21:10 -0700217 boolean mShowSoftInputOnFocus = true;
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -0800218 private boolean mPreserveSelection;
Adam Powell057a5852012-05-11 10:28:38 -0700219 boolean mTemporaryDetach;
Gilles Debunned88876a2012-03-16 17:34:04 -0700220
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900221 boolean mIsBeingLongClicked;
222
Gilles Debunned88876a2012-03-16 17:34:04 -0700223 SuggestionsPopupWindow mSuggestionsPopupWindow;
224 SuggestionRangeSpan mSuggestionRangeSpan;
225 Runnable mShowSuggestionRunnable;
226
227 final Drawable[] mCursorDrawable = new Drawable[2];
228 int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split)
229
230 private Drawable mSelectHandleLeft;
231 private Drawable mSelectHandleRight;
232 private Drawable mSelectHandleCenter;
233
234 // Global listener that detects changes in the global position of the TextView
235 private PositionListener mPositionListener;
236
237 float mLastDownPositionX, mLastDownPositionY;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900238 private float mContextMenuAnchorX, mContextMenuAnchorY;
Gilles Debunned88876a2012-03-16 17:34:04 -0700239 Callback mCustomSelectionActionModeCallback;
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100240 Callback mCustomInsertionActionModeCallback;
Gilles Debunned88876a2012-03-16 17:34:04 -0700241
242 // Set when this TextView gained focus with some text selected. Will start selection mode.
243 boolean mCreatedWithASelection;
244
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +0900245 // Indicates the current tap state (first tap, double tap, or triple click).
246 private int mTapState = TAP_STATE_INITIAL;
247 private long mLastTouchUpTime = 0;
248 private static final int TAP_STATE_INITIAL = 0;
249 private static final int TAP_STATE_FIRST_TAP = 1;
250 private static final int TAP_STATE_DOUBLE_TAP = 2;
251 // Only for mouse input.
252 private static final int TAP_STATE_TRIPLE_CLICK = 3;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100253
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +0900254 // The button state as of the last time #onTouchEvent is called.
255 private int mLastButtonState;
256
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100257 private Runnable mInsertionActionModeRunnable;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100258
Jean Chalardbaf30942013-02-28 16:01:51 -0800259 // The span controller helps monitoring the changes to which the Editor needs to react:
260 // - EasyEditSpans, for which we have some UI to display on attach and on hide
261 // - SelectionSpans, for which we need to call updateSelection if an IME is attached
262 private SpanController mSpanController;
Gilles Debunned88876a2012-03-16 17:34:04 -0700263
264 WordIterator mWordIterator;
265 SpellChecker mSpellChecker;
266
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800267 // This word iterator is set with text and used to determine word boundaries
268 // when a user is selecting text.
269 private WordIterator mWordIteratorWithText;
270 // Indicate that the text in the word iterator needs to be updated.
271 private boolean mUpdateWordIteratorText;
272
Gilles Debunned88876a2012-03-16 17:34:04 -0700273 private Rect mTempRect;
274
275 private TextView mTextView;
276
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700277 final ProcessTextIntentActionsHandler mProcessTextIntentActionsHandler;
278
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900279 final CursorAnchorInfoNotifier mCursorAnchorInfoNotifier = new CursorAnchorInfoNotifier();
280
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100281 private final Runnable mShowFloatingToolbar = new Runnable() {
282 @Override
283 public void run() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100284 if (mTextActionMode != null) {
Abodunrinwa Toki9e211282015-06-05 02:46:57 +0100285 mTextActionMode.hide(0); // hide off.
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100286 }
287 }
288 };
289
Clara Bayarrib71dddd2015-06-04 23:17:30 +0100290 boolean mIsInsertionActionModeStartPending = false;
291
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +0900292 private final SuggestionHelper mSuggestionHelper = new SuggestionHelper();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +0900293
Gilles Debunned88876a2012-03-16 17:34:04 -0700294 Editor(TextView textView) {
295 mTextView = textView;
James Cookf59152c2015-02-26 18:03:58 -0800296 // Synchronize the filter list, which places the undo input filter at the end.
297 mTextView.setFilters(mTextView.getFilters());
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700298 mProcessTextIntentActionsHandler = new ProcessTextIntentActionsHandler(this);
James Cookf59152c2015-02-26 18:03:58 -0800299 }
300
301 ParcelableParcel saveInstanceState() {
James Cookd2026682015-03-03 14:40:14 -0800302 ParcelableParcel state = new ParcelableParcel(getClass().getClassLoader());
303 Parcel parcel = state.getParcel();
304 mUndoManager.saveInstanceState(parcel);
305 mUndoInputFilter.saveInstanceState(parcel);
306 return state;
James Cookf59152c2015-02-26 18:03:58 -0800307 }
308
309 void restoreInstanceState(ParcelableParcel state) {
James Cookd2026682015-03-03 14:40:14 -0800310 Parcel parcel = state.getParcel();
311 mUndoManager.restoreInstanceState(parcel, state.getClassLoader());
312 mUndoInputFilter.restoreInstanceState(parcel);
James Cookf59152c2015-02-26 18:03:58 -0800313 // Re-associate this object as the owner of undo state.
314 mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
315 }
316
James Cook48e0fac2015-02-25 15:44:51 -0800317 /**
318 * Forgets all undo and redo operations for this Editor.
319 */
320 void forgetUndoRedo() {
321 UndoOwner[] owners = { mUndoOwner };
322 mUndoManager.forgetUndos(owners, -1 /* all */);
323 mUndoManager.forgetRedos(owners, -1 /* all */);
324 }
325
James Cookf59152c2015-02-26 18:03:58 -0800326 boolean canUndo() {
327 UndoOwner[] owners = { mUndoOwner };
James Cookf1dad1e2015-02-27 11:00:01 -0800328 return mAllowUndo && mUndoManager.countUndos(owners) > 0;
James Cookf59152c2015-02-26 18:03:58 -0800329 }
330
331 boolean canRedo() {
332 UndoOwner[] owners = { mUndoOwner };
James Cookf1dad1e2015-02-27 11:00:01 -0800333 return mAllowUndo && mUndoManager.countRedos(owners) > 0;
James Cookf59152c2015-02-26 18:03:58 -0800334 }
335
336 void undo() {
James Cookf1dad1e2015-02-27 11:00:01 -0800337 if (!mAllowUndo) {
338 return;
339 }
James Cookf59152c2015-02-26 18:03:58 -0800340 UndoOwner[] owners = { mUndoOwner };
341 mUndoManager.undo(owners, 1); // Undo 1 action.
342 }
343
344 void redo() {
James Cookf1dad1e2015-02-27 11:00:01 -0800345 if (!mAllowUndo) {
346 return;
347 }
James Cookf59152c2015-02-26 18:03:58 -0800348 UndoOwner[] owners = { mUndoOwner };
349 mUndoManager.redo(owners, 1); // Redo 1 action.
Gilles Debunned88876a2012-03-16 17:34:04 -0700350 }
351
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100352 void replace() {
Keisuke Kuroyanagi713be062016-02-29 16:07:54 -0800353 if (mSuggestionsPopupWindow == null) {
354 mSuggestionsPopupWindow = new SuggestionsPopupWindow();
355 }
356 hideCursorAndSpanControllers();
357 mSuggestionsPopupWindow.show();
358
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100359 int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100360 Selection.setSelection((Spannable) mTextView.getText(), middle);
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100361 }
362
Gilles Debunned88876a2012-03-16 17:34:04 -0700363 void onAttachedToWindow() {
364 if (mShowErrorAfterAttach) {
365 showError();
366 mShowErrorAfterAttach = false;
367 }
Adam Powell057a5852012-05-11 10:28:38 -0700368 mTemporaryDetach = false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700369
370 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
371 // No need to create the controller.
372 // The get method will add the listener on controller creation.
373 if (mInsertionPointCursorController != null) {
374 observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
375 }
376 if (mSelectionModifierCursorController != null) {
Adam Powell057a5852012-05-11 10:28:38 -0700377 mSelectionModifierCursorController.resetTouchOffsets();
Gilles Debunned88876a2012-03-16 17:34:04 -0700378 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
379 }
380 updateSpellCheckSpans(0, mTextView.getText().length(),
381 true /* create the spell checker if needed */);
Adam Powell057a5852012-05-11 10:28:38 -0700382
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -0800383 if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
Adam Powell057a5852012-05-11 10:28:38 -0700384 // We had an active selection from before, start the selection mode.
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100385 startSelectionActionMode();
Adam Powell057a5852012-05-11 10:28:38 -0700386 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900387
388 getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true);
Mikael Gullstrand5b734f22013-07-09 14:41:28 +0200389 resumeBlink();
Gilles Debunned88876a2012-03-16 17:34:04 -0700390 }
391
392 void onDetachedFromWindow() {
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900393 getPositionListener().removeSubscriber(mCursorAnchorInfoNotifier);
394
Gilles Debunned88876a2012-03-16 17:34:04 -0700395 if (mError != null) {
396 hideError();
397 }
398
Mikael Gullstrand5b734f22013-07-09 14:41:28 +0200399 suspendBlink();
Gilles Debunned88876a2012-03-16 17:34:04 -0700400
401 if (mInsertionPointCursorController != null) {
402 mInsertionPointCursorController.onDetached();
403 }
404
405 if (mSelectionModifierCursorController != null) {
406 mSelectionModifierCursorController.onDetached();
407 }
408
409 if (mShowSuggestionRunnable != null) {
410 mTextView.removeCallbacks(mShowSuggestionRunnable);
411 }
412
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100413 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100414 if (mInsertionActionModeRunnable != null) {
415 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100416 }
417
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100418 mTextView.removeCallbacks(mShowFloatingToolbar);
419
Chris Craik003cc3d2015-10-16 10:24:55 -0700420 discardTextDisplayLists();
Gilles Debunned88876a2012-03-16 17:34:04 -0700421
422 if (mSpellChecker != null) {
423 mSpellChecker.closeSession();
424 // Forces the creation of a new SpellChecker next time this window is created.
425 // Will handle the cases where the settings has been changed in the meantime.
426 mSpellChecker = null;
427 }
428
Mady Mellora2861452015-06-25 08:40:27 -0700429 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -0800430 stopTextActionModeWithPreservingSelection();
Adam Powell057a5852012-05-11 10:28:38 -0700431 mTemporaryDetach = false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700432 }
433
Chris Craik003cc3d2015-10-16 10:24:55 -0700434 private void discardTextDisplayLists() {
Chris Craik956f3402015-04-27 16:41:00 -0700435 if (mTextRenderNodes != null) {
436 for (int i = 0; i < mTextRenderNodes.length; i++) {
437 RenderNode displayList = mTextRenderNodes[i] != null
438 ? mTextRenderNodes[i].renderNode : null;
John Reck7558aa72014-03-05 14:59:59 -0800439 if (displayList != null && displayList.isValid()) {
Chris Craik003cc3d2015-10-16 10:24:55 -0700440 displayList.discardDisplayList();
John Reck7558aa72014-03-05 14:59:59 -0800441 }
442 }
443 }
444 }
445
Gilles Debunned88876a2012-03-16 17:34:04 -0700446 private void showError() {
447 if (mTextView.getWindowToken() == null) {
448 mShowErrorAfterAttach = true;
449 return;
450 }
451
452 if (mErrorPopup == null) {
453 LayoutInflater inflater = LayoutInflater.from(mTextView.getContext());
454 final TextView err = (TextView) inflater.inflate(
455 com.android.internal.R.layout.textview_hint, null);
456
457 final float scale = mTextView.getResources().getDisplayMetrics().density;
458 mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f));
459 mErrorPopup.setFocusable(false);
460 // The user is entering text, so the input method is needed. We
461 // don't want the popup to be displayed on top of it.
462 mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
463 }
464
465 TextView tv = (TextView) mErrorPopup.getContentView();
466 chooseSize(mErrorPopup, mError, tv);
467 tv.setText(mError);
468
469 mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY());
470 mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor());
471 }
472
473 public void setError(CharSequence error, Drawable icon) {
474 mError = TextUtils.stringOrSpannedString(error);
475 mErrorWasChanged = true;
Romain Guyd1cc1872012-11-05 17:43:25 -0800476
Gilles Debunned88876a2012-03-16 17:34:04 -0700477 if (mError == null) {
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800478 setErrorIcon(null);
Gilles Debunned88876a2012-03-16 17:34:04 -0700479 if (mErrorPopup != null) {
480 if (mErrorPopup.isShowing()) {
481 mErrorPopup.dismiss();
482 }
483
484 mErrorPopup = null;
485 }
Daniel 2 Olofssonf4ecc552013-08-13 10:30:26 +0200486 mShowErrorAfterAttach = false;
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800487 } else {
Romain Guyd1cc1872012-11-05 17:43:25 -0800488 setErrorIcon(icon);
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800489 if (mTextView.isFocused()) {
490 showError();
491 }
Romain Guyd1cc1872012-11-05 17:43:25 -0800492 }
493 }
494
495 private void setErrorIcon(Drawable icon) {
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800496 Drawables dr = mTextView.mDrawables;
497 if (dr == null) {
Fabrice Di Megliof7a5cdf2013-03-15 15:36:51 -0700498 mTextView.mDrawables = dr = new Drawables(mTextView.getContext());
Gilles Debunned88876a2012-03-16 17:34:04 -0700499 }
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800500 dr.setErrorDrawable(icon, mTextView);
501
502 mTextView.resetResolvedDrawables();
503 mTextView.invalidate();
504 mTextView.requestLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -0700505 }
506
507 private void hideError() {
508 if (mErrorPopup != null) {
509 if (mErrorPopup.isShowing()) {
510 mErrorPopup.dismiss();
511 }
512 }
513
514 mShowErrorAfterAttach = false;
515 }
516
517 /**
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800518 * Returns the X offset to make the pointy top of the error point
Gilles Debunned88876a2012-03-16 17:34:04 -0700519 * at the middle of the error icon.
520 */
521 private int getErrorX() {
522 /*
523 * The "25" is the distance between the point and the right edge
524 * of the background
525 */
526 final float scale = mTextView.getResources().getDisplayMetrics().density;
527
528 final Drawables dr = mTextView.mDrawables;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800529
530 final int layoutDirection = mTextView.getLayoutDirection();
531 int errorX;
532 int offset;
533 switch (layoutDirection) {
534 default:
535 case View.LAYOUT_DIRECTION_LTR:
536 offset = - (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
537 errorX = mTextView.getWidth() - mErrorPopup.getWidth() -
538 mTextView.getPaddingRight() + offset;
539 break;
540 case View.LAYOUT_DIRECTION_RTL:
541 offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f);
542 errorX = mTextView.getPaddingLeft() + offset;
543 break;
544 }
545 return errorX;
Gilles Debunned88876a2012-03-16 17:34:04 -0700546 }
547
548 /**
549 * Returns the Y offset to make the pointy top of the error point
550 * at the bottom of the error icon.
551 */
552 private int getErrorY() {
553 /*
554 * Compound, not extended, because the icon is not clipped
555 * if the text height is smaller.
556 */
557 final int compoundPaddingTop = mTextView.getCompoundPaddingTop();
558 int vspace = mTextView.getBottom() - mTextView.getTop() -
559 mTextView.getCompoundPaddingBottom() - compoundPaddingTop;
560
561 final Drawables dr = mTextView.mDrawables;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800562
563 final int layoutDirection = mTextView.getLayoutDirection();
564 int height;
565 switch (layoutDirection) {
566 default:
567 case View.LAYOUT_DIRECTION_LTR:
568 height = (dr != null ? dr.mDrawableHeightRight : 0);
569 break;
570 case View.LAYOUT_DIRECTION_RTL:
571 height = (dr != null ? dr.mDrawableHeightLeft : 0);
572 break;
573 }
574
575 int icontop = compoundPaddingTop + (vspace - height) / 2;
Gilles Debunned88876a2012-03-16 17:34:04 -0700576
577 /*
578 * The "2" is the distance between the point and the top edge
579 * of the background.
580 */
581 final float scale = mTextView.getResources().getDisplayMetrics().density;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800582 return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f);
Gilles Debunned88876a2012-03-16 17:34:04 -0700583 }
584
585 void createInputContentTypeIfNeeded() {
586 if (mInputContentType == null) {
587 mInputContentType = new InputContentType();
588 }
589 }
590
591 void createInputMethodStateIfNeeded() {
592 if (mInputMethodState == null) {
593 mInputMethodState = new InputMethodState();
594 }
595 }
596
597 boolean isCursorVisible() {
598 // The default value is true, even when there is no associated Editor
599 return mCursorVisible && mTextView.isTextEditable();
600 }
601
602 void prepareCursorControllers() {
603 boolean windowSupportsHandles = false;
604
605 ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams();
606 if (params instanceof WindowManager.LayoutParams) {
607 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
608 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
609 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
610 }
611
612 boolean enabled = windowSupportsHandles && mTextView.getLayout() != null;
613 mInsertionControllerEnabled = enabled && isCursorVisible();
614 mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected();
615
616 if (!mInsertionControllerEnabled) {
617 hideInsertionPointCursorController();
618 if (mInsertionPointCursorController != null) {
619 mInsertionPointCursorController.onDetached();
620 mInsertionPointCursorController = null;
621 }
622 }
623
624 if (!mSelectionControllerEnabled) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100625 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -0700626 if (mSelectionModifierCursorController != null) {
627 mSelectionModifierCursorController.onDetached();
628 mSelectionModifierCursorController = null;
629 }
630 }
631 }
632
Seigo Nonakabb6a62c2015-03-31 21:59:30 +0900633 void hideInsertionPointCursorController() {
Gilles Debunned88876a2012-03-16 17:34:04 -0700634 if (mInsertionPointCursorController != null) {
635 mInsertionPointCursorController.hide();
636 }
637 }
638
639 /**
Mady Mellora2861452015-06-25 08:40:27 -0700640 * Hides the insertion and span controllers.
Gilles Debunned88876a2012-03-16 17:34:04 -0700641 */
Mady Mellora2861452015-06-25 08:40:27 -0700642 void hideCursorAndSpanControllers() {
Gilles Debunned88876a2012-03-16 17:34:04 -0700643 hideCursorControllers();
644 hideSpanControllers();
645 }
646
647 private void hideSpanControllers() {
Jean Chalardbaf30942013-02-28 16:01:51 -0800648 if (mSpanController != null) {
649 mSpanController.hide();
Gilles Debunned88876a2012-03-16 17:34:04 -0700650 }
651 }
652
653 private void hideCursorControllers() {
Yohei Yukawa85d08f12015-04-29 20:12:37 -0700654 // When mTextView is not ExtractEditText, we need to distinguish two kinds of focus-lost.
655 // One is the true focus lost where suggestions pop-up (if any) should be dismissed, and the
656 // other is an side effect of showing the suggestions pop-up itself. We use isShowingUp()
657 // to distinguish one from the other.
Andrei Stingaceanub1891b32015-06-19 16:44:37 +0100658 if (mSuggestionsPopupWindow != null && ((mTextView.isInExtractedMode()) ||
Yohei Yukawa85d08f12015-04-29 20:12:37 -0700659 !mSuggestionsPopupWindow.isShowingUp())) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700660 // Should be done before hide insertion point controller since it triggers a show of it
661 mSuggestionsPopupWindow.hide();
662 }
663 hideInsertionPointCursorController();
Gilles Debunned88876a2012-03-16 17:34:04 -0700664 }
665
666 /**
667 * Create new SpellCheckSpans on the modified region.
668 */
669 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
Satoshi Kataokad7429c12013-06-05 16:30:23 +0900670 // Remove spans whose adjacent characters are text not punctuation
671 mTextView.removeAdjacentSuggestionSpans(start);
672 mTextView.removeAdjacentSuggestionSpans(end);
673
Gilles Debunned88876a2012-03-16 17:34:04 -0700674 if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() &&
Andrei Stingaceanub1891b32015-06-19 16:44:37 +0100675 !(mTextView.isInExtractedMode())) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700676 if (mSpellChecker == null && createSpellChecker) {
677 mSpellChecker = new SpellChecker(mTextView);
678 }
679 if (mSpellChecker != null) {
680 mSpellChecker.spellCheck(start, end);
681 }
682 }
683 }
684
685 void onScreenStateChanged(int screenState) {
686 switch (screenState) {
687 case View.SCREEN_STATE_ON:
688 resumeBlink();
689 break;
690 case View.SCREEN_STATE_OFF:
691 suspendBlink();
692 break;
693 }
694 }
695
696 private void suspendBlink() {
697 if (mBlink != null) {
698 mBlink.cancel();
699 }
700 }
701
702 private void resumeBlink() {
703 if (mBlink != null) {
704 mBlink.uncancel();
705 makeBlink();
706 }
707 }
708
709 void adjustInputType(boolean password, boolean passwordInputType,
710 boolean webPasswordInputType, boolean numberPasswordInputType) {
711 // mInputType has been set from inputType, possibly modified by mInputMethod.
712 // Specialize mInputType to [web]password if we have a text class and the original input
713 // type was a password.
714 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
715 if (password || passwordInputType) {
716 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
717 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
718 }
719 if (webPasswordInputType) {
720 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
721 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
722 }
723 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
724 if (numberPasswordInputType) {
725 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
726 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
727 }
728 }
729 }
730
731 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
732 int wid = tv.getPaddingLeft() + tv.getPaddingRight();
733 int ht = tv.getPaddingTop() + tv.getPaddingBottom();
734
735 int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize(
736 com.android.internal.R.dimen.textview_error_popup_default_width);
737 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
738 Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
739 float max = 0;
740 for (int i = 0; i < l.getLineCount(); i++) {
741 max = Math.max(max, l.getLineWidth(i));
742 }
743
744 /*
745 * Now set the popup size to be big enough for the text plus the border capped
746 * to DEFAULT_MAX_POPUP_WIDTH
747 */
748 pop.setWidth(wid + (int) Math.ceil(max));
749 pop.setHeight(ht + l.getHeight());
750 }
751
752 void setFrame() {
753 if (mErrorPopup != null) {
754 TextView tv = (TextView) mErrorPopup.getContentView();
755 chooseSize(mErrorPopup, mError, tv);
756 mErrorPopup.update(mTextView, getErrorX(), getErrorY(),
757 mErrorPopup.getWidth(), mErrorPopup.getHeight());
758 }
759 }
760
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800761 private int getWordStart(int offset) {
762 // FIXME - For this and similar methods we're not doing anything to check if there's
763 // a LocaleSpan in the text, this may be something we should try handling or checking for.
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700764 int retOffset = getWordIteratorWithText().prevBoundary(offset);
Mady Mellor58c90872015-05-12 11:09:37 -0700765 if (getWordIteratorWithText().isOnPunctuation(retOffset)) {
766 // On punctuation boundary or within group of punctuation, find punctuation start.
767 retOffset = getWordIteratorWithText().getPunctuationBeginning(offset);
768 } else {
769 // Not on a punctuation boundary, find the word start.
Mady Mellore264ac32015-06-22 16:46:29 -0700770 retOffset = getWordIteratorWithText().getPrevWordBeginningOnTwoWordsBoundary(offset);
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800771 }
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700772 if (retOffset == BreakIterator.DONE) {
773 return offset;
774 }
775 return retOffset;
776 }
777
778 private int getWordEnd(int offset) {
779 int retOffset = getWordIteratorWithText().nextBoundary(offset);
Mady Mellor58c90872015-05-12 11:09:37 -0700780 if (getWordIteratorWithText().isAfterPunctuation(retOffset)) {
781 // On punctuation boundary or within group of punctuation, find punctuation end.
782 retOffset = getWordIteratorWithText().getPunctuationEnd(offset);
783 } else {
784 // Not on a punctuation boundary, find the word end.
Mady Mellore264ac32015-06-22 16:46:29 -0700785 retOffset = getWordIteratorWithText().getNextWordEndOnTwoWordBoundary(offset);
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700786 }
787 if (retOffset == BreakIterator.DONE) {
788 return offset;
789 }
790 return retOffset;
791 }
792
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900793 private boolean needsToSelectAllToSelectWordOrParagraph() {
Andrei Stingaceanu47f82ae2015-04-28 17:43:54 +0100794 if (mTextView.hasPasswordTransformationMethod()) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700795 // Always select all on a password field.
796 // Cut/copy menu entries are not available for passwords, but being able to select all
797 // is however useful to delete or paste to replace the entire content.
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900798 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -0700799 }
800
801 int inputType = mTextView.getInputType();
802 int klass = inputType & InputType.TYPE_MASK_CLASS;
803 int variation = inputType & InputType.TYPE_MASK_VARIATION;
804
805 // Specific text field types: select the entire text for these
806 if (klass == InputType.TYPE_CLASS_NUMBER ||
807 klass == InputType.TYPE_CLASS_PHONE ||
808 klass == InputType.TYPE_CLASS_DATETIME ||
809 variation == InputType.TYPE_TEXT_VARIATION_URI ||
810 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
811 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
812 variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900813 return true;
814 }
815 return false;
816 }
817
818 /**
819 * Adjusts selection to the word under last touch offset. Return true if the operation was
820 * successfully performed.
821 */
822 private boolean selectCurrentWord() {
823 if (!mTextView.canSelectText()) {
824 return false;
825 }
826
827 if (needsToSelectAllToSelectWordOrParagraph()) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700828 return mTextView.selectAllText();
829 }
830
831 long lastTouchOffsets = getLastTouchOffsets();
832 final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
833 final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
834
835 // Safety check in case standard touch event handling has been bypassed
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -0800836 if (minOffset < 0 || minOffset > mTextView.getText().length()) return false;
837 if (maxOffset < 0 || maxOffset > mTextView.getText().length()) return false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700838
839 int selectionStart, selectionEnd;
840
841 // If a URLSpan (web address, email, phone...) is found at that position, select it.
842 URLSpan[] urlSpans = ((Spanned) mTextView.getText()).
843 getSpans(minOffset, maxOffset, URLSpan.class);
844 if (urlSpans.length >= 1) {
845 URLSpan urlSpan = urlSpans[0];
846 selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan);
847 selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan);
848 } else {
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800849 // FIXME - We should check if there's a LocaleSpan in the text, this may be
850 // something we should try handling or checking for.
Gilles Debunned88876a2012-03-16 17:34:04 -0700851 final WordIterator wordIterator = getWordIterator();
852 wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset);
853
854 selectionStart = wordIterator.getBeginning(minOffset);
855 selectionEnd = wordIterator.getEnd(maxOffset);
856
857 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
858 selectionStart == selectionEnd) {
859 // Possible when the word iterator does not properly handle the text's language
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900860 long range = getCharClusterRange(minOffset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700861 selectionStart = TextUtils.unpackRangeStartFromLong(range);
862 selectionEnd = TextUtils.unpackRangeEndFromLong(range);
863 }
864 }
865
866 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
867 return selectionEnd > selectionStart;
868 }
869
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900870 /**
871 * Adjusts selection to the paragraph under last touch offset. Return true if the operation was
872 * successfully performed.
873 */
874 private boolean selectCurrentParagraph() {
875 if (!mTextView.canSelectText()) {
876 return false;
877 }
878
879 if (needsToSelectAllToSelectWordOrParagraph()) {
880 return mTextView.selectAllText();
881 }
882
883 long lastTouchOffsets = getLastTouchOffsets();
884 final int minLastTouchOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
885 final int maxLastTouchOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
886
887 final long paragraphsRange = getParagraphsRange(minLastTouchOffset, maxLastTouchOffset);
888 final int start = TextUtils.unpackRangeStartFromLong(paragraphsRange);
889 final int end = TextUtils.unpackRangeEndFromLong(paragraphsRange);
890 if (start < end) {
891 Selection.setSelection((Spannable) mTextView.getText(), start, end);
892 return true;
893 }
894 return false;
895 }
896
897 /**
898 * Get the minimum range of paragraphs that contains startOffset and endOffset.
899 */
900 private long getParagraphsRange(int startOffset, int endOffset) {
901 final Layout layout = mTextView.getLayout();
902 if (layout == null) {
903 return TextUtils.packRangeInLong(-1, -1);
904 }
905 final CharSequence text = mTextView.getText();
906 int minLine = layout.getLineForOffset(startOffset);
907 // Search paragraph start.
908 while (minLine > 0) {
909 final int prevLineEndOffset = layout.getLineEnd(minLine - 1);
910 if (text.charAt(prevLineEndOffset - 1) == '\n') {
911 break;
912 }
913 minLine--;
914 }
915 int maxLine = layout.getLineForOffset(endOffset);
916 // Search paragraph end.
917 while (maxLine < layout.getLineCount() - 1) {
918 final int lineEndOffset = layout.getLineEnd(maxLine);
919 if (text.charAt(lineEndOffset - 1) == '\n') {
920 break;
921 }
922 maxLine++;
923 }
924 return TextUtils.packRangeInLong(layout.getLineStart(minLine), layout.getLineEnd(maxLine));
925 }
926
Gilles Debunned88876a2012-03-16 17:34:04 -0700927 void onLocaleChanged() {
Keisuke Kuroyanagie0ac5ac2016-03-09 15:33:30 +0900928 // Will be re-created on demand in getWordIterator and getWordIteratorWithText with the
929 // proper new locale
Gilles Debunned88876a2012-03-16 17:34:04 -0700930 mWordIterator = null;
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800931 mWordIteratorWithText = null;
Gilles Debunned88876a2012-03-16 17:34:04 -0700932 }
933
934 /**
935 * @hide
936 */
937 public WordIterator getWordIterator() {
938 if (mWordIterator == null) {
939 mWordIterator = new WordIterator(mTextView.getTextServicesLocale());
940 }
941 return mWordIterator;
942 }
943
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800944 private WordIterator getWordIteratorWithText() {
945 if (mWordIteratorWithText == null) {
946 mWordIteratorWithText = new WordIterator(mTextView.getTextServicesLocale());
947 mUpdateWordIteratorText = true;
948 }
949 if (mUpdateWordIteratorText) {
950 // FIXME - Shouldn't copy all of the text as only the area of the text relevant
951 // to the user's selection is needed. A possible solution would be to
952 // copy some number N of characters near the selection and then when the
953 // user approaches N then we'd do another copy of the next N characters.
954 CharSequence text = mTextView.getText();
955 mWordIteratorWithText.setCharSequence(text, 0, text.length());
956 mUpdateWordIteratorText = false;
957 }
958 return mWordIteratorWithText;
959 }
960
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900961 private int getNextCursorOffset(int offset, boolean findAfterGivenOffset) {
962 final Layout layout = mTextView.getLayout();
963 if (layout == null) return offset;
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -0800964 return findAfterGivenOffset == layout.isRtlCharAt(offset) ?
965 layout.getOffsetToLeftOf(offset) : layout.getOffsetToRightOf(offset);
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900966 }
967
968 private long getCharClusterRange(int offset) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700969 final int textLength = mTextView.getText().length();
Gilles Debunned88876a2012-03-16 17:34:04 -0700970 if (offset < textLength) {
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -0800971 final int clusterEndOffset = getNextCursorOffset(offset, true);
972 return TextUtils.packRangeInLong(
973 getNextCursorOffset(clusterEndOffset, false), clusterEndOffset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700974 }
975 if (offset - 1 >= 0) {
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -0800976 final int clusterStartOffset = getNextCursorOffset(offset, false);
977 return TextUtils.packRangeInLong(clusterStartOffset,
978 getNextCursorOffset(clusterStartOffset, true));
Gilles Debunned88876a2012-03-16 17:34:04 -0700979 }
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900980 return TextUtils.packRangeInLong(offset, offset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700981 }
982
983 private boolean touchPositionIsInSelection() {
984 int selectionStart = mTextView.getSelectionStart();
985 int selectionEnd = mTextView.getSelectionEnd();
986
987 if (selectionStart == selectionEnd) {
988 return false;
989 }
990
991 if (selectionStart > selectionEnd) {
992 int tmp = selectionStart;
993 selectionStart = selectionEnd;
994 selectionEnd = tmp;
995 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
996 }
997
998 SelectionModifierCursorController selectionController = getSelectionController();
999 int minOffset = selectionController.getMinTouchOffset();
1000 int maxOffset = selectionController.getMaxTouchOffset();
1001
1002 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
1003 }
1004
1005 private PositionListener getPositionListener() {
1006 if (mPositionListener == null) {
1007 mPositionListener = new PositionListener();
1008 }
1009 return mPositionListener;
1010 }
1011
1012 private interface TextViewPositionListener {
1013 public void updatePosition(int parentPositionX, int parentPositionY,
1014 boolean parentPositionChanged, boolean parentScrolled);
1015 }
1016
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09001017 private boolean isPositionVisible(final float positionX, final float positionY) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001018 synchronized (TEMP_POSITION) {
1019 final float[] position = TEMP_POSITION;
1020 position[0] = positionX;
1021 position[1] = positionY;
1022 View view = mTextView;
1023
1024 while (view != null) {
1025 if (view != mTextView) {
1026 // Local scroll is already taken into account in positionX/Y
1027 position[0] -= view.getScrollX();
1028 position[1] -= view.getScrollY();
1029 }
1030
1031 if (position[0] < 0 || position[1] < 0 ||
1032 position[0] > view.getWidth() || position[1] > view.getHeight()) {
1033 return false;
1034 }
1035
1036 if (!view.getMatrix().isIdentity()) {
1037 view.getMatrix().mapPoints(position);
1038 }
1039
1040 position[0] += view.getLeft();
1041 position[1] += view.getTop();
1042
1043 final ViewParent parent = view.getParent();
1044 if (parent instanceof View) {
1045 view = (View) parent;
1046 } else {
1047 // We've reached the ViewRoot, stop iterating
1048 view = null;
1049 }
1050 }
1051 }
1052
1053 // We've been able to walk up the view hierarchy and the position was never clipped
1054 return true;
1055 }
1056
1057 private boolean isOffsetVisible(int offset) {
1058 Layout layout = mTextView.getLayout();
Victoria Leaseb9b77ae2013-10-13 15:12:52 -07001059 if (layout == null) return false;
1060
Gilles Debunned88876a2012-03-16 17:34:04 -07001061 final int line = layout.getLineForOffset(offset);
1062 final int lineBottom = layout.getLineBottom(line);
1063 final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset);
1064 return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(),
1065 lineBottom + mTextView.viewportToContentVerticalOffset());
1066 }
1067
1068 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
1069 * in the view. Returns false when the position is in the empty space of left/right of text.
1070 */
1071 private boolean isPositionOnText(float x, float y) {
1072 Layout layout = mTextView.getLayout();
1073 if (layout == null) return false;
1074
1075 final int line = mTextView.getLineAtCoordinate(y);
1076 x = mTextView.convertToLocalHorizontalCoordinate(x);
1077
1078 if (x < layout.getLineLeft(line)) return false;
1079 if (x > layout.getLineRight(line)) return false;
1080 return true;
1081 }
1082
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001083 private void startDragAndDrop() {
1084 final int start = mTextView.getSelectionStart();
1085 final int end = mTextView.getSelectionEnd();
1086 CharSequence selectedText = mTextView.getTransformedText(start, end);
1087 ClipData data = ClipData.newPlainText(null, selectedText);
1088 DragLocalState localState = new DragLocalState(mTextView, start, end);
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08001089 mTextView.startDragAndDrop(data, getTextThumbnailBuilder(start, end), localState,
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001090 View.DRAG_FLAG_GLOBAL);
1091 stopTextActionMode();
1092 if (hasSelectionController()) {
1093 getSelectionController().resetTouchOffsets();
1094 }
1095 }
1096
Gilles Debunned88876a2012-03-16 17:34:04 -07001097 public boolean performLongClick(boolean handled) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001098 // Long press in empty space moves cursor and starts the insertion action mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07001099 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
1100 mInsertionControllerEnabled) {
1101 final int offset = mTextView.getOffsetForPosition(mLastDownPositionX,
1102 mLastDownPositionY);
Gilles Debunned88876a2012-03-16 17:34:04 -07001103 Selection.setSelection((Spannable) mTextView.getText(), offset);
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001104 getInsertionController().show();
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001105 mIsInsertionActionModeStartPending = true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001106 handled = true;
1107 }
1108
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001109 if (!handled && mTextActionMode != null) {
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +01001110 if (touchPositionIsInSelection()) {
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001111 startDragAndDrop();
Gilles Debunned88876a2012-03-16 17:34:04 -07001112 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001113 stopTextActionMode();
Clara Bayarridfac4432015-05-15 12:18:24 +01001114 selectCurrentWordAndStartDrag();
Gilles Debunned88876a2012-03-16 17:34:04 -07001115 }
1116 handled = true;
1117 }
1118
1119 // Start a new selection
1120 if (!handled) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001121 handled = selectCurrentWordAndStartDrag();
Gilles Debunned88876a2012-03-16 17:34:04 -07001122 }
1123
1124 return handled;
1125 }
1126
1127 private long getLastTouchOffsets() {
1128 SelectionModifierCursorController selectionController = getSelectionController();
1129 final int minOffset = selectionController.getMinTouchOffset();
1130 final int maxOffset = selectionController.getMaxTouchOffset();
1131 return TextUtils.packRangeInLong(minOffset, maxOffset);
1132 }
1133
1134 void onFocusChanged(boolean focused, int direction) {
1135 mShowCursor = SystemClock.uptimeMillis();
1136 ensureEndedBatchEdit();
1137
1138 if (focused) {
1139 int selStart = mTextView.getSelectionStart();
1140 int selEnd = mTextView.getSelectionEnd();
1141
1142 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
1143 // mode for these, unless there was a specific selection already started.
1144 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
1145 selEnd == mTextView.getText().length();
1146
1147 mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() &&
1148 !isFocusHighlighted;
1149
1150 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
1151 // If a tap was used to give focus to that view, move cursor at tap position.
1152 // Has to be done before onTakeFocus, which can be overloaded.
1153 final int lastTapPosition = getLastTapPosition();
1154 if (lastTapPosition >= 0) {
1155 Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition);
1156 }
1157
1158 // Note this may have to be moved out of the Editor class
1159 MovementMethod mMovement = mTextView.getMovementMethod();
1160 if (mMovement != null) {
1161 mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction);
1162 }
1163
1164 // The DecorView does not have focus when the 'Done' ExtractEditText button is
1165 // pressed. Since it is the ViewAncestor's mView, it requests focus before
1166 // ExtractEditText clears focus, which gives focus to the ExtractEditText.
1167 // This special case ensure that we keep current selection in that case.
1168 // It would be better to know why the DecorView does not have focus at that time.
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001169 if (((mTextView.isInExtractedMode()) || mSelectionMoved) &&
Gilles Debunned88876a2012-03-16 17:34:04 -07001170 selStart >= 0 && selEnd >= 0) {
1171 /*
1172 * Someone intentionally set the selection, so let them
1173 * do whatever it is that they wanted to do instead of
1174 * the default on-focus behavior. We reset the selection
1175 * here instead of just skipping the onTakeFocus() call
1176 * because some movement methods do something other than
1177 * just setting the selection in theirs and we still
1178 * need to go through that path.
1179 */
1180 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
1181 }
1182
1183 if (mSelectAllOnFocus) {
1184 mTextView.selectAllText();
1185 }
1186
1187 mTouchFocusSelected = true;
1188 }
1189
1190 mFrozenWithFocus = false;
1191 mSelectionMoved = false;
1192
1193 if (mError != null) {
1194 showError();
1195 }
1196
1197 makeBlink();
1198 } else {
1199 if (mError != null) {
1200 hideError();
1201 }
1202 // Don't leave us in the middle of a batch edit.
1203 mTextView.onEndBatchEdit();
1204
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001205 if (mTextView.isInExtractedMode()) {
Mady Mellora2861452015-06-25 08:40:27 -07001206 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001207 stopTextActionModeWithPreservingSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001208 } else {
Mady Mellora2861452015-06-25 08:40:27 -07001209 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001210 if (mTemporaryDetach) {
1211 stopTextActionModeWithPreservingSelection();
1212 } else {
1213 stopTextActionMode();
1214 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001215 downgradeEasyCorrectionSpans();
1216 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001217 // No need to create the controller
1218 if (mSelectionModifierCursorController != null) {
1219 mSelectionModifierCursorController.resetTouchOffsets();
1220 }
1221 }
1222 }
1223
1224 /**
1225 * Downgrades to simple suggestions all the easy correction spans that are not a spell check
1226 * span.
1227 */
1228 private void downgradeEasyCorrectionSpans() {
1229 CharSequence text = mTextView.getText();
1230 if (text instanceof Spannable) {
1231 Spannable spannable = (Spannable) text;
1232 SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
1233 spannable.length(), SuggestionSpan.class);
1234 for (int i = 0; i < suggestionSpans.length; i++) {
1235 int flags = suggestionSpans[i].getFlags();
1236 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
1237 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
1238 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
1239 suggestionSpans[i].setFlags(flags);
1240 }
1241 }
1242 }
1243 }
1244
1245 void sendOnTextChanged(int start, int after) {
1246 updateSpellCheckSpans(start, start + after, false);
1247
Mady Mellor2ff2cd82015-03-02 10:37:01 -08001248 // Flip flag to indicate the word iterator needs to have the text reset.
1249 mUpdateWordIteratorText = true;
1250
Gilles Debunned88876a2012-03-16 17:34:04 -07001251 // Hide the controllers as soon as text is modified (typing, procedural...)
1252 // We do not hide the span controllers, since they can be added when a new text is
1253 // inserted into the text view (voice IME).
1254 hideCursorControllers();
Keisuke Kuroyanagif4e347d2015-06-11 17:41:00 +09001255 // Reset drag accelerator.
1256 if (mSelectionModifierCursorController != null) {
1257 mSelectionModifierCursorController.resetTouchOffsets();
1258 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001259 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07001260 }
1261
1262 private int getLastTapPosition() {
1263 // No need to create the controller at that point, no last tap position saved
1264 if (mSelectionModifierCursorController != null) {
1265 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
1266 if (lastTapPosition >= 0) {
1267 // Safety check, should not be possible.
1268 if (lastTapPosition > mTextView.getText().length()) {
1269 lastTapPosition = mTextView.getText().length();
1270 }
1271 return lastTapPosition;
1272 }
1273 }
1274
1275 return -1;
1276 }
1277
1278 void onWindowFocusChanged(boolean hasWindowFocus) {
1279 if (hasWindowFocus) {
1280 if (mBlink != null) {
1281 mBlink.uncancel();
1282 makeBlink();
1283 }
Mady Mellora2861452015-06-25 08:40:27 -07001284 final InputMethodManager imm = InputMethodManager.peekInstance();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001285 if (mTextView.hasSelection() && !extractedTextModeWillBeStarted()) {
1286 startSelectionActionMode();
Mady Mellora2861452015-06-25 08:40:27 -07001287 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001288 } else {
1289 if (mBlink != null) {
1290 mBlink.cancel();
1291 }
1292 if (mInputContentType != null) {
1293 mInputContentType.enterDown = false;
1294 }
1295 // Order matters! Must be done before onParentLostFocus to rely on isShowingUp
Mady Mellora2861452015-06-25 08:40:27 -07001296 hideCursorAndSpanControllers();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001297 stopTextActionModeWithPreservingSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001298 if (mSuggestionsPopupWindow != null) {
1299 mSuggestionsPopupWindow.onParentLostFocus();
1300 }
1301
Gilles Debunnec72fba82012-06-26 14:47:07 -07001302 // Don't leave us in the middle of a batch edit. Same as in onFocusChanged
1303 ensureEndedBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001304 }
1305 }
1306
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09001307 private void updateTapState(MotionEvent event) {
1308 final int action = event.getActionMasked();
1309 if (action == MotionEvent.ACTION_DOWN) {
1310 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
1311 // Detect double tap and triple click.
1312 if (((mTapState == TAP_STATE_FIRST_TAP)
1313 || ((mTapState == TAP_STATE_DOUBLE_TAP) && isMouse))
1314 && (SystemClock.uptimeMillis() - mLastTouchUpTime) <=
1315 ViewConfiguration.getDoubleTapTimeout()) {
1316 if (mTapState == TAP_STATE_FIRST_TAP) {
1317 mTapState = TAP_STATE_DOUBLE_TAP;
1318 } else {
1319 mTapState = TAP_STATE_TRIPLE_CLICK;
1320 }
1321 } else {
1322 mTapState = TAP_STATE_FIRST_TAP;
1323 }
1324 }
1325 if (action == MotionEvent.ACTION_UP) {
1326 mLastTouchUpTime = SystemClock.uptimeMillis();
1327 }
1328 }
1329
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09001330 private boolean shouldFilterOutTouchEvent(MotionEvent event) {
1331 if (!event.isFromSource(InputDevice.SOURCE_MOUSE)) {
1332 return false;
1333 }
1334 final boolean primaryButtonStateChanged =
1335 ((mLastButtonState ^ event.getButtonState()) & MotionEvent.BUTTON_PRIMARY) != 0;
1336 final int action = event.getActionMasked();
1337 if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP)
1338 && !primaryButtonStateChanged) {
1339 return true;
1340 }
1341 if (action == MotionEvent.ACTION_MOVE
1342 && !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
1343 return true;
1344 }
1345 return false;
1346 }
1347
Gilles Debunned88876a2012-03-16 17:34:04 -07001348 void onTouchEvent(MotionEvent event) {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09001349 final boolean filterOutEvent = shouldFilterOutTouchEvent(event);
1350 mLastButtonState = event.getButtonState();
1351 if (filterOutEvent) {
1352 if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1353 mDiscardNextActionUp = true;
1354 }
1355 return;
1356 }
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09001357 updateTapState(event);
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001358 updateFloatingToolbarVisibility(event);
1359
Gilles Debunned88876a2012-03-16 17:34:04 -07001360 if (hasSelectionController()) {
1361 getSelectionController().onTouchEvent(event);
1362 }
1363
1364 if (mShowSuggestionRunnable != null) {
1365 mTextView.removeCallbacks(mShowSuggestionRunnable);
1366 mShowSuggestionRunnable = null;
1367 }
1368
1369 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1370 mLastDownPositionX = event.getX();
1371 mLastDownPositionY = event.getY();
1372
1373 // Reset this state; it will be re-set if super.onTouchEvent
1374 // causes focus to move to the view.
1375 mTouchFocusSelected = false;
1376 mIgnoreActionUpEvent = false;
1377 }
1378 }
1379
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001380 private void updateFloatingToolbarVisibility(MotionEvent event) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001381 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001382 switch (event.getActionMasked()) {
1383 case MotionEvent.ACTION_MOVE:
1384 hideFloatingToolbar();
1385 break;
1386 case MotionEvent.ACTION_UP: // fall through
1387 case MotionEvent.ACTION_CANCEL:
1388 showFloatingToolbar();
1389 }
1390 }
1391 }
1392
1393 private void hideFloatingToolbar() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001394 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001395 mTextView.removeCallbacks(mShowFloatingToolbar);
Abodunrinwa Tokif444b5c2015-06-16 15:47:04 +01001396 mTextActionMode.hide(ActionMode.DEFAULT_HIDE_DURATION);
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001397 }
1398 }
1399
1400 private void showFloatingToolbar() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001401 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001402 // Delay "show" so it doesn't interfere with click confirmations
1403 // or double-clicks that could "dismiss" the floating toolbar.
1404 int delay = ViewConfiguration.getDoubleTapTimeout();
1405 mTextView.postDelayed(mShowFloatingToolbar, delay);
1406 }
1407 }
1408
Gilles Debunned88876a2012-03-16 17:34:04 -07001409 public void beginBatchEdit() {
1410 mInBatchEditControllers = true;
1411 final InputMethodState ims = mInputMethodState;
1412 if (ims != null) {
1413 int nesting = ++ims.mBatchEditNesting;
1414 if (nesting == 1) {
1415 ims.mCursorChanged = false;
1416 ims.mChangedDelta = 0;
1417 if (ims.mContentChanged) {
1418 // We already have a pending change from somewhere else,
1419 // so turn this into a full update.
1420 ims.mChangedStart = 0;
1421 ims.mChangedEnd = mTextView.getText().length();
1422 } else {
1423 ims.mChangedStart = EXTRACT_UNKNOWN;
1424 ims.mChangedEnd = EXTRACT_UNKNOWN;
1425 ims.mContentChanged = false;
1426 }
James Cook48e0fac2015-02-25 15:44:51 -08001427 mUndoInputFilter.beginBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001428 mTextView.onBeginBatchEdit();
1429 }
1430 }
1431 }
1432
1433 public void endBatchEdit() {
1434 mInBatchEditControllers = false;
1435 final InputMethodState ims = mInputMethodState;
1436 if (ims != null) {
1437 int nesting = --ims.mBatchEditNesting;
1438 if (nesting == 0) {
1439 finishBatchEdit(ims);
1440 }
1441 }
1442 }
1443
1444 void ensureEndedBatchEdit() {
1445 final InputMethodState ims = mInputMethodState;
1446 if (ims != null && ims.mBatchEditNesting != 0) {
1447 ims.mBatchEditNesting = 0;
1448 finishBatchEdit(ims);
1449 }
1450 }
1451
1452 void finishBatchEdit(final InputMethodState ims) {
1453 mTextView.onEndBatchEdit();
James Cook48e0fac2015-02-25 15:44:51 -08001454 mUndoInputFilter.endBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001455
1456 if (ims.mContentChanged || ims.mSelectionModeChanged) {
1457 mTextView.updateAfterEdit();
1458 reportExtractedText();
1459 } else if (ims.mCursorChanged) {
Jean Chalardc99d33f2013-02-28 16:39:47 -08001460 // Cheesy way to get us to report the current cursor location.
Gilles Debunned88876a2012-03-16 17:34:04 -07001461 mTextView.invalidateCursor();
1462 }
Jean Chalardc99d33f2013-02-28 16:39:47 -08001463 // sendUpdateSelection knows to avoid sending if the selection did
1464 // not actually change.
1465 sendUpdateSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001466 }
1467
1468 static final int EXTRACT_NOTHING = -2;
1469 static final int EXTRACT_UNKNOWN = -1;
1470
1471 boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
1472 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
1473 EXTRACT_UNKNOWN, outText);
1474 }
1475
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001476 private boolean extractTextInternal(@Nullable ExtractedTextRequest request,
Gilles Debunned88876a2012-03-16 17:34:04 -07001477 int partialStartOffset, int partialEndOffset, int delta,
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001478 @Nullable ExtractedText outText) {
1479 if (request == null || outText == null) {
1480 return false;
Gilles Debunned88876a2012-03-16 17:34:04 -07001481 }
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001482
1483 final CharSequence content = mTextView.getText();
1484 if (content == null) {
1485 return false;
1486 }
1487
1488 if (partialStartOffset != EXTRACT_NOTHING) {
1489 final int N = content.length();
1490 if (partialStartOffset < 0) {
1491 outText.partialStartOffset = outText.partialEndOffset = -1;
1492 partialStartOffset = 0;
1493 partialEndOffset = N;
1494 } else {
1495 // Now use the delta to determine the actual amount of text
1496 // we need.
1497 partialEndOffset += delta;
1498 // Adjust offsets to ensure we contain full spans.
1499 if (content instanceof Spanned) {
1500 Spanned spanned = (Spanned)content;
1501 Object[] spans = spanned.getSpans(partialStartOffset,
1502 partialEndOffset, ParcelableSpan.class);
1503 int i = spans.length;
1504 while (i > 0) {
1505 i--;
1506 int j = spanned.getSpanStart(spans[i]);
1507 if (j < partialStartOffset) partialStartOffset = j;
1508 j = spanned.getSpanEnd(spans[i]);
1509 if (j > partialEndOffset) partialEndOffset = j;
1510 }
1511 }
1512 outText.partialStartOffset = partialStartOffset;
1513 outText.partialEndOffset = partialEndOffset - delta;
1514
1515 if (partialStartOffset > N) {
1516 partialStartOffset = N;
1517 } else if (partialStartOffset < 0) {
1518 partialStartOffset = 0;
1519 }
1520 if (partialEndOffset > N) {
1521 partialEndOffset = N;
1522 } else if (partialEndOffset < 0) {
1523 partialEndOffset = 0;
1524 }
1525 }
1526 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
1527 outText.text = content.subSequence(partialStartOffset,
1528 partialEndOffset);
1529 } else {
1530 outText.text = TextUtils.substring(content, partialStartOffset,
1531 partialEndOffset);
1532 }
1533 } else {
1534 outText.partialStartOffset = 0;
1535 outText.partialEndOffset = 0;
1536 outText.text = "";
1537 }
1538 outText.flags = 0;
1539 if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) {
1540 outText.flags |= ExtractedText.FLAG_SELECTING;
1541 }
1542 if (mTextView.isSingleLine()) {
1543 outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
1544 }
1545 outText.startOffset = 0;
1546 outText.selectionStart = mTextView.getSelectionStart();
1547 outText.selectionEnd = mTextView.getSelectionEnd();
1548 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001549 }
1550
1551 boolean reportExtractedText() {
1552 final Editor.InputMethodState ims = mInputMethodState;
1553 if (ims != null) {
1554 final boolean contentChanged = ims.mContentChanged;
1555 if (contentChanged || ims.mSelectionModeChanged) {
1556 ims.mContentChanged = false;
1557 ims.mSelectionModeChanged = false;
Gilles Debunnec62589c2012-04-12 14:50:23 -07001558 final ExtractedTextRequest req = ims.mExtractedTextRequest;
Gilles Debunned88876a2012-03-16 17:34:04 -07001559 if (req != null) {
1560 InputMethodManager imm = InputMethodManager.peekInstance();
1561 if (imm != null) {
1562 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1563 "Retrieving extracted start=" + ims.mChangedStart +
1564 " end=" + ims.mChangedEnd +
1565 " delta=" + ims.mChangedDelta);
1566 if (ims.mChangedStart < 0 && !contentChanged) {
1567 ims.mChangedStart = EXTRACT_NOTHING;
1568 }
1569 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
Gilles Debunnec62589c2012-04-12 14:50:23 -07001570 ims.mChangedDelta, ims.mExtractedText)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001571 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1572 "Reporting extracted start=" +
Gilles Debunnec62589c2012-04-12 14:50:23 -07001573 ims.mExtractedText.partialStartOffset +
1574 " end=" + ims.mExtractedText.partialEndOffset +
1575 ": " + ims.mExtractedText.text);
1576
1577 imm.updateExtractedText(mTextView, req.token, ims.mExtractedText);
Gilles Debunned88876a2012-03-16 17:34:04 -07001578 ims.mChangedStart = EXTRACT_UNKNOWN;
1579 ims.mChangedEnd = EXTRACT_UNKNOWN;
1580 ims.mChangedDelta = 0;
1581 ims.mContentChanged = false;
1582 return true;
1583 }
1584 }
1585 }
1586 }
1587 }
1588 return false;
1589 }
1590
Jean Chalarddf7c72f2013-02-28 15:28:54 -08001591 private void sendUpdateSelection() {
1592 if (null != mInputMethodState && mInputMethodState.mBatchEditNesting <= 0) {
1593 final InputMethodManager imm = InputMethodManager.peekInstance();
1594 if (null != imm) {
1595 final int selectionStart = mTextView.getSelectionStart();
1596 final int selectionEnd = mTextView.getSelectionEnd();
1597 int candStart = -1;
1598 int candEnd = -1;
1599 if (mTextView.getText() instanceof Spannable) {
1600 final Spannable sp = (Spannable) mTextView.getText();
1601 candStart = EditableInputConnection.getComposingSpanStart(sp);
1602 candEnd = EditableInputConnection.getComposingSpanEnd(sp);
1603 }
Jean Chalardc99d33f2013-02-28 16:39:47 -08001604 // InputMethodManager#updateSelection skips sending the message if
1605 // none of the parameters have changed since the last time we called it.
Jean Chalarddf7c72f2013-02-28 15:28:54 -08001606 imm.updateSelection(mTextView,
1607 selectionStart, selectionEnd, candStart, candEnd);
1608 }
1609 }
1610 }
1611
Gilles Debunned88876a2012-03-16 17:34:04 -07001612 void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint,
1613 int cursorOffsetVertical) {
1614 final int selectionStart = mTextView.getSelectionStart();
1615 final int selectionEnd = mTextView.getSelectionEnd();
1616
1617 final InputMethodState ims = mInputMethodState;
1618 if (ims != null && ims.mBatchEditNesting == 0) {
1619 InputMethodManager imm = InputMethodManager.peekInstance();
1620 if (imm != null) {
1621 if (imm.isActive(mTextView)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001622 if (ims.mContentChanged || ims.mSelectionModeChanged) {
1623 // We are in extract mode and the content has changed
1624 // in some way... just report complete new text to the
1625 // input method.
Yohei Yukawab6bec1a2015-05-01 16:18:25 -07001626 reportExtractedText();
Gilles Debunned88876a2012-03-16 17:34:04 -07001627 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001628 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001629 }
1630 }
1631
1632 if (mCorrectionHighlighter != null) {
1633 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
1634 }
1635
1636 if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) {
1637 drawCursor(canvas, cursorOffsetVertical);
1638 // Rely on the drawable entirely, do not draw the cursor line.
1639 // Has to be done after the IMM related code above which relies on the highlight.
1640 highlight = null;
1641 }
1642
1643 if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) {
1644 drawHardwareAccelerated(canvas, layout, highlight, highlightPaint,
1645 cursorOffsetVertical);
1646 } else {
1647 layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
1648 }
1649 }
1650
1651 private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight,
1652 Paint highlightPaint, int cursorOffsetVertical) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001653 final long lineRange = layout.getLineRangeForDraw(canvas);
1654 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
1655 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
1656 if (lastLine < 0) return;
1657
1658 layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
1659 firstLine, lastLine);
1660
1661 if (layout instanceof DynamicLayout) {
Chris Craik956f3402015-04-27 16:41:00 -07001662 if (mTextRenderNodes == null) {
1663 mTextRenderNodes = ArrayUtils.emptyArray(TextRenderNode.class);
Gilles Debunned88876a2012-03-16 17:34:04 -07001664 }
1665
1666 DynamicLayout dynamicLayout = (DynamicLayout) layout;
Gilles Debunne157aafc2012-04-19 17:21:57 -07001667 int[] blockEndLines = dynamicLayout.getBlockEndLines();
Gilles Debunned88876a2012-03-16 17:34:04 -07001668 int[] blockIndices = dynamicLayout.getBlockIndices();
1669 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
Sangkyu Lee955beb22012-12-10 15:47:00 +09001670 final int indexFirstChangedBlock = dynamicLayout.getIndexFirstChangedBlock();
Gilles Debunned88876a2012-03-16 17:34:04 -07001671
Gilles Debunned88876a2012-03-16 17:34:04 -07001672 int endOfPreviousBlock = -1;
1673 int searchStartIndex = 0;
1674 for (int i = 0; i < numberOfBlocks; i++) {
Gilles Debunne157aafc2012-04-19 17:21:57 -07001675 int blockEndLine = blockEndLines[i];
Gilles Debunned88876a2012-03-16 17:34:04 -07001676 int blockIndex = blockIndices[i];
1677
1678 final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX;
1679 if (blockIsInvalid) {
1680 blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks,
1681 searchStartIndex);
Gilles Debunne157aafc2012-04-19 17:21:57 -07001682 // Note how dynamic layout's internal block indices get updated from Editor
Gilles Debunned88876a2012-03-16 17:34:04 -07001683 blockIndices[i] = blockIndex;
Chris Craik956f3402015-04-27 16:41:00 -07001684 if (mTextRenderNodes[blockIndex] != null) {
1685 mTextRenderNodes[blockIndex].isDirty = true;
Raph Levienbb2397c2015-02-12 16:16:49 -08001686 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001687 searchStartIndex = blockIndex + 1;
1688 }
1689
Chris Craik956f3402015-04-27 16:41:00 -07001690 if (mTextRenderNodes[blockIndex] == null) {
1691 mTextRenderNodes[blockIndex] =
1692 new TextRenderNode("Text " + blockIndex);
Gilles Debunned88876a2012-03-16 17:34:04 -07001693 }
1694
Chris Craik956f3402015-04-27 16:41:00 -07001695 final boolean blockDisplayListIsInvalid = mTextRenderNodes[blockIndex].needsRecord();
1696 RenderNode blockDisplayList = mTextRenderNodes[blockIndex].renderNode;
Sangkyu Lee955beb22012-12-10 15:47:00 +09001697 if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) {
Gilles Debunne157aafc2012-04-19 17:21:57 -07001698 final int blockBeginLine = endOfPreviousBlock + 1;
1699 final int top = layout.getLineTop(blockBeginLine);
1700 final int bottom = layout.getLineBottom(blockEndLine);
Gilles Debunnefd5bc012012-04-23 16:21:35 -07001701 int left = 0;
1702 int right = mTextView.getWidth();
1703 if (mTextView.getHorizontallyScrolling()) {
1704 float min = Float.MAX_VALUE;
1705 float max = Float.MIN_VALUE;
1706 for (int line = blockBeginLine; line <= blockEndLine; line++) {
1707 min = Math.min(min, layout.getLineLeft(line));
1708 max = Math.max(max, layout.getLineRight(line));
1709 }
1710 left = (int) min;
1711 right = (int) (max + 0.5f);
1712 }
Gilles Debunne157aafc2012-04-19 17:21:57 -07001713
Sangkyu Lee955beb22012-12-10 15:47:00 +09001714 // Rebuild display list if it is invalid
1715 if (blockDisplayListIsInvalid) {
Chris Craikf6829a02015-03-10 10:28:59 -07001716 final DisplayListCanvas displayListCanvas = blockDisplayList.start(
Romain Guy52036b12013-02-14 18:03:37 -08001717 right - left, bottom - top);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001718 try {
Romain Guy52036b12013-02-14 18:03:37 -08001719 // drawText is always relative to TextView's origin, this translation
1720 // brings this range of text back to the top left corner of the viewport
Chris Craikf6829a02015-03-10 10:28:59 -07001721 displayListCanvas.translate(-left, -top);
1722 layout.drawText(displayListCanvas, blockBeginLine, blockEndLine);
Chris Craik956f3402015-04-27 16:41:00 -07001723 mTextRenderNodes[blockIndex].isDirty = false;
Romain Guy52036b12013-02-14 18:03:37 -08001724 // No need to untranslate, previous context is popped after
1725 // drawDisplayList
Sangkyu Lee955beb22012-12-10 15:47:00 +09001726 } finally {
Chris Craikf6829a02015-03-10 10:28:59 -07001727 blockDisplayList.end(displayListCanvas);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001728 // Same as drawDisplayList below, handled by our TextView's parent
Chet Haasedd671592013-04-19 14:54:34 -07001729 blockDisplayList.setClipToBounds(false);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001730 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001731 }
Sangkyu Lee955beb22012-12-10 15:47:00 +09001732
1733 // Valid disply list whose index is >= indexFirstChangedBlock
1734 // only needs to update its drawing location.
1735 blockDisplayList.setLeftTopRightBottom(left, top, right, bottom);
Gilles Debunned88876a2012-03-16 17:34:04 -07001736 }
1737
Chris Craik956f3402015-04-27 16:41:00 -07001738 ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList);
Gilles Debunnefd5bc012012-04-23 16:21:35 -07001739
Gilles Debunne157aafc2012-04-19 17:21:57 -07001740 endOfPreviousBlock = blockEndLine;
Gilles Debunned88876a2012-03-16 17:34:04 -07001741 }
Sangkyu Lee955beb22012-12-10 15:47:00 +09001742
1743 dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks);
Gilles Debunned88876a2012-03-16 17:34:04 -07001744 } else {
1745 // Boring layout is used for empty and hint text
1746 layout.drawText(canvas, firstLine, lastLine);
1747 }
1748 }
1749
1750 private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
1751 int searchStartIndex) {
Chris Craik956f3402015-04-27 16:41:00 -07001752 int length = mTextRenderNodes.length;
Gilles Debunned88876a2012-03-16 17:34:04 -07001753 for (int i = searchStartIndex; i < length; i++) {
1754 boolean blockIndexFound = false;
1755 for (int j = 0; j < numberOfBlocks; j++) {
1756 if (blockIndices[j] == i) {
1757 blockIndexFound = true;
1758 break;
1759 }
1760 }
1761 if (blockIndexFound) continue;
1762 return i;
1763 }
1764
1765 // No available index found, the pool has to grow
Chris Craik956f3402015-04-27 16:41:00 -07001766 mTextRenderNodes = GrowingArrayUtils.append(mTextRenderNodes, length, null);
Gilles Debunned88876a2012-03-16 17:34:04 -07001767 return length;
1768 }
1769
1770 private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
1771 final boolean translate = cursorOffsetVertical != 0;
1772 if (translate) canvas.translate(0, cursorOffsetVertical);
1773 for (int i = 0; i < mCursorCount; i++) {
1774 mCursorDrawable[i].draw(canvas);
1775 }
1776 if (translate) canvas.translate(0, -cursorOffsetVertical);
1777 }
1778
Gilles Debunneebc86af2012-04-20 15:10:47 -07001779 /**
1780 * Invalidates all the sub-display lists that overlap the specified character range
1781 */
1782 void invalidateTextDisplayList(Layout layout, int start, int end) {
Chris Craik956f3402015-04-27 16:41:00 -07001783 if (mTextRenderNodes != null && layout instanceof DynamicLayout) {
Gilles Debunneebc86af2012-04-20 15:10:47 -07001784 final int firstLine = layout.getLineForOffset(start);
1785 final int lastLine = layout.getLineForOffset(end);
1786
1787 DynamicLayout dynamicLayout = (DynamicLayout) layout;
1788 int[] blockEndLines = dynamicLayout.getBlockEndLines();
1789 int[] blockIndices = dynamicLayout.getBlockIndices();
1790 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1791
1792 int i = 0;
1793 // Skip the blocks before firstLine
1794 while (i < numberOfBlocks) {
1795 if (blockEndLines[i] >= firstLine) break;
1796 i++;
1797 }
1798
1799 // Invalidate all subsequent blocks until lastLine is passed
1800 while (i < numberOfBlocks) {
1801 final int blockIndex = blockIndices[i];
1802 if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
Chris Craik956f3402015-04-27 16:41:00 -07001803 mTextRenderNodes[blockIndex].isDirty = true;
Gilles Debunneebc86af2012-04-20 15:10:47 -07001804 }
1805 if (blockEndLines[i] >= lastLine) break;
1806 i++;
1807 }
1808 }
1809 }
1810
Gilles Debunned88876a2012-03-16 17:34:04 -07001811 void invalidateTextDisplayList() {
Chris Craik956f3402015-04-27 16:41:00 -07001812 if (mTextRenderNodes != null) {
1813 for (int i = 0; i < mTextRenderNodes.length; i++) {
1814 if (mTextRenderNodes[i] != null) mTextRenderNodes[i].isDirty = true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001815 }
1816 }
1817 }
1818
1819 void updateCursorsPositions() {
1820 if (mTextView.mCursorDrawableRes == 0) {
1821 mCursorCount = 0;
1822 return;
1823 }
1824
Mady Mellorff66ca52015-07-08 12:31:45 -07001825 Layout layout = getActiveLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -07001826 final int offset = mTextView.getSelectionStart();
1827 final int line = layout.getLineForOffset(offset);
1828 final int top = layout.getLineTop(line);
1829 final int bottom = layout.getLineTop(line + 1);
1830
1831 mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1;
1832
1833 int middle = bottom;
1834 if (mCursorCount == 2) {
1835 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
1836 middle = (top + bottom) >> 1;
1837 }
1838
Raph Levienafe8e9b2012-12-19 16:09:32 -08001839 boolean clamped = layout.shouldClampCursor(line);
Mady Mellorff66ca52015-07-08 12:31:45 -07001840 updateCursorPosition(0, top, middle, layout.getPrimaryHorizontal(offset, clamped));
Gilles Debunned88876a2012-03-16 17:34:04 -07001841
1842 if (mCursorCount == 2) {
Siyamed Sinir217c0f72016-02-01 18:30:02 -08001843 updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset, clamped));
Gilles Debunned88876a2012-03-16 17:34:04 -07001844 }
1845 }
1846
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001847 void refreshTextActionMode() {
1848 if (extractedTextModeWillBeStarted()) {
1849 return;
1850 }
1851 final boolean hasSelection = mTextView.hasSelection();
1852 final SelectionModifierCursorController selectionController = getSelectionController();
1853 final InsertionPointCursorController insertionController = getInsertionController();
1854 if ((selectionController != null && selectionController.isCursorBeingModified())
1855 || (insertionController != null && insertionController.isCursorBeingModified())) {
1856 // ActionMode should be managed by the currently active cursor controller.
1857 return;
1858 }
1859 if (hasSelection) {
1860 if (mTextActionMode == null || selectionController == null
1861 || !selectionController.isActive()) {
1862 // Avoid dismissing the selection if it exists.
1863 stopTextActionModeWithPreservingSelection();
1864 startSelectionActionMode();
1865 } else {
1866 mTextActionMode.invalidateContentRect();
1867 }
1868 } else {
1869 // Insertion action mode is started only when insertion controller is explicitly
1870 // activated.
1871 if (insertionController == null || !insertionController.isActive()) {
1872 stopTextActionMode();
1873 } else if (mTextActionMode != null) {
1874 mTextActionMode.invalidateContentRect();
1875 }
1876 }
1877 }
1878
Gilles Debunned88876a2012-03-16 17:34:04 -07001879 /**
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001880 * Start an Insertion action mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07001881 */
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001882 void startInsertionActionMode() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001883 if (mInsertionActionModeRunnable != null) {
1884 mTextView.removeCallbacks(mInsertionActionModeRunnable);
1885 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001886 if (extractedTextModeWillBeStarted()) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001887 return;
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001888 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001889 stopTextActionMode();
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001890
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001891 ActionMode.Callback actionModeCallback =
1892 new TextActionModeCallback(false /* hasSelection */);
1893 mTextActionMode = mTextView.startActionMode(
Clara Bayarrib8ed5b72015-04-09 15:26:41 +01001894 actionModeCallback, ActionMode.TYPE_FLOATING);
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001895 if (mTextActionMode != null && getInsertionController() != null) {
1896 getInsertionController().show();
1897 }
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001898 }
1899
1900 /**
Clara Bayarri578286f2015-04-10 15:35:31 +01001901 * Starts a Selection Action Mode with the current selection and ensures the selection handles
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001902 * are shown if there is a selection. This should be used when the mode is started from a
1903 * non-touch event.
Clara Bayarri578286f2015-04-10 15:35:31 +01001904 *
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001905 * @return true if the selection mode was actually started.
1906 */
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001907 private boolean startSelectionActionMode() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001908 boolean selectionStarted = startSelectionActionModeInternal();
Clara Bayarri578286f2015-04-10 15:35:31 +01001909 if (selectionStarted) {
1910 getSelectionController().show();
1911 }
1912 return selectionStarted;
1913 }
1914
Clara Bayarridfac4432015-05-15 12:18:24 +01001915 /**
1916 * If the TextView allows text selection, selects the current word when no existing selection
1917 * was available and starts a drag.
1918 *
1919 * @return true if the drag was started.
1920 */
1921 private boolean selectCurrentWordAndStartDrag() {
Clara Bayarri7184c8a2015-06-05 17:34:09 +01001922 if (mInsertionActionModeRunnable != null) {
1923 mTextView.removeCallbacks(mInsertionActionModeRunnable);
1924 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001925 if (extractedTextModeWillBeStarted()) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001926 return false;
1927 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001928 if (!checkField()) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001929 return false;
1930 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001931 if (!mTextView.hasSelection() && !selectCurrentWord()) {
1932 // No selection and cannot select a word.
1933 return false;
1934 }
1935 stopTextActionModeWithPreservingSelection();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08001936 getSelectionController().enterDrag(
1937 SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_WORD);
Clara Bayarridfac4432015-05-15 12:18:24 +01001938 return true;
1939 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001940
Clara Bayarridfac4432015-05-15 12:18:24 +01001941 /**
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001942 * Checks whether a selection can be performed on the current TextView.
Clara Bayarridfac4432015-05-15 12:18:24 +01001943 *
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001944 * @return true if a selection can be performed
Clara Bayarridfac4432015-05-15 12:18:24 +01001945 */
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001946 boolean checkField() {
Clara Bayarridfac4432015-05-15 12:18:24 +01001947 if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
1948 Log.w(TextView.LOG_TAG,
1949 "TextView does not support text selection. Selection cancelled.");
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001950 return false;
1951 }
Clara Bayarridfac4432015-05-15 12:18:24 +01001952 return true;
1953 }
1954
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001955 private boolean startSelectionActionModeInternal() {
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001956 if (extractedTextModeWillBeStarted()) {
1957 return false;
1958 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001959 if (mTextActionMode != null) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001960 // Text action mode is already started
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001961 mTextActionMode.invalidate();
Gilles Debunned88876a2012-03-16 17:34:04 -07001962 return false;
1963 }
1964
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001965 if (!checkField() || !mTextView.hasSelection()) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001966 return false;
1967 }
1968
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001969 ActionMode.Callback actionModeCallback =
1970 new TextActionModeCallback(true /* hasSelection */);
1971 mTextActionMode = mTextView.startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING);
Gilles Debunned88876a2012-03-16 17:34:04 -07001972
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08001973 final boolean selectionStarted = mTextActionMode != null;
Gilles Debunne3473b2b2012-04-20 16:21:10 -07001974 if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001975 // Show the IME to be able to replace text, except when selecting non editable text.
1976 final InputMethodManager imm = InputMethodManager.peekInstance();
1977 if (imm != null) {
1978 imm.showSoftInput(mTextView, 0, null);
1979 }
1980 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001981 return selectionStarted;
1982 }
1983
Andrei Stingaceanu99d3bbd2015-06-30 16:57:03 +01001984 boolean extractedTextModeWillBeStarted() {
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001985 if (!(mTextView.isInExtractedMode())) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001986 final InputMethodManager imm = InputMethodManager.peekInstance();
1987 return imm != null && imm.isFullscreenMode();
1988 }
1989 return false;
1990 }
1991
1992 /**
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09001993 * @return <code>true</code> if it's reasonable to offer to show suggestions depending on
1994 * the current cursor position or selection range. This method is consistent with the
1995 * method to show suggestions {@link SuggestionsPopupWindow#updateSuggestions}.
Gilles Debunned88876a2012-03-16 17:34:04 -07001996 */
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09001997 private boolean shouldOfferToShowSuggestions() {
Gilles Debunned88876a2012-03-16 17:34:04 -07001998 CharSequence text = mTextView.getText();
1999 if (!(text instanceof Spannable)) return false;
2000
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002001 final Spannable spannable = (Spannable) text;
2002 final int selectionStart = mTextView.getSelectionStart();
2003 final int selectionEnd = mTextView.getSelectionEnd();
2004 final SuggestionSpan[] suggestionSpans = spannable.getSpans(selectionStart, selectionEnd,
2005 SuggestionSpan.class);
2006 if (suggestionSpans.length == 0) {
2007 return false;
2008 }
2009 if (selectionStart == selectionEnd) {
2010 // Spans overlap the cursor.
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002011 for (int i = 0; i < suggestionSpans.length; i++) {
2012 if (suggestionSpans[i].getSuggestions().length > 0) {
2013 return true;
2014 }
2015 }
2016 return false;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002017 }
2018 int minSpanStart = mTextView.getText().length();
2019 int maxSpanEnd = 0;
2020 int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length();
2021 int unionOfSpansCoveringSelectionStartEnd = 0;
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002022 boolean hasValidSuggestions = false;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002023 for (int i = 0; i < suggestionSpans.length; i++) {
2024 final int spanStart = spannable.getSpanStart(suggestionSpans[i]);
2025 final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]);
2026 minSpanStart = Math.min(minSpanStart, spanStart);
2027 maxSpanEnd = Math.max(maxSpanEnd, spanEnd);
2028 if (selectionStart < spanStart || selectionStart > spanEnd) {
2029 // The span doesn't cover the current selection start point.
2030 continue;
2031 }
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002032 hasValidSuggestions =
2033 hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002034 unionOfSpansCoveringSelectionStartStart =
2035 Math.min(unionOfSpansCoveringSelectionStartStart, spanStart);
2036 unionOfSpansCoveringSelectionStartEnd =
2037 Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd);
2038 }
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002039 if (!hasValidSuggestions) {
2040 return false;
2041 }
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002042 if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) {
2043 // No spans cover the selection start point.
2044 return false;
2045 }
2046 if (minSpanStart < unionOfSpansCoveringSelectionStartStart
2047 || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) {
2048 // There is a span that is not covered by the union. In this case, we soouldn't offer
2049 // to show suggestions as it's confusing.
2050 return false;
2051 }
2052 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -07002053 }
2054
2055 /**
2056 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
2057 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
2058 */
2059 private boolean isCursorInsideEasyCorrectionSpan() {
2060 Spannable spannable = (Spannable) mTextView.getText();
2061 SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
2062 mTextView.getSelectionEnd(), SuggestionSpan.class);
2063 for (int i = 0; i < suggestionSpans.length; i++) {
2064 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
2065 return true;
2066 }
2067 }
2068 return false;
2069 }
2070
2071 void onTouchUpEvent(MotionEvent event) {
2072 boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
Mady Mellora2861452015-06-25 08:40:27 -07002073 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002074 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07002075 CharSequence text = mTextView.getText();
2076 if (!selectAllGotFocus && text.length() > 0) {
2077 // Move cursor
2078 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2079 Selection.setSelection((Spannable) text, offset);
2080 if (mSpellChecker != null) {
2081 // When the cursor moves, the word that was typed may need spell check
2082 mSpellChecker.onSelectionChanged();
2083 }
Andrei Stingaceanu35c550c2015-05-07 16:49:49 +01002084
Gilles Debunned88876a2012-03-16 17:34:04 -07002085 if (!extractedTextModeWillBeStarted()) {
2086 if (isCursorInsideEasyCorrectionSpan()) {
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01002087 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002088 if (mInsertionActionModeRunnable != null) {
2089 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01002090 }
2091
Gilles Debunned88876a2012-03-16 17:34:04 -07002092 mShowSuggestionRunnable = new Runnable() {
2093 public void run() {
Keisuke Kuroyanagi713be062016-02-29 16:07:54 -08002094 replace();
Gilles Debunned88876a2012-03-16 17:34:04 -07002095 }
2096 };
2097 // removeCallbacks is performed on every touch
2098 mTextView.postDelayed(mShowSuggestionRunnable,
2099 ViewConfiguration.getDoubleTapTimeout());
2100 } else if (hasInsertionController()) {
2101 getInsertionController().show();
2102 }
2103 }
2104 }
2105 }
2106
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002107 protected void stopTextActionMode() {
2108 if (mTextActionMode != null) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002109 // This will hide the mSelectionModifierCursorController
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002110 mTextActionMode.finish();
Gilles Debunned88876a2012-03-16 17:34:04 -07002111 }
2112 }
2113
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002114 private void stopTextActionModeWithPreservingSelection() {
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08002115 mPreserveSelection = true;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002116 stopTextActionMode();
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08002117 mPreserveSelection = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002118 }
2119
Gilles Debunned88876a2012-03-16 17:34:04 -07002120 /**
2121 * @return True if this view supports insertion handles.
2122 */
2123 boolean hasInsertionController() {
2124 return mInsertionControllerEnabled;
2125 }
2126
2127 /**
2128 * @return True if this view supports selection handles.
2129 */
2130 boolean hasSelectionController() {
2131 return mSelectionControllerEnabled;
2132 }
2133
2134 InsertionPointCursorController getInsertionController() {
2135 if (!mInsertionControllerEnabled) {
2136 return null;
2137 }
2138
2139 if (mInsertionPointCursorController == null) {
2140 mInsertionPointCursorController = new InsertionPointCursorController();
2141
2142 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2143 observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
2144 }
2145
2146 return mInsertionPointCursorController;
2147 }
2148
2149 SelectionModifierCursorController getSelectionController() {
2150 if (!mSelectionControllerEnabled) {
2151 return null;
2152 }
2153
2154 if (mSelectionModifierCursorController == null) {
2155 mSelectionModifierCursorController = new SelectionModifierCursorController();
2156
2157 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2158 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
2159 }
2160
2161 return mSelectionModifierCursorController;
2162 }
2163
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002164 /**
2165 * @hide
2166 */
2167 @VisibleForTesting
2168 public Drawable[] getCursorDrawable() {
2169 return mCursorDrawable;
2170 }
2171
Gilles Debunned88876a2012-03-16 17:34:04 -07002172 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
2173 if (mCursorDrawable[cursorIndex] == null)
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002174 mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07002175 mTextView.mCursorDrawableRes);
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002176 final Drawable drawable = mCursorDrawable[cursorIndex];
2177 final int left = clampCursorHorizontalPosition(drawable, horizontal);
2178 final int width = drawable.getIntrinsicWidth();
2179 drawable.setBounds(left, top - mTempRect.top, left + width,
Gilles Debunned88876a2012-03-16 17:34:04 -07002180 bottom + mTempRect.bottom);
2181 }
2182
2183 /**
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002184 * Return clamped position for the cursor. If the cursor is within the boundaries of the view,
2185 * then it is offset with the left padding of the cursor drawable. If the cursor is at
2186 * the beginning or the end of the text then its drawable edge is aligned with left or right of
2187 * the view boundary.
2188 *
2189 * @param drawable Cursor drawable.
2190 * @param horizontal Horizontal position for the cursor.
2191 * @return The clamped horizontal position for the cursor.
2192 */
2193 private final int clampCursorHorizontalPosition(final Drawable drawable, float
2194 horizontal) {
2195 horizontal = Math.max(0.5f, horizontal - 0.5f);
2196 if (mTempRect == null) mTempRect = new Rect();
2197 drawable.getPadding(mTempRect);
2198 int scrollX = mTextView.getScrollX();
2199 float horizontalDiff = horizontal - scrollX;
2200 int viewClippedWidth = mTextView.getWidth() - mTextView.getCompoundPaddingLeft()
2201 - mTextView.getCompoundPaddingRight();
2202
2203 final int left;
2204 if (horizontalDiff >= (viewClippedWidth - 1f)) {
2205 // at the rightmost position
2206 final int cursorWidth = drawable.getIntrinsicWidth();
2207 left = viewClippedWidth + scrollX - (cursorWidth - mTempRect.right);
2208 } else if (Math.abs(horizontalDiff) <= 1f) {
2209 // at the leftmost position
2210 left = scrollX - mTempRect.left;
2211 } else {
2212 left = (int) horizontal - mTempRect.left;
2213 }
2214 return left;
2215 }
2216
2217 /**
Gilles Debunned88876a2012-03-16 17:34:04 -07002218 * 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 -08002219 * a dictionary) from the current input method, provided by it calling
Gilles Debunned88876a2012-03-16 17:34:04 -07002220 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
2221 * implementation flashes the background of the corrected word to provide feedback to the user.
2222 *
2223 * @param info The auto correct info about the text that was corrected.
2224 */
2225 public void onCommitCorrection(CorrectionInfo info) {
2226 if (mCorrectionHighlighter == null) {
2227 mCorrectionHighlighter = new CorrectionHighlighter();
2228 } else {
2229 mCorrectionHighlighter.invalidate(false);
2230 }
2231
2232 mCorrectionHighlighter.highlight(info);
2233 }
2234
Gilles Debunned88876a2012-03-16 17:34:04 -07002235 void onScrollChanged() {
Gilles Debunne157aafc2012-04-19 17:21:57 -07002236 if (mPositionListener != null) {
2237 mPositionListener.onScrollChanged();
2238 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002239 if (mTextActionMode != null) {
2240 mTextActionMode.invalidateContentRect();
Abodunrinwa Toki56195db2015-04-22 06:46:54 +01002241 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002242 }
2243
2244 /**
2245 * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
2246 */
2247 private boolean shouldBlink() {
2248 if (!isCursorVisible() || !mTextView.isFocused()) return false;
2249
2250 final int start = mTextView.getSelectionStart();
2251 if (start < 0) return false;
2252
2253 final int end = mTextView.getSelectionEnd();
2254 if (end < 0) return false;
2255
2256 return start == end;
2257 }
2258
2259 void makeBlink() {
2260 if (shouldBlink()) {
2261 mShowCursor = SystemClock.uptimeMillis();
2262 if (mBlink == null) mBlink = new Blink();
John Reckd0374c62015-10-20 13:25:01 -07002263 mTextView.removeCallbacks(mBlink);
2264 mTextView.postDelayed(mBlink, BLINK);
Gilles Debunned88876a2012-03-16 17:34:04 -07002265 } else {
John Reckd0374c62015-10-20 13:25:01 -07002266 if (mBlink != null) mTextView.removeCallbacks(mBlink);
Gilles Debunned88876a2012-03-16 17:34:04 -07002267 }
2268 }
2269
John Reckd0374c62015-10-20 13:25:01 -07002270 private class Blink implements Runnable {
Gilles Debunned88876a2012-03-16 17:34:04 -07002271 private boolean mCancelled;
2272
2273 public void run() {
Gilles Debunned88876a2012-03-16 17:34:04 -07002274 if (mCancelled) {
2275 return;
2276 }
2277
John Reckd0374c62015-10-20 13:25:01 -07002278 mTextView.removeCallbacks(this);
Gilles Debunned88876a2012-03-16 17:34:04 -07002279
2280 if (shouldBlink()) {
2281 if (mTextView.getLayout() != null) {
2282 mTextView.invalidateCursorPath();
2283 }
2284
John Reckd0374c62015-10-20 13:25:01 -07002285 mTextView.postDelayed(this, BLINK);
Gilles Debunned88876a2012-03-16 17:34:04 -07002286 }
2287 }
2288
2289 void cancel() {
2290 if (!mCancelled) {
John Reckd0374c62015-10-20 13:25:01 -07002291 mTextView.removeCallbacks(this);
Gilles Debunned88876a2012-03-16 17:34:04 -07002292 mCancelled = true;
2293 }
2294 }
2295
2296 void uncancel() {
2297 mCancelled = false;
2298 }
2299 }
2300
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08002301 private DragShadowBuilder getTextThumbnailBuilder(int start, int end) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002302 TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
2303 com.android.internal.R.layout.text_drag_thumbnail, null);
2304
2305 if (shadowView == null) {
2306 throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
2307 }
2308
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08002309 if (end - start > DRAG_SHADOW_MAX_TEXT_LENGTH) {
2310 final long range = getCharClusterRange(start + DRAG_SHADOW_MAX_TEXT_LENGTH);
2311 end = TextUtils.unpackRangeEndFromLong(range);
Gilles Debunned88876a2012-03-16 17:34:04 -07002312 }
Keisuke Kuroyanagi5396d7e2016-02-19 15:28:26 -08002313 final CharSequence text = mTextView.getTransformedText(start, end);
Gilles Debunned88876a2012-03-16 17:34:04 -07002314 shadowView.setText(text);
2315 shadowView.setTextColor(mTextView.getTextColors());
2316
Alan Viverettebb98ebd2015-05-08 17:17:44 -07002317 shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge);
Gilles Debunned88876a2012-03-16 17:34:04 -07002318 shadowView.setGravity(Gravity.CENTER);
2319
2320 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2321 ViewGroup.LayoutParams.WRAP_CONTENT));
2322
2323 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
2324 shadowView.measure(size, size);
2325
2326 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
2327 shadowView.invalidate();
2328 return new DragShadowBuilder(shadowView);
2329 }
2330
2331 private static class DragLocalState {
2332 public TextView sourceTextView;
2333 public int start, end;
2334
2335 public DragLocalState(TextView sourceTextView, int start, int end) {
2336 this.sourceTextView = sourceTextView;
2337 this.start = start;
2338 this.end = end;
2339 }
2340 }
2341
2342 void onDrop(DragEvent event) {
2343 StringBuilder content = new StringBuilder("");
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -08002344
2345 final DropPermissions dropPermissions = DropPermissions.obtain(event);
2346 if (dropPermissions != null) {
2347 dropPermissions.takeTransient();
2348 }
2349
2350 try {
2351 ClipData clipData = event.getClipData();
2352 final int itemCount = clipData.getItemCount();
2353 for (int i=0; i < itemCount; i++) {
2354 Item item = clipData.getItemAt(i);
2355 content.append(item.coerceToStyledText(mTextView.getContext()));
2356 }
2357 }
2358 finally {
2359 if (dropPermissions != null) {
2360 dropPermissions.release();
2361 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002362 }
2363
2364 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2365
2366 Object localState = event.getLocalState();
2367 DragLocalState dragLocalState = null;
2368 if (localState instanceof DragLocalState) {
2369 dragLocalState = (DragLocalState) localState;
2370 }
2371 boolean dragDropIntoItself = dragLocalState != null &&
2372 dragLocalState.sourceTextView == mTextView;
2373
2374 if (dragDropIntoItself) {
2375 if (offset >= dragLocalState.start && offset < dragLocalState.end) {
2376 // A drop inside the original selection discards the drop.
2377 return;
2378 }
2379 }
2380
2381 final int originalLength = mTextView.getText().length();
Raph Levien5a689ce2014-09-10 11:03:18 -07002382 int min = offset;
2383 int max = offset;
Gilles Debunned88876a2012-03-16 17:34:04 -07002384
2385 Selection.setSelection((Spannable) mTextView.getText(), max);
2386 mTextView.replaceText_internal(min, max, content);
2387
2388 if (dragDropIntoItself) {
2389 int dragSourceStart = dragLocalState.start;
2390 int dragSourceEnd = dragLocalState.end;
2391 if (max <= dragSourceStart) {
2392 // Inserting text before selection has shifted positions
2393 final int shift = mTextView.getText().length() - originalLength;
2394 dragSourceStart += shift;
2395 dragSourceEnd += shift;
2396 }
2397
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08002398 mUndoInputFilter.setForceMerge(true);
2399 try {
2400 // Delete original selection
2401 mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
Gilles Debunned88876a2012-03-16 17:34:04 -07002402
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08002403 // Make sure we do not leave two adjacent spaces.
2404 final int prevCharIdx = Math.max(0, dragSourceStart - 1);
2405 final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1);
2406 if (nextCharIdx > prevCharIdx + 1) {
2407 CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx);
2408 if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) {
2409 mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1);
2410 }
Victoria Lease91373202012-09-07 16:41:59 -07002411 }
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08002412 } finally {
2413 mUndoInputFilter.setForceMerge(false);
Gilles Debunned88876a2012-03-16 17:34:04 -07002414 }
2415 }
2416 }
2417
Gilles Debunnec62589c2012-04-12 14:50:23 -07002418 public void addSpanWatchers(Spannable text) {
2419 final int textLength = text.length();
2420
2421 if (mKeyListener != null) {
2422 text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2423 }
2424
Jean Chalardbaf30942013-02-28 16:01:51 -08002425 if (mSpanController == null) {
2426 mSpanController = new SpanController();
Gilles Debunnec62589c2012-04-12 14:50:23 -07002427 }
Jean Chalardbaf30942013-02-28 16:01:51 -08002428 text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002429 }
2430
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002431 void setContextMenuAnchor(float x, float y) {
2432 mContextMenuAnchorX = x;
2433 mContextMenuAnchorY = y;
2434 }
2435
2436 void onCreateContextMenu(ContextMenu menu) {
2437 if (mIsBeingLongClicked || Float.isNaN(mContextMenuAnchorX)
2438 || Float.isNaN(mContextMenuAnchorY)) {
2439 return;
2440 }
2441 final int offset = mTextView.getOffsetForPosition(mContextMenuAnchorX, mContextMenuAnchorY);
2442 if (offset == -1) {
2443 return;
2444 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002445 stopTextActionModeWithPreservingSelection();
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002446 final boolean isOnSelection = mTextView.hasSelection()
2447 && offset >= mTextView.getSelectionStart() && offset <= mTextView.getSelectionEnd();
2448 if (!isOnSelection) {
2449 // Right clicked position is not on the selection. Remove the selection and move the
2450 // cursor to the right clicked position.
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002451 Selection.setSelection((Spannable) mTextView.getText(), offset);
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08002452 stopTextActionMode();
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002453 }
2454
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002455 if (shouldOfferToShowSuggestions()) {
Keisuke Kuroyanagi182f5fe2016-03-11 16:31:29 +09002456 final SuggestionInfo[] suggestionInfoArray =
2457 new SuggestionInfo[SuggestionSpan.SUGGESTIONS_MAX_SIZE];
2458 for (int i = 0; i < suggestionInfoArray.length; i++) {
2459 suggestionInfoArray[i] = new SuggestionInfo();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002460 }
2461 final SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, MENU_ITEM_ORDER_REPLACE,
2462 com.android.internal.R.string.replace);
Keisuke Kuroyanagi182f5fe2016-03-11 16:31:29 +09002463 final int numItems = mSuggestionHelper.getSuggestionInfo(suggestionInfoArray);
2464 for (int i = 0; i < numItems; i++) {
2465 final SuggestionInfo info = suggestionInfoArray[i];
2466 subMenu.add(Menu.NONE, Menu.NONE, i, info.mText)
2467 .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2468 @Override
2469 public boolean onMenuItemClick(MenuItem item) {
2470 replaceWithSuggestion(info);
2471 return true;
2472 }
2473 });
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002474 }
2475 }
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002476
2477 menu.add(Menu.NONE, TextView.ID_UNDO, MENU_ITEM_ORDER_UNDO,
2478 com.android.internal.R.string.undo)
2479 .setAlphabeticShortcut('z')
2480 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2481 .setEnabled(mTextView.canUndo());
2482 menu.add(Menu.NONE, TextView.ID_REDO, MENU_ITEM_ORDER_REDO,
2483 com.android.internal.R.string.redo)
2484 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2485 .setEnabled(mTextView.canRedo());
2486
2487 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
2488 com.android.internal.R.string.cut)
2489 .setAlphabeticShortcut('x')
2490 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2491 .setEnabled(mTextView.canCut());
2492 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
2493 com.android.internal.R.string.copy)
2494 .setAlphabeticShortcut('c')
2495 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2496 .setEnabled(mTextView.canCopy());
2497 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
2498 com.android.internal.R.string.paste)
2499 .setAlphabeticShortcut('v')
2500 .setEnabled(mTextView.canPaste())
2501 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2502 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT,
2503 com.android.internal.R.string.paste_as_plain_text)
2504 .setEnabled(mTextView.canPaste())
2505 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2506 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
2507 com.android.internal.R.string.share)
2508 .setEnabled(mTextView.canShare())
2509 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2510 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
2511 com.android.internal.R.string.selectAll)
2512 .setAlphabeticShortcut('a')
2513 .setEnabled(mTextView.canSelectAllText())
2514 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2515
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08002516 mPreserveSelection = true;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002517 }
2518
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08002519 private void replaceWithSuggestion(final SuggestionInfo suggestionInfo) {
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002520 final Editable editable = (Editable) mTextView.getText();
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08002521 if (editable.getSpanStart(suggestionInfo.mSuggestionSpan) < 0) {
2522 // Suggestion span coundn't be found. Try to find a suggestion span that has the same
2523 // contents.
2524 final SuggestionSpan[] suggestionSpans = editable.getSpans(
2525 suggestionInfo.mSuggestionSpanStart, suggestionInfo.mSuggestionSpanEnd,
2526 SuggestionSpan.class);
2527 for (final SuggestionSpan suggestionSpan : suggestionSpans) {
2528 final int spanStart = editable.getSpanStart(suggestionSpan);
2529 if (spanStart != suggestionInfo.mSuggestionSpanStart) {
2530 continue;
2531 }
2532 int spanEnd = editable.getSpanEnd(suggestionSpan);
2533 if (spanEnd != suggestionInfo.mSuggestionSpanEnd) {
2534 continue;
2535 }
2536 if (suggestionSpan.equals(suggestionInfo.mSuggestionSpan)) {
2537 // Found.
2538 suggestionInfo.mSuggestionSpan = suggestionSpan;
2539 break;
2540 }
2541 }
2542 }
2543 final int spanStart = editable.getSpanStart(suggestionInfo.mSuggestionSpan);
2544 final int spanEnd = editable.getSpanEnd(suggestionInfo.mSuggestionSpan);
2545 if (spanStart < 0 || spanEnd <= spanStart) {
2546 // Span has been removed
2547 return;
2548 }
2549
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002550 final String originalText = TextUtils.substring(editable, spanStart, spanEnd);
2551 // SuggestionSpans are removed by replace: save them before
2552 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
2553 SuggestionSpan.class);
2554 final int length = suggestionSpans.length;
2555 int[] suggestionSpansStarts = new int[length];
2556 int[] suggestionSpansEnds = new int[length];
2557 int[] suggestionSpansFlags = new int[length];
2558 for (int i = 0; i < length; i++) {
2559 final SuggestionSpan suggestionSpan = suggestionSpans[i];
2560 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
2561 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
2562 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
2563
2564 // Remove potential misspelled flags
2565 int suggestionSpanFlags = suggestionSpan.getFlags();
2566 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2567 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
2568 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
2569 suggestionSpan.setFlags(suggestionSpanFlags);
2570 }
2571 }
2572
2573 // Notify source IME of the suggestion pick. Do this before swapping texts.
2574 suggestionInfo.mSuggestionSpan.notifySelection(
2575 mTextView.getContext(), originalText, suggestionInfo.mSuggestionIndex);
2576
2577 // Swap text content between actual text and Suggestion span
2578 final int suggestionStart = suggestionInfo.mSuggestionStart;
2579 final int suggestionEnd = suggestionInfo.mSuggestionEnd;
2580 final String suggestion = suggestionInfo.mText.subSequence(
2581 suggestionStart, suggestionEnd).toString();
2582 mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
2583
2584 String[] suggestions = suggestionInfo.mSuggestionSpan.getSuggestions();
2585 suggestions[suggestionInfo.mSuggestionIndex] = originalText;
2586
2587 // Restore previous SuggestionSpans
2588 final int lengthDelta = suggestion.length() - (spanEnd - spanStart);
2589 for (int i = 0; i < length; i++) {
2590 // Only spans that include the modified region make sense after replacement
2591 // Spans partially included in the replaced region are removed, there is no
2592 // way to assign them a valid range after replacement
2593 if (suggestionSpansStarts[i] <= spanStart && suggestionSpansEnds[i] >= spanEnd) {
2594 mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
2595 suggestionSpansEnds[i] + lengthDelta, suggestionSpansFlags[i]);
2596 }
2597 }
2598 // Move cursor at the end of the replaced word
2599 final int newCursorPosition = spanEnd + lengthDelta;
2600 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
2601 }
2602
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002603 private final MenuItem.OnMenuItemClickListener mOnContextMenuItemClickListener =
2604 new MenuItem.OnMenuItemClickListener() {
2605 @Override
2606 public boolean onMenuItemClick(MenuItem item) {
2607 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
2608 return true;
2609 }
2610 return mTextView.onTextContextMenuItem(item.getItemId());
2611 }
2612 };
2613
Gilles Debunned88876a2012-03-16 17:34:04 -07002614 /**
2615 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
2616 * pop-up should be displayed.
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07002617 * Also monitors {@link Selection} to call back to the attached input method.
Gilles Debunned88876a2012-03-16 17:34:04 -07002618 */
Jean Chalardbaf30942013-02-28 16:01:51 -08002619 class SpanController implements SpanWatcher {
Gilles Debunned88876a2012-03-16 17:34:04 -07002620
2621 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
2622
2623 private EasyEditPopupWindow mPopupWindow;
2624
Gilles Debunned88876a2012-03-16 17:34:04 -07002625 private Runnable mHidePopup;
2626
Jean Chalardbaf30942013-02-28 16:01:51 -08002627 // This function is pure but inner classes can't have static functions
2628 private boolean isNonIntermediateSelectionSpan(final Spannable text,
2629 final Object span) {
2630 return (Selection.SELECTION_START == span || Selection.SELECTION_END == span)
2631 && (text.getSpanFlags(span) & Spanned.SPAN_INTERMEDIATE) == 0;
2632 }
2633
Gilles Debunnec62589c2012-04-12 14:50:23 -07002634 @Override
2635 public void onSpanAdded(Spannable text, Object span, int start, int end) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002636 if (isNonIntermediateSelectionSpan(text, span)) {
2637 sendUpdateSelection();
2638 } else if (span instanceof EasyEditSpan) {
Gilles Debunnec62589c2012-04-12 14:50:23 -07002639 if (mPopupWindow == null) {
2640 mPopupWindow = new EasyEditPopupWindow();
2641 mHidePopup = new Runnable() {
2642 @Override
2643 public void run() {
2644 hide();
2645 }
2646 };
2647 }
2648
2649 // Make sure there is only at most one EasyEditSpan in the text
2650 if (mPopupWindow.mEasyEditSpan != null) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002651 mPopupWindow.mEasyEditSpan.setDeleteEnabled(false);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002652 }
2653
2654 mPopupWindow.setEasyEditSpan((EasyEditSpan) span);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002655 mPopupWindow.setOnDeleteListener(new EasyEditDeleteListener() {
2656 @Override
2657 public void onDeleteClick(EasyEditSpan span) {
2658 Editable editable = (Editable) mTextView.getText();
2659 int start = editable.getSpanStart(span);
2660 int end = editable.getSpanEnd(span);
2661 if (start >= 0 && end >= 0) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002662 sendEasySpanNotification(EasyEditSpan.TEXT_DELETED, span);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002663 mTextView.deleteText_internal(start, end);
2664 }
2665 editable.removeSpan(span);
2666 }
2667 });
Gilles Debunnec62589c2012-04-12 14:50:23 -07002668
2669 if (mTextView.getWindowVisibility() != View.VISIBLE) {
2670 // The window is not visible yet, ignore the text change.
2671 return;
2672 }
2673
2674 if (mTextView.getLayout() == null) {
2675 // The view has not been laid out yet, ignore the text change
2676 return;
2677 }
2678
2679 if (extractedTextModeWillBeStarted()) {
2680 // The input is in extract mode. Do not handle the easy edit in
2681 // the original TextView, as the ExtractEditText will do
2682 return;
2683 }
2684
2685 mPopupWindow.show();
2686 mTextView.removeCallbacks(mHidePopup);
2687 mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
2688 }
2689 }
2690
2691 @Override
2692 public void onSpanRemoved(Spannable text, Object span, int start, int end) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002693 if (isNonIntermediateSelectionSpan(text, span)) {
2694 sendUpdateSelection();
2695 } else if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) {
Gilles Debunnec62589c2012-04-12 14:50:23 -07002696 hide();
2697 }
2698 }
2699
2700 @Override
2701 public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd,
2702 int newStart, int newEnd) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002703 if (isNonIntermediateSelectionSpan(text, span)) {
2704 sendUpdateSelection();
2705 } else if (mPopupWindow != null && span instanceof EasyEditSpan) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002706 EasyEditSpan easyEditSpan = (EasyEditSpan) span;
Jean Chalardbaf30942013-02-28 16:01:51 -08002707 sendEasySpanNotification(EasyEditSpan.TEXT_MODIFIED, easyEditSpan);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002708 text.removeSpan(easyEditSpan);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002709 }
2710 }
2711
Gilles Debunned88876a2012-03-16 17:34:04 -07002712 public void hide() {
2713 if (mPopupWindow != null) {
2714 mPopupWindow.hide();
2715 mTextView.removeCallbacks(mHidePopup);
2716 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002717 }
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002718
Jean Chalardbaf30942013-02-28 16:01:51 -08002719 private void sendEasySpanNotification(int textChangedType, EasyEditSpan span) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002720 try {
2721 PendingIntent pendingIntent = span.getPendingIntent();
2722 if (pendingIntent != null) {
2723 Intent intent = new Intent();
2724 intent.putExtra(EasyEditSpan.EXTRA_TEXT_CHANGED_TYPE, textChangedType);
2725 pendingIntent.send(mTextView.getContext(), 0, intent);
2726 }
2727 } catch (CanceledException e) {
2728 // This should not happen, as we should try to send the intent only once.
2729 Log.w(TAG, "PendingIntent for notification cannot be sent", e);
2730 }
2731 }
2732 }
2733
2734 /**
2735 * Listens for the delete event triggered by {@link EasyEditPopupWindow}.
2736 */
2737 private interface EasyEditDeleteListener {
2738
2739 /**
2740 * Clicks the delete pop-up.
2741 */
2742 void onDeleteClick(EasyEditSpan span);
Gilles Debunned88876a2012-03-16 17:34:04 -07002743 }
2744
2745 /**
2746 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07002747 * by {@link SpanController}.
Gilles Debunned88876a2012-03-16 17:34:04 -07002748 */
2749 private class EasyEditPopupWindow extends PinnedPopupWindow
2750 implements OnClickListener {
2751 private static final int POPUP_TEXT_LAYOUT =
2752 com.android.internal.R.layout.text_edit_action_popup_text;
2753 private TextView mDeleteTextView;
2754 private EasyEditSpan mEasyEditSpan;
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002755 private EasyEditDeleteListener mOnDeleteListener;
Gilles Debunned88876a2012-03-16 17:34:04 -07002756
2757 @Override
2758 protected void createPopupWindow() {
2759 mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2760 com.android.internal.R.attr.textSelectHandleWindowStyle);
2761 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2762 mPopupWindow.setClippingEnabled(true);
2763 }
2764
2765 @Override
2766 protected void initContentView() {
2767 LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2768 linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2769 mContentView = linearLayout;
2770 mContentView.setBackgroundResource(
2771 com.android.internal.R.drawable.text_edit_side_paste_window);
2772
2773 LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
2774 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2775
2776 LayoutParams wrapContent = new LayoutParams(
2777 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2778
2779 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2780 mDeleteTextView.setLayoutParams(wrapContent);
2781 mDeleteTextView.setText(com.android.internal.R.string.delete);
2782 mDeleteTextView.setOnClickListener(this);
2783 mContentView.addView(mDeleteTextView);
2784 }
2785
Gilles Debunnec62589c2012-04-12 14:50:23 -07002786 public void setEasyEditSpan(EasyEditSpan easyEditSpan) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002787 mEasyEditSpan = easyEditSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07002788 }
2789
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002790 private void setOnDeleteListener(EasyEditDeleteListener listener) {
2791 mOnDeleteListener = listener;
2792 }
2793
Gilles Debunned88876a2012-03-16 17:34:04 -07002794 @Override
2795 public void onClick(View view) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002796 if (view == mDeleteTextView
2797 && mEasyEditSpan != null && mEasyEditSpan.isDeleteEnabled()
2798 && mOnDeleteListener != null) {
2799 mOnDeleteListener.onDeleteClick(mEasyEditSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07002800 }
2801 }
2802
2803 @Override
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002804 public void hide() {
2805 if (mEasyEditSpan != null) {
2806 mEasyEditSpan.setDeleteEnabled(false);
2807 }
2808 mOnDeleteListener = null;
2809 super.hide();
2810 }
2811
2812 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07002813 protected int getTextOffset() {
2814 // Place the pop-up at the end of the span
2815 Editable editable = (Editable) mTextView.getText();
2816 return editable.getSpanEnd(mEasyEditSpan);
2817 }
2818
2819 @Override
2820 protected int getVerticalLocalPosition(int line) {
2821 return mTextView.getLayout().getLineBottom(line);
2822 }
2823
2824 @Override
2825 protected int clipVertically(int positionY) {
2826 // As we display the pop-up below the span, no vertical clipping is required.
2827 return positionY;
2828 }
2829 }
2830
2831 private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
2832 // 3 handles
2833 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09002834 // 1 CursorAnchorInfoNotifier
2835 private final int MAXIMUM_NUMBER_OF_LISTENERS = 7;
Gilles Debunned88876a2012-03-16 17:34:04 -07002836 private TextViewPositionListener[] mPositionListeners =
2837 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
2838 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
2839 private boolean mPositionHasChanged = true;
2840 // Absolute position of the TextView with respect to its parent window
2841 private int mPositionX, mPositionY;
2842 private int mNumberOfListeners;
2843 private boolean mScrollHasChanged;
2844 final int[] mTempCoords = new int[2];
2845
2846 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2847 if (mNumberOfListeners == 0) {
2848 updatePosition();
2849 ViewTreeObserver vto = mTextView.getViewTreeObserver();
2850 vto.addOnPreDrawListener(this);
2851 }
2852
2853 int emptySlotIndex = -1;
2854 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2855 TextViewPositionListener listener = mPositionListeners[i];
2856 if (listener == positionListener) {
2857 return;
2858 } else if (emptySlotIndex < 0 && listener == null) {
2859 emptySlotIndex = i;
2860 }
2861 }
2862
2863 mPositionListeners[emptySlotIndex] = positionListener;
2864 mCanMove[emptySlotIndex] = canMove;
2865 mNumberOfListeners++;
2866 }
2867
2868 public void removeSubscriber(TextViewPositionListener positionListener) {
2869 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2870 if (mPositionListeners[i] == positionListener) {
2871 mPositionListeners[i] = null;
2872 mNumberOfListeners--;
2873 break;
2874 }
2875 }
2876
2877 if (mNumberOfListeners == 0) {
2878 ViewTreeObserver vto = mTextView.getViewTreeObserver();
2879 vto.removeOnPreDrawListener(this);
2880 }
2881 }
2882
2883 public int getPositionX() {
2884 return mPositionX;
2885 }
2886
2887 public int getPositionY() {
2888 return mPositionY;
2889 }
2890
2891 @Override
2892 public boolean onPreDraw() {
2893 updatePosition();
2894
2895 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2896 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2897 TextViewPositionListener positionListener = mPositionListeners[i];
2898 if (positionListener != null) {
2899 positionListener.updatePosition(mPositionX, mPositionY,
2900 mPositionHasChanged, mScrollHasChanged);
2901 }
2902 }
2903 }
2904
2905 mScrollHasChanged = false;
2906 return true;
2907 }
2908
2909 private void updatePosition() {
2910 mTextView.getLocationInWindow(mTempCoords);
2911
2912 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2913
2914 mPositionX = mTempCoords[0];
2915 mPositionY = mTempCoords[1];
2916 }
2917
2918 public void onScrollChanged() {
2919 mScrollHasChanged = true;
2920 }
2921 }
2922
2923 private abstract class PinnedPopupWindow implements TextViewPositionListener {
2924 protected PopupWindow mPopupWindow;
2925 protected ViewGroup mContentView;
2926 int mPositionX, mPositionY;
Seigo Nonaka60490d12016-01-28 17:25:18 +09002927 int mClippingLimitLeft, mClippingLimitRight;
Gilles Debunned88876a2012-03-16 17:34:04 -07002928
2929 protected abstract void createPopupWindow();
2930 protected abstract void initContentView();
2931 protected abstract int getTextOffset();
2932 protected abstract int getVerticalLocalPosition(int line);
2933 protected abstract int clipVertically(int positionY);
2934
2935 public PinnedPopupWindow() {
2936 createPopupWindow();
2937
Alan Viverette80ebe0d2015-04-30 15:53:11 -07002938 mPopupWindow.setWindowLayoutType(
2939 WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL);
Gilles Debunned88876a2012-03-16 17:34:04 -07002940 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2941 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2942
2943 initContentView();
2944
2945 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2946 ViewGroup.LayoutParams.WRAP_CONTENT);
2947 mContentView.setLayoutParams(wrapContent);
2948
2949 mPopupWindow.setContentView(mContentView);
2950 }
2951
2952 public void show() {
2953 getPositionListener().addSubscriber(this, false /* offset is fixed */);
2954
2955 computeLocalPosition();
2956
2957 final PositionListener positionListener = getPositionListener();
2958 updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2959 }
2960
2961 protected void measureContent() {
2962 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2963 mContentView.measure(
2964 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
2965 View.MeasureSpec.AT_MOST),
2966 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
2967 View.MeasureSpec.AT_MOST));
2968 }
2969
2970 /* The popup window will be horizontally centered on the getTextOffset() and vertically
2971 * positioned according to viewportToContentHorizontalOffset.
2972 *
2973 * This method assumes that mContentView has properly been measured from its content. */
2974 private void computeLocalPosition() {
2975 measureContent();
2976 final int width = mContentView.getMeasuredWidth();
2977 final int offset = getTextOffset();
2978 mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
2979 mPositionX += mTextView.viewportToContentHorizontalOffset();
2980
2981 final int line = mTextView.getLayout().getLineForOffset(offset);
2982 mPositionY = getVerticalLocalPosition(line);
2983 mPositionY += mTextView.viewportToContentVerticalOffset();
2984 }
2985
2986 private void updatePosition(int parentPositionX, int parentPositionY) {
2987 int positionX = parentPositionX + mPositionX;
2988 int positionY = parentPositionY + mPositionY;
2989
2990 positionY = clipVertically(positionY);
2991
2992 // Horizontal clipping
2993 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2994 final int width = mContentView.getMeasuredWidth();
Seigo Nonaka60490d12016-01-28 17:25:18 +09002995 positionX = Math.min(
2996 displayMetrics.widthPixels - width + mClippingLimitRight, positionX);
2997 positionX = Math.max(-mClippingLimitLeft, positionX);
Gilles Debunned88876a2012-03-16 17:34:04 -07002998
2999 if (isShowing()) {
3000 mPopupWindow.update(positionX, positionY, -1, -1);
3001 } else {
3002 mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
3003 positionX, positionY);
3004 }
3005 }
3006
3007 public void hide() {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09003008 if (!isShowing()) {
3009 return;
3010 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003011 mPopupWindow.dismiss();
3012 getPositionListener().removeSubscriber(this);
3013 }
3014
3015 @Override
3016 public void updatePosition(int parentPositionX, int parentPositionY,
3017 boolean parentPositionChanged, boolean parentScrolled) {
3018 // Either parentPositionChanged or parentScrolled is true, check if still visible
3019 if (isShowing() && isOffsetVisible(getTextOffset())) {
3020 if (parentScrolled) computeLocalPosition();
3021 updatePosition(parentPositionX, parentPositionY);
3022 } else {
3023 hide();
3024 }
3025 }
3026
3027 public boolean isShowing() {
3028 return mPopupWindow.isShowing();
3029 }
3030 }
3031
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003032 private static class SuggestionInfo {
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003033 // Range of actual suggestion within mText
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003034 int mSuggestionStart, mSuggestionEnd;
3035
3036 // The SuggestionSpan that this TextView represents
3037 @Nullable
3038 SuggestionSpan mSuggestionSpan;
3039
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003040 // The SuggestionSpan start position
3041 int mSuggestionSpanStart;
3042
3043 // The SuggestionSpan end position
3044 int mSuggestionSpanEnd;
3045
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003046 // The index of this suggestion inside suggestionSpan
3047 int mSuggestionIndex;
3048
3049 final SpannableStringBuilder mText = new SpannableStringBuilder();
3050
3051 void clear() {
3052 mSuggestionSpan = null;
3053 mText.clear();
3054 }
3055 }
3056
3057 private class SuggestionHelper {
3058 private final Comparator<SuggestionSpan> mSuggestionSpanComparator =
3059 new SuggestionSpanComparator();
3060 private final HashMap<SuggestionSpan, Integer> mSpansLengths =
3061 new HashMap<SuggestionSpan, Integer>();
3062
3063 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
3064 public int compare(SuggestionSpan span1, SuggestionSpan span2) {
3065 final int flag1 = span1.getFlags();
3066 final int flag2 = span2.getFlags();
3067 if (flag1 != flag2) {
3068 // The order here should match what is used in updateDrawState
3069 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
3070 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
3071 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
3072 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
3073 if (easy1 && !misspelled1) return -1;
3074 if (easy2 && !misspelled2) return 1;
3075 if (misspelled1) return -1;
3076 if (misspelled2) return 1;
3077 }
3078
3079 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
3080 }
3081 }
3082
3083 /**
3084 * Returns the suggestion spans that cover the current cursor position. The suggestion
3085 * spans are sorted according to the length of text that they are attached to.
3086 */
3087 private SuggestionSpan[] getSortedSuggestionSpans() {
3088 int pos = mTextView.getSelectionStart();
3089 Spannable spannable = (Spannable) mTextView.getText();
3090 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
3091
3092 mSpansLengths.clear();
3093 for (SuggestionSpan suggestionSpan : suggestionSpans) {
3094 int start = spannable.getSpanStart(suggestionSpan);
3095 int end = spannable.getSpanEnd(suggestionSpan);
3096 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
3097 }
3098
3099 // The suggestions are sorted according to their types (easy correction first, then
3100 // misspelled) and to the length of the text that they cover (shorter first).
3101 Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
3102 mSpansLengths.clear();
3103
3104 return suggestionSpans;
3105 }
3106
3107 /**
3108 * Gets the SuggestionInfo list that contains suggestion information at the current cursor
3109 * position.
3110 *
3111 * @param suggestionInfos SuggestionInfo array the results will be set.
3112 * @return the number of suggestions actually fetched.
3113 */
3114 public int getSuggestionInfo(SuggestionInfo[] suggestionInfos) {
3115 final Spannable spannable = (Spannable) mTextView.getText();
3116 final SuggestionSpan[] suggestionSpans = getSortedSuggestionSpans();
3117 final int nbSpans = suggestionSpans.length;
3118 if (nbSpans == 0) return 0;
3119
3120 int numberOfSuggestions = 0;
3121 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
3122 final SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
3123 final int spanStart = spannable.getSpanStart(suggestionSpan);
3124 final int spanEnd = spannable.getSpanEnd(suggestionSpan);
3125
3126 final String[] suggestions = suggestionSpan.getSuggestions();
3127 final int nbSuggestions = suggestions.length;
3128 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
3129 final String suggestion = suggestions[suggestionIndex];
3130 boolean suggestionIsDuplicate = false;
3131 for (int i = 0; i < numberOfSuggestions; i++) {
3132 if (suggestionInfos[i].mText.toString().equals(suggestion)) {
3133 final SuggestionSpan otherSuggestionSpan =
3134 suggestionInfos[i].mSuggestionSpan;
3135 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
3136 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
3137 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
3138 suggestionIsDuplicate = true;
3139 break;
3140 }
3141 }
3142 }
3143
3144 if (suggestionIsDuplicate) {
3145 continue;
3146 }
3147 SuggestionInfo suggestionInfo = suggestionInfos[numberOfSuggestions];
3148 suggestionInfo.mSuggestionSpan = suggestionSpan;
3149 suggestionInfo.mSuggestionIndex = suggestionIndex;
3150 suggestionInfo.mSuggestionStart = 0;
3151 suggestionInfo.mSuggestionEnd = suggestion.length();
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003152 suggestionInfo.mSuggestionSpanStart = spanStart;
3153 suggestionInfo.mSuggestionSpanEnd = spanEnd;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003154 suggestionInfo.mText.replace(0, suggestionInfo.mText.length(), suggestion);
3155 numberOfSuggestions++;
3156 if (numberOfSuggestions >= suggestionInfos.length) {
3157 return numberOfSuggestions;
3158 }
3159 }
3160 }
3161 return numberOfSuggestions;
3162 }
3163 }
3164
Seigo Nonakaa60160b2015-08-19 12:38:35 -07003165 @VisibleForTesting
3166 public class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
Gilles Debunned88876a2012-03-16 17:34:04 -07003167 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003168
3169 // Key of intent extras for inserting new word into user dictionary.
3170 private static final String USER_DICTIONARY_EXTRA_WORD = "word";
3171 private static final String USER_DICTIONARY_EXTRA_LOCALE = "locale";
3172
Gilles Debunned88876a2012-03-16 17:34:04 -07003173 private SuggestionInfo[] mSuggestionInfos;
3174 private int mNumberOfSuggestions;
3175 private boolean mCursorWasVisibleBeforeSuggestions;
3176 private boolean mIsShowingUp = false;
3177 private SuggestionAdapter mSuggestionsAdapter;
Seigo Nonakabffbd302015-08-18 18:27:56 -07003178 private final TextAppearanceSpan mHighlightSpan = new TextAppearanceSpan(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003179 mTextView.getContext(), mTextView.mTextEditSuggestionHighlightStyle);
3180 private TextView mAddToDictionaryButton;
3181 private TextView mDeleteButton;
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003182 private ListView mSuggestionListView;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003183 private SuggestionSpan mMisspelledSpan;
Seigo Nonaka60490d12016-01-28 17:25:18 +09003184 private int mContainerMarginWidth;
3185 private int mContainerMarginTop;
Gilles Debunned88876a2012-03-16 17:34:04 -07003186
3187 private class CustomPopupWindow extends PopupWindow {
Gilles Debunned88876a2012-03-16 17:34:04 -07003188 @Override
3189 public void dismiss() {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09003190 if (!isShowing()) {
3191 return;
3192 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003193 super.dismiss();
Gilles Debunned88876a2012-03-16 17:34:04 -07003194 getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
3195
3196 // Safe cast since show() checks that mTextView.getText() is an Editable
3197 ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
3198
3199 mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
Keisuke Kuroyanagi4a696ac2016-02-23 11:02:07 -08003200 if (hasInsertionController() && !extractedTextModeWillBeStarted()) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003201 getInsertionController().show();
3202 }
3203 }
3204 }
3205
3206 public SuggestionsPopupWindow() {
3207 mCursorWasVisibleBeforeSuggestions = mCursorVisible;
Gilles Debunned88876a2012-03-16 17:34:04 -07003208 }
3209
3210 @Override
3211 protected void createPopupWindow() {
Seigo Nonaka3ed1b392016-01-19 13:54:59 +09003212 mPopupWindow = new CustomPopupWindow();
Gilles Debunned88876a2012-03-16 17:34:04 -07003213 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
Seigo Nonaka3ed1b392016-01-19 13:54:59 +09003214 mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Gilles Debunned88876a2012-03-16 17:34:04 -07003215 mPopupWindow.setFocusable(true);
3216 mPopupWindow.setClippingEnabled(false);
3217 }
3218
3219 @Override
3220 protected void initContentView() {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003221 final LayoutInflater inflater = (LayoutInflater) mTextView.getContext().
3222 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Seigo Nonaka60490d12016-01-28 17:25:18 +09003223 final ViewGroup relativeLayout = (ViewGroup) inflater.inflate(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003224 mTextView.mTextEditSuggestionContainerLayout, null);
Gilles Debunned88876a2012-03-16 17:34:04 -07003225
Seigo Nonaka60490d12016-01-28 17:25:18 +09003226 final LinearLayout suggestionWindowContainer =
3227 (LinearLayout) relativeLayout.findViewById(
3228 com.android.internal.R.id.suggestionWindowContainer);
3229 ViewGroup.MarginLayoutParams lp =
3230 (ViewGroup.MarginLayoutParams) suggestionWindowContainer.getLayoutParams();
3231 mContainerMarginWidth = lp.leftMargin + lp.rightMargin;
3232 mContainerMarginTop = lp.topMargin;
3233 mClippingLimitLeft = lp.leftMargin;
3234 mClippingLimitRight = lp.rightMargin;
3235
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003236 mSuggestionListView = (ListView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003237 com.android.internal.R.id.suggestionContainer);
3238
3239 mSuggestionsAdapter = new SuggestionAdapter();
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003240 mSuggestionListView.setAdapter(mSuggestionsAdapter);
3241 mSuggestionListView.setOnItemClickListener(this);
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003242
3243 // Inflate the suggestion items once and for all.
3244 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS];
Gilles Debunned88876a2012-03-16 17:34:04 -07003245 for (int i = 0; i < mSuggestionInfos.length; i++) {
3246 mSuggestionInfos[i] = new SuggestionInfo();
3247 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003248
Seigo Nonaka60490d12016-01-28 17:25:18 +09003249 mContentView = relativeLayout;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003250
Seigo Nonaka60490d12016-01-28 17:25:18 +09003251 mAddToDictionaryButton = (TextView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003252 com.android.internal.R.id.addToDictionaryButton);
3253 mAddToDictionaryButton.setOnClickListener(new View.OnClickListener() {
3254 public void onClick(View v) {
3255 final Editable editable = (Editable) mTextView.getText();
3256 final int spanStart = editable.getSpanStart(mMisspelledSpan);
3257 final int spanEnd = editable.getSpanEnd(mMisspelledSpan);
3258 final String originalText = TextUtils.substring(editable, spanStart, spanEnd);
3259
3260 final Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
3261 intent.putExtra(USER_DICTIONARY_EXTRA_WORD, originalText);
3262 intent.putExtra(USER_DICTIONARY_EXTRA_LOCALE,
3263 mTextView.getTextServicesLocale().toString());
3264 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3265 mTextView.getContext().startActivity(intent);
3266 // There is no way to know if the word was indeed added. Re-check.
3267 // TODO The ExtractEditText should remove the span in the original text instead
3268 editable.removeSpan(mMisspelledSpan);
3269 Selection.setSelection(editable, spanEnd);
3270 updateSpellCheckSpans(spanStart, spanEnd, false);
3271 hideWithCleanUp();
3272 }
3273 });
3274
Seigo Nonaka60490d12016-01-28 17:25:18 +09003275 mDeleteButton = (TextView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003276 com.android.internal.R.id.deleteButton);
3277 mDeleteButton.setOnClickListener(new View.OnClickListener() {
3278 public void onClick(View v) {
3279 final Editable editable = (Editable) mTextView.getText();
3280
3281 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
3282 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
3283 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
3284 // Do not leave two adjacent spaces after deletion, or one at beginning of
3285 // text
3286 if (spanUnionEnd < editable.length() &&
3287 Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
3288 (spanUnionStart == 0 ||
3289 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
3290 spanUnionEnd = spanUnionEnd + 1;
3291 }
3292 mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
3293 }
3294 hideWithCleanUp();
3295 }
3296 });
3297
Gilles Debunned88876a2012-03-16 17:34:04 -07003298 }
3299
3300 public boolean isShowingUp() {
3301 return mIsShowingUp;
3302 }
3303
3304 public void onParentLostFocus() {
3305 mIsShowingUp = false;
3306 }
3307
Gilles Debunned88876a2012-03-16 17:34:04 -07003308 private class SuggestionAdapter extends BaseAdapter {
3309 private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
3310 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3311
3312 @Override
3313 public int getCount() {
3314 return mNumberOfSuggestions;
3315 }
3316
3317 @Override
3318 public Object getItem(int position) {
3319 return mSuggestionInfos[position];
3320 }
3321
3322 @Override
3323 public long getItemId(int position) {
3324 return position;
3325 }
3326
3327 @Override
3328 public View getView(int position, View convertView, ViewGroup parent) {
3329 TextView textView = (TextView) convertView;
3330
3331 if (textView == null) {
3332 textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
3333 parent, false);
3334 }
3335
3336 final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003337 textView.setText(suggestionInfo.mText);
Gilles Debunned88876a2012-03-16 17:34:04 -07003338 return textView;
3339 }
3340 }
3341
Seigo Nonakaa60160b2015-08-19 12:38:35 -07003342 @VisibleForTesting
3343 public ViewGroup getContentViewForTesting() {
3344 return mContentView;
3345 }
3346
Gilles Debunned88876a2012-03-16 17:34:04 -07003347 @Override
3348 public void show() {
3349 if (!(mTextView.getText() instanceof Editable)) return;
Keisuke Kuroyanagi4a696ac2016-02-23 11:02:07 -08003350 if (extractedTextModeWillBeStarted()) {
3351 return;
3352 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003353
3354 if (updateSuggestions()) {
3355 mCursorWasVisibleBeforeSuggestions = mCursorVisible;
3356 mTextView.setCursorVisible(false);
3357 mIsShowingUp = true;
3358 super.show();
3359 }
3360 }
3361
3362 @Override
3363 protected void measureContent() {
3364 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3365 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
3366 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
3367 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
3368 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
3369
3370 int width = 0;
3371 View view = null;
3372 for (int i = 0; i < mNumberOfSuggestions; i++) {
3373 view = mSuggestionsAdapter.getView(i, view, mContentView);
3374 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
3375 view.measure(horizontalMeasure, verticalMeasure);
3376 width = Math.max(width, view.getMeasuredWidth());
3377 }
3378
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003379 if (mAddToDictionaryButton.getVisibility() != View.GONE) {
3380 mAddToDictionaryButton.measure(horizontalMeasure, verticalMeasure);
3381 width = Math.max(width, mAddToDictionaryButton.getMeasuredWidth());
3382 }
3383
3384 mDeleteButton.measure(horizontalMeasure, verticalMeasure);
3385 width = Math.max(width, mDeleteButton.getMeasuredWidth());
3386
Seigo Nonaka60490d12016-01-28 17:25:18 +09003387 width += mContainerMarginWidth;
3388
Gilles Debunned88876a2012-03-16 17:34:04 -07003389 // Enforce the width based on actual text widths
3390 mContentView.measure(
3391 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
3392 verticalMeasure);
3393
3394 Drawable popupBackground = mPopupWindow.getBackground();
3395 if (popupBackground != null) {
3396 if (mTempRect == null) mTempRect = new Rect();
3397 popupBackground.getPadding(mTempRect);
3398 width += mTempRect.left + mTempRect.right;
3399 }
Seigo Nonakaf47976e2016-03-01 09:17:37 -08003400 mSuggestionListView.getLayoutParams().width = width;
Gilles Debunned88876a2012-03-16 17:34:04 -07003401 mPopupWindow.setWidth(width);
3402 }
3403
3404 @Override
3405 protected int getTextOffset() {
Keisuke Kuroyanagi713be062016-02-29 16:07:54 -08003406 return (mTextView.getSelectionStart() + mTextView.getSelectionStart()) / 2;
Gilles Debunned88876a2012-03-16 17:34:04 -07003407 }
3408
3409 @Override
3410 protected int getVerticalLocalPosition(int line) {
Seigo Nonaka60490d12016-01-28 17:25:18 +09003411 return mTextView.getLayout().getLineBottom(line) - mContainerMarginTop;
Gilles Debunned88876a2012-03-16 17:34:04 -07003412 }
3413
3414 @Override
3415 protected int clipVertically(int positionY) {
3416 final int height = mContentView.getMeasuredHeight();
3417 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3418 return Math.min(positionY, displayMetrics.heightPixels - height);
3419 }
3420
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003421 private void hideWithCleanUp() {
3422 for (final SuggestionInfo info : mSuggestionInfos) {
3423 info.clear();
3424 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003425 mMisspelledSpan = null;
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003426 hide();
Gilles Debunned88876a2012-03-16 17:34:04 -07003427 }
3428
3429 private boolean updateSuggestions() {
3430 Spannable spannable = (Spannable) mTextView.getText();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003431 mNumberOfSuggestions =
3432 mSuggestionHelper.getSuggestionInfo(mSuggestionInfos);
3433 if (mNumberOfSuggestions == 0) {
3434 return false;
3435 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003436
Gilles Debunned88876a2012-03-16 17:34:04 -07003437 int spanUnionStart = mTextView.getText().length();
3438 int spanUnionEnd = 0;
3439
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003440 mMisspelledSpan = null;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003441 for (int i = 0; i < mNumberOfSuggestions; i++) {
3442 final SuggestionInfo suggestionInfo = mSuggestionInfos[i];
3443 final SuggestionSpan suggestionSpan = suggestionInfo.mSuggestionSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07003444 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003445 mMisspelledSpan = suggestionSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07003446 }
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003447 spanUnionStart = Math.min(spanUnionStart, suggestionInfo.mSuggestionSpanStart);
3448 spanUnionEnd = Math.max(spanUnionEnd, suggestionInfo.mSuggestionSpanEnd);
Gilles Debunned88876a2012-03-16 17:34:04 -07003449 }
3450
3451 for (int i = 0; i < mNumberOfSuggestions; i++) {
3452 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
3453 }
3454
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003455 // Make "Add to dictionary" item visible if there is a span with the misspelled flag
3456 int addToDictionaryButtonVisibility = View.GONE;
3457 if (mMisspelledSpan != null) {
3458 final int misspelledStart = spannable.getSpanStart(mMisspelledSpan);
3459 final int misspelledEnd = spannable.getSpanEnd(mMisspelledSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07003460 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003461 addToDictionaryButtonVisibility = View.VISIBLE;
Gilles Debunned88876a2012-03-16 17:34:04 -07003462 }
3463 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003464 mAddToDictionaryButton.setVisibility(addToDictionaryButtonVisibility);
Gilles Debunned88876a2012-03-16 17:34:04 -07003465
3466 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003467 final int underlineColor = mSuggestionInfos[0].mSuggestionSpan.getUnderlineColor();
Gilles Debunned88876a2012-03-16 17:34:04 -07003468 if (underlineColor == 0) {
3469 // Fallback on the default highlight color when the first span does not provide one
3470 mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
3471 } else {
3472 final float BACKGROUND_TRANSPARENCY = 0.4f;
3473 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
3474 mSuggestionRangeSpan.setBackgroundColor(
3475 (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
3476 }
3477 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
3478 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
3479
3480 mSuggestionsAdapter.notifyDataSetChanged();
3481 return true;
3482 }
3483
3484 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
3485 int unionEnd) {
3486 final Spannable text = (Spannable) mTextView.getText();
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003487 final int spanStart = suggestionInfo.mSuggestionSpanStart;
3488 final int spanEnd = suggestionInfo.mSuggestionSpanEnd;
Gilles Debunned88876a2012-03-16 17:34:04 -07003489
3490 // Adjust the start/end of the suggestion span
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003491 suggestionInfo.mSuggestionStart = spanStart - unionStart;
3492 suggestionInfo.mSuggestionEnd = suggestionInfo.mSuggestionStart
3493 + suggestionInfo.mText.length();
Gilles Debunned88876a2012-03-16 17:34:04 -07003494
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003495 suggestionInfo.mText.setSpan(mHighlightSpan, 0, suggestionInfo.mText.length(),
Seigo Nonakabffbd302015-08-18 18:27:56 -07003496 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Gilles Debunned88876a2012-03-16 17:34:04 -07003497
3498 // Add the text before and after the span.
3499 final String textAsString = text.toString();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003500 suggestionInfo.mText.insert(0, textAsString.substring(unionStart, spanStart));
3501 suggestionInfo.mText.append(textAsString.substring(spanEnd, unionEnd));
Gilles Debunned88876a2012-03-16 17:34:04 -07003502 }
3503
3504 @Override
3505 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003506 SuggestionInfo suggestionInfo = mSuggestionInfos[position];
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003507 replaceWithSuggestion(suggestionInfo);
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003508 hideWithCleanUp();
Gilles Debunned88876a2012-03-16 17:34:04 -07003509 }
3510 }
3511
3512 /**
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003513 * An ActionMode Callback class that is used to provide actions while in text insertion or
3514 * selection mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07003515 *
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003516 * The default callback provides a subset of Select All, Cut, Copy, Paste, Share and Replace
3517 * actions, depending on which of these this TextView supports and the current selection.
Gilles Debunned88876a2012-03-16 17:34:04 -07003518 */
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003519 private class TextActionModeCallback extends ActionMode.Callback2 {
Clara Bayarriea4f1502015-03-18 00:25:01 +00003520 private final Path mSelectionPath = new Path();
3521 private final RectF mSelectionBounds = new RectF();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003522 private final boolean mHasSelection;
Clara Bayarriea4f1502015-03-18 00:25:01 +00003523
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003524 private int mHandleHeight;
Clara Bayarriea4f1502015-03-18 00:25:01 +00003525
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003526 public TextActionModeCallback(boolean hasSelection) {
3527 mHasSelection = hasSelection;
3528 if (mHasSelection) {
3529 SelectionModifierCursorController selectionController = getSelectionController();
3530 if (selectionController.mStartHandle == null) {
3531 // As these are for initializing selectionController, hide() must be called.
3532 selectionController.initDrawables();
3533 selectionController.initHandles();
3534 selectionController.hide();
3535 }
3536 mHandleHeight = Math.max(
3537 mSelectHandleLeft.getMinimumHeight(),
3538 mSelectHandleRight.getMinimumHeight());
3539 } else {
3540 InsertionPointCursorController insertionController = getInsertionController();
3541 if (insertionController != null) {
3542 insertionController.getHandle();
3543 mHandleHeight = mSelectHandleCenter.getMinimumHeight();
3544 }
Clara Bayarri7fc946e2015-03-31 14:48:33 +01003545 }
Clara Bayarriea4f1502015-03-18 00:25:01 +00003546 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003547
3548 @Override
3549 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003550 mode.setTitle(null);
Clara Bayarri13152d12015-04-09 12:02:04 +01003551 mode.setSubtitle(null);
3552 mode.setTitleOptionalHint(true);
3553 populateMenuWithItems(menu);
3554
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003555 Callback customCallback = getCustomCallback();
3556 if (customCallback != null) {
3557 if (!customCallback.onCreateActionMode(mode, menu)) {
Clara Bayarri01243ac2015-06-03 00:46:29 +01003558 // The custom mode can choose to cancel the action mode, dismiss selection.
3559 Selection.setSelection((Spannable) mTextView.getText(),
3560 mTextView.getSelectionEnd());
Clara Bayarri13152d12015-04-09 12:02:04 +01003561 return false;
3562 }
3563 }
3564
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07003565 if (mTextView.canProcessText()) {
3566 mProcessTextIntentActionsHandler.onInitializeMenu(menu);
3567 }
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00003568
Clara Bayarri13152d12015-04-09 12:02:04 +01003569 if (menu.hasVisibleItems() || mode.getCustomView() != null) {
Clara Bayarri13152d12015-04-09 12:02:04 +01003570 return true;
3571 } else {
3572 return false;
3573 }
3574 }
3575
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003576 private Callback getCustomCallback() {
3577 return mHasSelection
3578 ? mCustomSelectionActionModeCallback
3579 : mCustomInsertionActionModeCallback;
3580 }
3581
Clara Bayarri13152d12015-04-09 12:02:04 +01003582 private void populateMenuWithItems(Menu menu) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003583 if (mTextView.canCut()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003584 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
3585 com.android.internal.R.string.cut).
Gilles Debunned88876a2012-03-16 17:34:04 -07003586 setAlphabeticShortcut('x').
Clara Bayarriaee243b2015-05-18 17:05:46 +01003587 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003588 }
3589
3590 if (mTextView.canCopy()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003591 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
3592 com.android.internal.R.string.copy).
Gilles Debunned88876a2012-03-16 17:34:04 -07003593 setAlphabeticShortcut('c').
Clara Bayarriaee243b2015-05-18 17:05:46 +01003594 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003595 }
3596
3597 if (mTextView.canPaste()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003598 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
3599 com.android.internal.R.string.paste).
3600 setAlphabeticShortcut('v').
3601 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003602 }
3603
Andrei Stingaceanu7f0c5bd2015-04-14 17:12:08 +01003604 if (mTextView.canShare()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003605 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
3606 com.android.internal.R.string.share).
3607 setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
Andrei Stingaceanu7f0c5bd2015-04-14 17:12:08 +01003608 }
3609
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003610 updateSelectAllItem(menu);
Clara Bayarri13152d12015-04-09 12:02:04 +01003611 updateReplaceItem(menu);
Gilles Debunned88876a2012-03-16 17:34:04 -07003612 }
3613
3614 @Override
3615 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003616 updateSelectAllItem(menu);
Clara Bayarri13152d12015-04-09 12:02:04 +01003617 updateReplaceItem(menu);
3618
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003619 Callback customCallback = getCustomCallback();
3620 if (customCallback != null) {
3621 return customCallback.onPrepareActionMode(mode, menu);
Gilles Debunned88876a2012-03-16 17:34:04 -07003622 }
3623 return true;
3624 }
3625
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003626 private void updateSelectAllItem(Menu menu) {
3627 boolean canSelectAll = mTextView.canSelectAllText();
3628 boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null;
3629 if (canSelectAll && !selectAllItemExists) {
3630 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
3631 com.android.internal.R.string.selectAll)
3632 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3633 } else if (!canSelectAll && selectAllItemExists) {
3634 menu.removeItem(TextView.ID_SELECT_ALL);
3635 }
3636 }
3637
Clara Bayarri13152d12015-04-09 12:02:04 +01003638 private void updateReplaceItem(Menu menu) {
Keisuke Kuroyanagid31945032016-02-26 16:09:12 -08003639 boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
Clara Bayarri13152d12015-04-09 12:02:04 +01003640 boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3641 if (canReplace && !replaceItemExists) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003642 menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
3643 com.android.internal.R.string.replace)
3644 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
Clara Bayarri13152d12015-04-09 12:02:04 +01003645 } else if (!canReplace && replaceItemExists) {
3646 menu.removeItem(TextView.ID_REPLACE);
3647 }
3648 }
3649
Gilles Debunned88876a2012-03-16 17:34:04 -07003650 @Override
3651 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07003652 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00003653 return true;
3654 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003655 Callback customCallback = getCustomCallback();
3656 if (customCallback != null && customCallback.onActionItemClicked(mode, item)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003657 return true;
3658 }
3659 return mTextView.onTextContextMenuItem(item.getItemId());
3660 }
3661
3662 @Override
3663 public void onDestroyActionMode(ActionMode mode) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003664 Callback customCallback = getCustomCallback();
3665 if (customCallback != null) {
3666 customCallback.onDestroyActionMode(mode);
Gilles Debunned88876a2012-03-16 17:34:04 -07003667 }
Adam Powell057a5852012-05-11 10:28:38 -07003668
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08003669 if (!mPreserveSelection) {
3670 /*
3671 * Leave current selection when we tentatively destroy action mode for the
3672 * selection. If we're detaching from a window, we'll bring back the selection
3673 * mode when (if) we get reattached.
3674 */
Adam Powell057a5852012-05-11 10:28:38 -07003675 Selection.setSelection((Spannable) mTextView.getText(),
3676 mTextView.getSelectionEnd());
Adam Powell057a5852012-05-11 10:28:38 -07003677 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003678
3679 if (mSelectionModifierCursorController != null) {
3680 mSelectionModifierCursorController.hide();
3681 }
3682
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003683 mTextActionMode = null;
Gilles Debunned88876a2012-03-16 17:34:04 -07003684 }
Clara Bayarriea4f1502015-03-18 00:25:01 +00003685
3686 @Override
3687 public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
3688 if (!view.equals(mTextView) || mTextView.getLayout() == null) {
3689 super.onGetContentRect(mode, view, outRect);
3690 return;
3691 }
3692 if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
3693 // We have a selection.
3694 mSelectionPath.reset();
3695 mTextView.getLayout().getSelectionPath(
3696 mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
3697 mSelectionPath.computeBounds(mSelectionBounds, true);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003698 mSelectionBounds.bottom += mHandleHeight;
Clara Bayarrib7419dd2015-04-09 15:24:58 +01003699 } else if (mCursorCount == 2) {
3700 // We have a split cursor. In this case, we take the rectangle that includes both
3701 // parts of the cursor to ensure we don't obscure either of them.
3702 Rect firstCursorBounds = mCursorDrawable[0].getBounds();
3703 Rect secondCursorBounds = mCursorDrawable[1].getBounds();
3704 mSelectionBounds.set(
3705 Math.min(firstCursorBounds.left, secondCursorBounds.left),
3706 Math.min(firstCursorBounds.top, secondCursorBounds.top),
3707 Math.max(firstCursorBounds.right, secondCursorBounds.right),
3708 Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom)
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003709 + mHandleHeight);
Clara Bayarriea4f1502015-03-18 00:25:01 +00003710 } else {
3711 // We have a single cursor.
Mady Mellorff66ca52015-07-08 12:31:45 -07003712 Layout layout = getActiveLayout();
3713 int line = layout.getLineForOffset(mTextView.getSelectionStart());
Clara Bayarriea4f1502015-03-18 00:25:01 +00003714 float primaryHorizontal =
Mady Mellorff66ca52015-07-08 12:31:45 -07003715 layout.getPrimaryHorizontal(mTextView.getSelectionStart());
Clara Bayarriea4f1502015-03-18 00:25:01 +00003716 mSelectionBounds.set(
3717 primaryHorizontal,
Mady Mellorff66ca52015-07-08 12:31:45 -07003718 layout.getLineTop(line),
Clara Bayarrif95ed102015-08-12 19:46:47 +01003719 primaryHorizontal,
Mady Mellorff66ca52015-07-08 12:31:45 -07003720 layout.getLineTop(line + 1) + mHandleHeight);
Clara Bayarriea4f1502015-03-18 00:25:01 +00003721 }
3722 // Take TextView's padding and scroll into account.
3723 int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
3724 int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
3725 outRect.set(
3726 (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
3727 (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
3728 (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
3729 (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
3730 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003731 }
3732
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003733 /**
3734 * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
3735 * while the input method is requesting the cursor/anchor position. Does nothing as long as
3736 * {@link InputMethodManager#isWatchingCursor(View)} returns false.
3737 */
3738 private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
Yohei Yukawac46b5f02014-06-10 12:26:34 +09003739 final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003740 final int[] mTmpIntOffset = new int[2];
3741 final Matrix mViewToScreenMatrix = new Matrix();
3742
3743 @Override
3744 public void updatePosition(int parentPositionX, int parentPositionY,
3745 boolean parentPositionChanged, boolean parentScrolled) {
3746 final InputMethodState ims = mInputMethodState;
3747 if (ims == null || ims.mBatchEditNesting > 0) {
3748 return;
3749 }
3750 final InputMethodManager imm = InputMethodManager.peekInstance();
3751 if (null == imm) {
3752 return;
3753 }
Yohei Yukawa0023d0e2014-07-11 04:13:03 +09003754 if (!imm.isActive(mTextView)) {
3755 return;
3756 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003757 // Skip if the IME has not requested the cursor/anchor position.
Yohei Yukawa0023d0e2014-07-11 04:13:03 +09003758 if (!imm.isCursorAnchorInfoEnabled()) {
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003759 return;
3760 }
3761 Layout layout = mTextView.getLayout();
3762 if (layout == null) {
3763 return;
3764 }
3765
Yohei Yukawac46b5f02014-06-10 12:26:34 +09003766 final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003767 builder.reset();
3768
3769 final int selectionStart = mTextView.getSelectionStart();
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003770 builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003771
3772 // Construct transformation matrix from view local coordinates to screen coordinates.
3773 mViewToScreenMatrix.set(mTextView.getMatrix());
3774 mTextView.getLocationOnScreen(mTmpIntOffset);
3775 mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
3776 builder.setMatrix(mViewToScreenMatrix);
3777
3778 final float viewportToContentHorizontalOffset =
3779 mTextView.viewportToContentHorizontalOffset();
3780 final float viewportToContentVerticalOffset =
3781 mTextView.viewportToContentVerticalOffset();
3782
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003783 final CharSequence text = mTextView.getText();
3784 if (text instanceof Spannable) {
3785 final Spannable sp = (Spannable) text;
3786 int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
3787 int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
3788 if (composingTextEnd < composingTextStart) {
3789 final int temp = composingTextEnd;
3790 composingTextEnd = composingTextStart;
3791 composingTextStart = temp;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003792 }
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003793 final boolean hasComposingText =
3794 (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
3795 if (hasComposingText) {
3796 final CharSequence composingText = text.subSequence(composingTextStart,
3797 composingTextEnd);
3798 builder.setComposingText(composingTextStart, composingText);
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003799
3800 final int minLine = layout.getLineForOffset(composingTextStart);
3801 final int maxLine = layout.getLineForOffset(composingTextEnd - 1);
3802 for (int line = minLine; line <= maxLine; ++line) {
3803 final int lineStart = layout.getLineStart(line);
3804 final int lineEnd = layout.getLineEnd(line);
3805 final int offsetStart = Math.max(lineStart, composingTextStart);
3806 final int offsetEnd = Math.min(lineEnd, composingTextEnd);
3807 final boolean ltrLine =
3808 layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT;
3809 final float[] widths = new float[offsetEnd - offsetStart];
3810 layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths);
3811 final float top = layout.getLineTop(line);
3812 final float bottom = layout.getLineBottom(line);
3813 for (int offset = offsetStart; offset < offsetEnd; ++offset) {
3814 final float charWidth = widths[offset - offsetStart];
3815 final boolean isRtl = layout.isRtlCharAt(offset);
3816 final float primary = layout.getPrimaryHorizontal(offset);
3817 final float secondary = layout.getSecondaryHorizontal(offset);
3818 // TODO: This doesn't work perfectly for text with custom styles and
3819 // TAB chars.
3820 final float left;
3821 final float right;
3822 if (ltrLine) {
3823 if (isRtl) {
3824 left = secondary - charWidth;
3825 right = secondary;
3826 } else {
3827 left = primary;
3828 right = primary + charWidth;
3829 }
3830 } else {
3831 if (!isRtl) {
3832 left = secondary;
3833 right = secondary + charWidth;
3834 } else {
3835 left = primary - charWidth;
3836 right = primary;
3837 }
3838 }
3839 // TODO: Check top-right and bottom-left as well.
3840 final float localLeft = left + viewportToContentHorizontalOffset;
3841 final float localRight = right + viewportToContentHorizontalOffset;
3842 final float localTop = top + viewportToContentVerticalOffset;
3843 final float localBottom = bottom + viewportToContentVerticalOffset;
3844 final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop);
3845 final boolean isBottomRightVisible =
3846 isPositionVisible(localRight, localBottom);
3847 int characterBoundsFlags = 0;
3848 if (isTopLeftVisible || isBottomRightVisible) {
3849 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3850 }
Andreas Gampe4976e2d2015-03-17 16:08:43 -07003851 if (!isTopLeftVisible || !isBottomRightVisible) {
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003852 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3853 }
3854 if (isRtl) {
3855 characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3856 }
3857 // Here offset is the index in Java chars.
3858 builder.addCharacterBounds(offset, localLeft, localTop, localRight,
3859 localBottom, characterBoundsFlags);
3860 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003861 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003862 }
3863 }
3864
3865 // Treat selectionStart as the insertion point.
3866 if (0 <= selectionStart) {
3867 final int offset = selectionStart;
3868 final int line = layout.getLineForOffset(offset);
3869 final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
3870 + viewportToContentHorizontalOffset;
3871 final float insertionMarkerTop = layout.getLineTop(line)
3872 + viewportToContentVerticalOffset;
3873 final float insertionMarkerBaseline = layout.getLineBaseline(line)
3874 + viewportToContentVerticalOffset;
3875 final float insertionMarkerBottom = layout.getLineBottom(line)
3876 + viewportToContentVerticalOffset;
Yohei Yukawacc24e2b2014-08-29 20:21:10 -07003877 final boolean isTopVisible =
3878 isPositionVisible(insertionMarkerX, insertionMarkerTop);
3879 final boolean isBottomVisible =
3880 isPositionVisible(insertionMarkerX, insertionMarkerBottom);
3881 int insertionMarkerFlags = 0;
3882 if (isTopVisible || isBottomVisible) {
3883 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3884 }
3885 if (!isTopVisible || !isBottomVisible) {
3886 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3887 }
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003888 if (layout.isRtlCharAt(offset)) {
3889 insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3890 }
Yohei Yukawa0b01e7f2014-07-08 15:29:51 +09003891 builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
Yohei Yukawacc24e2b2014-08-29 20:21:10 -07003892 insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003893 }
3894
3895 imm.updateCursorAnchorInfo(mTextView, builder.build());
3896 }
3897 }
3898
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003899 @VisibleForTesting
3900 public abstract class HandleView extends View implements TextViewPositionListener {
Gilles Debunned88876a2012-03-16 17:34:04 -07003901 protected Drawable mDrawable;
3902 protected Drawable mDrawableLtr;
3903 protected Drawable mDrawableRtl;
3904 private final PopupWindow mContainer;
3905 // Position with respect to the parent TextView
3906 private int mPositionX, mPositionY;
3907 private boolean mIsDragging;
3908 // Offset from touch position to mPosition
3909 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
3910 protected int mHotspotX;
Adam Powell3fceabd2014-08-19 18:28:04 -07003911 protected int mHorizontalGravity;
Gilles Debunned88876a2012-03-16 17:34:04 -07003912 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
3913 private float mTouchOffsetY;
3914 // Where the touch position should be on the handle to ensure a maximum cursor visibility
3915 private float mIdealVerticalOffset;
3916 // Parent's (TextView) previous position in window
3917 private int mLastParentX, mLastParentY;
Gilles Debunned88876a2012-03-16 17:34:04 -07003918 // Previous text character offset
Mady Mellorc2225b92015-04-01 15:59:20 -07003919 protected int mPreviousOffset = -1;
Gilles Debunned88876a2012-03-16 17:34:04 -07003920 // Previous text character offset
3921 private boolean mPositionHasChanged = true;
Adam Powell3fceabd2014-08-19 18:28:04 -07003922 // Minimum touch target size for handles
3923 private int mMinSize;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08003924 // Indicates the line of text that the handle is on.
Mady Mellora6a0f782015-07-10 16:43:32 -07003925 protected int mPrevLine = UNSET_LINE;
3926 // Indicates the line of text that the user was touching. This can differ from mPrevLine
3927 // when selecting text when the handles jump to the end / start of words which may be on
3928 // a different line.
3929 protected int mPreviousLineTouched = UNSET_LINE;
Gilles Debunned88876a2012-03-16 17:34:04 -07003930
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003931 private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003932 super(mTextView.getContext());
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003933 setId(id);
Gilles Debunned88876a2012-03-16 17:34:04 -07003934 mContainer = new PopupWindow(mTextView.getContext(), null,
3935 com.android.internal.R.attr.textSelectHandleWindowStyle);
3936 mContainer.setSplitTouchEnabled(true);
3937 mContainer.setClippingEnabled(false);
3938 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
Keisuke Kuroyanagi7340be72015-02-27 17:57:49 +09003939 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
3940 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
Gilles Debunned88876a2012-03-16 17:34:04 -07003941 mContainer.setContentView(this);
3942
3943 mDrawableLtr = drawableLtr;
3944 mDrawableRtl = drawableRtl;
Adam Powell3fceabd2014-08-19 18:28:04 -07003945 mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
3946 com.android.internal.R.dimen.text_handle_min_size);
Gilles Debunned88876a2012-03-16 17:34:04 -07003947
3948 updateDrawable();
3949
Adam Powell3fceabd2014-08-19 18:28:04 -07003950 final int handleHeight = getPreferredHeight();
Gilles Debunned88876a2012-03-16 17:34:04 -07003951 mTouchOffsetY = -0.3f * handleHeight;
3952 mIdealVerticalOffset = 0.7f * handleHeight;
3953 }
3954
Mady Mellor7a936442015-05-20 10:05:52 -07003955 public float getIdealVerticalOffset() {
3956 return mIdealVerticalOffset;
3957 }
3958
Gilles Debunned88876a2012-03-16 17:34:04 -07003959 protected void updateDrawable() {
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09003960 if (mIsDragging) {
3961 // Don't update drawable during dragging.
3962 return;
3963 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003964 final int offset = getCurrentCursorOffset();
3965 final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
Keisuke Kuroyanagi33f81ac2015-05-14 20:10:57 +09003966 final Drawable oldDrawable = mDrawable;
Gilles Debunned88876a2012-03-16 17:34:04 -07003967 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
3968 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
Adam Powell3fceabd2014-08-19 18:28:04 -07003969 mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09003970 final Layout layout = mTextView.getLayout();
3971 if (layout != null && oldDrawable != mDrawable && isShowing()) {
3972 // Update popup window position.
Siyamed Sinir217c0f72016-02-01 18:30:02 -08003973 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX -
3974 getHorizontalOffset() + getCursorOffset();
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09003975 mPositionX += mTextView.viewportToContentHorizontalOffset();
3976 mPositionHasChanged = true;
3977 updatePosition(mLastParentX, mLastParentY, false, false);
Keisuke Kuroyanagi33f81ac2015-05-14 20:10:57 +09003978 postInvalidate();
3979 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003980 }
3981
3982 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
Adam Powell3fceabd2014-08-19 18:28:04 -07003983 protected abstract int getHorizontalGravity(boolean isRtlRun);
Gilles Debunned88876a2012-03-16 17:34:04 -07003984
3985 // Touch-up filter: number of previous positions remembered
3986 private static final int HISTORY_SIZE = 5;
3987 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
3988 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
3989 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
3990 private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
3991 private int mPreviousOffsetIndex = 0;
3992 private int mNumberPreviousOffsets = 0;
3993
3994 private void startTouchUpFilter(int offset) {
3995 mNumberPreviousOffsets = 0;
3996 addPositionToTouchUpFilter(offset);
3997 }
3998
3999 private void addPositionToTouchUpFilter(int offset) {
4000 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
4001 mPreviousOffsets[mPreviousOffsetIndex] = offset;
4002 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
4003 mNumberPreviousOffsets++;
4004 }
4005
4006 private void filterOnTouchUp() {
4007 final long now = SystemClock.uptimeMillis();
4008 int i = 0;
4009 int index = mPreviousOffsetIndex;
4010 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
4011 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
4012 i++;
4013 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
4014 }
4015
4016 if (i > 0 && i < iMax &&
4017 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
4018 positionAtCursorOffset(mPreviousOffsets[index], false);
4019 }
4020 }
4021
4022 public boolean offsetHasBeenChanged() {
4023 return mNumberPreviousOffsets > 1;
4024 }
4025
4026 @Override
4027 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Powell3fceabd2014-08-19 18:28:04 -07004028 setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
4029 }
4030
4031 private int getPreferredWidth() {
4032 return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
4033 }
4034
4035 private int getPreferredHeight() {
4036 return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
Gilles Debunned88876a2012-03-16 17:34:04 -07004037 }
4038
4039 public void show() {
4040 if (isShowing()) return;
4041
4042 getPositionListener().addSubscriber(this, true /* local position may change */);
4043
4044 // Make sure the offset is always considered new, even when focusing at same position
4045 mPreviousOffset = -1;
4046 positionAtCursorOffset(getCurrentCursorOffset(), false);
Gilles Debunned88876a2012-03-16 17:34:04 -07004047 }
4048
4049 protected void dismiss() {
4050 mIsDragging = false;
4051 mContainer.dismiss();
4052 onDetached();
4053 }
4054
4055 public void hide() {
4056 dismiss();
4057
4058 getPositionListener().removeSubscriber(this);
4059 }
4060
Gilles Debunned88876a2012-03-16 17:34:04 -07004061 public boolean isShowing() {
4062 return mContainer.isShowing();
4063 }
4064
4065 private boolean isVisible() {
4066 // Always show a dragging handle.
4067 if (mIsDragging) {
4068 return true;
4069 }
4070
4071 if (mTextView.isInBatchEditMode()) {
4072 return false;
4073 }
4074
Keisuke Kuroyanagi6cda1e22015-04-22 21:41:14 +09004075 return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
Gilles Debunned88876a2012-03-16 17:34:04 -07004076 }
4077
4078 public abstract int getCurrentCursorOffset();
4079
4080 protected abstract void updateSelection(int offset);
4081
4082 public abstract void updatePosition(float x, float y);
4083
4084 protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4085 // A HandleView relies on the layout, which may be nulled by external methods
4086 Layout layout = mTextView.getLayout();
4087 if (layout == null) {
4088 // Will update controllers' state, hiding them and stopping selection mode if needed
4089 prepareCursorControllers();
4090 return;
4091 }
Mady Mellorff66ca52015-07-08 12:31:45 -07004092 layout = getActiveLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -07004093
4094 boolean offsetChanged = offset != mPreviousOffset;
4095 if (offsetChanged || parentScrolled) {
4096 if (offsetChanged) {
4097 updateSelection(offset);
4098 addPositionToTouchUpFilter(offset);
4099 }
4100 final int line = layout.getLineForOffset(offset);
Mady Mellorb9bbbb12015-03-23 11:50:46 -07004101 mPrevLine = line;
Gilles Debunned88876a2012-03-16 17:34:04 -07004102
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004103 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX -
4104 getHorizontalOffset() + getCursorOffset();
Gilles Debunned88876a2012-03-16 17:34:04 -07004105 mPositionY = layout.getLineBottom(line);
4106
4107 // Take TextView's padding and scroll into account.
4108 mPositionX += mTextView.viewportToContentHorizontalOffset();
4109 mPositionY += mTextView.viewportToContentVerticalOffset();
4110
4111 mPreviousOffset = offset;
4112 mPositionHasChanged = true;
4113 }
4114 }
4115
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004116 /**
4117 * Return the clamped horizontal position for the first cursor.
4118 *
4119 * @param layout Text layout.
4120 * @param offset Character offset for the cursor.
4121 * @return The clamped horizontal position for the cursor.
4122 */
4123 int getCursorHorizontalPosition(Layout layout, int offset) {
4124 return (int) (layout.getPrimaryHorizontal(offset) - 0.5f);
4125 }
4126
Gilles Debunned88876a2012-03-16 17:34:04 -07004127 public void updatePosition(int parentPositionX, int parentPositionY,
4128 boolean parentPositionChanged, boolean parentScrolled) {
4129 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
4130 if (parentPositionChanged || mPositionHasChanged) {
4131 if (mIsDragging) {
4132 // Update touchToWindow offset in case of parent scrolling while dragging
4133 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
4134 mTouchToWindowOffsetX += parentPositionX - mLastParentX;
4135 mTouchToWindowOffsetY += parentPositionY - mLastParentY;
4136 mLastParentX = parentPositionX;
4137 mLastParentY = parentPositionY;
4138 }
4139
4140 onHandleMoved();
4141 }
4142
4143 if (isVisible()) {
Seigo Nonaka2f229ca2016-02-18 17:53:54 +09004144 // Transform to the window coordinates to follow the view tranformation.
4145 final int[] pts = { mPositionX + mHotspotX + getHorizontalOffset(), mPositionY};
4146 mTextView.transformFromViewToWindowSpace(pts);
4147 pts[0] -= mHotspotX + getHorizontalOffset();
4148
Gilles Debunned88876a2012-03-16 17:34:04 -07004149 if (isShowing()) {
Seigo Nonaka2f229ca2016-02-18 17:53:54 +09004150 mContainer.update(pts[0], pts[1], -1, -1);
Gilles Debunned88876a2012-03-16 17:34:04 -07004151 } else {
Seigo Nonaka2f229ca2016-02-18 17:53:54 +09004152 mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY, pts[0], pts[1]);
Gilles Debunned88876a2012-03-16 17:34:04 -07004153 }
4154 } else {
4155 if (isShowing()) {
4156 dismiss();
4157 }
4158 }
4159
4160 mPositionHasChanged = false;
4161 }
4162 }
4163
4164 @Override
4165 protected void onDraw(Canvas c) {
Adam Powell3fceabd2014-08-19 18:28:04 -07004166 final int drawWidth = mDrawable.getIntrinsicWidth();
4167 final int left = getHorizontalOffset();
4168
4169 mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
Gilles Debunned88876a2012-03-16 17:34:04 -07004170 mDrawable.draw(c);
4171 }
4172
Adam Powell3fceabd2014-08-19 18:28:04 -07004173 private int getHorizontalOffset() {
4174 final int width = getPreferredWidth();
4175 final int drawWidth = mDrawable.getIntrinsicWidth();
4176 final int left;
4177 switch (mHorizontalGravity) {
4178 case Gravity.LEFT:
4179 left = 0;
4180 break;
4181 default:
4182 case Gravity.CENTER:
4183 left = (width - drawWidth) / 2;
4184 break;
4185 case Gravity.RIGHT:
4186 left = width - drawWidth;
4187 break;
4188 }
4189 return left;
4190 }
4191
4192 protected int getCursorOffset() {
4193 return 0;
4194 }
4195
Gilles Debunned88876a2012-03-16 17:34:04 -07004196 @Override
4197 public boolean onTouchEvent(MotionEvent ev) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01004198 updateFloatingToolbarVisibility(ev);
4199
Gilles Debunned88876a2012-03-16 17:34:04 -07004200 switch (ev.getActionMasked()) {
4201 case MotionEvent.ACTION_DOWN: {
4202 startTouchUpFilter(getCurrentCursorOffset());
4203 mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
4204 mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
4205
4206 final PositionListener positionListener = getPositionListener();
4207 mLastParentX = positionListener.getPositionX();
4208 mLastParentY = positionListener.getPositionY();
4209 mIsDragging = true;
Mady Mellora6a0f782015-07-10 16:43:32 -07004210 mPreviousLineTouched = UNSET_LINE;
Gilles Debunned88876a2012-03-16 17:34:04 -07004211 break;
4212 }
4213
4214 case MotionEvent.ACTION_MOVE: {
4215 final float rawX = ev.getRawX();
4216 final float rawY = ev.getRawY();
4217
4218 // Vertical hysteresis: vertical down movement tends to snap to ideal offset
4219 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
4220 final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
4221 float newVerticalOffset;
4222 if (previousVerticalOffset < mIdealVerticalOffset) {
4223 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
4224 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
4225 } else {
4226 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
4227 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
4228 }
4229 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
4230
Keisuke Kuroyanagibc89a5c2015-05-18 14:49:29 +09004231 final float newPosX =
4232 rawX - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
Gilles Debunned88876a2012-03-16 17:34:04 -07004233 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
4234
4235 updatePosition(newPosX, newPosY);
4236 break;
4237 }
4238
4239 case MotionEvent.ACTION_UP:
4240 filterOnTouchUp();
4241 mIsDragging = false;
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004242 updateDrawable();
Gilles Debunned88876a2012-03-16 17:34:04 -07004243 break;
4244
4245 case MotionEvent.ACTION_CANCEL:
4246 mIsDragging = false;
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004247 updateDrawable();
Gilles Debunned88876a2012-03-16 17:34:04 -07004248 break;
4249 }
4250 return true;
4251 }
4252
4253 public boolean isDragging() {
4254 return mIsDragging;
4255 }
4256
Clara Bayarri6351e662015-03-16 23:17:59 +00004257 void onHandleMoved() {}
Gilles Debunned88876a2012-03-16 17:34:04 -07004258
Clara Bayarri6351e662015-03-16 23:17:59 +00004259 public void onDetached() {}
Gilles Debunned88876a2012-03-16 17:34:04 -07004260 }
4261
Mady Mellorff66ca52015-07-08 12:31:45 -07004262 /**
4263 * Returns the active layout (hint or text layout). Note that the text layout can be null.
4264 */
4265 private Layout getActiveLayout() {
4266 Layout layout = mTextView.getLayout();
4267 Layout hintLayout = mTextView.getHintLayout();
4268 if (TextUtils.isEmpty(layout.getText()) && hintLayout != null &&
4269 !TextUtils.isEmpty(hintLayout.getText())) {
4270 layout = hintLayout;
4271 }
4272 return layout;
4273 }
4274
Gilles Debunned88876a2012-03-16 17:34:04 -07004275 private class InsertionHandleView extends HandleView {
4276 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
4277 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
4278
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004279 // Used to detect taps on the insertion handle, which will affect the insertion action mode
Gilles Debunned88876a2012-03-16 17:34:04 -07004280 private float mDownPositionX, mDownPositionY;
4281 private Runnable mHider;
4282
4283 public InsertionHandleView(Drawable drawable) {
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09004284 super(drawable, drawable, com.android.internal.R.id.insertion_handle);
Gilles Debunned88876a2012-03-16 17:34:04 -07004285 }
4286
4287 @Override
4288 public void show() {
4289 super.show();
4290
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004291 final long durationSinceCutOrCopy =
Andrei Stingaceanu77b9c382015-05-06 13:25:19 +01004292 SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004293
4294 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004295 if (mInsertionActionModeRunnable != null
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004296 && ((mTapState == TAP_STATE_DOUBLE_TAP)
4297 || (mTapState == TAP_STATE_TRIPLE_CLICK)
4298 || isCursorInsideEasyCorrectionSpan())) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004299 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004300 }
4301
4302 // Prepare and schedule the single tap runnable to run exactly after the double tap
4303 // timeout has passed.
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004304 if ((mTapState != TAP_STATE_DOUBLE_TAP) && (mTapState != TAP_STATE_TRIPLE_CLICK)
4305 && !isCursorInsideEasyCorrectionSpan()
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01004306 && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004307 if (mTextActionMode == null) {
4308 if (mInsertionActionModeRunnable == null) {
4309 mInsertionActionModeRunnable = new Runnable() {
4310 @Override
4311 public void run() {
4312 startInsertionActionMode();
4313 }
4314 };
4315 }
4316 mTextView.postDelayed(
4317 mInsertionActionModeRunnable,
4318 ViewConfiguration.getDoubleTapTimeout() + 1);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004319 }
4320
Gilles Debunned88876a2012-03-16 17:34:04 -07004321 }
4322
4323 hideAfterDelay();
4324 }
4325
Gilles Debunned88876a2012-03-16 17:34:04 -07004326 private void hideAfterDelay() {
4327 if (mHider == null) {
4328 mHider = new Runnable() {
4329 public void run() {
4330 hide();
4331 }
4332 };
4333 } else {
4334 removeHiderCallback();
4335 }
4336 mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
4337 }
4338
4339 private void removeHiderCallback() {
4340 if (mHider != null) {
4341 mTextView.removeCallbacks(mHider);
4342 }
4343 }
4344
4345 @Override
4346 protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4347 return drawable.getIntrinsicWidth() / 2;
4348 }
4349
4350 @Override
Adam Powell3fceabd2014-08-19 18:28:04 -07004351 protected int getHorizontalGravity(boolean isRtlRun) {
4352 return Gravity.CENTER_HORIZONTAL;
4353 }
4354
4355 @Override
4356 protected int getCursorOffset() {
4357 int offset = super.getCursorOffset();
4358 final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
4359 if (cursor != null) {
4360 cursor.getPadding(mTempRect);
4361 offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
4362 }
4363 return offset;
4364 }
4365
4366 @Override
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004367 int getCursorHorizontalPosition(Layout layout, int offset) {
4368 final Drawable drawable = mCursorCount > 0 ? mCursorDrawable[0] : null;
4369 if (drawable != null) {
4370 final float horizontal = layout.getPrimaryHorizontal(offset);
4371 return clampCursorHorizontalPosition(drawable, horizontal) + mTempRect.left;
4372 }
4373 return super.getCursorHorizontalPosition(layout, offset);
4374 }
4375
4376 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07004377 public boolean onTouchEvent(MotionEvent ev) {
4378 final boolean result = super.onTouchEvent(ev);
4379
4380 switch (ev.getActionMasked()) {
4381 case MotionEvent.ACTION_DOWN:
4382 mDownPositionX = ev.getRawX();
4383 mDownPositionY = ev.getRawY();
4384 break;
4385
4386 case MotionEvent.ACTION_UP:
4387 if (!offsetHasBeenChanged()) {
4388 final float deltaX = mDownPositionX - ev.getRawX();
4389 final float deltaY = mDownPositionY - ev.getRawY();
4390 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4391
4392 final ViewConfiguration viewConfiguration = ViewConfiguration.get(
4393 mTextView.getContext());
4394 final int touchSlop = viewConfiguration.getScaledTouchSlop();
4395
4396 if (distanceSquared < touchSlop * touchSlop) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004397 // Tapping on the handle toggles the insertion action mode.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004398 if (mTextActionMode != null) {
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08004399 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07004400 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004401 startInsertionActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07004402 }
4403 }
Abodunrinwa Tokibcdf0ab2015-04-25 00:11:25 +01004404 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004405 if (mTextActionMode != null) {
4406 mTextActionMode.invalidateContentRect();
Abodunrinwa Tokibcdf0ab2015-04-25 00:11:25 +01004407 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004408 }
4409 hideAfterDelay();
4410 break;
4411
4412 case MotionEvent.ACTION_CANCEL:
4413 hideAfterDelay();
4414 break;
4415
4416 default:
4417 break;
4418 }
4419
4420 return result;
4421 }
4422
4423 @Override
4424 public int getCurrentCursorOffset() {
4425 return mTextView.getSelectionStart();
4426 }
4427
4428 @Override
4429 public void updateSelection(int offset) {
4430 Selection.setSelection((Spannable) mTextView.getText(), offset);
4431 }
4432
4433 @Override
4434 public void updatePosition(float x, float y) {
Mady Melloree3821e2015-06-05 11:12:01 -07004435 Layout layout = mTextView.getLayout();
4436 int offset;
4437 if (layout != null) {
Mady Mellora6a0f782015-07-10 16:43:32 -07004438 if (mPreviousLineTouched == UNSET_LINE) {
4439 mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4440 }
4441 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
Mady Melloree3821e2015-06-05 11:12:01 -07004442 offset = mTextView.getOffsetAtCoordinate(currLine, x);
Mady Mellora6a0f782015-07-10 16:43:32 -07004443 mPreviousLineTouched = currLine;
Mady Melloree3821e2015-06-05 11:12:01 -07004444 } else {
4445 offset = mTextView.getOffsetForPosition(x, y);
4446 }
4447 positionAtCursorOffset(offset, false);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004448 if (mTextActionMode != null) {
4449 mTextActionMode.invalidate();
Clara Bayarri1baed512015-05-11 15:29:16 +01004450 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004451 }
4452
4453 @Override
4454 void onHandleMoved() {
4455 super.onHandleMoved();
4456 removeHiderCallback();
4457 }
4458
4459 @Override
4460 public void onDetached() {
4461 super.onDetached();
4462 removeHiderCallback();
4463 }
4464 }
4465
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004466 @Retention(RetentionPolicy.SOURCE)
4467 @IntDef({HANDLE_TYPE_SELECTION_START, HANDLE_TYPE_SELECTION_END})
4468 public @interface HandleType {}
4469 public static final int HANDLE_TYPE_SELECTION_START = 0;
4470 public static final int HANDLE_TYPE_SELECTION_END = 1;
4471
4472 private class SelectionHandleView extends HandleView {
4473 // Indicates the handle type, selection start (HANDLE_TYPE_SELECTION_START) or selection
4474 // end (HANDLE_TYPE_SELECTION_END).
4475 @HandleType
4476 private final int mHandleType;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004477 // Indicates whether the cursor is making adjustments within a word.
4478 private boolean mInWord = false;
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004479 // Difference between touch position and word boundary position.
4480 private float mTouchWordDelta;
Mady Mellore264ac32015-06-22 16:46:29 -07004481 // X value of the previous updatePosition call.
4482 private float mPrevX;
4483 // Indicates if the handle has moved a boundary between LTR and RTL text.
4484 private boolean mLanguageDirectionChanged = false;
Mady Mellor42390aa2015-07-24 13:08:42 -07004485 // Distance from edge of horizontally scrolling text view
4486 // to use to switch to character mode.
4487 private final float mTextViewEdgeSlop;
4488 // Used to save text view location.
4489 private final int[] mTextViewLocation = new int[2];
Gilles Debunned88876a2012-03-16 17:34:04 -07004490
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004491 public SelectionHandleView(Drawable drawableLtr, Drawable drawableRtl, int id,
4492 @HandleType int handleType) {
4493 super(drawableLtr, drawableRtl, id);
4494 mHandleType = handleType;
4495 ViewConfiguration viewConfiguration = ViewConfiguration.get(mTextView.getContext());
Mady Mellor42390aa2015-07-24 13:08:42 -07004496 mTextViewEdgeSlop = viewConfiguration.getScaledTouchSlop() * 4;
Gilles Debunned88876a2012-03-16 17:34:04 -07004497 }
4498
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004499 private boolean isStartHandle() {
4500 return mHandleType == HANDLE_TYPE_SELECTION_START;
4501 }
4502
Gilles Debunned88876a2012-03-16 17:34:04 -07004503 @Override
4504 protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004505 if (isRtlRun == isStartHandle()) {
Mady Mellor709386f2015-05-14 12:41:18 -07004506 return drawable.getIntrinsicWidth() / 4;
4507 } else {
4508 return (drawable.getIntrinsicWidth() * 3) / 4;
4509 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004510 }
4511
4512 @Override
Adam Powell3fceabd2014-08-19 18:28:04 -07004513 protected int getHorizontalGravity(boolean isRtlRun) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004514 return (isRtlRun == isStartHandle()) ? Gravity.LEFT : Gravity.RIGHT;
Adam Powell3fceabd2014-08-19 18:28:04 -07004515 }
4516
4517 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07004518 public int getCurrentCursorOffset() {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004519 return isStartHandle() ? mTextView.getSelectionStart() : mTextView.getSelectionEnd();
Gilles Debunned88876a2012-03-16 17:34:04 -07004520 }
4521
4522 @Override
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004523 protected void updateSelection(int offset) {
4524 if (isStartHandle()) {
4525 Selection.setSelection((Spannable) mTextView.getText(), offset,
4526 mTextView.getSelectionEnd());
4527 } else {
4528 Selection.setSelection((Spannable) mTextView.getText(),
4529 mTextView.getSelectionStart(), offset);
4530 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004531 updateDrawable();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004532 if (mTextActionMode != null) {
4533 mTextActionMode.invalidate();
Clara Bayarri13152d12015-04-09 12:02:04 +01004534 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004535 }
4536
4537 @Override
4538 public void updatePosition(float x, float y) {
Mady Mellor81fa3e82015-05-14 09:17:41 -07004539 final Layout layout = mTextView.getLayout();
Mady Mellorcc65c372015-06-17 09:25:19 -07004540 if (layout == null) {
4541 // HandleView will deal appropriately in positionAtCursorOffset when
4542 // layout is null.
Mady Mellor42390aa2015-07-24 13:08:42 -07004543 positionAndAdjustForCrossingHandles(mTextView.getOffsetForPosition(x, y));
Mady Mellorcc65c372015-06-17 09:25:19 -07004544 return;
4545 }
4546
Mady Mellora6a0f782015-07-10 16:43:32 -07004547 if (mPreviousLineTouched == UNSET_LINE) {
4548 mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4549 }
4550
Mady Mellorb9bbbb12015-03-23 11:50:46 -07004551 boolean positionCursor = false;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004552 final int anotherHandleOffset =
4553 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
Mady Mellora6a0f782015-07-10 16:43:32 -07004554 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
Mady Mellorcc65c372015-06-17 09:25:19 -07004555 int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
Mady Mellor81fa3e82015-05-14 09:17:41 -07004556
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004557 if (isStartHandle() && initialOffset >= anotherHandleOffset
4558 || !isStartHandle() && initialOffset <= anotherHandleOffset) {
4559 // Handles have crossed, bound it to the first selected line and
Mady Mellor81fa3e82015-05-14 09:17:41 -07004560 // adjust by word / char as normal.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004561 currLine = layout.getLineForOffset(anotherHandleOffset);
Mady Mellor81fa3e82015-05-14 09:17:41 -07004562 initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4563 }
4564
4565 int offset = initialOffset;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004566 final int wordEnd = getWordEnd(offset);
4567 final int wordStart = getWordStart(offset);
Gilles Debunned88876a2012-03-16 17:34:04 -07004568
Mady Mellore264ac32015-06-22 16:46:29 -07004569 if (mPrevX == UNSET_X_VALUE) {
4570 mPrevX = x;
4571 }
4572
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004573 final int currentOffset = getCurrentCursorOffset();
4574 final boolean rtlAtCurrentOffset = layout.isRtlCharAt(currentOffset);
Mady Mellore264ac32015-06-22 16:46:29 -07004575 final boolean atRtl = layout.isRtlCharAt(offset);
4576 final boolean isLvlBoundary = layout.isLevelBoundary(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004577
4578 // We can't determine if the user is expanding or shrinking the selection if they're
4579 // on a bi-di boundary, so until they've moved past the boundary we'll just place
4580 // the cursor at the current position.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004581 if (isLvlBoundary || (rtlAtCurrentOffset && !atRtl) || (!rtlAtCurrentOffset && atRtl)) {
Mady Mellore264ac32015-06-22 16:46:29 -07004582 // We're on a boundary or this is the first direction change -- just update
4583 // to the current position.
4584 mLanguageDirectionChanged = true;
4585 mTouchWordDelta = 0.0f;
Mady Mellor42390aa2015-07-24 13:08:42 -07004586 positionAndAdjustForCrossingHandles(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004587 return;
4588 } else if (mLanguageDirectionChanged && !isLvlBoundary) {
4589 // We've just moved past the boundary so update the position. After this we can
4590 // figure out if the user is expanding or shrinking to go by word or character.
Mady Mellor42390aa2015-07-24 13:08:42 -07004591 positionAndAdjustForCrossingHandles(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004592 mTouchWordDelta = 0.0f;
4593 mLanguageDirectionChanged = false;
4594 return;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004595 }
4596
4597 boolean isExpanding;
4598 final float xDiff = x - mPrevX;
Keisuke Kuroyanagi26454142015-12-02 15:04:57 -08004599 if (isStartHandle()) {
4600 isExpanding = currLine < mPreviousLineTouched;
Mady Mellore264ac32015-06-22 16:46:29 -07004601 } else {
Keisuke Kuroyanagi26454142015-12-02 15:04:57 -08004602 isExpanding = currLine > mPreviousLineTouched;
4603 }
4604 if (atRtl == isStartHandle()) {
4605 isExpanding |= xDiff > 0;
4606 } else {
4607 isExpanding |= xDiff < 0;
Mady Mellore264ac32015-06-22 16:46:29 -07004608 }
4609
Mady Mellor42390aa2015-07-24 13:08:42 -07004610 if (mTextView.getHorizontallyScrolling()) {
4611 if (positionNearEdgeOfScrollingView(x, atRtl)
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004612 && ((isStartHandle() && mTextView.getScrollX() != 0)
4613 || (!isStartHandle()
4614 && mTextView.canScrollHorizontally(atRtl ? -1 : 1)))
4615 && ((isExpanding && ((isStartHandle() && offset < currentOffset)
4616 || (!isStartHandle() && offset > currentOffset)))
4617 || !isExpanding)) {
4618 // If we're expanding ensure that the offset is actually expanding compared to
4619 // the current offset, if the handle snapped to the word, the finger position
Mady Mellor42390aa2015-07-24 13:08:42 -07004620 // may be out of sync and we don't want the selection to jump back.
4621 mTouchWordDelta = 0.0f;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004622 final int nextOffset = (atRtl == isStartHandle())
4623 ? layout.getOffsetToRightOf(mPreviousOffset)
Mady Mellor42390aa2015-07-24 13:08:42 -07004624 : layout.getOffsetToLeftOf(mPreviousOffset);
4625 positionAndAdjustForCrossingHandles(nextOffset);
4626 return;
4627 }
4628 }
4629
Mady Mellore264ac32015-06-22 16:46:29 -07004630 if (isExpanding) {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004631 // User is increasing the selection.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004632 final boolean snapToWord = !mInWord
4633 || (isStartHandle() ? currLine < mPrevLine : currLine > mPrevLine);
4634 if (snapToWord) {
Mady Mellora5266832015-06-26 14:28:12 -07004635 // Sometimes words can be broken across lines (Chinese, hyphenation).
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004636 // We still snap to the word boundary but we only use the letters on the
Mady Mellora5266832015-06-26 14:28:12 -07004637 // current line to determine if the user is far enough into the word to snap.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004638 int wordBoundary = isStartHandle() ? wordStart : wordEnd;
4639 if (layout != null && layout.getLineForOffset(wordBoundary) != currLine) {
4640 wordBoundary = isStartHandle() ?
4641 layout.getLineStart(currLine) : layout.getLineEnd(currLine);
Mady Mellora5266832015-06-26 14:28:12 -07004642 }
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004643 final int offsetThresholdToSnap = isStartHandle()
4644 ? wordEnd - ((wordEnd - wordBoundary) / 2)
4645 : wordStart + ((wordBoundary - wordStart) / 2);
4646 if (isStartHandle()
4647 && (offset <= offsetThresholdToSnap || currLine < mPrevLine)) {
4648 // User is far enough into the word or on a different line so we expand by
4649 // word.
4650 offset = wordStart;
4651 } else if (!isStartHandle()
4652 && (offset >= offsetThresholdToSnap || currLine > mPrevLine)) {
4653 // User is far enough into the word or on a different line so we expand by
4654 // word.
4655 offset = wordEnd;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004656 } else {
Mady Mellorc2225b92015-04-01 15:59:20 -07004657 offset = mPreviousOffset;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004658 }
4659 }
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004660 if (layout != null && (isStartHandle() && offset < initialOffset)
4661 || (!isStartHandle() && offset > initialOffset)) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004662 final float adjustedX = layout.getPrimaryHorizontal(offset);
4663 mTouchWordDelta =
4664 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
Keisuke Kuroyanagi50a927c2015-05-07 17:34:21 +09004665 } else {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004666 mTouchWordDelta = 0.0f;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004667 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004668 positionCursor = true;
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004669 } else {
4670 final int adjustedOffset =
4671 mTextView.getOffsetAtCoordinate(currLine, x - mTouchWordDelta);
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004672 final boolean shrinking = isStartHandle()
4673 ? adjustedOffset > mPreviousOffset || currLine > mPrevLine
4674 : adjustedOffset < mPreviousOffset || currLine < mPrevLine;
4675 if (shrinking) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004676 // User is shrinking the selection.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004677 if (currLine != mPrevLine) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004678 // We're on a different line, so we'll snap to word boundaries.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004679 offset = isStartHandle() ? wordStart : wordEnd;
4680 if (layout != null && (isStartHandle() && offset < initialOffset)
4681 || (!isStartHandle() && offset > initialOffset)) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004682 final float adjustedX = layout.getPrimaryHorizontal(offset);
4683 mTouchWordDelta =
4684 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4685 } else {
4686 mTouchWordDelta = 0.0f;
4687 }
4688 } else {
4689 offset = adjustedOffset;
4690 }
4691 positionCursor = true;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004692 } else if ((isStartHandle() && adjustedOffset < mPreviousOffset)
4693 || (!isStartHandle() && adjustedOffset > mPreviousOffset)) {
4694 // Handle has jumped to the word boundary, and the user is moving
Mady Mellor43fd2f42015-06-08 14:03:34 -07004695 // their finger towards the handle, the delta should be updated.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004696 mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x) -
4697 layout.getPrimaryHorizontal(mPreviousOffset);
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004698 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004699 }
4700
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004701 if (positionCursor) {
Mady Mellora6a0f782015-07-10 16:43:32 -07004702 mPreviousLineTouched = currLine;
Mady Mellor42390aa2015-07-24 13:08:42 -07004703 positionAndAdjustForCrossingHandles(offset);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004704 }
Mady Mellore264ac32015-06-22 16:46:29 -07004705 mPrevX = x;
Gilles Debunned88876a2012-03-16 17:34:04 -07004706 }
4707
Yoshiki Iguchi9582e152015-10-15 13:34:41 +09004708 /**
4709 * @param offset Cursor offset. Must be in [-1, length].
4710 * @param parentScrolled If the parent has been scrolled or not.
4711 */
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004712 @Override
Mady Mellor36d5a7b2015-05-22 10:31:12 -07004713 protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4714 super.positionAtCursorOffset(offset, parentScrolled);
Yoshiki Iguchi9582e152015-10-15 13:34:41 +09004715 mInWord = (offset != -1) && !getWordIteratorWithText().isBoundary(offset);
Mady Mellor36d5a7b2015-05-22 10:31:12 -07004716 }
4717
4718 @Override
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004719 public boolean onTouchEvent(MotionEvent event) {
4720 boolean superResult = super.onTouchEvent(event);
Mady Mellora6a0f782015-07-10 16:43:32 -07004721 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
4722 // Reset the touch word offset and x value when the user
4723 // re-engages the handle.
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004724 mTouchWordDelta = 0.0f;
Mady Mellore264ac32015-06-22 16:46:29 -07004725 mPrevX = UNSET_X_VALUE;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004726 }
4727 return superResult;
4728 }
Mady Mellor42390aa2015-07-24 13:08:42 -07004729
Mady Mellor42390aa2015-07-24 13:08:42 -07004730 private void positionAndAdjustForCrossingHandles(int offset) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004731 final int anotherHandleOffset =
4732 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
4733 if ((isStartHandle() && offset >= anotherHandleOffset)
4734 || (!isStartHandle() && offset <= anotherHandleOffset)) {
Mady Mellor42390aa2015-07-24 13:08:42 -07004735 // Handles can not cross and selection is at least one character.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004736 offset = getNextCursorOffset(anotherHandleOffset, !isStartHandle());
Mady Mellor42390aa2015-07-24 13:08:42 -07004737 mTouchWordDelta = 0.0f;
4738 }
4739 positionAtCursorOffset(offset, false);
4740 }
4741
Mady Mellor42390aa2015-07-24 13:08:42 -07004742 private boolean positionNearEdgeOfScrollingView(float x, boolean atRtl) {
4743 mTextView.getLocationOnScreen(mTextViewLocation);
4744 boolean nearEdge;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004745 if (atRtl == isStartHandle()) {
Mady Mellor42390aa2015-07-24 13:08:42 -07004746 int rightEdge = mTextViewLocation[0] + mTextView.getWidth()
4747 - mTextView.getPaddingRight();
4748 nearEdge = x > rightEdge - mTextViewEdgeSlop;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004749 } else {
4750 int leftEdge = mTextViewLocation[0] + mTextView.getPaddingLeft();
4751 nearEdge = x < leftEdge + mTextViewEdgeSlop;
Mady Mellor42390aa2015-07-24 13:08:42 -07004752 }
4753 return nearEdge;
4754 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004755 }
4756
Mady Mellorcc65c372015-06-17 09:25:19 -07004757 private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
Mady Mellor80679072015-07-09 16:05:36 -07004758 final int trueLine = mTextView.getLineAtCoordinate(y);
Mady Mellorcc65c372015-06-17 09:25:19 -07004759 if (layout == null || prevLine > layout.getLineCount()
4760 || layout.getLineCount() <= 0 || prevLine < 0) {
4761 // Invalid parameters, just return whatever line is at y.
Mady Mellor80679072015-07-09 16:05:36 -07004762 return trueLine;
4763 }
4764
4765 if (Math.abs(trueLine - prevLine) >= 2) {
4766 // Only stick to lines if we're within a line of the previous selection.
4767 return trueLine;
Mady Mellorcc65c372015-06-17 09:25:19 -07004768 }
4769
4770 final float verticalOffset = mTextView.viewportToContentVerticalOffset();
4771 final int lineCount = layout.getLineCount();
4772 final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
4773
4774 final float firstLineTop = layout.getLineTop(0) + verticalOffset;
4775 final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
4776 final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
4777
4778 final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
4779 final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
4780 final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
4781
4782 // Determine if we've moved lines based on y position and previous line.
4783 int currLine;
4784 if (y <= yTopBound) {
4785 currLine = Math.max(prevLine - 1, 0);
4786 } else if (y >= yBottomBound) {
4787 currLine = Math.min(prevLine + 1, lineCount - 1);
4788 } else {
4789 currLine = prevLine;
4790 }
4791 return currLine;
4792 }
4793
Gilles Debunned88876a2012-03-16 17:34:04 -07004794 /**
4795 * A CursorController instance can be used to control a cursor in the text.
4796 */
4797 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
4798 /**
4799 * Makes the cursor controller visible on screen.
4800 * See also {@link #hide()}.
4801 */
4802 public void show();
4803
4804 /**
4805 * Hide the cursor controller from screen.
4806 * See also {@link #show()}.
4807 */
4808 public void hide();
4809
4810 /**
4811 * Called when the view is detached from window. Perform house keeping task, such as
4812 * stopping Runnable thread that would otherwise keep a reference on the context, thus
4813 * preventing the activity from being recycled.
4814 */
4815 public void onDetached();
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08004816
4817 public boolean isCursorBeingModified();
4818
4819 public boolean isActive();
Gilles Debunned88876a2012-03-16 17:34:04 -07004820 }
4821
4822 private class InsertionPointCursorController implements CursorController {
4823 private InsertionHandleView mHandle;
4824
4825 public void show() {
4826 getHandle().show();
Andrei Stingaceanu35c550c2015-05-07 16:49:49 +01004827
4828 if (mSelectionModifierCursorController != null) {
4829 mSelectionModifierCursorController.hide();
4830 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004831 }
4832
Gilles Debunned88876a2012-03-16 17:34:04 -07004833 public void hide() {
4834 if (mHandle != null) {
4835 mHandle.hide();
4836 }
4837 }
4838
4839 public void onTouchModeChanged(boolean isInTouchMode) {
4840 if (!isInTouchMode) {
4841 hide();
4842 }
4843 }
4844
4845 private InsertionHandleView getHandle() {
4846 if (mSelectHandleCenter == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004847 mSelectHandleCenter = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004848 mTextView.mTextSelectHandleRes);
4849 }
4850 if (mHandle == null) {
4851 mHandle = new InsertionHandleView(mSelectHandleCenter);
4852 }
4853 return mHandle;
4854 }
4855
4856 @Override
4857 public void onDetached() {
4858 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4859 observer.removeOnTouchModeChangeListener(this);
4860
4861 if (mHandle != null) mHandle.onDetached();
4862 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08004863
4864 @Override
4865 public boolean isCursorBeingModified() {
4866 return mHandle != null && mHandle.isDragging();
4867 }
4868
4869 @Override
4870 public boolean isActive() {
4871 return mHandle != null && mHandle.isShowing();
4872 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004873 }
4874
4875 class SelectionModifierCursorController implements CursorController {
Gilles Debunned88876a2012-03-16 17:34:04 -07004876 // The cursor controller handles, lazily created when shown.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004877 private SelectionHandleView mStartHandle;
4878 private SelectionHandleView mEndHandle;
Gilles Debunned88876a2012-03-16 17:34:04 -07004879 // The offsets of that last touch down event. Remembered to start selection there.
4880 private int mMinTouchOffset, mMaxTouchOffset;
4881
Gilles Debunned88876a2012-03-16 17:34:04 -07004882 private float mDownPositionX, mDownPositionY;
4883 private boolean mGestureStayedInTapRegion;
4884
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004885 // Where the user first starts the drag motion.
4886 private int mStartOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004887
Mady Mellor7a936442015-05-20 10:05:52 -07004888 private boolean mHaventMovedEnoughToStartDrag;
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07004889 // The line that a selection happened most recently with the drag accelerator.
4890 private int mLineSelectionIsOn = -1;
4891 // Whether the drag accelerator has selected past the initial line.
4892 private boolean mSwitchedLines = false;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004893
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004894 // Indicates the drag accelerator mode that the user is currently using.
4895 private int mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
4896 // Drag accelerator is inactive.
4897 private static final int DRAG_ACCELERATOR_MODE_INACTIVE = 0;
4898 // Character based selection by dragging. Only for mouse.
4899 private static final int DRAG_ACCELERATOR_MODE_CHARACTER = 1;
4900 // Word based selection by dragging. Enabled after long pressing or double tapping.
4901 private static final int DRAG_ACCELERATOR_MODE_WORD = 2;
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09004902 // Paragraph based selection by dragging. Enabled after mouse triple click.
4903 private static final int DRAG_ACCELERATOR_MODE_PARAGRAPH = 3;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004904
Gilles Debunned88876a2012-03-16 17:34:04 -07004905 SelectionModifierCursorController() {
4906 resetTouchOffsets();
4907 }
4908
4909 public void show() {
4910 if (mTextView.isInBatchEditMode()) {
4911 return;
4912 }
4913 initDrawables();
4914 initHandles();
Gilles Debunned88876a2012-03-16 17:34:04 -07004915 }
4916
4917 private void initDrawables() {
4918 if (mSelectHandleLeft == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004919 mSelectHandleLeft = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004920 mTextView.mTextSelectHandleLeftRes);
4921 }
4922 if (mSelectHandleRight == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004923 mSelectHandleRight = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004924 mTextView.mTextSelectHandleRightRes);
4925 }
4926 }
4927
4928 private void initHandles() {
4929 // Lazy object creation has to be done before updatePosition() is called.
4930 if (mStartHandle == null) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004931 mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight,
4932 com.android.internal.R.id.selection_start_handle,
4933 HANDLE_TYPE_SELECTION_START);
Gilles Debunned88876a2012-03-16 17:34:04 -07004934 }
4935 if (mEndHandle == null) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004936 mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft,
4937 com.android.internal.R.id.selection_end_handle,
4938 HANDLE_TYPE_SELECTION_END);
Gilles Debunned88876a2012-03-16 17:34:04 -07004939 }
4940
4941 mStartHandle.show();
4942 mEndHandle.show();
4943
Gilles Debunned88876a2012-03-16 17:34:04 -07004944 hideInsertionPointCursorController();
4945 }
4946
4947 public void hide() {
4948 if (mStartHandle != null) mStartHandle.hide();
4949 if (mEndHandle != null) mEndHandle.hide();
4950 }
4951
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004952 public void enterDrag(int dragAcceleratorMode) {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004953 // Just need to init the handles / hide insertion cursor.
4954 show();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004955 mDragAcceleratorMode = dragAcceleratorMode;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004956 // Start location of selection.
4957 mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
4958 mLastDownPositionY);
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07004959 mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004960 // Don't show the handles until user has lifted finger.
4961 hide();
4962
4963 // This stops scrolling parents from intercepting the touch event, allowing
4964 // the user to continue dragging across the screen to select text; TextView will
4965 // scroll as necessary.
4966 mTextView.getParent().requestDisallowInterceptTouchEvent(true);
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004967 mTextView.cancelLongPress();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004968 }
4969
Gilles Debunned88876a2012-03-16 17:34:04 -07004970 public void onTouchEvent(MotionEvent event) {
4971 // This is done even when the View does not have focus, so that long presses can start
4972 // selection and tap can move cursor from this tap position.
Mady Mellor7a936442015-05-20 10:05:52 -07004973 final float eventX = event.getX();
4974 final float eventY = event.getY();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004975 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
Gilles Debunned88876a2012-03-16 17:34:04 -07004976 switch (event.getActionMasked()) {
4977 case MotionEvent.ACTION_DOWN:
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004978 if (extractedTextModeWillBeStarted()) {
4979 // Prevent duplicating the selection handles until the mode starts.
4980 hide();
4981 } else {
4982 // Remember finger down position, to be able to start selection from there.
4983 mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
4984 eventX, eventY);
Gilles Debunned88876a2012-03-16 17:34:04 -07004985
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004986 // Double tap detection
4987 if (mGestureStayedInTapRegion) {
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004988 if (mTapState == TAP_STATE_DOUBLE_TAP
4989 || mTapState == TAP_STATE_TRIPLE_CLICK) {
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004990 final float deltaX = eventX - mDownPositionX;
4991 final float deltaY = eventY - mDownPositionY;
4992 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
Gilles Debunned88876a2012-03-16 17:34:04 -07004993
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004994 ViewConfiguration viewConfiguration = ViewConfiguration.get(
4995 mTextView.getContext());
4996 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
4997 boolean stayedInArea =
4998 distanceSquared < doubleTapSlop * doubleTapSlop;
Gilles Debunned88876a2012-03-16 17:34:04 -07004999
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005000 if (stayedInArea && (isMouse || isPositionOnText(eventX, eventY))) {
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09005001 if (mTapState == TAP_STATE_DOUBLE_TAP) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005002 selectCurrentWordAndStartDrag();
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09005003 } else if (mTapState == TAP_STATE_TRIPLE_CLICK) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005004 selectCurrentParagraphAndStartDrag();
5005 }
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005006 mDiscardNextActionUp = true;
5007 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005008 }
5009 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005010
Andrei Stingaceanu838307272015-06-19 17:58:47 +01005011 mDownPositionX = eventX;
5012 mDownPositionY = eventY;
5013 mGestureStayedInTapRegion = true;
5014 mHaventMovedEnoughToStartDrag = true;
5015 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005016 break;
5017
5018 case MotionEvent.ACTION_POINTER_DOWN:
5019 case MotionEvent.ACTION_POINTER_UP:
5020 // Handle multi-point gestures. Keep min and max offset positions.
5021 // Only activated for devices that correctly handle multi-touch.
5022 if (mTextView.getContext().getPackageManager().hasSystemFeature(
5023 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
5024 updateMinAndMaxOffsets(event);
5025 }
5026 break;
5027
5028 case MotionEvent.ACTION_MOVE:
Mady Mellor7a936442015-05-20 10:05:52 -07005029 final ViewConfiguration viewConfig = ViewConfiguration.get(
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005030 mTextView.getContext());
Mady Mellor7a936442015-05-20 10:05:52 -07005031 final int touchSlop = viewConfig.getScaledTouchSlop();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005032
Mady Mellor7a936442015-05-20 10:05:52 -07005033 if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
5034 final float deltaX = eventX - mDownPositionX;
5035 final float deltaY = eventY - mDownPositionY;
Gilles Debunned88876a2012-03-16 17:34:04 -07005036 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5037
Mady Mellor7a936442015-05-20 10:05:52 -07005038 if (mGestureStayedInTapRegion) {
5039 int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
5040 mGestureStayedInTapRegion =
5041 distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
5042 }
5043 if (mHaventMovedEnoughToStartDrag) {
5044 // We don't start dragging until the user has moved enough.
5045 mHaventMovedEnoughToStartDrag =
5046 distanceSquared <= touchSlop * touchSlop;
Gilles Debunned88876a2012-03-16 17:34:04 -07005047 }
5048 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005049
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005050 if (isMouse && !isDragAcceleratorActive()) {
5051 final int offset = mTextView.getOffsetForPosition(eventX, eventY);
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09005052 if (mTextView.hasSelection()
5053 && (!mHaventMovedEnoughToStartDrag || mStartOffset != offset)
5054 && offset >= mTextView.getSelectionStart()
5055 && offset <= mTextView.getSelectionEnd()) {
5056 startDragAndDrop();
5057 break;
5058 }
5059
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005060 if (mStartOffset != offset) {
5061 // Start character based drag accelerator.
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005062 stopTextActionMode();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005063 enterDrag(DRAG_ACCELERATOR_MODE_CHARACTER);
5064 mDiscardNextActionUp = true;
5065 mHaventMovedEnoughToStartDrag = false;
5066 }
5067 }
5068
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005069 if (mStartHandle != null && mStartHandle.isShowing()) {
5070 // Don't do the drag if the handles are showing already.
5071 break;
5072 }
5073
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005074 updateSelection(event);
Gilles Debunned88876a2012-03-16 17:34:04 -07005075 break;
5076
5077 case MotionEvent.ACTION_UP:
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005078 if (!isDragAcceleratorActive()) {
5079 break;
5080 }
5081 updateSelection(event);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005082
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005083 // No longer dragging to select text, let the parent intercept events.
5084 mTextView.getParent().requestDisallowInterceptTouchEvent(false);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005085
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005086 int startOffset = mTextView.getSelectionStart();
5087 int endOffset = mTextView.getSelectionEnd();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005088
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005089 // Since we don't let drag handles pass once they're visible, we need to
5090 // make sure the start / end locations are correct because the user *can*
5091 // switch directions during the initial drag.
5092 if (endOffset < startOffset) {
5093 int tmp = endOffset;
5094 endOffset = startOffset;
5095 startOffset = tmp;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005096
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005097 // Also update the selection with the right offsets in this case.
5098 Selection.setSelection((Spannable) mTextView.getText(),
5099 startOffset, endOffset);
5100 }
5101 if (startOffset != endOffset) {
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +01005102 startSelectionActionMode();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005103 }
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005104
5105 // No longer the first dragging motion, reset.
5106 resetDragAcceleratorState();
Gilles Debunned88876a2012-03-16 17:34:04 -07005107 break;
5108 }
5109 }
5110
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005111 private void updateSelection(MotionEvent event) {
5112 if (mTextView.getLayout() != null) {
5113 switch (mDragAcceleratorMode) {
5114 case DRAG_ACCELERATOR_MODE_CHARACTER:
5115 updateCharacterBasedSelection(event);
5116 break;
5117 case DRAG_ACCELERATOR_MODE_WORD:
5118 updateWordBasedSelection(event);
5119 break;
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005120 case DRAG_ACCELERATOR_MODE_PARAGRAPH:
5121 updateParagraphBasedSelection(event);
5122 break;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005123 }
5124 }
5125 }
5126
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005127 /**
5128 * If the TextView allows text selection, selects the current paragraph and starts a drag.
5129 *
5130 * @return true if the drag was started.
5131 */
5132 private boolean selectCurrentParagraphAndStartDrag() {
5133 if (mInsertionActionModeRunnable != null) {
5134 mTextView.removeCallbacks(mInsertionActionModeRunnable);
5135 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005136 stopTextActionMode();
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005137 if (!selectCurrentParagraph()) {
5138 return false;
5139 }
5140 enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_PARAGRAPH);
5141 return true;
5142 }
5143
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005144 private void updateCharacterBasedSelection(MotionEvent event) {
5145 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5146 Selection.setSelection((Spannable) mTextView.getText(), mStartOffset, offset);
5147 }
5148
5149 private void updateWordBasedSelection(MotionEvent event) {
5150 if (mHaventMovedEnoughToStartDrag) {
5151 return;
5152 }
5153 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5154 final ViewConfiguration viewConfig = ViewConfiguration.get(
5155 mTextView.getContext());
5156 final float eventX = event.getX();
5157 final float eventY = event.getY();
5158 final int currLine;
5159 if (isMouse) {
5160 // No need to offset the y coordinate for mouse input.
5161 currLine = mTextView.getLineAtCoordinate(eventY);
5162 } else {
5163 float y = eventY;
5164 if (mSwitchedLines) {
5165 // Offset the finger by the same vertical offset as the handles.
5166 // This improves visibility of the content being selected by
5167 // shifting the finger below the content, this is applied once
5168 // the user has switched lines.
5169 final int touchSlop = viewConfig.getScaledTouchSlop();
5170 final float fingerOffset = (mStartHandle != null)
5171 ? mStartHandle.getIdealVerticalOffset()
5172 : touchSlop;
5173 y = eventY - fingerOffset;
5174 }
5175
5176 currLine = getCurrentLineAdjustedForSlop(mTextView.getLayout(), mLineSelectionIsOn,
5177 y);
5178 if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
5179 // Break early here, we want to offset the finger position from
5180 // the selection highlight, once the user moved their finger
5181 // to a different line we should apply the offset and *not* switch
5182 // lines until recomputing the position with the finger offset.
5183 mSwitchedLines = true;
5184 return;
5185 }
5186 }
5187
5188 int startOffset;
5189 int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
5190 // Snap to word boundaries.
5191 if (mStartOffset < offset) {
5192 // Expanding with end handle.
5193 offset = getWordEnd(offset);
5194 startOffset = getWordStart(mStartOffset);
5195 } else {
5196 // Expanding with start handle.
5197 offset = getWordStart(offset);
5198 startOffset = getWordEnd(mStartOffset);
5199 }
5200 mLineSelectionIsOn = currLine;
5201 Selection.setSelection((Spannable) mTextView.getText(),
5202 startOffset, offset);
5203 }
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005204
5205 private void updateParagraphBasedSelection(MotionEvent event) {
5206 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5207
5208 final int start = Math.min(offset, mStartOffset);
5209 final int end = Math.max(offset, mStartOffset);
5210 final long paragraphsRange = getParagraphsRange(start, end);
5211 final int selectionStart = TextUtils.unpackRangeStartFromLong(paragraphsRange);
5212 final int selectionEnd = TextUtils.unpackRangeEndFromLong(paragraphsRange);
5213 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
5214 }
5215
Gilles Debunned88876a2012-03-16 17:34:04 -07005216 /**
5217 * @param event
5218 */
5219 private void updateMinAndMaxOffsets(MotionEvent event) {
5220 int pointerCount = event.getPointerCount();
5221 for (int index = 0; index < pointerCount; index++) {
5222 int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
5223 if (offset < mMinTouchOffset) mMinTouchOffset = offset;
5224 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
5225 }
5226 }
5227
5228 public int getMinTouchOffset() {
5229 return mMinTouchOffset;
5230 }
5231
5232 public int getMaxTouchOffset() {
5233 return mMaxTouchOffset;
5234 }
5235
5236 public void resetTouchOffsets() {
5237 mMinTouchOffset = mMaxTouchOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005238 resetDragAcceleratorState();
5239 }
5240
5241 private void resetDragAcceleratorState() {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005242 mStartOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005243 mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07005244 mSwitchedLines = false;
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005245 final int selectionStart = mTextView.getSelectionStart();
5246 final int selectionEnd = mTextView.getSelectionEnd();
5247 if (selectionStart > selectionEnd) {
5248 Selection.setSelection((Spannable) mTextView.getText(),
5249 selectionEnd, selectionStart);
5250 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005251 }
5252
5253 /**
5254 * @return true iff this controller is currently used to move the selection start.
5255 */
5256 public boolean isSelectionStartDragged() {
5257 return mStartHandle != null && mStartHandle.isDragging();
5258 }
5259
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005260 @Override
5261 public boolean isCursorBeingModified() {
5262 return isDragAcceleratorActive() || isSelectionStartDragged()
5263 || (mEndHandle != null && mEndHandle.isDragging());
5264 }
5265
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005266 /**
5267 * @return true if the user is selecting text using the drag accelerator.
5268 */
5269 public boolean isDragAcceleratorActive() {
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005270 return mDragAcceleratorMode != DRAG_ACCELERATOR_MODE_INACTIVE;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005271 }
5272
Gilles Debunned88876a2012-03-16 17:34:04 -07005273 public void onTouchModeChanged(boolean isInTouchMode) {
5274 if (!isInTouchMode) {
5275 hide();
5276 }
5277 }
5278
5279 @Override
5280 public void onDetached() {
5281 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5282 observer.removeOnTouchModeChangeListener(this);
5283
5284 if (mStartHandle != null) mStartHandle.onDetached();
5285 if (mEndHandle != null) mEndHandle.onDetached();
5286 }
Keisuke Kuroyanagibec97152016-02-24 18:40:09 -08005287
5288 @Override
5289 public boolean isActive() {
5290 return mStartHandle != null && mStartHandle.isShowing();
5291 }
Gilles Debunned88876a2012-03-16 17:34:04 -07005292 }
5293
5294 private class CorrectionHighlighter {
5295 private final Path mPath = new Path();
Chris Craik6a49dde2015-05-12 10:28:14 -07005296 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Gilles Debunned88876a2012-03-16 17:34:04 -07005297 private int mStart, mEnd;
5298 private long mFadingStartTime;
5299 private RectF mTempRectF;
5300 private final static int FADE_OUT_DURATION = 400;
5301
5302 public CorrectionHighlighter() {
5303 mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
5304 applicationScale);
5305 mPaint.setStyle(Paint.Style.FILL);
5306 }
5307
5308 public void highlight(CorrectionInfo info) {
5309 mStart = info.getOffset();
5310 mEnd = mStart + info.getNewText().length();
5311 mFadingStartTime = SystemClock.uptimeMillis();
5312
5313 if (mStart < 0 || mEnd < 0) {
5314 stopAnimation();
5315 }
5316 }
5317
5318 public void draw(Canvas canvas, int cursorOffsetVertical) {
5319 if (updatePath() && updatePaint()) {
5320 if (cursorOffsetVertical != 0) {
5321 canvas.translate(0, cursorOffsetVertical);
5322 }
5323
5324 canvas.drawPath(mPath, mPaint);
5325
5326 if (cursorOffsetVertical != 0) {
5327 canvas.translate(0, -cursorOffsetVertical);
5328 }
5329 invalidate(true); // TODO invalidate cursor region only
5330 } else {
5331 stopAnimation();
5332 invalidate(false); // TODO invalidate cursor region only
5333 }
5334 }
5335
5336 private boolean updatePaint() {
5337 final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5338 if (duration > FADE_OUT_DURATION) return false;
5339
5340 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5341 final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
5342 final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
5343 ((int) (highlightColorAlpha * coef) << 24);
5344 mPaint.setColor(color);
5345 return true;
5346 }
5347
5348 private boolean updatePath() {
5349 final Layout layout = mTextView.getLayout();
5350 if (layout == null) return false;
5351
5352 // Update in case text is edited while the animation is run
5353 final int length = mTextView.getText().length();
5354 int start = Math.min(length, mStart);
5355 int end = Math.min(length, mEnd);
5356
5357 mPath.reset();
5358 layout.getSelectionPath(start, end, mPath);
5359 return true;
5360 }
5361
5362 private void invalidate(boolean delayed) {
5363 if (mTextView.getLayout() == null) return;
5364
5365 if (mTempRectF == null) mTempRectF = new RectF();
5366 mPath.computeBounds(mTempRectF, false);
5367
5368 int left = mTextView.getCompoundPaddingLeft();
5369 int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
5370
5371 if (delayed) {
5372 mTextView.postInvalidateOnAnimation(
5373 left + (int) mTempRectF.left, top + (int) mTempRectF.top,
5374 left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
5375 } else {
5376 mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
5377 (int) mTempRectF.right, (int) mTempRectF.bottom);
5378 }
5379 }
5380
5381 private void stopAnimation() {
5382 Editor.this.mCorrectionHighlighter = null;
5383 }
5384 }
5385
5386 private static class ErrorPopup extends PopupWindow {
5387 private boolean mAbove = false;
5388 private final TextView mView;
5389 private int mPopupInlineErrorBackgroundId = 0;
5390 private int mPopupInlineErrorAboveBackgroundId = 0;
5391
5392 ErrorPopup(TextView v, int width, int height) {
5393 super(v, width, height);
5394 mView = v;
5395 // 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 -08005396 // shown and positioned. Initialized with below background, which should have
Gilles Debunned88876a2012-03-16 17:34:04 -07005397 // dimensions identical to the above version for this to work (and is more likely).
5398 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5399 com.android.internal.R.styleable.Theme_errorMessageBackground);
5400 mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
5401 }
5402
5403 void fixDirection(boolean above) {
5404 mAbove = above;
5405
5406 if (above) {
5407 mPopupInlineErrorAboveBackgroundId =
5408 getResourceId(mPopupInlineErrorAboveBackgroundId,
5409 com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
5410 } else {
5411 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5412 com.android.internal.R.styleable.Theme_errorMessageBackground);
5413 }
5414
5415 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
5416 mPopupInlineErrorBackgroundId);
5417 }
5418
5419 private int getResourceId(int currentId, int index) {
5420 if (currentId == 0) {
5421 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
5422 R.styleable.Theme);
5423 currentId = styledAttributes.getResourceId(index, 0);
5424 styledAttributes.recycle();
5425 }
5426 return currentId;
5427 }
5428
5429 @Override
5430 public void update(int x, int y, int w, int h, boolean force) {
5431 super.update(x, y, w, h, force);
5432
5433 boolean above = isAboveAnchor();
5434 if (above != mAbove) {
5435 fixDirection(above);
5436 }
5437 }
5438 }
5439
5440 static class InputContentType {
5441 int imeOptions = EditorInfo.IME_NULL;
5442 String privateImeOptions;
5443 CharSequence imeActionLabel;
5444 int imeActionId;
5445 Bundle extras;
5446 OnEditorActionListener onEditorActionListener;
5447 boolean enterDown;
Yohei Yukawad469f212016-01-21 12:38:09 -08005448 LocaleList imeHintLocales;
Gilles Debunned88876a2012-03-16 17:34:04 -07005449 }
5450
5451 static class InputMethodState {
Gilles Debunnec62589c2012-04-12 14:50:23 -07005452 ExtractedTextRequest mExtractedTextRequest;
5453 final ExtractedText mExtractedText = new ExtractedText();
Gilles Debunned88876a2012-03-16 17:34:04 -07005454 int mBatchEditNesting;
5455 boolean mCursorChanged;
5456 boolean mSelectionModeChanged;
5457 boolean mContentChanged;
5458 int mChangedStart, mChangedEnd, mChangedDelta;
5459 }
Satoshi Kataoka0e3849a2012-12-13 14:37:19 +09005460
James Cookf59152c2015-02-26 18:03:58 -08005461 /**
James Cook471559f2015-02-27 10:31:20 -08005462 * @return True iff (start, end) is a valid range within the text.
5463 */
5464 private static boolean isValidRange(CharSequence text, int start, int end) {
5465 return 0 <= start && start <= end && end <= text.length();
5466 }
5467
Seigo Nonakaa60160b2015-08-19 12:38:35 -07005468 @VisibleForTesting
5469 public SuggestionsPopupWindow getSuggestionsPopupWindowForTesting() {
5470 return mSuggestionsPopupWindow;
5471 }
5472
James Cook471559f2015-02-27 10:31:20 -08005473 /**
James Cookf59152c2015-02-26 18:03:58 -08005474 * An InputFilter that monitors text input to maintain undo history. It does not modify the
5475 * text being typed (and hence always returns null from the filter() method).
5476 */
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005477 public static class UndoInputFilter implements InputFilter {
James Cookf59152c2015-02-26 18:03:58 -08005478 private final Editor mEditor;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005479
James Cook48e0fac2015-02-25 15:44:51 -08005480 // Whether the current filter pass is directly caused by an end-user text edit.
5481 private boolean mIsUserEdit;
5482
James Cookd2026682015-03-03 14:40:14 -08005483 // Whether the text field is handling an IME composition. Must be parceled in case the user
5484 // rotates the screen during composition.
5485 private boolean mHasComposition;
James Cook48e0fac2015-02-25 15:44:51 -08005486
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005487 // Whether to merge events into one operation.
5488 private boolean mForceMerge;
5489
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005490 public UndoInputFilter(Editor editor) {
5491 mEditor = editor;
5492 }
5493
James Cookd2026682015-03-03 14:40:14 -08005494 public void saveInstanceState(Parcel parcel) {
5495 parcel.writeInt(mIsUserEdit ? 1 : 0);
5496 parcel.writeInt(mHasComposition ? 1 : 0);
5497 }
5498
5499 public void restoreInstanceState(Parcel parcel) {
5500 mIsUserEdit = parcel.readInt() != 0;
5501 mHasComposition = parcel.readInt() != 0;
5502 }
5503
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005504 public void setForceMerge(boolean forceMerge) {
5505 mForceMerge = forceMerge;
5506 }
5507
James Cook48e0fac2015-02-25 15:44:51 -08005508 /**
5509 * Signals that a user-triggered edit is starting.
5510 */
5511 public void beginBatchEdit() {
5512 if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
5513 mIsUserEdit = true;
James Cook48e0fac2015-02-25 15:44:51 -08005514 }
5515
5516 public void endBatchEdit() {
5517 if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
5518 mIsUserEdit = false;
5519 }
5520
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005521 @Override
5522 public CharSequence filter(CharSequence source, int start, int end,
5523 Spanned dest, int dstart, int dend) {
5524 if (DEBUG_UNDO) {
James Cook471559f2015-02-27 10:31:20 -08005525 Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " +
5526 "dest=" + dest + " (" + dstart + "-" + dend + ")");
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005527 }
James Cookf1dad1e2015-02-27 11:00:01 -08005528
James Cook48e0fac2015-02-25 15:44:51 -08005529 // Check to see if this edit should be tracked for undo.
5530 if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
James Cookf1dad1e2015-02-27 11:00:01 -08005531 return null;
5532 }
5533
James Cookd2026682015-03-03 14:40:14 -08005534 // Check for and handle IME composition edits.
5535 if (handleCompositionEdit(source, start, end, dstart)) {
5536 return null;
5537 }
5538
5539 // Handle keyboard edits.
5540 handleKeyboardEdit(source, start, end, dest, dstart, dend);
5541 return null;
5542 }
5543
5544 /**
5545 * Returns true iff the edit was handled, either because it should be ignored or because
5546 * this function created an undo operation for it.
5547 */
5548 private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) {
5549 // Ignore edits while the user is composing.
5550 if (isComposition(source)) {
5551 mHasComposition = true;
5552 return true;
5553 }
5554 final boolean hadComposition = mHasComposition;
5555 mHasComposition = false;
5556
5557 // Check for the transition out of the composing state.
5558 if (hadComposition) {
5559 // If there was no text the user canceled composition. Ignore the edit.
5560 if (start == end) {
5561 return true;
5562 }
5563
5564 // Otherwise the user inserted the composition.
5565 String newText = TextUtils.substring(source, start, end);
James Cook22054252015-03-25 14:04:01 -07005566 EditOperation edit = new EditOperation(mEditor, "", dstart, newText);
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005567 recordEdit(edit, mForceMerge);
James Cookd2026682015-03-03 14:40:14 -08005568 return true;
5569 }
5570
5571 // This was neither a composition event nor a transition out of composing.
5572 return false;
5573 }
5574
5575 private void handleKeyboardEdit(CharSequence source, int start, int end,
5576 Spanned dest, int dstart, int dend) {
James Cook48e0fac2015-02-25 15:44:51 -08005577 // An application may install a TextWatcher to provide additional modifications after
5578 // the initial input filters run (e.g. a credit card formatter that adds spaces to a
5579 // string). This results in multiple filter() calls for what the user considers to be
5580 // a single operation. Always undo the whole set of changes in one step.
Keisuke Kuroyanagifae45782016-02-24 18:53:00 -08005581 final boolean forceMerge = mForceMerge || isInTextWatcher();
James Cook471559f2015-02-27 10:31:20 -08005582
5583 // Build a new operation with all the information from this edit.
James Cookd2026682015-03-03 14:40:14 -08005584 String newText = TextUtils.substring(source, start, end);
5585 String oldText = TextUtils.substring(dest, dstart, dend);
James Cook22054252015-03-25 14:04:01 -07005586 EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText);
5587 recordEdit(edit, forceMerge);
James Cookd2026682015-03-03 14:40:14 -08005588 }
James Cook471559f2015-02-27 10:31:20 -08005589
James Cook22054252015-03-25 14:04:01 -07005590 /**
5591 * Fetches the last undo operation and checks to see if a new edit should be merged into it.
5592 * If forceMerge is true then the new edit is always merged.
5593 */
5594 private void recordEdit(EditOperation edit, boolean forceMerge) {
James Cook471559f2015-02-27 10:31:20 -08005595 // Fetch the last edit operation and attempt to merge in the new edit.
James Cook48e0fac2015-02-25 15:44:51 -08005596 final UndoManager um = mEditor.mUndoManager;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005597 um.beginUpdate("Edit text");
James Cook471559f2015-02-27 10:31:20 -08005598 EditOperation lastEdit = um.getLastOperation(
5599 EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
5600 if (lastEdit == null) {
5601 // Add this as the first edit.
5602 if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
5603 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook22054252015-03-25 14:04:01 -07005604 } else if (forceMerge) {
5605 // Forced merges take priority because they could be the result of a non-user-edit
5606 // change and this case should not create a new undo operation.
5607 if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
5608 lastEdit.forceMergeWith(edit);
James Cook48e0fac2015-02-25 15:44:51 -08005609 } else if (!mIsUserEdit) {
5610 // An application directly modified the Editable outside of a text edit. Treat this
5611 // as a new change and don't attempt to merge.
5612 if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
5613 um.commitState(mEditor.mUndoOwner);
5614 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook471559f2015-02-27 10:31:20 -08005615 } else if (lastEdit.mergeWith(edit)) {
5616 // Merge succeeded, nothing else to do.
5617 if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
James Cook3ac0bcb2015-02-26 10:53:41 -08005618 } else {
James Cook471559f2015-02-27 10:31:20 -08005619 // Could not merge with the last edit, so commit the last edit and add this edit.
5620 if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
5621 um.commitState(mEditor.mUndoOwner);
5622 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook3ac0bcb2015-02-26 10:53:41 -08005623 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005624 um.endUpdate();
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005625 }
James Cook48e0fac2015-02-25 15:44:51 -08005626
5627 private boolean canUndoEdit(CharSequence source, int start, int end,
5628 Spanned dest, int dstart, int dend) {
5629 if (!mEditor.mAllowUndo) {
5630 if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
5631 return false;
5632 }
5633
5634 if (mEditor.mUndoManager.isInUndo()) {
5635 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
5636 return false;
5637 }
5638
5639 // Text filters run before input operations are applied. However, some input operations
5640 // are invalid and will throw exceptions when applied. This is common in tests. Don't
5641 // attempt to undo invalid operations.
5642 if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
5643 if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
5644 return false;
5645 }
5646
5647 // Earlier filters can rewrite input to be a no-op, for example due to a length limit
5648 // on an input field. Skip no-op changes.
5649 if (start == end && dstart == dend) {
5650 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
5651 return false;
5652 }
5653
5654 return true;
5655 }
James Cookd2026682015-03-03 14:40:14 -08005656
5657 private boolean isComposition(CharSequence source) {
5658 if (!(source instanceof Spannable)) {
5659 return false;
5660 }
5661 // This is a composition edit if the source has a non-zero-length composing span.
5662 Spannable text = (Spannable) source;
5663 int composeBegin = EditableInputConnection.getComposingSpanStart(text);
5664 int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
5665 return composeBegin < composeEnd;
5666 }
5667
5668 private boolean isInTextWatcher() {
5669 CharSequence text = mEditor.mTextView.getText();
5670 return (text instanceof SpannableStringBuilder)
5671 && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
5672 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005673 }
5674
James Cookf59152c2015-02-26 18:03:58 -08005675 /**
5676 * An operation to undo a single "edit" to a text view.
5677 */
James Cook471559f2015-02-27 10:31:20 -08005678 public static class EditOperation extends UndoOperation<Editor> {
5679 private static final int TYPE_INSERT = 0;
5680 private static final int TYPE_DELETE = 1;
5681 private static final int TYPE_REPLACE = 2;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005682
James Cook471559f2015-02-27 10:31:20 -08005683 private int mType;
5684 private String mOldText;
5685 private int mOldTextStart;
5686 private String mNewText;
5687 private int mNewTextStart;
5688
5689 private int mOldCursorPos;
5690 private int mNewCursorPos;
5691
5692 /**
James Cookd2026682015-03-03 14:40:14 -08005693 * Constructs an edit operation from a text input operation on editor that replaces the
James Cook22054252015-03-25 14:04:01 -07005694 * oldText starting at dstart with newText.
James Cook471559f2015-02-27 10:31:20 -08005695 */
James Cook22054252015-03-25 14:04:01 -07005696 public EditOperation(Editor editor, String oldText, int dstart, String newText) {
James Cook471559f2015-02-27 10:31:20 -08005697 super(editor.mUndoOwner);
James Cookd2026682015-03-03 14:40:14 -08005698 mOldText = oldText;
5699 mNewText = newText;
James Cook471559f2015-02-27 10:31:20 -08005700
5701 // Determine the type of the edit and store where it occurred. Avoid storing
5702 // irrevelant data (e.g. mNewTextStart for a delete) because that makes the
5703 // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being
5704 // outside the bounds of the final text).
5705 if (mNewText.length() > 0 && mOldText.length() == 0) {
5706 mType = TYPE_INSERT;
5707 mNewTextStart = dstart;
5708 } else if (mNewText.length() == 0 && mOldText.length() > 0) {
5709 mType = TYPE_DELETE;
5710 mOldTextStart = dstart;
5711 } else {
5712 mType = TYPE_REPLACE;
5713 mOldTextStart = mNewTextStart = dstart;
5714 }
5715
5716 // Store cursor data.
5717 mOldCursorPos = editor.mTextView.getSelectionStart();
James Cookd2026682015-03-03 14:40:14 -08005718 mNewCursorPos = dstart + mNewText.length();
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005719 }
5720
James Cook471559f2015-02-27 10:31:20 -08005721 public EditOperation(Parcel src, ClassLoader loader) {
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005722 super(src, loader);
James Cook471559f2015-02-27 10:31:20 -08005723 mType = src.readInt();
5724 mOldText = src.readString();
5725 mOldTextStart = src.readInt();
5726 mNewText = src.readString();
5727 mNewTextStart = src.readInt();
5728 mOldCursorPos = src.readInt();
5729 mNewCursorPos = src.readInt();
5730 }
5731
5732 @Override
5733 public void writeToParcel(Parcel dest, int flags) {
5734 dest.writeInt(mType);
5735 dest.writeString(mOldText);
5736 dest.writeInt(mOldTextStart);
5737 dest.writeString(mNewText);
5738 dest.writeInt(mNewTextStart);
5739 dest.writeInt(mOldCursorPos);
5740 dest.writeInt(mNewCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005741 }
5742
James Cook48e0fac2015-02-25 15:44:51 -08005743 private int getNewTextEnd() {
5744 return mNewTextStart + mNewText.length();
5745 }
5746
5747 private int getOldTextEnd() {
5748 return mOldTextStart + mOldText.length();
5749 }
5750
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005751 @Override
5752 public void commit() {
5753 }
5754
5755 @Override
5756 public void undo() {
James Cook471559f2015-02-27 10:31:20 -08005757 if (DEBUG_UNDO) Log.d(TAG, "undo");
5758 // Remove the new text and insert the old.
James Cook48e0fac2015-02-25 15:44:51 -08005759 Editor editor = getOwnerData();
5760 Editable text = (Editable) editor.mTextView.getText();
5761 modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5762 mOldCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005763 }
5764
5765 @Override
5766 public void redo() {
James Cook471559f2015-02-27 10:31:20 -08005767 if (DEBUG_UNDO) Log.d(TAG, "redo");
5768 // Remove the old text and insert the new.
James Cook48e0fac2015-02-25 15:44:51 -08005769 Editor editor = getOwnerData();
5770 Editable text = (Editable) editor.mTextView.getText();
5771 modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart,
5772 mNewCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005773 }
5774
James Cook471559f2015-02-27 10:31:20 -08005775 /**
5776 * Attempts to merge this existing operation with a new edit.
5777 * @param edit The new edit operation.
5778 * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
5779 * object unchanged.
5780 */
5781 private boolean mergeWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005782 if (DEBUG_UNDO) {
5783 Log.d(TAG, "mergeWith old " + this);
5784 Log.d(TAG, "mergeWith new " + edit);
5785 }
James Cook471559f2015-02-27 10:31:20 -08005786 switch (mType) {
5787 case TYPE_INSERT:
5788 return mergeInsertWith(edit);
5789 case TYPE_DELETE:
5790 return mergeDeleteWith(edit);
5791 case TYPE_REPLACE:
5792 return mergeReplaceWith(edit);
5793 default:
5794 return false;
5795 }
5796 }
5797
5798 private boolean mergeInsertWith(EditOperation edit) {
James Cook471559f2015-02-27 10:31:20 -08005799 // Only merge continuous insertions.
5800 if (edit.mType != TYPE_INSERT) {
5801 return false;
5802 }
5803 // Only merge insertions that are contiguous.
5804 if (getNewTextEnd() != edit.mNewTextStart) {
5805 return false;
5806 }
5807 mNewText += edit.mNewText;
5808 mNewCursorPos = edit.mNewCursorPos;
5809 return true;
5810 }
5811
5812 // TODO: Support forward delete.
5813 private boolean mergeDeleteWith(EditOperation edit) {
James Cook471559f2015-02-27 10:31:20 -08005814 // Only merge continuous deletes.
5815 if (edit.mType != TYPE_DELETE) {
5816 return false;
5817 }
5818 // Only merge deletions that are contiguous.
5819 if (mOldTextStart != edit.getOldTextEnd()) {
5820 return false;
5821 }
5822 mOldTextStart = edit.mOldTextStart;
5823 mOldText = edit.mOldText + mOldText;
5824 mNewCursorPos = edit.mNewCursorPos;
5825 return true;
5826 }
5827
5828 private boolean mergeReplaceWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005829 // Replacements can merge only with adjacent inserts.
5830 if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) {
James Cook471559f2015-02-27 10:31:20 -08005831 return false;
5832 }
5833 mOldText += edit.mOldText;
5834 mNewText += edit.mNewText;
5835 mNewCursorPos = edit.mNewCursorPos;
5836 return true;
5837 }
5838
James Cook48e0fac2015-02-25 15:44:51 -08005839 /**
5840 * Forcibly creates a single merged edit operation by simulating the entire text
5841 * contents being replaced.
5842 */
James Cook22054252015-03-25 14:04:01 -07005843 public void forceMergeWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005844 if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
James Cookf59152c2015-02-26 18:03:58 -08005845 Editor editor = getOwnerData();
James Cook48e0fac2015-02-25 15:44:51 -08005846
5847 // Copy the text of the current field.
5848 // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
5849 // but would require two parallel implementations of modifyText() because Editable and
5850 // StringBuilder do not share an interface for replace/delete/insert.
5851 Editable editable = (Editable) editor.mTextView.getText();
5852 Editable originalText = new SpannableStringBuilder(editable.toString());
5853
5854 // Roll back the last operation.
5855 modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5856 mOldCursorPos);
5857
5858 // Clone the text again and apply the new operation.
5859 Editable finalText = new SpannableStringBuilder(editable.toString());
5860 modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText,
5861 edit.mNewTextStart, edit.mNewCursorPos);
5862
5863 // Convert this operation into a non-mergeable replacement of the entire string.
5864 mType = TYPE_REPLACE;
5865 mNewText = finalText.toString();
5866 mNewTextStart = 0;
5867 mOldText = originalText.toString();
5868 mOldTextStart = 0;
5869 mNewCursorPos = edit.mNewCursorPos;
5870 // mOldCursorPos is unchanged.
5871 }
5872
5873 private static void modifyText(Editable text, int deleteFrom, int deleteTo,
5874 CharSequence newText, int newTextInsertAt, int newCursorPos) {
James Cook471559f2015-02-27 10:31:20 -08005875 // Apply the edit if it is still valid.
5876 if (isValidRange(text, deleteFrom, deleteTo) &&
5877 newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
5878 if (deleteFrom != deleteTo) {
5879 text.delete(deleteFrom, deleteTo);
5880 }
5881 if (newText.length() != 0) {
5882 text.insert(newTextInsertAt, newText);
5883 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005884 }
James Cook900185d2015-03-10 09:48:11 -07005885 // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
5886 // don't explicitly set it and rely on SpannableStringBuilder to position it.
James Cook471559f2015-02-27 10:31:20 -08005887 // TODO: Select all the text that was undone.
James Cook900185d2015-03-10 09:48:11 -07005888 if (0 <= newCursorPos && newCursorPos <= text.length()) {
James Cook471559f2015-02-27 10:31:20 -08005889 Selection.setSelection(text, newCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005890 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005891 }
5892
James Cook48e0fac2015-02-25 15:44:51 -08005893 private String getTypeString() {
5894 switch (mType) {
5895 case TYPE_INSERT:
5896 return "insert";
5897 case TYPE_DELETE:
5898 return "delete";
5899 case TYPE_REPLACE:
5900 return "replace";
5901 default:
5902 return "";
5903 }
5904 }
5905
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005906 @Override
James Cook471559f2015-02-27 10:31:20 -08005907 public String toString() {
James Cook48e0fac2015-02-25 15:44:51 -08005908 return "[mType=" + getTypeString() + ", " +
James Cook471559f2015-02-27 10:31:20 -08005909 "mOldText=" + mOldText + ", " +
5910 "mOldTextStart=" + mOldTextStart + ", " +
5911 "mNewText=" + mNewText + ", " +
5912 "mNewTextStart=" + mNewTextStart + ", " +
5913 "mOldCursorPos=" + mOldCursorPos + ", " +
5914 "mNewCursorPos=" + mNewCursorPos + "]";
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005915 }
5916
James Cook471559f2015-02-27 10:31:20 -08005917 public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR
5918 = new Parcelable.ClassLoaderCreator<EditOperation>() {
James Cookf59152c2015-02-26 18:03:58 -08005919 @Override
James Cook471559f2015-02-27 10:31:20 -08005920 public EditOperation createFromParcel(Parcel in) {
5921 return new EditOperation(in, null);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005922 }
5923
James Cookf59152c2015-02-26 18:03:58 -08005924 @Override
James Cook471559f2015-02-27 10:31:20 -08005925 public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
5926 return new EditOperation(in, loader);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005927 }
5928
James Cookf59152c2015-02-26 18:03:58 -08005929 @Override
James Cook471559f2015-02-27 10:31:20 -08005930 public EditOperation[] newArray(int size) {
5931 return new EditOperation[size];
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005932 }
5933 };
5934 }
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07005935
5936 /**
5937 * A helper for enabling and handling "PROCESS_TEXT" menu actions.
5938 * These allow external applications to plug into currently selected text.
5939 */
5940 static final class ProcessTextIntentActionsHandler {
5941
5942 private final Editor mEditor;
5943 private final TextView mTextView;
5944 private final PackageManager mPackageManager;
5945 private final SparseArray<Intent> mAccessibilityIntents = new SparseArray<Intent>();
5946 private final SparseArray<AccessibilityNodeInfo.AccessibilityAction> mAccessibilityActions
5947 = new SparseArray<AccessibilityNodeInfo.AccessibilityAction>();
5948
5949 private ProcessTextIntentActionsHandler(Editor editor) {
5950 mEditor = Preconditions.checkNotNull(editor);
5951 mTextView = Preconditions.checkNotNull(mEditor.mTextView);
5952 mPackageManager = Preconditions.checkNotNull(
5953 mTextView.getContext().getPackageManager());
5954 }
5955
5956 /**
5957 * Adds "PROCESS_TEXT" menu items to the specified menu.
5958 */
5959 public void onInitializeMenu(Menu menu) {
5960 int i = 0;
5961 for (ResolveInfo resolveInfo : getSupportedActivities()) {
5962 menu.add(Menu.NONE, Menu.NONE,
5963 Editor.MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i++,
5964 getLabel(resolveInfo))
5965 .setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
5966 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
5967 }
5968 }
5969
5970 /**
5971 * Performs a "PROCESS_TEXT" action if there is one associated with the specified
5972 * menu item.
5973 *
5974 * @return True if the action was performed, false otherwise.
5975 */
5976 public boolean performMenuItemAction(MenuItem item) {
5977 return fireIntent(item.getIntent());
5978 }
5979
5980 /**
5981 * Initializes and caches "PROCESS_TEXT" accessibility actions.
5982 */
5983 public void initializeAccessibilityActions() {
5984 mAccessibilityIntents.clear();
5985 mAccessibilityActions.clear();
5986 int i = 0;
5987 for (ResolveInfo resolveInfo : getSupportedActivities()) {
5988 int actionId = TextView.ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID + i++;
5989 mAccessibilityActions.put(
5990 actionId,
5991 new AccessibilityNodeInfo.AccessibilityAction(
5992 actionId, getLabel(resolveInfo)));
5993 mAccessibilityIntents.put(
5994 actionId, createProcessTextIntentForResolveInfo(resolveInfo));
5995 }
5996 }
5997
5998 /**
5999 * Adds "PROCESS_TEXT" accessibility actions to the specified accessibility node info.
6000 * NOTE: This needs a prior call to {@link #initializeAccessibilityActions()} to make the
6001 * latest accessibility actions available for this call.
6002 */
6003 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo) {
6004 for (int i = 0; i < mAccessibilityActions.size(); i++) {
6005 nodeInfo.addAction(mAccessibilityActions.valueAt(i));
6006 }
6007 }
6008
6009 /**
6010 * Performs a "PROCESS_TEXT" action if there is one associated with the specified
6011 * accessibility action id.
6012 *
6013 * @return True if the action was performed, false otherwise.
6014 */
6015 public boolean performAccessibilityAction(int actionId) {
6016 return fireIntent(mAccessibilityIntents.get(actionId));
6017 }
6018
6019 private boolean fireIntent(Intent intent) {
6020 if (intent != null && Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) {
6021 intent.putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText());
Keisuke Kuroyanagiaf4caa62016-02-29 12:53:58 -08006022 mEditor.mPreserveSelection = true;
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07006023 mTextView.startActivityForResult(intent, TextView.PROCESS_TEXT_REQUEST_CODE);
6024 return true;
6025 }
6026 return false;
6027 }
6028
6029 private List<ResolveInfo> getSupportedActivities() {
6030 PackageManager packageManager = mTextView.getContext().getPackageManager();
6031 return packageManager.queryIntentActivities(createProcessTextIntent(), 0);
6032 }
6033
6034 private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
6035 return createProcessTextIntent()
6036 .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
6037 .setClassName(info.activityInfo.packageName, info.activityInfo.name);
6038 }
6039
6040 private Intent createProcessTextIntent() {
6041 return new Intent()
6042 .setAction(Intent.ACTION_PROCESS_TEXT)
6043 .setType("text/plain");
6044 }
6045
6046 private CharSequence getLabel(ResolveInfo resolveInfo) {
6047 return resolveInfo.loadLabel(mPackageManager);
6048 }
6049 }
Gilles Debunned88876a2012-03-16 17:34:04 -07006050}