blob: 1826dd82abed9b9e7b1d669ac7542825254f1acc [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;
Adam Powell057a5852012-05-11 10:28:38 -0700218 boolean mPreserveDetachedSelection;
219 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();
293 private SuggestionInfo[] mSuggestionInfosInContextMenu;
294
Gilles Debunned88876a2012-03-16 17:34:04 -0700295 Editor(TextView textView) {
296 mTextView = textView;
James Cookf59152c2015-02-26 18:03:58 -0800297 // Synchronize the filter list, which places the undo input filter at the end.
298 mTextView.setFilters(mTextView.getFilters());
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -0700299 mProcessTextIntentActionsHandler = new ProcessTextIntentActionsHandler(this);
James Cookf59152c2015-02-26 18:03:58 -0800300 }
301
302 ParcelableParcel saveInstanceState() {
James Cookd2026682015-03-03 14:40:14 -0800303 ParcelableParcel state = new ParcelableParcel(getClass().getClassLoader());
304 Parcel parcel = state.getParcel();
305 mUndoManager.saveInstanceState(parcel);
306 mUndoInputFilter.saveInstanceState(parcel);
307 return state;
James Cookf59152c2015-02-26 18:03:58 -0800308 }
309
310 void restoreInstanceState(ParcelableParcel state) {
James Cookd2026682015-03-03 14:40:14 -0800311 Parcel parcel = state.getParcel();
312 mUndoManager.restoreInstanceState(parcel, state.getClassLoader());
313 mUndoInputFilter.restoreInstanceState(parcel);
James Cookf59152c2015-02-26 18:03:58 -0800314 // Re-associate this object as the owner of undo state.
315 mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
316 }
317
James Cook48e0fac2015-02-25 15:44:51 -0800318 /**
319 * Forgets all undo and redo operations for this Editor.
320 */
321 void forgetUndoRedo() {
322 UndoOwner[] owners = { mUndoOwner };
323 mUndoManager.forgetUndos(owners, -1 /* all */);
324 mUndoManager.forgetRedos(owners, -1 /* all */);
325 }
326
James Cookf59152c2015-02-26 18:03:58 -0800327 boolean canUndo() {
328 UndoOwner[] owners = { mUndoOwner };
James Cookf1dad1e2015-02-27 11:00:01 -0800329 return mAllowUndo && mUndoManager.countUndos(owners) > 0;
James Cookf59152c2015-02-26 18:03:58 -0800330 }
331
332 boolean canRedo() {
333 UndoOwner[] owners = { mUndoOwner };
James Cookf1dad1e2015-02-27 11:00:01 -0800334 return mAllowUndo && mUndoManager.countRedos(owners) > 0;
James Cookf59152c2015-02-26 18:03:58 -0800335 }
336
337 void undo() {
James Cookf1dad1e2015-02-27 11:00:01 -0800338 if (!mAllowUndo) {
339 return;
340 }
James Cookf59152c2015-02-26 18:03:58 -0800341 UndoOwner[] owners = { mUndoOwner };
342 mUndoManager.undo(owners, 1); // Undo 1 action.
343 }
344
345 void redo() {
James Cookf1dad1e2015-02-27 11:00:01 -0800346 if (!mAllowUndo) {
347 return;
348 }
James Cookf59152c2015-02-26 18:03:58 -0800349 UndoOwner[] owners = { mUndoOwner };
350 mUndoManager.redo(owners, 1); // Redo 1 action.
Gilles Debunned88876a2012-03-16 17:34:04 -0700351 }
352
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100353 void replace() {
354 int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100355 stopTextActionMode();
Andrei Stingaceanueeb9afc2015-05-12 12:39:07 +0100356 Selection.setSelection((Spannable) mTextView.getText(), middle);
357 showSuggestions();
358 }
359
Gilles Debunned88876a2012-03-16 17:34:04 -0700360 void onAttachedToWindow() {
361 if (mShowErrorAfterAttach) {
362 showError();
363 mShowErrorAfterAttach = false;
364 }
Adam Powell057a5852012-05-11 10:28:38 -0700365 mTemporaryDetach = false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700366
367 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
368 // No need to create the controller.
369 // The get method will add the listener on controller creation.
370 if (mInsertionPointCursorController != null) {
371 observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
372 }
373 if (mSelectionModifierCursorController != null) {
Adam Powell057a5852012-05-11 10:28:38 -0700374 mSelectionModifierCursorController.resetTouchOffsets();
Gilles Debunned88876a2012-03-16 17:34:04 -0700375 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
376 }
377 updateSpellCheckSpans(0, mTextView.getText().length(),
378 true /* create the spell checker if needed */);
Adam Powell057a5852012-05-11 10:28:38 -0700379
380 if (mTextView.hasTransientState() &&
381 mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
382 // Since transient state is reference counted make sure it stays matched
383 // with our own calls to it for managing selection.
384 // The action mode callback will set this back again when/if the action mode starts.
385 mTextView.setHasTransientState(false);
386
387 // We had an active selection from before, start the selection mode.
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100388 startSelectionActionMode();
Adam Powell057a5852012-05-11 10:28:38 -0700389 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900390
391 getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true);
Mikael Gullstrand5b734f22013-07-09 14:41:28 +0200392 resumeBlink();
Gilles Debunned88876a2012-03-16 17:34:04 -0700393 }
394
395 void onDetachedFromWindow() {
Yohei Yukawa83b68ba2014-05-12 15:46:25 +0900396 getPositionListener().removeSubscriber(mCursorAnchorInfoNotifier);
397
Gilles Debunned88876a2012-03-16 17:34:04 -0700398 if (mError != null) {
399 hideError();
400 }
401
Mikael Gullstrand5b734f22013-07-09 14:41:28 +0200402 suspendBlink();
Gilles Debunned88876a2012-03-16 17:34:04 -0700403
404 if (mInsertionPointCursorController != null) {
405 mInsertionPointCursorController.onDetached();
406 }
407
408 if (mSelectionModifierCursorController != null) {
409 mSelectionModifierCursorController.onDetached();
410 }
411
412 if (mShowSuggestionRunnable != null) {
413 mTextView.removeCallbacks(mShowSuggestionRunnable);
414 }
415
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100416 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100417 if (mInsertionActionModeRunnable != null) {
418 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +0100419 }
420
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +0100421 mTextView.removeCallbacks(mShowFloatingToolbar);
422
Chris Craik003cc3d2015-10-16 10:24:55 -0700423 discardTextDisplayLists();
Gilles Debunned88876a2012-03-16 17:34:04 -0700424
425 if (mSpellChecker != null) {
426 mSpellChecker.closeSession();
427 // Forces the creation of a new SpellChecker next time this window is created.
428 // Will handle the cases where the settings has been changed in the meantime.
429 mSpellChecker = null;
430 }
431
Adam Powell057a5852012-05-11 10:28:38 -0700432 mPreserveDetachedSelection = true;
Mady Mellora2861452015-06-25 08:40:27 -0700433 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100434 stopTextActionMode();
Adam Powell057a5852012-05-11 10:28:38 -0700435 mPreserveDetachedSelection = false;
436 mTemporaryDetach = false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700437 }
438
Chris Craik003cc3d2015-10-16 10:24:55 -0700439 private void discardTextDisplayLists() {
Chris Craik956f3402015-04-27 16:41:00 -0700440 if (mTextRenderNodes != null) {
441 for (int i = 0; i < mTextRenderNodes.length; i++) {
442 RenderNode displayList = mTextRenderNodes[i] != null
443 ? mTextRenderNodes[i].renderNode : null;
John Reck7558aa72014-03-05 14:59:59 -0800444 if (displayList != null && displayList.isValid()) {
Chris Craik003cc3d2015-10-16 10:24:55 -0700445 displayList.discardDisplayList();
John Reck7558aa72014-03-05 14:59:59 -0800446 }
447 }
448 }
449 }
450
Gilles Debunned88876a2012-03-16 17:34:04 -0700451 private void showError() {
452 if (mTextView.getWindowToken() == null) {
453 mShowErrorAfterAttach = true;
454 return;
455 }
456
457 if (mErrorPopup == null) {
458 LayoutInflater inflater = LayoutInflater.from(mTextView.getContext());
459 final TextView err = (TextView) inflater.inflate(
460 com.android.internal.R.layout.textview_hint, null);
461
462 final float scale = mTextView.getResources().getDisplayMetrics().density;
463 mErrorPopup = new ErrorPopup(err, (int)(200 * scale + 0.5f), (int)(50 * scale + 0.5f));
464 mErrorPopup.setFocusable(false);
465 // The user is entering text, so the input method is needed. We
466 // don't want the popup to be displayed on top of it.
467 mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
468 }
469
470 TextView tv = (TextView) mErrorPopup.getContentView();
471 chooseSize(mErrorPopup, mError, tv);
472 tv.setText(mError);
473
474 mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY());
475 mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor());
476 }
477
478 public void setError(CharSequence error, Drawable icon) {
479 mError = TextUtils.stringOrSpannedString(error);
480 mErrorWasChanged = true;
Romain Guyd1cc1872012-11-05 17:43:25 -0800481
Gilles Debunned88876a2012-03-16 17:34:04 -0700482 if (mError == null) {
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800483 setErrorIcon(null);
Gilles Debunned88876a2012-03-16 17:34:04 -0700484 if (mErrorPopup != null) {
485 if (mErrorPopup.isShowing()) {
486 mErrorPopup.dismiss();
487 }
488
489 mErrorPopup = null;
490 }
Daniel 2 Olofssonf4ecc552013-08-13 10:30:26 +0200491 mShowErrorAfterAttach = false;
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800492 } else {
Romain Guyd1cc1872012-11-05 17:43:25 -0800493 setErrorIcon(icon);
Fabrice Di Meglio5acc3792012-11-12 14:08:00 -0800494 if (mTextView.isFocused()) {
495 showError();
496 }
Romain Guyd1cc1872012-11-05 17:43:25 -0800497 }
498 }
499
500 private void setErrorIcon(Drawable icon) {
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800501 Drawables dr = mTextView.mDrawables;
502 if (dr == null) {
Fabrice Di Megliof7a5cdf2013-03-15 15:36:51 -0700503 mTextView.mDrawables = dr = new Drawables(mTextView.getContext());
Gilles Debunned88876a2012-03-16 17:34:04 -0700504 }
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800505 dr.setErrorDrawable(icon, mTextView);
506
507 mTextView.resetResolvedDrawables();
508 mTextView.invalidate();
509 mTextView.requestLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -0700510 }
511
512 private void hideError() {
513 if (mErrorPopup != null) {
514 if (mErrorPopup.isShowing()) {
515 mErrorPopup.dismiss();
516 }
517 }
518
519 mShowErrorAfterAttach = false;
520 }
521
522 /**
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800523 * Returns the X offset to make the pointy top of the error point
Gilles Debunned88876a2012-03-16 17:34:04 -0700524 * at the middle of the error icon.
525 */
526 private int getErrorX() {
527 /*
528 * The "25" is the distance between the point and the right edge
529 * of the background
530 */
531 final float scale = mTextView.getResources().getDisplayMetrics().density;
532
533 final Drawables dr = mTextView.mDrawables;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800534
535 final int layoutDirection = mTextView.getLayoutDirection();
536 int errorX;
537 int offset;
538 switch (layoutDirection) {
539 default:
540 case View.LAYOUT_DIRECTION_LTR:
541 offset = - (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
542 errorX = mTextView.getWidth() - mErrorPopup.getWidth() -
543 mTextView.getPaddingRight() + offset;
544 break;
545 case View.LAYOUT_DIRECTION_RTL:
546 offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f);
547 errorX = mTextView.getPaddingLeft() + offset;
548 break;
549 }
550 return errorX;
Gilles Debunned88876a2012-03-16 17:34:04 -0700551 }
552
553 /**
554 * Returns the Y offset to make the pointy top of the error point
555 * at the bottom of the error icon.
556 */
557 private int getErrorY() {
558 /*
559 * Compound, not extended, because the icon is not clipped
560 * if the text height is smaller.
561 */
562 final int compoundPaddingTop = mTextView.getCompoundPaddingTop();
563 int vspace = mTextView.getBottom() - mTextView.getTop() -
564 mTextView.getCompoundPaddingBottom() - compoundPaddingTop;
565
566 final Drawables dr = mTextView.mDrawables;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800567
568 final int layoutDirection = mTextView.getLayoutDirection();
569 int height;
570 switch (layoutDirection) {
571 default:
572 case View.LAYOUT_DIRECTION_LTR:
573 height = (dr != null ? dr.mDrawableHeightRight : 0);
574 break;
575 case View.LAYOUT_DIRECTION_RTL:
576 height = (dr != null ? dr.mDrawableHeightLeft : 0);
577 break;
578 }
579
580 int icontop = compoundPaddingTop + (vspace - height) / 2;
Gilles Debunned88876a2012-03-16 17:34:04 -0700581
582 /*
583 * The "2" is the distance between the point and the top edge
584 * of the background.
585 */
586 final float scale = mTextView.getResources().getDisplayMetrics().density;
Fabrice Di Megliobb0cbae2012-11-13 20:51:24 -0800587 return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f);
Gilles Debunned88876a2012-03-16 17:34:04 -0700588 }
589
590 void createInputContentTypeIfNeeded() {
591 if (mInputContentType == null) {
592 mInputContentType = new InputContentType();
593 }
594 }
595
596 void createInputMethodStateIfNeeded() {
597 if (mInputMethodState == null) {
598 mInputMethodState = new InputMethodState();
599 }
600 }
601
602 boolean isCursorVisible() {
603 // The default value is true, even when there is no associated Editor
604 return mCursorVisible && mTextView.isTextEditable();
605 }
606
607 void prepareCursorControllers() {
608 boolean windowSupportsHandles = false;
609
610 ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams();
611 if (params instanceof WindowManager.LayoutParams) {
612 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
613 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW
614 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
615 }
616
617 boolean enabled = windowSupportsHandles && mTextView.getLayout() != null;
618 mInsertionControllerEnabled = enabled && isCursorVisible();
619 mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected();
620
621 if (!mInsertionControllerEnabled) {
622 hideInsertionPointCursorController();
623 if (mInsertionPointCursorController != null) {
624 mInsertionPointCursorController.onDetached();
625 mInsertionPointCursorController = null;
626 }
627 }
628
629 if (!mSelectionControllerEnabled) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +0100630 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -0700631 if (mSelectionModifierCursorController != null) {
632 mSelectionModifierCursorController.onDetached();
633 mSelectionModifierCursorController = null;
634 }
635 }
636 }
637
Seigo Nonakabb6a62c2015-03-31 21:59:30 +0900638 void hideInsertionPointCursorController() {
Gilles Debunned88876a2012-03-16 17:34:04 -0700639 if (mInsertionPointCursorController != null) {
640 mInsertionPointCursorController.hide();
641 }
642 }
643
644 /**
Mady Mellora2861452015-06-25 08:40:27 -0700645 * Hides the insertion and span controllers.
Gilles Debunned88876a2012-03-16 17:34:04 -0700646 */
Mady Mellora2861452015-06-25 08:40:27 -0700647 void hideCursorAndSpanControllers() {
Gilles Debunned88876a2012-03-16 17:34:04 -0700648 hideCursorControllers();
649 hideSpanControllers();
650 }
651
652 private void hideSpanControllers() {
Jean Chalardbaf30942013-02-28 16:01:51 -0800653 if (mSpanController != null) {
654 mSpanController.hide();
Gilles Debunned88876a2012-03-16 17:34:04 -0700655 }
656 }
657
658 private void hideCursorControllers() {
Yohei Yukawa85d08f12015-04-29 20:12:37 -0700659 // When mTextView is not ExtractEditText, we need to distinguish two kinds of focus-lost.
660 // One is the true focus lost where suggestions pop-up (if any) should be dismissed, and the
661 // other is an side effect of showing the suggestions pop-up itself. We use isShowingUp()
662 // to distinguish one from the other.
Andrei Stingaceanub1891b32015-06-19 16:44:37 +0100663 if (mSuggestionsPopupWindow != null && ((mTextView.isInExtractedMode()) ||
Yohei Yukawa85d08f12015-04-29 20:12:37 -0700664 !mSuggestionsPopupWindow.isShowingUp())) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700665 // Should be done before hide insertion point controller since it triggers a show of it
666 mSuggestionsPopupWindow.hide();
667 }
668 hideInsertionPointCursorController();
Gilles Debunned88876a2012-03-16 17:34:04 -0700669 }
670
671 /**
672 * Create new SpellCheckSpans on the modified region.
673 */
674 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
Satoshi Kataokad7429c12013-06-05 16:30:23 +0900675 // Remove spans whose adjacent characters are text not punctuation
676 mTextView.removeAdjacentSuggestionSpans(start);
677 mTextView.removeAdjacentSuggestionSpans(end);
678
Gilles Debunned88876a2012-03-16 17:34:04 -0700679 if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() &&
Andrei Stingaceanub1891b32015-06-19 16:44:37 +0100680 !(mTextView.isInExtractedMode())) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700681 if (mSpellChecker == null && createSpellChecker) {
682 mSpellChecker = new SpellChecker(mTextView);
683 }
684 if (mSpellChecker != null) {
685 mSpellChecker.spellCheck(start, end);
686 }
687 }
688 }
689
690 void onScreenStateChanged(int screenState) {
691 switch (screenState) {
692 case View.SCREEN_STATE_ON:
693 resumeBlink();
694 break;
695 case View.SCREEN_STATE_OFF:
696 suspendBlink();
697 break;
698 }
699 }
700
701 private void suspendBlink() {
702 if (mBlink != null) {
703 mBlink.cancel();
704 }
705 }
706
707 private void resumeBlink() {
708 if (mBlink != null) {
709 mBlink.uncancel();
710 makeBlink();
711 }
712 }
713
714 void adjustInputType(boolean password, boolean passwordInputType,
715 boolean webPasswordInputType, boolean numberPasswordInputType) {
716 // mInputType has been set from inputType, possibly modified by mInputMethod.
717 // Specialize mInputType to [web]password if we have a text class and the original input
718 // type was a password.
719 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
720 if (password || passwordInputType) {
721 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
722 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
723 }
724 if (webPasswordInputType) {
725 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
726 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
727 }
728 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
729 if (numberPasswordInputType) {
730 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
731 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
732 }
733 }
734 }
735
736 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
737 int wid = tv.getPaddingLeft() + tv.getPaddingRight();
738 int ht = tv.getPaddingTop() + tv.getPaddingBottom();
739
740 int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize(
741 com.android.internal.R.dimen.textview_error_popup_default_width);
742 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
743 Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
744 float max = 0;
745 for (int i = 0; i < l.getLineCount(); i++) {
746 max = Math.max(max, l.getLineWidth(i));
747 }
748
749 /*
750 * Now set the popup size to be big enough for the text plus the border capped
751 * to DEFAULT_MAX_POPUP_WIDTH
752 */
753 pop.setWidth(wid + (int) Math.ceil(max));
754 pop.setHeight(ht + l.getHeight());
755 }
756
757 void setFrame() {
758 if (mErrorPopup != null) {
759 TextView tv = (TextView) mErrorPopup.getContentView();
760 chooseSize(mErrorPopup, mError, tv);
761 mErrorPopup.update(mTextView, getErrorX(), getErrorY(),
762 mErrorPopup.getWidth(), mErrorPopup.getHeight());
763 }
764 }
765
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800766 private int getWordStart(int offset) {
767 // FIXME - For this and similar methods we're not doing anything to check if there's
768 // a LocaleSpan in the text, this may be something we should try handling or checking for.
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700769 int retOffset = getWordIteratorWithText().prevBoundary(offset);
Mady Mellor58c90872015-05-12 11:09:37 -0700770 if (getWordIteratorWithText().isOnPunctuation(retOffset)) {
771 // On punctuation boundary or within group of punctuation, find punctuation start.
772 retOffset = getWordIteratorWithText().getPunctuationBeginning(offset);
773 } else {
774 // Not on a punctuation boundary, find the word start.
Mady Mellore264ac32015-06-22 16:46:29 -0700775 retOffset = getWordIteratorWithText().getPrevWordBeginningOnTwoWordsBoundary(offset);
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800776 }
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700777 if (retOffset == BreakIterator.DONE) {
778 return offset;
779 }
780 return retOffset;
781 }
782
783 private int getWordEnd(int offset) {
784 int retOffset = getWordIteratorWithText().nextBoundary(offset);
Mady Mellor58c90872015-05-12 11:09:37 -0700785 if (getWordIteratorWithText().isAfterPunctuation(retOffset)) {
786 // On punctuation boundary or within group of punctuation, find punctuation end.
787 retOffset = getWordIteratorWithText().getPunctuationEnd(offset);
788 } else {
789 // Not on a punctuation boundary, find the word end.
Mady Mellore264ac32015-06-22 16:46:29 -0700790 retOffset = getWordIteratorWithText().getNextWordEndOnTwoWordBoundary(offset);
Mady Mellor6c7b4ad2015-04-15 14:23:26 -0700791 }
792 if (retOffset == BreakIterator.DONE) {
793 return offset;
794 }
795 return retOffset;
796 }
797
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900798 private boolean needsToSelectAllToSelectWordOrParagraph() {
Andrei Stingaceanu47f82ae2015-04-28 17:43:54 +0100799 if (mTextView.hasPasswordTransformationMethod()) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700800 // Always select all on a password field.
801 // Cut/copy menu entries are not available for passwords, but being able to select all
802 // is however useful to delete or paste to replace the entire content.
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900803 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -0700804 }
805
806 int inputType = mTextView.getInputType();
807 int klass = inputType & InputType.TYPE_MASK_CLASS;
808 int variation = inputType & InputType.TYPE_MASK_VARIATION;
809
810 // Specific text field types: select the entire text for these
811 if (klass == InputType.TYPE_CLASS_NUMBER ||
812 klass == InputType.TYPE_CLASS_PHONE ||
813 klass == InputType.TYPE_CLASS_DATETIME ||
814 variation == InputType.TYPE_TEXT_VARIATION_URI ||
815 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
816 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
817 variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900818 return true;
819 }
820 return false;
821 }
822
823 /**
824 * Adjusts selection to the word under last touch offset. Return true if the operation was
825 * successfully performed.
826 */
827 private boolean selectCurrentWord() {
828 if (!mTextView.canSelectText()) {
829 return false;
830 }
831
832 if (needsToSelectAllToSelectWordOrParagraph()) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700833 return mTextView.selectAllText();
834 }
835
836 long lastTouchOffsets = getLastTouchOffsets();
837 final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
838 final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
839
840 // Safety check in case standard touch event handling has been bypassed
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -0800841 if (minOffset < 0 || minOffset > mTextView.getText().length()) return false;
842 if (maxOffset < 0 || maxOffset > mTextView.getText().length()) return false;
Gilles Debunned88876a2012-03-16 17:34:04 -0700843
844 int selectionStart, selectionEnd;
845
846 // If a URLSpan (web address, email, phone...) is found at that position, select it.
847 URLSpan[] urlSpans = ((Spanned) mTextView.getText()).
848 getSpans(minOffset, maxOffset, URLSpan.class);
849 if (urlSpans.length >= 1) {
850 URLSpan urlSpan = urlSpans[0];
851 selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan);
852 selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan);
853 } else {
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800854 // FIXME - We should check if there's a LocaleSpan in the text, this may be
855 // something we should try handling or checking for.
Gilles Debunned88876a2012-03-16 17:34:04 -0700856 final WordIterator wordIterator = getWordIterator();
857 wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset);
858
859 selectionStart = wordIterator.getBeginning(minOffset);
860 selectionEnd = wordIterator.getEnd(maxOffset);
861
862 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
863 selectionStart == selectionEnd) {
864 // Possible when the word iterator does not properly handle the text's language
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900865 long range = getCharClusterRange(minOffset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700866 selectionStart = TextUtils.unpackRangeStartFromLong(range);
867 selectionEnd = TextUtils.unpackRangeEndFromLong(range);
868 }
869 }
870
871 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
872 return selectionEnd > selectionStart;
873 }
874
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +0900875 /**
876 * Adjusts selection to the paragraph under last touch offset. Return true if the operation was
877 * successfully performed.
878 */
879 private boolean selectCurrentParagraph() {
880 if (!mTextView.canSelectText()) {
881 return false;
882 }
883
884 if (needsToSelectAllToSelectWordOrParagraph()) {
885 return mTextView.selectAllText();
886 }
887
888 long lastTouchOffsets = getLastTouchOffsets();
889 final int minLastTouchOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
890 final int maxLastTouchOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
891
892 final long paragraphsRange = getParagraphsRange(minLastTouchOffset, maxLastTouchOffset);
893 final int start = TextUtils.unpackRangeStartFromLong(paragraphsRange);
894 final int end = TextUtils.unpackRangeEndFromLong(paragraphsRange);
895 if (start < end) {
896 Selection.setSelection((Spannable) mTextView.getText(), start, end);
897 return true;
898 }
899 return false;
900 }
901
902 /**
903 * Get the minimum range of paragraphs that contains startOffset and endOffset.
904 */
905 private long getParagraphsRange(int startOffset, int endOffset) {
906 final Layout layout = mTextView.getLayout();
907 if (layout == null) {
908 return TextUtils.packRangeInLong(-1, -1);
909 }
910 final CharSequence text = mTextView.getText();
911 int minLine = layout.getLineForOffset(startOffset);
912 // Search paragraph start.
913 while (minLine > 0) {
914 final int prevLineEndOffset = layout.getLineEnd(minLine - 1);
915 if (text.charAt(prevLineEndOffset - 1) == '\n') {
916 break;
917 }
918 minLine--;
919 }
920 int maxLine = layout.getLineForOffset(endOffset);
921 // Search paragraph end.
922 while (maxLine < layout.getLineCount() - 1) {
923 final int lineEndOffset = layout.getLineEnd(maxLine);
924 if (text.charAt(lineEndOffset - 1) == '\n') {
925 break;
926 }
927 maxLine++;
928 }
929 return TextUtils.packRangeInLong(layout.getLineStart(minLine), layout.getLineEnd(maxLine));
930 }
931
Gilles Debunned88876a2012-03-16 17:34:04 -0700932 void onLocaleChanged() {
933 // Will be re-created on demand in getWordIterator with the proper new locale
934 mWordIterator = null;
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800935 mWordIteratorWithText = null;
Gilles Debunned88876a2012-03-16 17:34:04 -0700936 }
937
938 /**
939 * @hide
940 */
941 public WordIterator getWordIterator() {
942 if (mWordIterator == null) {
943 mWordIterator = new WordIterator(mTextView.getTextServicesLocale());
944 }
945 return mWordIterator;
946 }
947
Mady Mellor2ff2cd82015-03-02 10:37:01 -0800948 private WordIterator getWordIteratorWithText() {
949 if (mWordIteratorWithText == null) {
950 mWordIteratorWithText = new WordIterator(mTextView.getTextServicesLocale());
951 mUpdateWordIteratorText = true;
952 }
953 if (mUpdateWordIteratorText) {
954 // FIXME - Shouldn't copy all of the text as only the area of the text relevant
955 // to the user's selection is needed. A possible solution would be to
956 // copy some number N of characters near the selection and then when the
957 // user approaches N then we'd do another copy of the next N characters.
958 CharSequence text = mTextView.getText();
959 mWordIteratorWithText.setCharSequence(text, 0, text.length());
960 mUpdateWordIteratorText = false;
961 }
962 return mWordIteratorWithText;
963 }
964
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900965 private int getNextCursorOffset(int offset, boolean findAfterGivenOffset) {
966 final Layout layout = mTextView.getLayout();
967 if (layout == null) return offset;
968 final CharSequence text = mTextView.getText();
969 final int nextOffset = layout.getPaint().getTextRunCursor(text, 0, text.length(),
970 layout.isRtlCharAt(offset) ? Paint.DIRECTION_RTL : Paint.DIRECTION_LTR,
971 offset, findAfterGivenOffset ? Paint.CURSOR_AFTER : Paint.CURSOR_BEFORE);
972 return nextOffset == -1 ? offset : nextOffset;
973 }
974
975 private long getCharClusterRange(int offset) {
Gilles Debunned88876a2012-03-16 17:34:04 -0700976 final int textLength = mTextView.getText().length();
Gilles Debunned88876a2012-03-16 17:34:04 -0700977 if (offset < textLength) {
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900978 return TextUtils.packRangeInLong(offset, getNextCursorOffset(offset, true));
Gilles Debunned88876a2012-03-16 17:34:04 -0700979 }
980 if (offset - 1 >= 0) {
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900981 return TextUtils.packRangeInLong(getNextCursorOffset(offset, false), offset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700982 }
Keisuke Kuroyanagi9c68b292015-04-24 18:55:56 +0900983 return TextUtils.packRangeInLong(offset, offset);
Gilles Debunned88876a2012-03-16 17:34:04 -0700984 }
985
986 private boolean touchPositionIsInSelection() {
987 int selectionStart = mTextView.getSelectionStart();
988 int selectionEnd = mTextView.getSelectionEnd();
989
990 if (selectionStart == selectionEnd) {
991 return false;
992 }
993
994 if (selectionStart > selectionEnd) {
995 int tmp = selectionStart;
996 selectionStart = selectionEnd;
997 selectionEnd = tmp;
998 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
999 }
1000
1001 SelectionModifierCursorController selectionController = getSelectionController();
1002 int minOffset = selectionController.getMinTouchOffset();
1003 int maxOffset = selectionController.getMaxTouchOffset();
1004
1005 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
1006 }
1007
1008 private PositionListener getPositionListener() {
1009 if (mPositionListener == null) {
1010 mPositionListener = new PositionListener();
1011 }
1012 return mPositionListener;
1013 }
1014
1015 private interface TextViewPositionListener {
1016 public void updatePosition(int parentPositionX, int parentPositionY,
1017 boolean parentPositionChanged, boolean parentScrolled);
1018 }
1019
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09001020 private boolean isPositionVisible(final float positionX, final float positionY) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001021 synchronized (TEMP_POSITION) {
1022 final float[] position = TEMP_POSITION;
1023 position[0] = positionX;
1024 position[1] = positionY;
1025 View view = mTextView;
1026
1027 while (view != null) {
1028 if (view != mTextView) {
1029 // Local scroll is already taken into account in positionX/Y
1030 position[0] -= view.getScrollX();
1031 position[1] -= view.getScrollY();
1032 }
1033
1034 if (position[0] < 0 || position[1] < 0 ||
1035 position[0] > view.getWidth() || position[1] > view.getHeight()) {
1036 return false;
1037 }
1038
1039 if (!view.getMatrix().isIdentity()) {
1040 view.getMatrix().mapPoints(position);
1041 }
1042
1043 position[0] += view.getLeft();
1044 position[1] += view.getTop();
1045
1046 final ViewParent parent = view.getParent();
1047 if (parent instanceof View) {
1048 view = (View) parent;
1049 } else {
1050 // We've reached the ViewRoot, stop iterating
1051 view = null;
1052 }
1053 }
1054 }
1055
1056 // We've been able to walk up the view hierarchy and the position was never clipped
1057 return true;
1058 }
1059
1060 private boolean isOffsetVisible(int offset) {
1061 Layout layout = mTextView.getLayout();
Victoria Leaseb9b77ae2013-10-13 15:12:52 -07001062 if (layout == null) return false;
1063
Gilles Debunned88876a2012-03-16 17:34:04 -07001064 final int line = layout.getLineForOffset(offset);
1065 final int lineBottom = layout.getLineBottom(line);
1066 final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset);
1067 return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(),
1068 lineBottom + mTextView.viewportToContentVerticalOffset());
1069 }
1070
1071 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
1072 * in the view. Returns false when the position is in the empty space of left/right of text.
1073 */
1074 private boolean isPositionOnText(float x, float y) {
1075 Layout layout = mTextView.getLayout();
1076 if (layout == null) return false;
1077
1078 final int line = mTextView.getLineAtCoordinate(y);
1079 x = mTextView.convertToLocalHorizontalCoordinate(x);
1080
1081 if (x < layout.getLineLeft(line)) return false;
1082 if (x > layout.getLineRight(line)) return false;
1083 return true;
1084 }
1085
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001086 private void startDragAndDrop() {
1087 final int start = mTextView.getSelectionStart();
1088 final int end = mTextView.getSelectionEnd();
1089 CharSequence selectedText = mTextView.getTransformedText(start, end);
1090 ClipData data = ClipData.newPlainText(null, selectedText);
1091 DragLocalState localState = new DragLocalState(mTextView, start, end);
1092 mTextView.startDragAndDrop(data, getTextThumbnailBuilder(selectedText), localState,
1093 View.DRAG_FLAG_GLOBAL);
1094 stopTextActionMode();
1095 if (hasSelectionController()) {
1096 getSelectionController().resetTouchOffsets();
1097 }
1098 }
1099
Gilles Debunned88876a2012-03-16 17:34:04 -07001100 public boolean performLongClick(boolean handled) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001101 // Long press in empty space moves cursor and starts the insertion action mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07001102 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
1103 mInsertionControllerEnabled) {
1104 final int offset = mTextView.getOffsetForPosition(mLastDownPositionX,
1105 mLastDownPositionY);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001106 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07001107 Selection.setSelection((Spannable) mTextView.getText(), offset);
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001108 getInsertionController().show();
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001109 mIsInsertionActionModeStartPending = true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001110 handled = true;
1111 }
1112
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001113 if (!handled && mTextActionMode != null) {
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +01001114 if (touchPositionIsInSelection()) {
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09001115 startDragAndDrop();
Gilles Debunned88876a2012-03-16 17:34:04 -07001116 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001117 stopTextActionMode();
Clara Bayarridfac4432015-05-15 12:18:24 +01001118 selectCurrentWordAndStartDrag();
Gilles Debunned88876a2012-03-16 17:34:04 -07001119 }
1120 handled = true;
1121 }
1122
1123 // Start a new selection
1124 if (!handled) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001125 handled = selectCurrentWordAndStartDrag();
Gilles Debunned88876a2012-03-16 17:34:04 -07001126 }
1127
1128 return handled;
1129 }
1130
1131 private long getLastTouchOffsets() {
1132 SelectionModifierCursorController selectionController = getSelectionController();
1133 final int minOffset = selectionController.getMinTouchOffset();
1134 final int maxOffset = selectionController.getMaxTouchOffset();
1135 return TextUtils.packRangeInLong(minOffset, maxOffset);
1136 }
1137
1138 void onFocusChanged(boolean focused, int direction) {
1139 mShowCursor = SystemClock.uptimeMillis();
1140 ensureEndedBatchEdit();
1141
1142 if (focused) {
1143 int selStart = mTextView.getSelectionStart();
1144 int selEnd = mTextView.getSelectionEnd();
1145
1146 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection
1147 // mode for these, unless there was a specific selection already started.
1148 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 &&
1149 selEnd == mTextView.getText().length();
1150
1151 mCreatedWithASelection = mFrozenWithFocus && mTextView.hasSelection() &&
1152 !isFocusHighlighted;
1153
1154 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) {
1155 // If a tap was used to give focus to that view, move cursor at tap position.
1156 // Has to be done before onTakeFocus, which can be overloaded.
1157 final int lastTapPosition = getLastTapPosition();
1158 if (lastTapPosition >= 0) {
1159 Selection.setSelection((Spannable) mTextView.getText(), lastTapPosition);
1160 }
1161
1162 // Note this may have to be moved out of the Editor class
1163 MovementMethod mMovement = mTextView.getMovementMethod();
1164 if (mMovement != null) {
1165 mMovement.onTakeFocus(mTextView, (Spannable) mTextView.getText(), direction);
1166 }
1167
1168 // The DecorView does not have focus when the 'Done' ExtractEditText button is
1169 // pressed. Since it is the ViewAncestor's mView, it requests focus before
1170 // ExtractEditText clears focus, which gives focus to the ExtractEditText.
1171 // This special case ensure that we keep current selection in that case.
1172 // It would be better to know why the DecorView does not have focus at that time.
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001173 if (((mTextView.isInExtractedMode()) || mSelectionMoved) &&
Gilles Debunned88876a2012-03-16 17:34:04 -07001174 selStart >= 0 && selEnd >= 0) {
1175 /*
1176 * Someone intentionally set the selection, so let them
1177 * do whatever it is that they wanted to do instead of
1178 * the default on-focus behavior. We reset the selection
1179 * here instead of just skipping the onTakeFocus() call
1180 * because some movement methods do something other than
1181 * just setting the selection in theirs and we still
1182 * need to go through that path.
1183 */
1184 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
1185 }
1186
1187 if (mSelectAllOnFocus) {
1188 mTextView.selectAllText();
1189 }
1190
1191 mTouchFocusSelected = true;
1192 }
1193
1194 mFrozenWithFocus = false;
1195 mSelectionMoved = false;
1196
1197 if (mError != null) {
1198 showError();
1199 }
1200
1201 makeBlink();
1202 } else {
1203 if (mError != null) {
1204 hideError();
1205 }
1206 // Don't leave us in the middle of a batch edit.
1207 mTextView.onEndBatchEdit();
1208
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001209 if (mTextView.isInExtractedMode()) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001210 // terminateTextSelectionMode removes selection, which we want to keep when
1211 // ExtractEditText goes out of focus.
1212 final int selStart = mTextView.getSelectionStart();
1213 final int selEnd = mTextView.getSelectionEnd();
Mady Mellora2861452015-06-25 08:40:27 -07001214 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001215 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07001216 Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd);
1217 } else {
Adam Powell057a5852012-05-11 10:28:38 -07001218 if (mTemporaryDetach) mPreserveDetachedSelection = true;
Mady Mellora2861452015-06-25 08:40:27 -07001219 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001220 stopTextActionMode();
Adam Powell057a5852012-05-11 10:28:38 -07001221 if (mTemporaryDetach) mPreserveDetachedSelection = false;
Gilles Debunned88876a2012-03-16 17:34:04 -07001222 downgradeEasyCorrectionSpans();
1223 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001224 // No need to create the controller
1225 if (mSelectionModifierCursorController != null) {
1226 mSelectionModifierCursorController.resetTouchOffsets();
1227 }
1228 }
1229 }
1230
1231 /**
1232 * Downgrades to simple suggestions all the easy correction spans that are not a spell check
1233 * span.
1234 */
1235 private void downgradeEasyCorrectionSpans() {
1236 CharSequence text = mTextView.getText();
1237 if (text instanceof Spannable) {
1238 Spannable spannable = (Spannable) text;
1239 SuggestionSpan[] suggestionSpans = spannable.getSpans(0,
1240 spannable.length(), SuggestionSpan.class);
1241 for (int i = 0; i < suggestionSpans.length; i++) {
1242 int flags = suggestionSpans[i].getFlags();
1243 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
1244 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) {
1245 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
1246 suggestionSpans[i].setFlags(flags);
1247 }
1248 }
1249 }
1250 }
1251
1252 void sendOnTextChanged(int start, int after) {
1253 updateSpellCheckSpans(start, start + after, false);
1254
Mady Mellor2ff2cd82015-03-02 10:37:01 -08001255 // Flip flag to indicate the word iterator needs to have the text reset.
1256 mUpdateWordIteratorText = true;
1257
Gilles Debunned88876a2012-03-16 17:34:04 -07001258 // Hide the controllers as soon as text is modified (typing, procedural...)
1259 // We do not hide the span controllers, since they can be added when a new text is
1260 // inserted into the text view (voice IME).
1261 hideCursorControllers();
Keisuke Kuroyanagif4e347d2015-06-11 17:41:00 +09001262 // Reset drag accelerator.
1263 if (mSelectionModifierCursorController != null) {
1264 mSelectionModifierCursorController.resetTouchOffsets();
1265 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001266 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07001267 }
1268
1269 private int getLastTapPosition() {
1270 // No need to create the controller at that point, no last tap position saved
1271 if (mSelectionModifierCursorController != null) {
1272 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset();
1273 if (lastTapPosition >= 0) {
1274 // Safety check, should not be possible.
1275 if (lastTapPosition > mTextView.getText().length()) {
1276 lastTapPosition = mTextView.getText().length();
1277 }
1278 return lastTapPosition;
1279 }
1280 }
1281
1282 return -1;
1283 }
1284
1285 void onWindowFocusChanged(boolean hasWindowFocus) {
1286 if (hasWindowFocus) {
1287 if (mBlink != null) {
1288 mBlink.uncancel();
1289 makeBlink();
1290 }
Mady Mellora2861452015-06-25 08:40:27 -07001291 final InputMethodManager imm = InputMethodManager.peekInstance();
1292 final boolean immFullScreen = (imm != null && imm.isFullscreenMode());
1293 if (mSelectionModifierCursorController != null && mTextView.hasSelection()
Keisuke Kuroyanagi4712b8e2015-07-01 20:06:51 +09001294 && !immFullScreen && mTextActionMode != null) {
Mady Mellora2861452015-06-25 08:40:27 -07001295 mSelectionModifierCursorController.show();
1296 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001297 } else {
1298 if (mBlink != null) {
1299 mBlink.cancel();
1300 }
1301 if (mInputContentType != null) {
1302 mInputContentType.enterDown = false;
1303 }
1304 // Order matters! Must be done before onParentLostFocus to rely on isShowingUp
Mady Mellora2861452015-06-25 08:40:27 -07001305 hideCursorAndSpanControllers();
1306 if (mSelectionModifierCursorController != null) {
1307 mSelectionModifierCursorController.hide();
1308 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001309 if (mSuggestionsPopupWindow != null) {
1310 mSuggestionsPopupWindow.onParentLostFocus();
1311 }
1312
Gilles Debunnec72fba82012-06-26 14:47:07 -07001313 // Don't leave us in the middle of a batch edit. Same as in onFocusChanged
1314 ensureEndedBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001315 }
1316 }
1317
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09001318 private void updateTapState(MotionEvent event) {
1319 final int action = event.getActionMasked();
1320 if (action == MotionEvent.ACTION_DOWN) {
1321 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
1322 // Detect double tap and triple click.
1323 if (((mTapState == TAP_STATE_FIRST_TAP)
1324 || ((mTapState == TAP_STATE_DOUBLE_TAP) && isMouse))
1325 && (SystemClock.uptimeMillis() - mLastTouchUpTime) <=
1326 ViewConfiguration.getDoubleTapTimeout()) {
1327 if (mTapState == TAP_STATE_FIRST_TAP) {
1328 mTapState = TAP_STATE_DOUBLE_TAP;
1329 } else {
1330 mTapState = TAP_STATE_TRIPLE_CLICK;
1331 }
1332 } else {
1333 mTapState = TAP_STATE_FIRST_TAP;
1334 }
1335 }
1336 if (action == MotionEvent.ACTION_UP) {
1337 mLastTouchUpTime = SystemClock.uptimeMillis();
1338 }
1339 }
1340
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09001341 private boolean shouldFilterOutTouchEvent(MotionEvent event) {
1342 if (!event.isFromSource(InputDevice.SOURCE_MOUSE)) {
1343 return false;
1344 }
1345 final boolean primaryButtonStateChanged =
1346 ((mLastButtonState ^ event.getButtonState()) & MotionEvent.BUTTON_PRIMARY) != 0;
1347 final int action = event.getActionMasked();
1348 if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP)
1349 && !primaryButtonStateChanged) {
1350 return true;
1351 }
1352 if (action == MotionEvent.ACTION_MOVE
1353 && !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
1354 return true;
1355 }
1356 return false;
1357 }
1358
Gilles Debunned88876a2012-03-16 17:34:04 -07001359 void onTouchEvent(MotionEvent event) {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09001360 final boolean filterOutEvent = shouldFilterOutTouchEvent(event);
1361 mLastButtonState = event.getButtonState();
1362 if (filterOutEvent) {
1363 if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1364 mDiscardNextActionUp = true;
1365 }
1366 return;
1367 }
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09001368 updateTapState(event);
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001369 updateFloatingToolbarVisibility(event);
1370
Gilles Debunned88876a2012-03-16 17:34:04 -07001371 if (hasSelectionController()) {
1372 getSelectionController().onTouchEvent(event);
1373 }
1374
1375 if (mShowSuggestionRunnable != null) {
1376 mTextView.removeCallbacks(mShowSuggestionRunnable);
1377 mShowSuggestionRunnable = null;
1378 }
1379
1380 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1381 mLastDownPositionX = event.getX();
1382 mLastDownPositionY = event.getY();
1383
1384 // Reset this state; it will be re-set if super.onTouchEvent
1385 // causes focus to move to the view.
1386 mTouchFocusSelected = false;
1387 mIgnoreActionUpEvent = false;
1388 }
1389 }
1390
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001391 private void updateFloatingToolbarVisibility(MotionEvent event) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001392 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001393 switch (event.getActionMasked()) {
1394 case MotionEvent.ACTION_MOVE:
1395 hideFloatingToolbar();
1396 break;
1397 case MotionEvent.ACTION_UP: // fall through
1398 case MotionEvent.ACTION_CANCEL:
1399 showFloatingToolbar();
1400 }
1401 }
1402 }
1403
1404 private void hideFloatingToolbar() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001405 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001406 mTextView.removeCallbacks(mShowFloatingToolbar);
Abodunrinwa Tokif444b5c2015-06-16 15:47:04 +01001407 mTextActionMode.hide(ActionMode.DEFAULT_HIDE_DURATION);
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001408 }
1409 }
1410
1411 private void showFloatingToolbar() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001412 if (mTextActionMode != null) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01001413 // Delay "show" so it doesn't interfere with click confirmations
1414 // or double-clicks that could "dismiss" the floating toolbar.
1415 int delay = ViewConfiguration.getDoubleTapTimeout();
1416 mTextView.postDelayed(mShowFloatingToolbar, delay);
1417 }
1418 }
1419
Gilles Debunned88876a2012-03-16 17:34:04 -07001420 public void beginBatchEdit() {
1421 mInBatchEditControllers = true;
1422 final InputMethodState ims = mInputMethodState;
1423 if (ims != null) {
1424 int nesting = ++ims.mBatchEditNesting;
1425 if (nesting == 1) {
1426 ims.mCursorChanged = false;
1427 ims.mChangedDelta = 0;
1428 if (ims.mContentChanged) {
1429 // We already have a pending change from somewhere else,
1430 // so turn this into a full update.
1431 ims.mChangedStart = 0;
1432 ims.mChangedEnd = mTextView.getText().length();
1433 } else {
1434 ims.mChangedStart = EXTRACT_UNKNOWN;
1435 ims.mChangedEnd = EXTRACT_UNKNOWN;
1436 ims.mContentChanged = false;
1437 }
James Cook48e0fac2015-02-25 15:44:51 -08001438 mUndoInputFilter.beginBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001439 mTextView.onBeginBatchEdit();
1440 }
1441 }
1442 }
1443
1444 public void endBatchEdit() {
1445 mInBatchEditControllers = false;
1446 final InputMethodState ims = mInputMethodState;
1447 if (ims != null) {
1448 int nesting = --ims.mBatchEditNesting;
1449 if (nesting == 0) {
1450 finishBatchEdit(ims);
1451 }
1452 }
1453 }
1454
1455 void ensureEndedBatchEdit() {
1456 final InputMethodState ims = mInputMethodState;
1457 if (ims != null && ims.mBatchEditNesting != 0) {
1458 ims.mBatchEditNesting = 0;
1459 finishBatchEdit(ims);
1460 }
1461 }
1462
1463 void finishBatchEdit(final InputMethodState ims) {
1464 mTextView.onEndBatchEdit();
James Cook48e0fac2015-02-25 15:44:51 -08001465 mUndoInputFilter.endBatchEdit();
Gilles Debunned88876a2012-03-16 17:34:04 -07001466
1467 if (ims.mContentChanged || ims.mSelectionModeChanged) {
1468 mTextView.updateAfterEdit();
1469 reportExtractedText();
1470 } else if (ims.mCursorChanged) {
Jean Chalardc99d33f2013-02-28 16:39:47 -08001471 // Cheesy way to get us to report the current cursor location.
Gilles Debunned88876a2012-03-16 17:34:04 -07001472 mTextView.invalidateCursor();
1473 }
Jean Chalardc99d33f2013-02-28 16:39:47 -08001474 // sendUpdateSelection knows to avoid sending if the selection did
1475 // not actually change.
1476 sendUpdateSelection();
Gilles Debunned88876a2012-03-16 17:34:04 -07001477 }
1478
1479 static final int EXTRACT_NOTHING = -2;
1480 static final int EXTRACT_UNKNOWN = -1;
1481
1482 boolean extractText(ExtractedTextRequest request, ExtractedText outText) {
1483 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN,
1484 EXTRACT_UNKNOWN, outText);
1485 }
1486
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001487 private boolean extractTextInternal(@Nullable ExtractedTextRequest request,
Gilles Debunned88876a2012-03-16 17:34:04 -07001488 int partialStartOffset, int partialEndOffset, int delta,
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001489 @Nullable ExtractedText outText) {
1490 if (request == null || outText == null) {
1491 return false;
Gilles Debunned88876a2012-03-16 17:34:04 -07001492 }
Yoshiki Iguchiee147722015-04-14 00:12:44 +09001493
1494 final CharSequence content = mTextView.getText();
1495 if (content == null) {
1496 return false;
1497 }
1498
1499 if (partialStartOffset != EXTRACT_NOTHING) {
1500 final int N = content.length();
1501 if (partialStartOffset < 0) {
1502 outText.partialStartOffset = outText.partialEndOffset = -1;
1503 partialStartOffset = 0;
1504 partialEndOffset = N;
1505 } else {
1506 // Now use the delta to determine the actual amount of text
1507 // we need.
1508 partialEndOffset += delta;
1509 // Adjust offsets to ensure we contain full spans.
1510 if (content instanceof Spanned) {
1511 Spanned spanned = (Spanned)content;
1512 Object[] spans = spanned.getSpans(partialStartOffset,
1513 partialEndOffset, ParcelableSpan.class);
1514 int i = spans.length;
1515 while (i > 0) {
1516 i--;
1517 int j = spanned.getSpanStart(spans[i]);
1518 if (j < partialStartOffset) partialStartOffset = j;
1519 j = spanned.getSpanEnd(spans[i]);
1520 if (j > partialEndOffset) partialEndOffset = j;
1521 }
1522 }
1523 outText.partialStartOffset = partialStartOffset;
1524 outText.partialEndOffset = partialEndOffset - delta;
1525
1526 if (partialStartOffset > N) {
1527 partialStartOffset = N;
1528 } else if (partialStartOffset < 0) {
1529 partialStartOffset = 0;
1530 }
1531 if (partialEndOffset > N) {
1532 partialEndOffset = N;
1533 } else if (partialEndOffset < 0) {
1534 partialEndOffset = 0;
1535 }
1536 }
1537 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) {
1538 outText.text = content.subSequence(partialStartOffset,
1539 partialEndOffset);
1540 } else {
1541 outText.text = TextUtils.substring(content, partialStartOffset,
1542 partialEndOffset);
1543 }
1544 } else {
1545 outText.partialStartOffset = 0;
1546 outText.partialEndOffset = 0;
1547 outText.text = "";
1548 }
1549 outText.flags = 0;
1550 if (MetaKeyKeyListener.getMetaState(content, MetaKeyKeyListener.META_SELECTING) != 0) {
1551 outText.flags |= ExtractedText.FLAG_SELECTING;
1552 }
1553 if (mTextView.isSingleLine()) {
1554 outText.flags |= ExtractedText.FLAG_SINGLE_LINE;
1555 }
1556 outText.startOffset = 0;
1557 outText.selectionStart = mTextView.getSelectionStart();
1558 outText.selectionEnd = mTextView.getSelectionEnd();
1559 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001560 }
1561
1562 boolean reportExtractedText() {
1563 final Editor.InputMethodState ims = mInputMethodState;
1564 if (ims != null) {
1565 final boolean contentChanged = ims.mContentChanged;
1566 if (contentChanged || ims.mSelectionModeChanged) {
1567 ims.mContentChanged = false;
1568 ims.mSelectionModeChanged = false;
Gilles Debunnec62589c2012-04-12 14:50:23 -07001569 final ExtractedTextRequest req = ims.mExtractedTextRequest;
Gilles Debunned88876a2012-03-16 17:34:04 -07001570 if (req != null) {
1571 InputMethodManager imm = InputMethodManager.peekInstance();
1572 if (imm != null) {
1573 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1574 "Retrieving extracted start=" + ims.mChangedStart +
1575 " end=" + ims.mChangedEnd +
1576 " delta=" + ims.mChangedDelta);
1577 if (ims.mChangedStart < 0 && !contentChanged) {
1578 ims.mChangedStart = EXTRACT_NOTHING;
1579 }
1580 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd,
Gilles Debunnec62589c2012-04-12 14:50:23 -07001581 ims.mChangedDelta, ims.mExtractedText)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001582 if (TextView.DEBUG_EXTRACT) Log.v(TextView.LOG_TAG,
1583 "Reporting extracted start=" +
Gilles Debunnec62589c2012-04-12 14:50:23 -07001584 ims.mExtractedText.partialStartOffset +
1585 " end=" + ims.mExtractedText.partialEndOffset +
1586 ": " + ims.mExtractedText.text);
1587
1588 imm.updateExtractedText(mTextView, req.token, ims.mExtractedText);
Gilles Debunned88876a2012-03-16 17:34:04 -07001589 ims.mChangedStart = EXTRACT_UNKNOWN;
1590 ims.mChangedEnd = EXTRACT_UNKNOWN;
1591 ims.mChangedDelta = 0;
1592 ims.mContentChanged = false;
1593 return true;
1594 }
1595 }
1596 }
1597 }
1598 }
1599 return false;
1600 }
1601
Jean Chalarddf7c72f2013-02-28 15:28:54 -08001602 private void sendUpdateSelection() {
1603 if (null != mInputMethodState && mInputMethodState.mBatchEditNesting <= 0) {
1604 final InputMethodManager imm = InputMethodManager.peekInstance();
1605 if (null != imm) {
1606 final int selectionStart = mTextView.getSelectionStart();
1607 final int selectionEnd = mTextView.getSelectionEnd();
1608 int candStart = -1;
1609 int candEnd = -1;
1610 if (mTextView.getText() instanceof Spannable) {
1611 final Spannable sp = (Spannable) mTextView.getText();
1612 candStart = EditableInputConnection.getComposingSpanStart(sp);
1613 candEnd = EditableInputConnection.getComposingSpanEnd(sp);
1614 }
Jean Chalardc99d33f2013-02-28 16:39:47 -08001615 // InputMethodManager#updateSelection skips sending the message if
1616 // none of the parameters have changed since the last time we called it.
Jean Chalarddf7c72f2013-02-28 15:28:54 -08001617 imm.updateSelection(mTextView,
1618 selectionStart, selectionEnd, candStart, candEnd);
1619 }
1620 }
1621 }
1622
Gilles Debunned88876a2012-03-16 17:34:04 -07001623 void onDraw(Canvas canvas, Layout layout, Path highlight, Paint highlightPaint,
1624 int cursorOffsetVertical) {
1625 final int selectionStart = mTextView.getSelectionStart();
1626 final int selectionEnd = mTextView.getSelectionEnd();
1627
1628 final InputMethodState ims = mInputMethodState;
1629 if (ims != null && ims.mBatchEditNesting == 0) {
1630 InputMethodManager imm = InputMethodManager.peekInstance();
1631 if (imm != null) {
1632 if (imm.isActive(mTextView)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001633 if (ims.mContentChanged || ims.mSelectionModeChanged) {
1634 // We are in extract mode and the content has changed
1635 // in some way... just report complete new text to the
1636 // input method.
Yohei Yukawab6bec1a2015-05-01 16:18:25 -07001637 reportExtractedText();
Gilles Debunned88876a2012-03-16 17:34:04 -07001638 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001639 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001640 }
1641 }
1642
1643 if (mCorrectionHighlighter != null) {
1644 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical);
1645 }
1646
1647 if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) {
1648 drawCursor(canvas, cursorOffsetVertical);
1649 // Rely on the drawable entirely, do not draw the cursor line.
1650 // Has to be done after the IMM related code above which relies on the highlight.
1651 highlight = null;
1652 }
1653
1654 if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) {
1655 drawHardwareAccelerated(canvas, layout, highlight, highlightPaint,
1656 cursorOffsetVertical);
1657 } else {
1658 layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);
1659 }
1660 }
1661
1662 private void drawHardwareAccelerated(Canvas canvas, Layout layout, Path highlight,
1663 Paint highlightPaint, int cursorOffsetVertical) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001664 final long lineRange = layout.getLineRangeForDraw(canvas);
1665 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
1666 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
1667 if (lastLine < 0) return;
1668
1669 layout.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
1670 firstLine, lastLine);
1671
1672 if (layout instanceof DynamicLayout) {
Chris Craik956f3402015-04-27 16:41:00 -07001673 if (mTextRenderNodes == null) {
1674 mTextRenderNodes = ArrayUtils.emptyArray(TextRenderNode.class);
Gilles Debunned88876a2012-03-16 17:34:04 -07001675 }
1676
1677 DynamicLayout dynamicLayout = (DynamicLayout) layout;
Gilles Debunne157aafc2012-04-19 17:21:57 -07001678 int[] blockEndLines = dynamicLayout.getBlockEndLines();
Gilles Debunned88876a2012-03-16 17:34:04 -07001679 int[] blockIndices = dynamicLayout.getBlockIndices();
1680 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
Sangkyu Lee955beb22012-12-10 15:47:00 +09001681 final int indexFirstChangedBlock = dynamicLayout.getIndexFirstChangedBlock();
Gilles Debunned88876a2012-03-16 17:34:04 -07001682
Gilles Debunned88876a2012-03-16 17:34:04 -07001683 int endOfPreviousBlock = -1;
1684 int searchStartIndex = 0;
1685 for (int i = 0; i < numberOfBlocks; i++) {
Gilles Debunne157aafc2012-04-19 17:21:57 -07001686 int blockEndLine = blockEndLines[i];
Gilles Debunned88876a2012-03-16 17:34:04 -07001687 int blockIndex = blockIndices[i];
1688
1689 final boolean blockIsInvalid = blockIndex == DynamicLayout.INVALID_BLOCK_INDEX;
1690 if (blockIsInvalid) {
1691 blockIndex = getAvailableDisplayListIndex(blockIndices, numberOfBlocks,
1692 searchStartIndex);
Gilles Debunne157aafc2012-04-19 17:21:57 -07001693 // Note how dynamic layout's internal block indices get updated from Editor
Gilles Debunned88876a2012-03-16 17:34:04 -07001694 blockIndices[i] = blockIndex;
Chris Craik956f3402015-04-27 16:41:00 -07001695 if (mTextRenderNodes[blockIndex] != null) {
1696 mTextRenderNodes[blockIndex].isDirty = true;
Raph Levienbb2397c2015-02-12 16:16:49 -08001697 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001698 searchStartIndex = blockIndex + 1;
1699 }
1700
Chris Craik956f3402015-04-27 16:41:00 -07001701 if (mTextRenderNodes[blockIndex] == null) {
1702 mTextRenderNodes[blockIndex] =
1703 new TextRenderNode("Text " + blockIndex);
Gilles Debunned88876a2012-03-16 17:34:04 -07001704 }
1705
Chris Craik956f3402015-04-27 16:41:00 -07001706 final boolean blockDisplayListIsInvalid = mTextRenderNodes[blockIndex].needsRecord();
1707 RenderNode blockDisplayList = mTextRenderNodes[blockIndex].renderNode;
Sangkyu Lee955beb22012-12-10 15:47:00 +09001708 if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) {
Gilles Debunne157aafc2012-04-19 17:21:57 -07001709 final int blockBeginLine = endOfPreviousBlock + 1;
1710 final int top = layout.getLineTop(blockBeginLine);
1711 final int bottom = layout.getLineBottom(blockEndLine);
Gilles Debunnefd5bc012012-04-23 16:21:35 -07001712 int left = 0;
1713 int right = mTextView.getWidth();
1714 if (mTextView.getHorizontallyScrolling()) {
1715 float min = Float.MAX_VALUE;
1716 float max = Float.MIN_VALUE;
1717 for (int line = blockBeginLine; line <= blockEndLine; line++) {
1718 min = Math.min(min, layout.getLineLeft(line));
1719 max = Math.max(max, layout.getLineRight(line));
1720 }
1721 left = (int) min;
1722 right = (int) (max + 0.5f);
1723 }
Gilles Debunne157aafc2012-04-19 17:21:57 -07001724
Sangkyu Lee955beb22012-12-10 15:47:00 +09001725 // Rebuild display list if it is invalid
1726 if (blockDisplayListIsInvalid) {
Chris Craikf6829a02015-03-10 10:28:59 -07001727 final DisplayListCanvas displayListCanvas = blockDisplayList.start(
Romain Guy52036b12013-02-14 18:03:37 -08001728 right - left, bottom - top);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001729 try {
Romain Guy52036b12013-02-14 18:03:37 -08001730 // drawText is always relative to TextView's origin, this translation
1731 // brings this range of text back to the top left corner of the viewport
Chris Craikf6829a02015-03-10 10:28:59 -07001732 displayListCanvas.translate(-left, -top);
1733 layout.drawText(displayListCanvas, blockBeginLine, blockEndLine);
Chris Craik956f3402015-04-27 16:41:00 -07001734 mTextRenderNodes[blockIndex].isDirty = false;
Romain Guy52036b12013-02-14 18:03:37 -08001735 // No need to untranslate, previous context is popped after
1736 // drawDisplayList
Sangkyu Lee955beb22012-12-10 15:47:00 +09001737 } finally {
Chris Craikf6829a02015-03-10 10:28:59 -07001738 blockDisplayList.end(displayListCanvas);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001739 // Same as drawDisplayList below, handled by our TextView's parent
Chet Haasedd671592013-04-19 14:54:34 -07001740 blockDisplayList.setClipToBounds(false);
Sangkyu Lee955beb22012-12-10 15:47:00 +09001741 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001742 }
Sangkyu Lee955beb22012-12-10 15:47:00 +09001743
1744 // Valid disply list whose index is >= indexFirstChangedBlock
1745 // only needs to update its drawing location.
1746 blockDisplayList.setLeftTopRightBottom(left, top, right, bottom);
Gilles Debunned88876a2012-03-16 17:34:04 -07001747 }
1748
Chris Craik956f3402015-04-27 16:41:00 -07001749 ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList);
Gilles Debunnefd5bc012012-04-23 16:21:35 -07001750
Gilles Debunne157aafc2012-04-19 17:21:57 -07001751 endOfPreviousBlock = blockEndLine;
Gilles Debunned88876a2012-03-16 17:34:04 -07001752 }
Sangkyu Lee955beb22012-12-10 15:47:00 +09001753
1754 dynamicLayout.setIndexFirstChangedBlock(numberOfBlocks);
Gilles Debunned88876a2012-03-16 17:34:04 -07001755 } else {
1756 // Boring layout is used for empty and hint text
1757 layout.drawText(canvas, firstLine, lastLine);
1758 }
1759 }
1760
1761 private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
1762 int searchStartIndex) {
Chris Craik956f3402015-04-27 16:41:00 -07001763 int length = mTextRenderNodes.length;
Gilles Debunned88876a2012-03-16 17:34:04 -07001764 for (int i = searchStartIndex; i < length; i++) {
1765 boolean blockIndexFound = false;
1766 for (int j = 0; j < numberOfBlocks; j++) {
1767 if (blockIndices[j] == i) {
1768 blockIndexFound = true;
1769 break;
1770 }
1771 }
1772 if (blockIndexFound) continue;
1773 return i;
1774 }
1775
1776 // No available index found, the pool has to grow
Chris Craik956f3402015-04-27 16:41:00 -07001777 mTextRenderNodes = GrowingArrayUtils.append(mTextRenderNodes, length, null);
Gilles Debunned88876a2012-03-16 17:34:04 -07001778 return length;
1779 }
1780
1781 private void drawCursor(Canvas canvas, int cursorOffsetVertical) {
1782 final boolean translate = cursorOffsetVertical != 0;
1783 if (translate) canvas.translate(0, cursorOffsetVertical);
1784 for (int i = 0; i < mCursorCount; i++) {
1785 mCursorDrawable[i].draw(canvas);
1786 }
1787 if (translate) canvas.translate(0, -cursorOffsetVertical);
1788 }
1789
Gilles Debunneebc86af2012-04-20 15:10:47 -07001790 /**
1791 * Invalidates all the sub-display lists that overlap the specified character range
1792 */
1793 void invalidateTextDisplayList(Layout layout, int start, int end) {
Chris Craik956f3402015-04-27 16:41:00 -07001794 if (mTextRenderNodes != null && layout instanceof DynamicLayout) {
Gilles Debunneebc86af2012-04-20 15:10:47 -07001795 final int firstLine = layout.getLineForOffset(start);
1796 final int lastLine = layout.getLineForOffset(end);
1797
1798 DynamicLayout dynamicLayout = (DynamicLayout) layout;
1799 int[] blockEndLines = dynamicLayout.getBlockEndLines();
1800 int[] blockIndices = dynamicLayout.getBlockIndices();
1801 final int numberOfBlocks = dynamicLayout.getNumberOfBlocks();
1802
1803 int i = 0;
1804 // Skip the blocks before firstLine
1805 while (i < numberOfBlocks) {
1806 if (blockEndLines[i] >= firstLine) break;
1807 i++;
1808 }
1809
1810 // Invalidate all subsequent blocks until lastLine is passed
1811 while (i < numberOfBlocks) {
1812 final int blockIndex = blockIndices[i];
1813 if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
Chris Craik956f3402015-04-27 16:41:00 -07001814 mTextRenderNodes[blockIndex].isDirty = true;
Gilles Debunneebc86af2012-04-20 15:10:47 -07001815 }
1816 if (blockEndLines[i] >= lastLine) break;
1817 i++;
1818 }
1819 }
1820 }
1821
Gilles Debunned88876a2012-03-16 17:34:04 -07001822 void invalidateTextDisplayList() {
Chris Craik956f3402015-04-27 16:41:00 -07001823 if (mTextRenderNodes != null) {
1824 for (int i = 0; i < mTextRenderNodes.length; i++) {
1825 if (mTextRenderNodes[i] != null) mTextRenderNodes[i].isDirty = true;
Gilles Debunned88876a2012-03-16 17:34:04 -07001826 }
1827 }
1828 }
1829
1830 void updateCursorsPositions() {
1831 if (mTextView.mCursorDrawableRes == 0) {
1832 mCursorCount = 0;
1833 return;
1834 }
1835
Mady Mellorff66ca52015-07-08 12:31:45 -07001836 Layout layout = getActiveLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -07001837 final int offset = mTextView.getSelectionStart();
1838 final int line = layout.getLineForOffset(offset);
1839 final int top = layout.getLineTop(line);
1840 final int bottom = layout.getLineTop(line + 1);
1841
1842 mCursorCount = layout.isLevelBoundary(offset) ? 2 : 1;
1843
1844 int middle = bottom;
1845 if (mCursorCount == 2) {
1846 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)}
1847 middle = (top + bottom) >> 1;
1848 }
1849
Raph Levienafe8e9b2012-12-19 16:09:32 -08001850 boolean clamped = layout.shouldClampCursor(line);
Mady Mellorff66ca52015-07-08 12:31:45 -07001851 updateCursorPosition(0, top, middle, layout.getPrimaryHorizontal(offset, clamped));
Gilles Debunned88876a2012-03-16 17:34:04 -07001852
1853 if (mCursorCount == 2) {
Siyamed Sinir217c0f72016-02-01 18:30:02 -08001854 updateCursorPosition(1, middle, bottom, layout.getSecondaryHorizontal(offset, clamped));
Gilles Debunned88876a2012-03-16 17:34:04 -07001855 }
1856 }
1857
1858 /**
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001859 * Start an Insertion action mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07001860 */
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001861 void startInsertionActionMode() {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001862 if (mInsertionActionModeRunnable != null) {
1863 mTextView.removeCallbacks(mInsertionActionModeRunnable);
1864 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001865 if (extractedTextModeWillBeStarted()) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001866 return;
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001867 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001868 stopTextActionMode();
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001869
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001870 ActionMode.Callback actionModeCallback =
1871 new TextActionModeCallback(false /* hasSelection */);
1872 mTextActionMode = mTextView.startActionMode(
Clara Bayarrib8ed5b72015-04-09 15:26:41 +01001873 actionModeCallback, ActionMode.TYPE_FLOATING);
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001874 if (mTextActionMode != null && getInsertionController() != null) {
1875 getInsertionController().show();
1876 }
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001877 }
1878
1879 /**
Clara Bayarri578286f2015-04-10 15:35:31 +01001880 * Starts a Selection Action Mode with the current selection and ensures the selection handles
Clara Bayarridfac4432015-05-15 12:18:24 +01001881 * are shown if there is a selection, otherwise the insertion handle is shown. This should be
1882 * used when the mode is started from a non-touch event.
Clara Bayarri578286f2015-04-10 15:35:31 +01001883 *
Clara Bayarri29d2b5aa2015-03-13 17:41:56 +00001884 * @return true if the selection mode was actually started.
1885 */
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001886 boolean startSelectionActionMode() {
1887 boolean selectionStarted = startSelectionActionModeInternal();
Clara Bayarri578286f2015-04-10 15:35:31 +01001888 if (selectionStarted) {
1889 getSelectionController().show();
Clara Bayarridfac4432015-05-15 12:18:24 +01001890 } else if (getInsertionController() != null) {
1891 getInsertionController().show();
Clara Bayarri578286f2015-04-10 15:35:31 +01001892 }
1893 return selectionStarted;
1894 }
1895
Clara Bayarridfac4432015-05-15 12:18:24 +01001896 /**
1897 * If the TextView allows text selection, selects the current word when no existing selection
1898 * was available and starts a drag.
1899 *
1900 * @return true if the drag was started.
1901 */
1902 private boolean selectCurrentWordAndStartDrag() {
Clara Bayarri7184c8a2015-06-05 17:34:09 +01001903 if (mInsertionActionModeRunnable != null) {
1904 mTextView.removeCallbacks(mInsertionActionModeRunnable);
1905 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001906 if (extractedTextModeWillBeStarted()) {
Clara Bayarridfac4432015-05-15 12:18:24 +01001907 return false;
1908 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001909 if (mTextActionMode != null) {
1910 mTextActionMode.finish();
Clara Bayarridfac4432015-05-15 12:18:24 +01001911 }
1912 if (!checkFieldAndSelectCurrentWord()) {
1913 return false;
1914 }
Clara Bayarri01243ac2015-06-03 00:46:29 +01001915
1916 // Avoid dismissing the selection if it exists.
1917 mPreserveDetachedSelection = true;
1918 stopTextActionMode();
1919 mPreserveDetachedSelection = false;
1920
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08001921 getSelectionController().enterDrag(
1922 SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_WORD);
Clara Bayarridfac4432015-05-15 12:18:24 +01001923 return true;
1924 }
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001925
Clara Bayarridfac4432015-05-15 12:18:24 +01001926 /**
1927 * Checks whether a selection can be performed on the current TextView and if so selects
1928 * the current word.
1929 *
1930 * @return true if there already was a selection or if the current word was selected.
1931 */
Andrei Stingaceanu99d3bbd2015-06-30 16:57:03 +01001932 boolean checkFieldAndSelectCurrentWord() {
Clara Bayarridfac4432015-05-15 12:18:24 +01001933 if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
1934 Log.w(TextView.LOG_TAG,
1935 "TextView does not support text selection. Selection cancelled.");
Andrei Stingaceanu975a8d02015-05-19 17:29:16 +01001936 return false;
1937 }
1938
Clara Bayarridfac4432015-05-15 12:18:24 +01001939 if (!mTextView.hasSelection()) {
1940 // There may already be a selection on device rotation
1941 return selectCurrentWord();
1942 }
1943 return true;
1944 }
1945
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001946 private boolean startSelectionActionModeInternal() {
1947 if (mTextActionMode != null) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01001948 // Text action mode is already started
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001949 mTextActionMode.invalidate();
Gilles Debunned88876a2012-03-16 17:34:04 -07001950 return false;
1951 }
1952
Clara Bayarridfac4432015-05-15 12:18:24 +01001953 if (!checkFieldAndSelectCurrentWord()) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001954 return false;
1955 }
1956
Gilles Debunned88876a2012-03-16 17:34:04 -07001957 boolean willExtract = extractedTextModeWillBeStarted();
1958
1959 // Do not start the action mode when extracted text will show up full screen, which would
1960 // immediately hide the newly created action bar and would be visually distracting.
1961 if (!willExtract) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001962 ActionMode.Callback actionModeCallback =
1963 new TextActionModeCallback(true /* hasSelection */);
1964 mTextActionMode = mTextView.startActionMode(
Clara Bayarrib8ed5b72015-04-09 15:26:41 +01001965 actionModeCallback, ActionMode.TYPE_FLOATING);
Gilles Debunned88876a2012-03-16 17:34:04 -07001966 }
1967
Clara Bayarri7938cdb2015-06-02 20:03:45 +01001968 final boolean selectionStarted = mTextActionMode != null || willExtract;
Gilles Debunne3473b2b2012-04-20 16:21:10 -07001969 if (selectionStarted && !mTextView.isTextSelectable() && mShowSoftInputOnFocus) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001970 // Show the IME to be able to replace text, except when selecting non editable text.
1971 final InputMethodManager imm = InputMethodManager.peekInstance();
1972 if (imm != null) {
1973 imm.showSoftInput(mTextView, 0, null);
1974 }
1975 }
Gilles Debunned88876a2012-03-16 17:34:04 -07001976 return selectionStarted;
1977 }
1978
Andrei Stingaceanu99d3bbd2015-06-30 16:57:03 +01001979 boolean extractedTextModeWillBeStarted() {
Andrei Stingaceanub1891b32015-06-19 16:44:37 +01001980 if (!(mTextView.isInExtractedMode())) {
Gilles Debunned88876a2012-03-16 17:34:04 -07001981 final InputMethodManager imm = InputMethodManager.peekInstance();
1982 return imm != null && imm.isFullscreenMode();
1983 }
1984 return false;
1985 }
1986
1987 /**
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09001988 * @return <code>true</code> if it's reasonable to offer to show suggestions depending on
1989 * the current cursor position or selection range. This method is consistent with the
1990 * method to show suggestions {@link SuggestionsPopupWindow#updateSuggestions}.
Gilles Debunned88876a2012-03-16 17:34:04 -07001991 */
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09001992 private boolean shouldOfferToShowSuggestions() {
Gilles Debunned88876a2012-03-16 17:34:04 -07001993 CharSequence text = mTextView.getText();
1994 if (!(text instanceof Spannable)) return false;
1995
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09001996 final Spannable spannable = (Spannable) text;
1997 final int selectionStart = mTextView.getSelectionStart();
1998 final int selectionEnd = mTextView.getSelectionEnd();
1999 final SuggestionSpan[] suggestionSpans = spannable.getSpans(selectionStart, selectionEnd,
2000 SuggestionSpan.class);
2001 if (suggestionSpans.length == 0) {
2002 return false;
2003 }
2004 if (selectionStart == selectionEnd) {
2005 // Spans overlap the cursor.
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002006 for (int i = 0; i < suggestionSpans.length; i++) {
2007 if (suggestionSpans[i].getSuggestions().length > 0) {
2008 return true;
2009 }
2010 }
2011 return false;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002012 }
2013 int minSpanStart = mTextView.getText().length();
2014 int maxSpanEnd = 0;
2015 int unionOfSpansCoveringSelectionStartStart = mTextView.getText().length();
2016 int unionOfSpansCoveringSelectionStartEnd = 0;
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002017 boolean hasValidSuggestions = false;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002018 for (int i = 0; i < suggestionSpans.length; i++) {
2019 final int spanStart = spannable.getSpanStart(suggestionSpans[i]);
2020 final int spanEnd = spannable.getSpanEnd(suggestionSpans[i]);
2021 minSpanStart = Math.min(minSpanStart, spanStart);
2022 maxSpanEnd = Math.max(maxSpanEnd, spanEnd);
2023 if (selectionStart < spanStart || selectionStart > spanEnd) {
2024 // The span doesn't cover the current selection start point.
2025 continue;
2026 }
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002027 hasValidSuggestions =
2028 hasValidSuggestions || suggestionSpans[i].getSuggestions().length > 0;
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002029 unionOfSpansCoveringSelectionStartStart =
2030 Math.min(unionOfSpansCoveringSelectionStartStart, spanStart);
2031 unionOfSpansCoveringSelectionStartEnd =
2032 Math.max(unionOfSpansCoveringSelectionStartEnd, spanEnd);
2033 }
Keisuke Kuroyanagi7e4fbe02015-05-22 14:37:01 +09002034 if (!hasValidSuggestions) {
2035 return false;
2036 }
Keisuke Kuroyanagi05fd8d52015-03-16 17:44:26 +09002037 if (unionOfSpansCoveringSelectionStartStart >= unionOfSpansCoveringSelectionStartEnd) {
2038 // No spans cover the selection start point.
2039 return false;
2040 }
2041 if (minSpanStart < unionOfSpansCoveringSelectionStartStart
2042 || maxSpanEnd > unionOfSpansCoveringSelectionStartEnd) {
2043 // There is a span that is not covered by the union. In this case, we soouldn't offer
2044 // to show suggestions as it's confusing.
2045 return false;
2046 }
2047 return true;
Gilles Debunned88876a2012-03-16 17:34:04 -07002048 }
2049
2050 /**
2051 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with
2052 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set.
2053 */
2054 private boolean isCursorInsideEasyCorrectionSpan() {
2055 Spannable spannable = (Spannable) mTextView.getText();
2056 SuggestionSpan[] suggestionSpans = spannable.getSpans(mTextView.getSelectionStart(),
2057 mTextView.getSelectionEnd(), SuggestionSpan.class);
2058 for (int i = 0; i < suggestionSpans.length; i++) {
2059 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) {
2060 return true;
2061 }
2062 }
2063 return false;
2064 }
2065
2066 void onTouchUpEvent(MotionEvent event) {
2067 boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect();
Mady Mellora2861452015-06-25 08:40:27 -07002068 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002069 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07002070 CharSequence text = mTextView.getText();
2071 if (!selectAllGotFocus && text.length() > 0) {
2072 // Move cursor
2073 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2074 Selection.setSelection((Spannable) text, offset);
2075 if (mSpellChecker != null) {
2076 // When the cursor moves, the word that was typed may need spell check
2077 mSpellChecker.onSelectionChanged();
2078 }
Andrei Stingaceanu35c550c2015-05-07 16:49:49 +01002079
Gilles Debunned88876a2012-03-16 17:34:04 -07002080 if (!extractedTextModeWillBeStarted()) {
2081 if (isCursorInsideEasyCorrectionSpan()) {
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01002082 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002083 if (mInsertionActionModeRunnable != null) {
2084 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01002085 }
2086
Gilles Debunned88876a2012-03-16 17:34:04 -07002087 mShowSuggestionRunnable = new Runnable() {
2088 public void run() {
2089 showSuggestions();
2090 }
2091 };
2092 // removeCallbacks is performed on every touch
2093 mTextView.postDelayed(mShowSuggestionRunnable,
2094 ViewConfiguration.getDoubleTapTimeout());
2095 } else if (hasInsertionController()) {
2096 getInsertionController().show();
2097 }
2098 }
2099 }
2100 }
2101
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002102 protected void stopTextActionMode() {
2103 if (mTextActionMode != null) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002104 // This will hide the mSelectionModifierCursorController
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002105 mTextActionMode.finish();
Gilles Debunned88876a2012-03-16 17:34:04 -07002106 }
2107 }
2108
2109 /**
2110 * @return True if this view supports insertion handles.
2111 */
2112 boolean hasInsertionController() {
2113 return mInsertionControllerEnabled;
2114 }
2115
2116 /**
2117 * @return True if this view supports selection handles.
2118 */
2119 boolean hasSelectionController() {
2120 return mSelectionControllerEnabled;
2121 }
2122
2123 InsertionPointCursorController getInsertionController() {
2124 if (!mInsertionControllerEnabled) {
2125 return null;
2126 }
2127
2128 if (mInsertionPointCursorController == null) {
2129 mInsertionPointCursorController = new InsertionPointCursorController();
2130
2131 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2132 observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
2133 }
2134
2135 return mInsertionPointCursorController;
2136 }
2137
2138 SelectionModifierCursorController getSelectionController() {
2139 if (!mSelectionControllerEnabled) {
2140 return null;
2141 }
2142
2143 if (mSelectionModifierCursorController == null) {
2144 mSelectionModifierCursorController = new SelectionModifierCursorController();
2145
2146 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
2147 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
2148 }
2149
2150 return mSelectionModifierCursorController;
2151 }
2152
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002153 /**
2154 * @hide
2155 */
2156 @VisibleForTesting
2157 public Drawable[] getCursorDrawable() {
2158 return mCursorDrawable;
2159 }
2160
Gilles Debunned88876a2012-03-16 17:34:04 -07002161 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) {
2162 if (mCursorDrawable[cursorIndex] == null)
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002163 mCursorDrawable[cursorIndex] = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07002164 mTextView.mCursorDrawableRes);
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002165 final Drawable drawable = mCursorDrawable[cursorIndex];
2166 final int left = clampCursorHorizontalPosition(drawable, horizontal);
2167 final int width = drawable.getIntrinsicWidth();
2168 drawable.setBounds(left, top - mTempRect.top, left + width,
Gilles Debunned88876a2012-03-16 17:34:04 -07002169 bottom + mTempRect.bottom);
2170 }
2171
2172 /**
Siyamed Sinir217c0f72016-02-01 18:30:02 -08002173 * Return clamped position for the cursor. If the cursor is within the boundaries of the view,
2174 * then it is offset with the left padding of the cursor drawable. If the cursor is at
2175 * the beginning or the end of the text then its drawable edge is aligned with left or right of
2176 * the view boundary.
2177 *
2178 * @param drawable Cursor drawable.
2179 * @param horizontal Horizontal position for the cursor.
2180 * @return The clamped horizontal position for the cursor.
2181 */
2182 private final int clampCursorHorizontalPosition(final Drawable drawable, float
2183 horizontal) {
2184 horizontal = Math.max(0.5f, horizontal - 0.5f);
2185 if (mTempRect == null) mTempRect = new Rect();
2186 drawable.getPadding(mTempRect);
2187 int scrollX = mTextView.getScrollX();
2188 float horizontalDiff = horizontal - scrollX;
2189 int viewClippedWidth = mTextView.getWidth() - mTextView.getCompoundPaddingLeft()
2190 - mTextView.getCompoundPaddingRight();
2191
2192 final int left;
2193 if (horizontalDiff >= (viewClippedWidth - 1f)) {
2194 // at the rightmost position
2195 final int cursorWidth = drawable.getIntrinsicWidth();
2196 left = viewClippedWidth + scrollX - (cursorWidth - mTempRect.right);
2197 } else if (Math.abs(horizontalDiff) <= 1f) {
2198 // at the leftmost position
2199 left = scrollX - mTempRect.left;
2200 } else {
2201 left = (int) horizontal - mTempRect.left;
2202 }
2203 return left;
2204 }
2205
2206 /**
Gilles Debunned88876a2012-03-16 17:34:04 -07002207 * 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 -08002208 * a dictionary) from the current input method, provided by it calling
Gilles Debunned88876a2012-03-16 17:34:04 -07002209 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default
2210 * implementation flashes the background of the corrected word to provide feedback to the user.
2211 *
2212 * @param info The auto correct info about the text that was corrected.
2213 */
2214 public void onCommitCorrection(CorrectionInfo info) {
2215 if (mCorrectionHighlighter == null) {
2216 mCorrectionHighlighter = new CorrectionHighlighter();
2217 } else {
2218 mCorrectionHighlighter.invalidate(false);
2219 }
2220
2221 mCorrectionHighlighter.highlight(info);
2222 }
2223
2224 void showSuggestions() {
2225 if (mSuggestionsPopupWindow == null) {
2226 mSuggestionsPopupWindow = new SuggestionsPopupWindow();
2227 }
Mady Mellora2861452015-06-25 08:40:27 -07002228 hideCursorAndSpanControllers();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002229 stopTextActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07002230 mSuggestionsPopupWindow.show();
2231 }
2232
Gilles Debunned88876a2012-03-16 17:34:04 -07002233 void onScrollChanged() {
Gilles Debunne157aafc2012-04-19 17:21:57 -07002234 if (mPositionListener != null) {
2235 mPositionListener.onScrollChanged();
2236 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01002237 if (mTextActionMode != null) {
2238 mTextActionMode.invalidateContentRect();
Abodunrinwa Toki56195db2015-04-22 06:46:54 +01002239 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002240 }
2241
2242 /**
2243 * @return True when the TextView isFocused and has a valid zero-length selection (cursor).
2244 */
2245 private boolean shouldBlink() {
2246 if (!isCursorVisible() || !mTextView.isFocused()) return false;
2247
2248 final int start = mTextView.getSelectionStart();
2249 if (start < 0) return false;
2250
2251 final int end = mTextView.getSelectionEnd();
2252 if (end < 0) return false;
2253
2254 return start == end;
2255 }
2256
2257 void makeBlink() {
2258 if (shouldBlink()) {
2259 mShowCursor = SystemClock.uptimeMillis();
2260 if (mBlink == null) mBlink = new Blink();
John Reckd0374c62015-10-20 13:25:01 -07002261 mTextView.removeCallbacks(mBlink);
2262 mTextView.postDelayed(mBlink, BLINK);
Gilles Debunned88876a2012-03-16 17:34:04 -07002263 } else {
John Reckd0374c62015-10-20 13:25:01 -07002264 if (mBlink != null) mTextView.removeCallbacks(mBlink);
Gilles Debunned88876a2012-03-16 17:34:04 -07002265 }
2266 }
2267
John Reckd0374c62015-10-20 13:25:01 -07002268 private class Blink implements Runnable {
Gilles Debunned88876a2012-03-16 17:34:04 -07002269 private boolean mCancelled;
2270
2271 public void run() {
Gilles Debunned88876a2012-03-16 17:34:04 -07002272 if (mCancelled) {
2273 return;
2274 }
2275
John Reckd0374c62015-10-20 13:25:01 -07002276 mTextView.removeCallbacks(this);
Gilles Debunned88876a2012-03-16 17:34:04 -07002277
2278 if (shouldBlink()) {
2279 if (mTextView.getLayout() != null) {
2280 mTextView.invalidateCursorPath();
2281 }
2282
John Reckd0374c62015-10-20 13:25:01 -07002283 mTextView.postDelayed(this, BLINK);
Gilles Debunned88876a2012-03-16 17:34:04 -07002284 }
2285 }
2286
2287 void cancel() {
2288 if (!mCancelled) {
John Reckd0374c62015-10-20 13:25:01 -07002289 mTextView.removeCallbacks(this);
Gilles Debunned88876a2012-03-16 17:34:04 -07002290 mCancelled = true;
2291 }
2292 }
2293
2294 void uncancel() {
2295 mCancelled = false;
2296 }
2297 }
2298
2299 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
2300 TextView shadowView = (TextView) View.inflate(mTextView.getContext(),
2301 com.android.internal.R.layout.text_drag_thumbnail, null);
2302
2303 if (shadowView == null) {
2304 throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
2305 }
2306
2307 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
2308 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
2309 }
2310 shadowView.setText(text);
2311 shadowView.setTextColor(mTextView.getTextColors());
2312
Alan Viverettebb98ebd2015-05-08 17:17:44 -07002313 shadowView.setTextAppearance(R.styleable.Theme_textAppearanceLarge);
Gilles Debunned88876a2012-03-16 17:34:04 -07002314 shadowView.setGravity(Gravity.CENTER);
2315
2316 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2317 ViewGroup.LayoutParams.WRAP_CONTENT));
2318
2319 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
2320 shadowView.measure(size, size);
2321
2322 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
2323 shadowView.invalidate();
2324 return new DragShadowBuilder(shadowView);
2325 }
2326
2327 private static class DragLocalState {
2328 public TextView sourceTextView;
2329 public int start, end;
2330
2331 public DragLocalState(TextView sourceTextView, int start, int end) {
2332 this.sourceTextView = sourceTextView;
2333 this.start = start;
2334 this.end = end;
2335 }
2336 }
2337
2338 void onDrop(DragEvent event) {
2339 StringBuilder content = new StringBuilder("");
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -08002340
2341 final DropPermissions dropPermissions = DropPermissions.obtain(event);
2342 if (dropPermissions != null) {
2343 dropPermissions.takeTransient();
2344 }
2345
2346 try {
2347 ClipData clipData = event.getClipData();
2348 final int itemCount = clipData.getItemCount();
2349 for (int i=0; i < itemCount; i++) {
2350 Item item = clipData.getItemAt(i);
2351 content.append(item.coerceToStyledText(mTextView.getContext()));
2352 }
2353 }
2354 finally {
2355 if (dropPermissions != null) {
2356 dropPermissions.release();
2357 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002358 }
2359
2360 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
2361
2362 Object localState = event.getLocalState();
2363 DragLocalState dragLocalState = null;
2364 if (localState instanceof DragLocalState) {
2365 dragLocalState = (DragLocalState) localState;
2366 }
2367 boolean dragDropIntoItself = dragLocalState != null &&
2368 dragLocalState.sourceTextView == mTextView;
2369
2370 if (dragDropIntoItself) {
2371 if (offset >= dragLocalState.start && offset < dragLocalState.end) {
2372 // A drop inside the original selection discards the drop.
2373 return;
2374 }
2375 }
2376
2377 final int originalLength = mTextView.getText().length();
Raph Levien5a689ce2014-09-10 11:03:18 -07002378 int min = offset;
2379 int max = offset;
Gilles Debunned88876a2012-03-16 17:34:04 -07002380
2381 Selection.setSelection((Spannable) mTextView.getText(), max);
2382 mTextView.replaceText_internal(min, max, content);
2383
2384 if (dragDropIntoItself) {
2385 int dragSourceStart = dragLocalState.start;
2386 int dragSourceEnd = dragLocalState.end;
2387 if (max <= dragSourceStart) {
2388 // Inserting text before selection has shifted positions
2389 final int shift = mTextView.getText().length() - originalLength;
2390 dragSourceStart += shift;
2391 dragSourceEnd += shift;
2392 }
2393
2394 // Delete original selection
2395 mTextView.deleteText_internal(dragSourceStart, dragSourceEnd);
2396
2397 // Make sure we do not leave two adjacent spaces.
Victoria Lease91373202012-09-07 16:41:59 -07002398 final int prevCharIdx = Math.max(0, dragSourceStart - 1);
2399 final int nextCharIdx = Math.min(mTextView.getText().length(), dragSourceStart + 1);
2400 if (nextCharIdx > prevCharIdx + 1) {
2401 CharSequence t = mTextView.getTransformedText(prevCharIdx, nextCharIdx);
2402 if (Character.isSpaceChar(t.charAt(0)) && Character.isSpaceChar(t.charAt(1))) {
2403 mTextView.deleteText_internal(prevCharIdx, prevCharIdx + 1);
2404 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002405 }
2406 }
2407 }
2408
Gilles Debunnec62589c2012-04-12 14:50:23 -07002409 public void addSpanWatchers(Spannable text) {
2410 final int textLength = text.length();
2411
2412 if (mKeyListener != null) {
2413 text.setSpan(mKeyListener, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2414 }
2415
Jean Chalardbaf30942013-02-28 16:01:51 -08002416 if (mSpanController == null) {
2417 mSpanController = new SpanController();
Gilles Debunnec62589c2012-04-12 14:50:23 -07002418 }
Jean Chalardbaf30942013-02-28 16:01:51 -08002419 text.setSpan(mSpanController, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002420 }
2421
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002422 void setContextMenuAnchor(float x, float y) {
2423 mContextMenuAnchorX = x;
2424 mContextMenuAnchorY = y;
2425 }
2426
2427 void onCreateContextMenu(ContextMenu menu) {
2428 if (mIsBeingLongClicked || Float.isNaN(mContextMenuAnchorX)
2429 || Float.isNaN(mContextMenuAnchorY)) {
2430 return;
2431 }
2432 final int offset = mTextView.getOffsetForPosition(mContextMenuAnchorX, mContextMenuAnchorY);
2433 if (offset == -1) {
2434 return;
2435 }
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002436 mPreserveDetachedSelection = true;
2437 stopTextActionMode();
2438 mPreserveDetachedSelection = false;
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002439 final boolean isOnSelection = mTextView.hasSelection()
2440 && offset >= mTextView.getSelectionStart() && offset <= mTextView.getSelectionEnd();
2441 if (!isOnSelection) {
2442 // Right clicked position is not on the selection. Remove the selection and move the
2443 // cursor to the right clicked position.
2444 stopTextActionMode();
2445 Selection.setSelection((Spannable) mTextView.getText(), offset);
2446 }
2447
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002448 if (shouldOfferToShowSuggestions()) {
2449 if (mSuggestionInfosInContextMenu == null) {
2450 mSuggestionInfosInContextMenu =
2451 new SuggestionInfo[SuggestionSpan.SUGGESTIONS_MAX_SIZE];
2452 for (int i = 0; i < mSuggestionInfosInContextMenu.length; i++) {
2453 mSuggestionInfosInContextMenu[i] = new SuggestionInfo();
2454 }
2455 }
2456 final SubMenu subMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, MENU_ITEM_ORDER_REPLACE,
2457 com.android.internal.R.string.replace);
2458 mSuggestionHelper.getSuggestionInfo(mSuggestionInfosInContextMenu);
2459 int i = 0;
2460 for (final SuggestionInfo info : mSuggestionInfosInContextMenu) {
2461 info.mSuggestionEnd = info.mText.length();
2462 subMenu.add(Menu.NONE, Menu.NONE, i++, info.mText)
2463 .setOnMenuItemClickListener(mOnContextMenuReplaceItemClickListener);
2464 }
2465 }
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002466
2467 menu.add(Menu.NONE, TextView.ID_UNDO, MENU_ITEM_ORDER_UNDO,
2468 com.android.internal.R.string.undo)
2469 .setAlphabeticShortcut('z')
2470 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2471 .setEnabled(mTextView.canUndo());
2472 menu.add(Menu.NONE, TextView.ID_REDO, MENU_ITEM_ORDER_REDO,
2473 com.android.internal.R.string.redo)
2474 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2475 .setEnabled(mTextView.canRedo());
2476
2477 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
2478 com.android.internal.R.string.cut)
2479 .setAlphabeticShortcut('x')
2480 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2481 .setEnabled(mTextView.canCut());
2482 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
2483 com.android.internal.R.string.copy)
2484 .setAlphabeticShortcut('c')
2485 .setOnMenuItemClickListener(mOnContextMenuItemClickListener)
2486 .setEnabled(mTextView.canCopy());
2487 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
2488 com.android.internal.R.string.paste)
2489 .setAlphabeticShortcut('v')
2490 .setEnabled(mTextView.canPaste())
2491 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2492 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT,
2493 com.android.internal.R.string.paste_as_plain_text)
2494 .setEnabled(mTextView.canPaste())
2495 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2496 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
2497 com.android.internal.R.string.share)
2498 .setEnabled(mTextView.canShare())
2499 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2500 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
2501 com.android.internal.R.string.selectAll)
2502 .setAlphabeticShortcut('a')
2503 .setEnabled(mTextView.canSelectAllText())
2504 .setOnMenuItemClickListener(mOnContextMenuItemClickListener);
2505
2506 mPreserveDetachedSelection = true;
2507 }
2508
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002509 private void replaceWithSuggestion(SuggestionInfo suggestionInfo, int spanStart, int spanEnd) {
2510 final Editable editable = (Editable) mTextView.getText();
2511 final String originalText = TextUtils.substring(editable, spanStart, spanEnd);
2512 // SuggestionSpans are removed by replace: save them before
2513 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd,
2514 SuggestionSpan.class);
2515 final int length = suggestionSpans.length;
2516 int[] suggestionSpansStarts = new int[length];
2517 int[] suggestionSpansEnds = new int[length];
2518 int[] suggestionSpansFlags = new int[length];
2519 for (int i = 0; i < length; i++) {
2520 final SuggestionSpan suggestionSpan = suggestionSpans[i];
2521 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan);
2522 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan);
2523 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan);
2524
2525 // Remove potential misspelled flags
2526 int suggestionSpanFlags = suggestionSpan.getFlags();
2527 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) != 0) {
2528 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED;
2529 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT;
2530 suggestionSpan.setFlags(suggestionSpanFlags);
2531 }
2532 }
2533
2534 // Notify source IME of the suggestion pick. Do this before swapping texts.
2535 suggestionInfo.mSuggestionSpan.notifySelection(
2536 mTextView.getContext(), originalText, suggestionInfo.mSuggestionIndex);
2537
2538 // Swap text content between actual text and Suggestion span
2539 final int suggestionStart = suggestionInfo.mSuggestionStart;
2540 final int suggestionEnd = suggestionInfo.mSuggestionEnd;
2541 final String suggestion = suggestionInfo.mText.subSequence(
2542 suggestionStart, suggestionEnd).toString();
2543 mTextView.replaceText_internal(spanStart, spanEnd, suggestion);
2544
2545 String[] suggestions = suggestionInfo.mSuggestionSpan.getSuggestions();
2546 suggestions[suggestionInfo.mSuggestionIndex] = originalText;
2547
2548 // Restore previous SuggestionSpans
2549 final int lengthDelta = suggestion.length() - (spanEnd - spanStart);
2550 for (int i = 0; i < length; i++) {
2551 // Only spans that include the modified region make sense after replacement
2552 // Spans partially included in the replaced region are removed, there is no
2553 // way to assign them a valid range after replacement
2554 if (suggestionSpansStarts[i] <= spanStart && suggestionSpansEnds[i] >= spanEnd) {
2555 mTextView.setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i],
2556 suggestionSpansEnds[i] + lengthDelta, suggestionSpansFlags[i]);
2557 }
2558 }
2559 // Move cursor at the end of the replaced word
2560 final int newCursorPosition = spanEnd + lengthDelta;
2561 mTextView.setCursorPosition_internal(newCursorPosition, newCursorPosition);
2562 }
2563
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002564 private final MenuItem.OnMenuItemClickListener mOnContextMenuItemClickListener =
2565 new MenuItem.OnMenuItemClickListener() {
2566 @Override
2567 public boolean onMenuItemClick(MenuItem item) {
2568 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
2569 return true;
2570 }
2571 return mTextView.onTextContextMenuItem(item.getItemId());
2572 }
2573 };
2574
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09002575 private final MenuItem.OnMenuItemClickListener mOnContextMenuReplaceItemClickListener =
2576 new MenuItem.OnMenuItemClickListener() {
2577 @Override
2578 public boolean onMenuItemClick(MenuItem item) {
2579 int index = item.getOrder();
2580 if (index < 0 || index >= mSuggestionInfosInContextMenu.length) {
2581 clear();
2582 return false;
2583 }
2584 final Spannable spannable = (Spannable) mTextView.getText();
2585 final SuggestionSpan suggestionSpan =
2586 mSuggestionInfosInContextMenu[index].mSuggestionSpan;
2587 replaceWithSuggestion(mSuggestionInfosInContextMenu[index],
2588 spannable.getSpanStart(suggestionSpan), spannable.getSpanEnd(suggestionSpan));
2589 clear();
2590 return true;
2591 }
2592
2593 private void clear() {
2594 for (final SuggestionInfo info : mSuggestionInfosInContextMenu) {
2595 info.clear();
2596 }
2597 }
2598 };
2599
Gilles Debunned88876a2012-03-16 17:34:04 -07002600 /**
2601 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related
2602 * pop-up should be displayed.
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07002603 * Also monitors {@link Selection} to call back to the attached input method.
Gilles Debunned88876a2012-03-16 17:34:04 -07002604 */
Jean Chalardbaf30942013-02-28 16:01:51 -08002605 class SpanController implements SpanWatcher {
Gilles Debunned88876a2012-03-16 17:34:04 -07002606
2607 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs
2608
2609 private EasyEditPopupWindow mPopupWindow;
2610
Gilles Debunned88876a2012-03-16 17:34:04 -07002611 private Runnable mHidePopup;
2612
Jean Chalardbaf30942013-02-28 16:01:51 -08002613 // This function is pure but inner classes can't have static functions
2614 private boolean isNonIntermediateSelectionSpan(final Spannable text,
2615 final Object span) {
2616 return (Selection.SELECTION_START == span || Selection.SELECTION_END == span)
2617 && (text.getSpanFlags(span) & Spanned.SPAN_INTERMEDIATE) == 0;
2618 }
2619
Gilles Debunnec62589c2012-04-12 14:50:23 -07002620 @Override
2621 public void onSpanAdded(Spannable text, Object span, int start, int end) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002622 if (isNonIntermediateSelectionSpan(text, span)) {
2623 sendUpdateSelection();
2624 } else if (span instanceof EasyEditSpan) {
Gilles Debunnec62589c2012-04-12 14:50:23 -07002625 if (mPopupWindow == null) {
2626 mPopupWindow = new EasyEditPopupWindow();
2627 mHidePopup = new Runnable() {
2628 @Override
2629 public void run() {
2630 hide();
2631 }
2632 };
2633 }
2634
2635 // Make sure there is only at most one EasyEditSpan in the text
2636 if (mPopupWindow.mEasyEditSpan != null) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002637 mPopupWindow.mEasyEditSpan.setDeleteEnabled(false);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002638 }
2639
2640 mPopupWindow.setEasyEditSpan((EasyEditSpan) span);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002641 mPopupWindow.setOnDeleteListener(new EasyEditDeleteListener() {
2642 @Override
2643 public void onDeleteClick(EasyEditSpan span) {
2644 Editable editable = (Editable) mTextView.getText();
2645 int start = editable.getSpanStart(span);
2646 int end = editable.getSpanEnd(span);
2647 if (start >= 0 && end >= 0) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002648 sendEasySpanNotification(EasyEditSpan.TEXT_DELETED, span);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002649 mTextView.deleteText_internal(start, end);
2650 }
2651 editable.removeSpan(span);
2652 }
2653 });
Gilles Debunnec62589c2012-04-12 14:50:23 -07002654
2655 if (mTextView.getWindowVisibility() != View.VISIBLE) {
2656 // The window is not visible yet, ignore the text change.
2657 return;
2658 }
2659
2660 if (mTextView.getLayout() == null) {
2661 // The view has not been laid out yet, ignore the text change
2662 return;
2663 }
2664
2665 if (extractedTextModeWillBeStarted()) {
2666 // The input is in extract mode. Do not handle the easy edit in
2667 // the original TextView, as the ExtractEditText will do
2668 return;
2669 }
2670
2671 mPopupWindow.show();
2672 mTextView.removeCallbacks(mHidePopup);
2673 mTextView.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS);
2674 }
2675 }
2676
2677 @Override
2678 public void onSpanRemoved(Spannable text, Object span, int start, int end) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002679 if (isNonIntermediateSelectionSpan(text, span)) {
2680 sendUpdateSelection();
2681 } else if (mPopupWindow != null && span == mPopupWindow.mEasyEditSpan) {
Gilles Debunnec62589c2012-04-12 14:50:23 -07002682 hide();
2683 }
2684 }
2685
2686 @Override
2687 public void onSpanChanged(Spannable text, Object span, int previousStart, int previousEnd,
2688 int newStart, int newEnd) {
Jean Chalardbaf30942013-02-28 16:01:51 -08002689 if (isNonIntermediateSelectionSpan(text, span)) {
2690 sendUpdateSelection();
2691 } else if (mPopupWindow != null && span instanceof EasyEditSpan) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002692 EasyEditSpan easyEditSpan = (EasyEditSpan) span;
Jean Chalardbaf30942013-02-28 16:01:51 -08002693 sendEasySpanNotification(EasyEditSpan.TEXT_MODIFIED, easyEditSpan);
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002694 text.removeSpan(easyEditSpan);
Gilles Debunnec62589c2012-04-12 14:50:23 -07002695 }
2696 }
2697
Gilles Debunned88876a2012-03-16 17:34:04 -07002698 public void hide() {
2699 if (mPopupWindow != null) {
2700 mPopupWindow.hide();
2701 mTextView.removeCallbacks(mHidePopup);
2702 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002703 }
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002704
Jean Chalardbaf30942013-02-28 16:01:51 -08002705 private void sendEasySpanNotification(int textChangedType, EasyEditSpan span) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002706 try {
2707 PendingIntent pendingIntent = span.getPendingIntent();
2708 if (pendingIntent != null) {
2709 Intent intent = new Intent();
2710 intent.putExtra(EasyEditSpan.EXTRA_TEXT_CHANGED_TYPE, textChangedType);
2711 pendingIntent.send(mTextView.getContext(), 0, intent);
2712 }
2713 } catch (CanceledException e) {
2714 // This should not happen, as we should try to send the intent only once.
2715 Log.w(TAG, "PendingIntent for notification cannot be sent", e);
2716 }
2717 }
2718 }
2719
2720 /**
2721 * Listens for the delete event triggered by {@link EasyEditPopupWindow}.
2722 */
2723 private interface EasyEditDeleteListener {
2724
2725 /**
2726 * Clicks the delete pop-up.
2727 */
2728 void onDeleteClick(EasyEditSpan span);
Gilles Debunned88876a2012-03-16 17:34:04 -07002729 }
2730
2731 /**
2732 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07002733 * by {@link SpanController}.
Gilles Debunned88876a2012-03-16 17:34:04 -07002734 */
2735 private class EasyEditPopupWindow extends PinnedPopupWindow
2736 implements OnClickListener {
2737 private static final int POPUP_TEXT_LAYOUT =
2738 com.android.internal.R.layout.text_edit_action_popup_text;
2739 private TextView mDeleteTextView;
2740 private EasyEditSpan mEasyEditSpan;
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002741 private EasyEditDeleteListener mOnDeleteListener;
Gilles Debunned88876a2012-03-16 17:34:04 -07002742
2743 @Override
2744 protected void createPopupWindow() {
2745 mPopupWindow = new PopupWindow(mTextView.getContext(), null,
2746 com.android.internal.R.attr.textSelectHandleWindowStyle);
2747 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
2748 mPopupWindow.setClippingEnabled(true);
2749 }
2750
2751 @Override
2752 protected void initContentView() {
2753 LinearLayout linearLayout = new LinearLayout(mTextView.getContext());
2754 linearLayout.setOrientation(LinearLayout.HORIZONTAL);
2755 mContentView = linearLayout;
2756 mContentView.setBackgroundResource(
2757 com.android.internal.R.drawable.text_edit_side_paste_window);
2758
2759 LayoutInflater inflater = (LayoutInflater)mTextView.getContext().
2760 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2761
2762 LayoutParams wrapContent = new LayoutParams(
2763 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
2764
2765 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null);
2766 mDeleteTextView.setLayoutParams(wrapContent);
2767 mDeleteTextView.setText(com.android.internal.R.string.delete);
2768 mDeleteTextView.setOnClickListener(this);
2769 mContentView.addView(mDeleteTextView);
2770 }
2771
Gilles Debunnec62589c2012-04-12 14:50:23 -07002772 public void setEasyEditSpan(EasyEditSpan easyEditSpan) {
Gilles Debunned88876a2012-03-16 17:34:04 -07002773 mEasyEditSpan = easyEditSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07002774 }
2775
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002776 private void setOnDeleteListener(EasyEditDeleteListener listener) {
2777 mOnDeleteListener = listener;
2778 }
2779
Gilles Debunned88876a2012-03-16 17:34:04 -07002780 @Override
2781 public void onClick(View view) {
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002782 if (view == mDeleteTextView
2783 && mEasyEditSpan != null && mEasyEditSpan.isDeleteEnabled()
2784 && mOnDeleteListener != null) {
2785 mOnDeleteListener.onDeleteClick(mEasyEditSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07002786 }
2787 }
2788
2789 @Override
Luca Zanolin1b15ba52013-02-20 14:31:37 +00002790 public void hide() {
2791 if (mEasyEditSpan != null) {
2792 mEasyEditSpan.setDeleteEnabled(false);
2793 }
2794 mOnDeleteListener = null;
2795 super.hide();
2796 }
2797
2798 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07002799 protected int getTextOffset() {
2800 // Place the pop-up at the end of the span
2801 Editable editable = (Editable) mTextView.getText();
2802 return editable.getSpanEnd(mEasyEditSpan);
2803 }
2804
2805 @Override
2806 protected int getVerticalLocalPosition(int line) {
2807 return mTextView.getLayout().getLineBottom(line);
2808 }
2809
2810 @Override
2811 protected int clipVertically(int positionY) {
2812 // As we display the pop-up below the span, no vertical clipping is required.
2813 return positionY;
2814 }
2815 }
2816
2817 private class PositionListener implements ViewTreeObserver.OnPreDrawListener {
2818 // 3 handles
2819 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others)
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09002820 // 1 CursorAnchorInfoNotifier
2821 private final int MAXIMUM_NUMBER_OF_LISTENERS = 7;
Gilles Debunned88876a2012-03-16 17:34:04 -07002822 private TextViewPositionListener[] mPositionListeners =
2823 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS];
2824 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS];
2825 private boolean mPositionHasChanged = true;
2826 // Absolute position of the TextView with respect to its parent window
2827 private int mPositionX, mPositionY;
2828 private int mNumberOfListeners;
2829 private boolean mScrollHasChanged;
2830 final int[] mTempCoords = new int[2];
2831
2832 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) {
2833 if (mNumberOfListeners == 0) {
2834 updatePosition();
2835 ViewTreeObserver vto = mTextView.getViewTreeObserver();
2836 vto.addOnPreDrawListener(this);
2837 }
2838
2839 int emptySlotIndex = -1;
2840 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2841 TextViewPositionListener listener = mPositionListeners[i];
2842 if (listener == positionListener) {
2843 return;
2844 } else if (emptySlotIndex < 0 && listener == null) {
2845 emptySlotIndex = i;
2846 }
2847 }
2848
2849 mPositionListeners[emptySlotIndex] = positionListener;
2850 mCanMove[emptySlotIndex] = canMove;
2851 mNumberOfListeners++;
2852 }
2853
2854 public void removeSubscriber(TextViewPositionListener positionListener) {
2855 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2856 if (mPositionListeners[i] == positionListener) {
2857 mPositionListeners[i] = null;
2858 mNumberOfListeners--;
2859 break;
2860 }
2861 }
2862
2863 if (mNumberOfListeners == 0) {
2864 ViewTreeObserver vto = mTextView.getViewTreeObserver();
2865 vto.removeOnPreDrawListener(this);
2866 }
2867 }
2868
2869 public int getPositionX() {
2870 return mPositionX;
2871 }
2872
2873 public int getPositionY() {
2874 return mPositionY;
2875 }
2876
2877 @Override
2878 public boolean onPreDraw() {
2879 updatePosition();
2880
2881 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) {
2882 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) {
2883 TextViewPositionListener positionListener = mPositionListeners[i];
2884 if (positionListener != null) {
2885 positionListener.updatePosition(mPositionX, mPositionY,
2886 mPositionHasChanged, mScrollHasChanged);
2887 }
2888 }
2889 }
2890
2891 mScrollHasChanged = false;
2892 return true;
2893 }
2894
2895 private void updatePosition() {
2896 mTextView.getLocationInWindow(mTempCoords);
2897
2898 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY;
2899
2900 mPositionX = mTempCoords[0];
2901 mPositionY = mTempCoords[1];
2902 }
2903
2904 public void onScrollChanged() {
2905 mScrollHasChanged = true;
2906 }
2907 }
2908
2909 private abstract class PinnedPopupWindow implements TextViewPositionListener {
2910 protected PopupWindow mPopupWindow;
2911 protected ViewGroup mContentView;
2912 int mPositionX, mPositionY;
Seigo Nonaka60490d12016-01-28 17:25:18 +09002913 int mClippingLimitLeft, mClippingLimitRight;
Gilles Debunned88876a2012-03-16 17:34:04 -07002914
2915 protected abstract void createPopupWindow();
2916 protected abstract void initContentView();
2917 protected abstract int getTextOffset();
2918 protected abstract int getVerticalLocalPosition(int line);
2919 protected abstract int clipVertically(int positionY);
2920
2921 public PinnedPopupWindow() {
2922 createPopupWindow();
2923
Alan Viverette80ebe0d2015-04-30 15:53:11 -07002924 mPopupWindow.setWindowLayoutType(
2925 WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL);
Gilles Debunned88876a2012-03-16 17:34:04 -07002926 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
2927 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
2928
2929 initContentView();
2930
2931 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
2932 ViewGroup.LayoutParams.WRAP_CONTENT);
2933 mContentView.setLayoutParams(wrapContent);
2934
2935 mPopupWindow.setContentView(mContentView);
2936 }
2937
2938 public void show() {
2939 getPositionListener().addSubscriber(this, false /* offset is fixed */);
2940
2941 computeLocalPosition();
2942
2943 final PositionListener positionListener = getPositionListener();
2944 updatePosition(positionListener.getPositionX(), positionListener.getPositionY());
2945 }
2946
2947 protected void measureContent() {
2948 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2949 mContentView.measure(
2950 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels,
2951 View.MeasureSpec.AT_MOST),
2952 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels,
2953 View.MeasureSpec.AT_MOST));
2954 }
2955
2956 /* The popup window will be horizontally centered on the getTextOffset() and vertically
2957 * positioned according to viewportToContentHorizontalOffset.
2958 *
2959 * This method assumes that mContentView has properly been measured from its content. */
2960 private void computeLocalPosition() {
2961 measureContent();
2962 final int width = mContentView.getMeasuredWidth();
2963 final int offset = getTextOffset();
2964 mPositionX = (int) (mTextView.getLayout().getPrimaryHorizontal(offset) - width / 2.0f);
2965 mPositionX += mTextView.viewportToContentHorizontalOffset();
2966
2967 final int line = mTextView.getLayout().getLineForOffset(offset);
2968 mPositionY = getVerticalLocalPosition(line);
2969 mPositionY += mTextView.viewportToContentVerticalOffset();
2970 }
2971
2972 private void updatePosition(int parentPositionX, int parentPositionY) {
2973 int positionX = parentPositionX + mPositionX;
2974 int positionY = parentPositionY + mPositionY;
2975
2976 positionY = clipVertically(positionY);
2977
2978 // Horizontal clipping
2979 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
2980 final int width = mContentView.getMeasuredWidth();
Seigo Nonaka60490d12016-01-28 17:25:18 +09002981 positionX = Math.min(
2982 displayMetrics.widthPixels - width + mClippingLimitRight, positionX);
2983 positionX = Math.max(-mClippingLimitLeft, positionX);
Gilles Debunned88876a2012-03-16 17:34:04 -07002984
2985 if (isShowing()) {
2986 mPopupWindow.update(positionX, positionY, -1, -1);
2987 } else {
2988 mPopupWindow.showAtLocation(mTextView, Gravity.NO_GRAVITY,
2989 positionX, positionY);
2990 }
2991 }
2992
2993 public void hide() {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09002994 if (!isShowing()) {
2995 return;
2996 }
Gilles Debunned88876a2012-03-16 17:34:04 -07002997 mPopupWindow.dismiss();
2998 getPositionListener().removeSubscriber(this);
2999 }
3000
3001 @Override
3002 public void updatePosition(int parentPositionX, int parentPositionY,
3003 boolean parentPositionChanged, boolean parentScrolled) {
3004 // Either parentPositionChanged or parentScrolled is true, check if still visible
3005 if (isShowing() && isOffsetVisible(getTextOffset())) {
3006 if (parentScrolled) computeLocalPosition();
3007 updatePosition(parentPositionX, parentPositionY);
3008 } else {
3009 hide();
3010 }
3011 }
3012
3013 public boolean isShowing() {
3014 return mPopupWindow.isShowing();
3015 }
3016 }
3017
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003018 private static class SuggestionInfo {
3019 // Range of actual suggestion within text
3020 int mSuggestionStart, mSuggestionEnd;
3021
3022 // The SuggestionSpan that this TextView represents
3023 @Nullable
3024 SuggestionSpan mSuggestionSpan;
3025
3026 // The index of this suggestion inside suggestionSpan
3027 int mSuggestionIndex;
3028
3029 final SpannableStringBuilder mText = new SpannableStringBuilder();
3030
3031 void clear() {
3032 mSuggestionSpan = null;
3033 mText.clear();
3034 }
3035 }
3036
3037 private class SuggestionHelper {
3038 private final Comparator<SuggestionSpan> mSuggestionSpanComparator =
3039 new SuggestionSpanComparator();
3040 private final HashMap<SuggestionSpan, Integer> mSpansLengths =
3041 new HashMap<SuggestionSpan, Integer>();
3042
3043 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> {
3044 public int compare(SuggestionSpan span1, SuggestionSpan span2) {
3045 final int flag1 = span1.getFlags();
3046 final int flag2 = span2.getFlags();
3047 if (flag1 != flag2) {
3048 // The order here should match what is used in updateDrawState
3049 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
3050 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0;
3051 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0;
3052 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0;
3053 if (easy1 && !misspelled1) return -1;
3054 if (easy2 && !misspelled2) return 1;
3055 if (misspelled1) return -1;
3056 if (misspelled2) return 1;
3057 }
3058
3059 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue();
3060 }
3061 }
3062
3063 /**
3064 * Returns the suggestion spans that cover the current cursor position. The suggestion
3065 * spans are sorted according to the length of text that they are attached to.
3066 */
3067 private SuggestionSpan[] getSortedSuggestionSpans() {
3068 int pos = mTextView.getSelectionStart();
3069 Spannable spannable = (Spannable) mTextView.getText();
3070 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class);
3071
3072 mSpansLengths.clear();
3073 for (SuggestionSpan suggestionSpan : suggestionSpans) {
3074 int start = spannable.getSpanStart(suggestionSpan);
3075 int end = spannable.getSpanEnd(suggestionSpan);
3076 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start));
3077 }
3078
3079 // The suggestions are sorted according to their types (easy correction first, then
3080 // misspelled) and to the length of the text that they cover (shorter first).
3081 Arrays.sort(suggestionSpans, mSuggestionSpanComparator);
3082 mSpansLengths.clear();
3083
3084 return suggestionSpans;
3085 }
3086
3087 /**
3088 * Gets the SuggestionInfo list that contains suggestion information at the current cursor
3089 * position.
3090 *
3091 * @param suggestionInfos SuggestionInfo array the results will be set.
3092 * @return the number of suggestions actually fetched.
3093 */
3094 public int getSuggestionInfo(SuggestionInfo[] suggestionInfos) {
3095 final Spannable spannable = (Spannable) mTextView.getText();
3096 final SuggestionSpan[] suggestionSpans = getSortedSuggestionSpans();
3097 final int nbSpans = suggestionSpans.length;
3098 if (nbSpans == 0) return 0;
3099
3100 int numberOfSuggestions = 0;
3101 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) {
3102 final SuggestionSpan suggestionSpan = suggestionSpans[spanIndex];
3103 final int spanStart = spannable.getSpanStart(suggestionSpan);
3104 final int spanEnd = spannable.getSpanEnd(suggestionSpan);
3105
3106 final String[] suggestions = suggestionSpan.getSuggestions();
3107 final int nbSuggestions = suggestions.length;
3108 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) {
3109 final String suggestion = suggestions[suggestionIndex];
3110 boolean suggestionIsDuplicate = false;
3111 for (int i = 0; i < numberOfSuggestions; i++) {
3112 if (suggestionInfos[i].mText.toString().equals(suggestion)) {
3113 final SuggestionSpan otherSuggestionSpan =
3114 suggestionInfos[i].mSuggestionSpan;
3115 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan);
3116 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan);
3117 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) {
3118 suggestionIsDuplicate = true;
3119 break;
3120 }
3121 }
3122 }
3123
3124 if (suggestionIsDuplicate) {
3125 continue;
3126 }
3127 SuggestionInfo suggestionInfo = suggestionInfos[numberOfSuggestions];
3128 suggestionInfo.mSuggestionSpan = suggestionSpan;
3129 suggestionInfo.mSuggestionIndex = suggestionIndex;
3130 suggestionInfo.mSuggestionStart = 0;
3131 suggestionInfo.mSuggestionEnd = suggestion.length();
3132 suggestionInfo.mText.replace(0, suggestionInfo.mText.length(), suggestion);
3133 numberOfSuggestions++;
3134 if (numberOfSuggestions >= suggestionInfos.length) {
3135 return numberOfSuggestions;
3136 }
3137 }
3138 }
3139 return numberOfSuggestions;
3140 }
3141 }
3142
Seigo Nonakaa60160b2015-08-19 12:38:35 -07003143 @VisibleForTesting
3144 public class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener {
Gilles Debunned88876a2012-03-16 17:34:04 -07003145 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003146
3147 // Key of intent extras for inserting new word into user dictionary.
3148 private static final String USER_DICTIONARY_EXTRA_WORD = "word";
3149 private static final String USER_DICTIONARY_EXTRA_LOCALE = "locale";
3150
Gilles Debunned88876a2012-03-16 17:34:04 -07003151 private SuggestionInfo[] mSuggestionInfos;
3152 private int mNumberOfSuggestions;
3153 private boolean mCursorWasVisibleBeforeSuggestions;
3154 private boolean mIsShowingUp = false;
3155 private SuggestionAdapter mSuggestionsAdapter;
Seigo Nonakabffbd302015-08-18 18:27:56 -07003156 private final TextAppearanceSpan mHighlightSpan = new TextAppearanceSpan(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003157 mTextView.getContext(), mTextView.mTextEditSuggestionHighlightStyle);
3158 private TextView mAddToDictionaryButton;
3159 private TextView mDeleteButton;
3160 private SuggestionSpan mMisspelledSpan;
Seigo Nonaka60490d12016-01-28 17:25:18 +09003161 private int mContainerMarginWidth;
3162 private int mContainerMarginTop;
Gilles Debunned88876a2012-03-16 17:34:04 -07003163
3164 private class CustomPopupWindow extends PopupWindow {
Gilles Debunned88876a2012-03-16 17:34:04 -07003165 @Override
3166 public void dismiss() {
Keisuke Kuroyanagid0560812015-12-17 17:50:42 +09003167 if (!isShowing()) {
3168 return;
3169 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003170 super.dismiss();
Gilles Debunned88876a2012-03-16 17:34:04 -07003171 getPositionListener().removeSubscriber(SuggestionsPopupWindow.this);
3172
3173 // Safe cast since show() checks that mTextView.getText() is an Editable
3174 ((Spannable) mTextView.getText()).removeSpan(mSuggestionRangeSpan);
3175
3176 mTextView.setCursorVisible(mCursorWasVisibleBeforeSuggestions);
3177 if (hasInsertionController()) {
3178 getInsertionController().show();
3179 }
3180 }
3181 }
3182
3183 public SuggestionsPopupWindow() {
3184 mCursorWasVisibleBeforeSuggestions = mCursorVisible;
Gilles Debunned88876a2012-03-16 17:34:04 -07003185 }
3186
3187 @Override
3188 protected void createPopupWindow() {
Seigo Nonaka3ed1b392016-01-19 13:54:59 +09003189 mPopupWindow = new CustomPopupWindow();
Gilles Debunned88876a2012-03-16 17:34:04 -07003190 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
Seigo Nonaka3ed1b392016-01-19 13:54:59 +09003191 mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Gilles Debunned88876a2012-03-16 17:34:04 -07003192 mPopupWindow.setFocusable(true);
3193 mPopupWindow.setClippingEnabled(false);
3194 }
3195
3196 @Override
3197 protected void initContentView() {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003198 final LayoutInflater inflater = (LayoutInflater) mTextView.getContext().
3199 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Seigo Nonaka60490d12016-01-28 17:25:18 +09003200 final ViewGroup relativeLayout = (ViewGroup) inflater.inflate(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003201 mTextView.mTextEditSuggestionContainerLayout, null);
Gilles Debunned88876a2012-03-16 17:34:04 -07003202
Seigo Nonaka60490d12016-01-28 17:25:18 +09003203 final LinearLayout suggestionWindowContainer =
3204 (LinearLayout) relativeLayout.findViewById(
3205 com.android.internal.R.id.suggestionWindowContainer);
3206 ViewGroup.MarginLayoutParams lp =
3207 (ViewGroup.MarginLayoutParams) suggestionWindowContainer.getLayoutParams();
3208 mContainerMarginWidth = lp.leftMargin + lp.rightMargin;
3209 mContainerMarginTop = lp.topMargin;
3210 mClippingLimitLeft = lp.leftMargin;
3211 mClippingLimitRight = lp.rightMargin;
3212
3213 final ListView suggestionListView = (ListView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003214 com.android.internal.R.id.suggestionContainer);
3215
3216 mSuggestionsAdapter = new SuggestionAdapter();
3217 suggestionListView.setAdapter(mSuggestionsAdapter);
3218 suggestionListView.setOnItemClickListener(this);
3219
3220 // Inflate the suggestion items once and for all.
3221 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS];
Gilles Debunned88876a2012-03-16 17:34:04 -07003222 for (int i = 0; i < mSuggestionInfos.length; i++) {
3223 mSuggestionInfos[i] = new SuggestionInfo();
3224 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003225
Seigo Nonaka60490d12016-01-28 17:25:18 +09003226 mContentView = relativeLayout;
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003227
Seigo Nonaka60490d12016-01-28 17:25:18 +09003228 mAddToDictionaryButton = (TextView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003229 com.android.internal.R.id.addToDictionaryButton);
3230 mAddToDictionaryButton.setOnClickListener(new View.OnClickListener() {
3231 public void onClick(View v) {
3232 final Editable editable = (Editable) mTextView.getText();
3233 final int spanStart = editable.getSpanStart(mMisspelledSpan);
3234 final int spanEnd = editable.getSpanEnd(mMisspelledSpan);
3235 final String originalText = TextUtils.substring(editable, spanStart, spanEnd);
3236
3237 final Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT);
3238 intent.putExtra(USER_DICTIONARY_EXTRA_WORD, originalText);
3239 intent.putExtra(USER_DICTIONARY_EXTRA_LOCALE,
3240 mTextView.getTextServicesLocale().toString());
3241 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3242 mTextView.getContext().startActivity(intent);
3243 // There is no way to know if the word was indeed added. Re-check.
3244 // TODO The ExtractEditText should remove the span in the original text instead
3245 editable.removeSpan(mMisspelledSpan);
3246 Selection.setSelection(editable, spanEnd);
3247 updateSpellCheckSpans(spanStart, spanEnd, false);
3248 hideWithCleanUp();
3249 }
3250 });
3251
Seigo Nonaka60490d12016-01-28 17:25:18 +09003252 mDeleteButton = (TextView) relativeLayout.findViewById(
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003253 com.android.internal.R.id.deleteButton);
3254 mDeleteButton.setOnClickListener(new View.OnClickListener() {
3255 public void onClick(View v) {
3256 final Editable editable = (Editable) mTextView.getText();
3257
3258 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
3259 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
3260 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
3261 // Do not leave two adjacent spaces after deletion, or one at beginning of
3262 // text
3263 if (spanUnionEnd < editable.length() &&
3264 Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
3265 (spanUnionStart == 0 ||
3266 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
3267 spanUnionEnd = spanUnionEnd + 1;
3268 }
3269 mTextView.deleteText_internal(spanUnionStart, spanUnionEnd);
3270 }
3271 hideWithCleanUp();
3272 }
3273 });
3274
Gilles Debunned88876a2012-03-16 17:34:04 -07003275 }
3276
3277 public boolean isShowingUp() {
3278 return mIsShowingUp;
3279 }
3280
3281 public void onParentLostFocus() {
3282 mIsShowingUp = false;
3283 }
3284
Gilles Debunned88876a2012-03-16 17:34:04 -07003285 private class SuggestionAdapter extends BaseAdapter {
3286 private LayoutInflater mInflater = (LayoutInflater) mTextView.getContext().
3287 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3288
3289 @Override
3290 public int getCount() {
3291 return mNumberOfSuggestions;
3292 }
3293
3294 @Override
3295 public Object getItem(int position) {
3296 return mSuggestionInfos[position];
3297 }
3298
3299 @Override
3300 public long getItemId(int position) {
3301 return position;
3302 }
3303
3304 @Override
3305 public View getView(int position, View convertView, ViewGroup parent) {
3306 TextView textView = (TextView) convertView;
3307
3308 if (textView == null) {
3309 textView = (TextView) mInflater.inflate(mTextView.mTextEditSuggestionItemLayout,
3310 parent, false);
3311 }
3312
3313 final SuggestionInfo suggestionInfo = mSuggestionInfos[position];
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003314 textView.setText(suggestionInfo.mText);
Gilles Debunned88876a2012-03-16 17:34:04 -07003315 return textView;
3316 }
3317 }
3318
Seigo Nonakaa60160b2015-08-19 12:38:35 -07003319 @VisibleForTesting
3320 public ViewGroup getContentViewForTesting() {
3321 return mContentView;
3322 }
3323
Gilles Debunned88876a2012-03-16 17:34:04 -07003324 @Override
3325 public void show() {
3326 if (!(mTextView.getText() instanceof Editable)) return;
3327
3328 if (updateSuggestions()) {
3329 mCursorWasVisibleBeforeSuggestions = mCursorVisible;
3330 mTextView.setCursorVisible(false);
3331 mIsShowingUp = true;
3332 super.show();
3333 }
3334 }
3335
3336 @Override
3337 protected void measureContent() {
3338 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3339 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec(
3340 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST);
3341 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec(
3342 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST);
3343
3344 int width = 0;
3345 View view = null;
3346 for (int i = 0; i < mNumberOfSuggestions; i++) {
3347 view = mSuggestionsAdapter.getView(i, view, mContentView);
3348 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
3349 view.measure(horizontalMeasure, verticalMeasure);
3350 width = Math.max(width, view.getMeasuredWidth());
3351 }
3352
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003353 if (mAddToDictionaryButton.getVisibility() != View.GONE) {
3354 mAddToDictionaryButton.measure(horizontalMeasure, verticalMeasure);
3355 width = Math.max(width, mAddToDictionaryButton.getMeasuredWidth());
3356 }
3357
3358 mDeleteButton.measure(horizontalMeasure, verticalMeasure);
3359 width = Math.max(width, mDeleteButton.getMeasuredWidth());
3360
Seigo Nonaka60490d12016-01-28 17:25:18 +09003361 width += mContainerMarginWidth;
3362
Gilles Debunned88876a2012-03-16 17:34:04 -07003363 // Enforce the width based on actual text widths
3364 mContentView.measure(
3365 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
3366 verticalMeasure);
3367
3368 Drawable popupBackground = mPopupWindow.getBackground();
3369 if (popupBackground != null) {
3370 if (mTempRect == null) mTempRect = new Rect();
3371 popupBackground.getPadding(mTempRect);
3372 width += mTempRect.left + mTempRect.right;
3373 }
3374 mPopupWindow.setWidth(width);
3375 }
3376
3377 @Override
3378 protected int getTextOffset() {
3379 return mTextView.getSelectionStart();
3380 }
3381
3382 @Override
3383 protected int getVerticalLocalPosition(int line) {
Seigo Nonaka60490d12016-01-28 17:25:18 +09003384 return mTextView.getLayout().getLineBottom(line) - mContainerMarginTop;
Gilles Debunned88876a2012-03-16 17:34:04 -07003385 }
3386
3387 @Override
3388 protected int clipVertically(int positionY) {
3389 final int height = mContentView.getMeasuredHeight();
3390 final DisplayMetrics displayMetrics = mTextView.getResources().getDisplayMetrics();
3391 return Math.min(positionY, displayMetrics.heightPixels - height);
3392 }
3393
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003394 private void hideWithCleanUp() {
3395 for (final SuggestionInfo info : mSuggestionInfos) {
3396 info.clear();
3397 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003398 mMisspelledSpan = null;
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003399 hide();
Gilles Debunned88876a2012-03-16 17:34:04 -07003400 }
3401
3402 private boolean updateSuggestions() {
3403 Spannable spannable = (Spannable) mTextView.getText();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003404 mNumberOfSuggestions =
3405 mSuggestionHelper.getSuggestionInfo(mSuggestionInfos);
3406 if (mNumberOfSuggestions == 0) {
3407 return false;
3408 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003409
Gilles Debunned88876a2012-03-16 17:34:04 -07003410 int spanUnionStart = mTextView.getText().length();
3411 int spanUnionEnd = 0;
3412
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003413 mMisspelledSpan = null;
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003414 for (int i = 0; i < mNumberOfSuggestions; i++) {
3415 final SuggestionInfo suggestionInfo = mSuggestionInfos[i];
3416 final SuggestionSpan suggestionSpan = suggestionInfo.mSuggestionSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07003417 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003418 mMisspelledSpan = suggestionSpan;
Gilles Debunned88876a2012-03-16 17:34:04 -07003419 }
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003420 final int spanStart = spannable.getSpanStart(suggestionSpan);
3421 final int spanEnd = spannable.getSpanEnd(suggestionSpan);
3422 spanUnionStart = Math.min(spanUnionStart, spanStart);
3423 spanUnionEnd = Math.max(spanUnionEnd, spanEnd);
Gilles Debunned88876a2012-03-16 17:34:04 -07003424 }
3425
3426 for (int i = 0; i < mNumberOfSuggestions; i++) {
3427 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd);
3428 }
3429
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003430 // Make "Add to dictionary" item visible if there is a span with the misspelled flag
3431 int addToDictionaryButtonVisibility = View.GONE;
3432 if (mMisspelledSpan != null) {
3433 final int misspelledStart = spannable.getSpanStart(mMisspelledSpan);
3434 final int misspelledEnd = spannable.getSpanEnd(mMisspelledSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07003435 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) {
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003436 addToDictionaryButtonVisibility = View.VISIBLE;
Gilles Debunned88876a2012-03-16 17:34:04 -07003437 }
3438 }
Seigo Nonakaa71a2442015-06-19 15:00:43 +09003439 mAddToDictionaryButton.setVisibility(addToDictionaryButtonVisibility);
Gilles Debunned88876a2012-03-16 17:34:04 -07003440
3441 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003442 final int underlineColor = mSuggestionInfos[0].mSuggestionSpan.getUnderlineColor();
Gilles Debunned88876a2012-03-16 17:34:04 -07003443 if (underlineColor == 0) {
3444 // Fallback on the default highlight color when the first span does not provide one
3445 mSuggestionRangeSpan.setBackgroundColor(mTextView.mHighlightColor);
3446 } else {
3447 final float BACKGROUND_TRANSPARENCY = 0.4f;
3448 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY);
3449 mSuggestionRangeSpan.setBackgroundColor(
3450 (underlineColor & 0x00FFFFFF) + (newAlpha << 24));
3451 }
3452 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd,
3453 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
3454
3455 mSuggestionsAdapter.notifyDataSetChanged();
3456 return true;
3457 }
3458
3459 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart,
3460 int unionEnd) {
3461 final Spannable text = (Spannable) mTextView.getText();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003462 final int spanStart = text.getSpanStart(suggestionInfo.mSuggestionSpan);
3463 final int spanEnd = text.getSpanEnd(suggestionInfo.mSuggestionSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07003464
3465 // Adjust the start/end of the suggestion span
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003466 suggestionInfo.mSuggestionStart = spanStart - unionStart;
3467 suggestionInfo.mSuggestionEnd = suggestionInfo.mSuggestionStart
3468 + suggestionInfo.mText.length();
Gilles Debunned88876a2012-03-16 17:34:04 -07003469
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003470 suggestionInfo.mText.setSpan(mHighlightSpan, 0, suggestionInfo.mText.length(),
Seigo Nonakabffbd302015-08-18 18:27:56 -07003471 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Gilles Debunned88876a2012-03-16 17:34:04 -07003472
3473 // Add the text before and after the span.
3474 final String textAsString = text.toString();
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003475 suggestionInfo.mText.insert(0, textAsString.substring(unionStart, spanStart));
3476 suggestionInfo.mText.append(textAsString.substring(spanEnd, unionEnd));
Gilles Debunned88876a2012-03-16 17:34:04 -07003477 }
3478
3479 @Override
3480 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
3481 Editable editable = (Editable) mTextView.getText();
3482 SuggestionInfo suggestionInfo = mSuggestionInfos[position];
3483
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003484 final int spanStart = editable.getSpanStart(suggestionInfo.mSuggestionSpan);
3485 final int spanEnd = editable.getSpanEnd(suggestionInfo.mSuggestionSpan);
Gilles Debunned88876a2012-03-16 17:34:04 -07003486 if (spanStart < 0 || spanEnd <= spanStart) {
3487 // Span has been removed
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003488 hideWithCleanUp();
Gilles Debunned88876a2012-03-16 17:34:04 -07003489 return;
3490 }
Keisuke Kuroyanagi1cd8aac2015-12-21 18:01:40 +09003491 replaceWithSuggestion(suggestionInfo, spanStart, spanEnd);
Seigo Nonaka7afa67c2015-10-07 17:06:04 +09003492 hideWithCleanUp();
Gilles Debunned88876a2012-03-16 17:34:04 -07003493 }
3494 }
3495
3496 /**
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003497 * An ActionMode Callback class that is used to provide actions while in text insertion or
3498 * selection mode.
Gilles Debunned88876a2012-03-16 17:34:04 -07003499 *
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003500 * The default callback provides a subset of Select All, Cut, Copy, Paste, Share and Replace
3501 * actions, depending on which of these this TextView supports and the current selection.
Gilles Debunned88876a2012-03-16 17:34:04 -07003502 */
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003503 private class TextActionModeCallback extends ActionMode.Callback2 {
Clara Bayarriea4f1502015-03-18 00:25:01 +00003504 private final Path mSelectionPath = new Path();
3505 private final RectF mSelectionBounds = new RectF();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003506 private final boolean mHasSelection;
Clara Bayarriea4f1502015-03-18 00:25:01 +00003507
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003508 private int mHandleHeight;
Clara Bayarriea4f1502015-03-18 00:25:01 +00003509
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003510 public TextActionModeCallback(boolean hasSelection) {
3511 mHasSelection = hasSelection;
3512 if (mHasSelection) {
3513 SelectionModifierCursorController selectionController = getSelectionController();
3514 if (selectionController.mStartHandle == null) {
3515 // As these are for initializing selectionController, hide() must be called.
3516 selectionController.initDrawables();
3517 selectionController.initHandles();
3518 selectionController.hide();
3519 }
3520 mHandleHeight = Math.max(
3521 mSelectHandleLeft.getMinimumHeight(),
3522 mSelectHandleRight.getMinimumHeight());
3523 } else {
3524 InsertionPointCursorController insertionController = getInsertionController();
3525 if (insertionController != null) {
3526 insertionController.getHandle();
3527 mHandleHeight = mSelectHandleCenter.getMinimumHeight();
3528 }
Clara Bayarri7fc946e2015-03-31 14:48:33 +01003529 }
Clara Bayarriea4f1502015-03-18 00:25:01 +00003530 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003531
3532 @Override
3533 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003534 mode.setTitle(null);
Clara Bayarri13152d12015-04-09 12:02:04 +01003535 mode.setSubtitle(null);
3536 mode.setTitleOptionalHint(true);
3537 populateMenuWithItems(menu);
3538
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003539 Callback customCallback = getCustomCallback();
3540 if (customCallback != null) {
3541 if (!customCallback.onCreateActionMode(mode, menu)) {
Clara Bayarri01243ac2015-06-03 00:46:29 +01003542 // The custom mode can choose to cancel the action mode, dismiss selection.
3543 Selection.setSelection((Spannable) mTextView.getText(),
3544 mTextView.getSelectionEnd());
Clara Bayarri13152d12015-04-09 12:02:04 +01003545 return false;
3546 }
3547 }
3548
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07003549 if (mTextView.canProcessText()) {
3550 mProcessTextIntentActionsHandler.onInitializeMenu(menu);
3551 }
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00003552
Clara Bayarri13152d12015-04-09 12:02:04 +01003553 if (menu.hasVisibleItems() || mode.getCustomView() != null) {
3554 mTextView.setHasTransientState(true);
3555 return true;
3556 } else {
3557 return false;
3558 }
3559 }
3560
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003561 private Callback getCustomCallback() {
3562 return mHasSelection
3563 ? mCustomSelectionActionModeCallback
3564 : mCustomInsertionActionModeCallback;
3565 }
3566
Clara Bayarri13152d12015-04-09 12:02:04 +01003567 private void populateMenuWithItems(Menu menu) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003568 if (mTextView.canCut()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003569 menu.add(Menu.NONE, TextView.ID_CUT, MENU_ITEM_ORDER_CUT,
3570 com.android.internal.R.string.cut).
Gilles Debunned88876a2012-03-16 17:34:04 -07003571 setAlphabeticShortcut('x').
Clara Bayarriaee243b2015-05-18 17:05:46 +01003572 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003573 }
3574
3575 if (mTextView.canCopy()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003576 menu.add(Menu.NONE, TextView.ID_COPY, MENU_ITEM_ORDER_COPY,
3577 com.android.internal.R.string.copy).
Gilles Debunned88876a2012-03-16 17:34:04 -07003578 setAlphabeticShortcut('c').
Clara Bayarriaee243b2015-05-18 17:05:46 +01003579 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003580 }
3581
3582 if (mTextView.canPaste()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003583 menu.add(Menu.NONE, TextView.ID_PASTE, MENU_ITEM_ORDER_PASTE,
3584 com.android.internal.R.string.paste).
3585 setAlphabeticShortcut('v').
3586 setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
Gilles Debunned88876a2012-03-16 17:34:04 -07003587 }
3588
Andrei Stingaceanu7f0c5bd2015-04-14 17:12:08 +01003589 if (mTextView.canShare()) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003590 menu.add(Menu.NONE, TextView.ID_SHARE, MENU_ITEM_ORDER_SHARE,
3591 com.android.internal.R.string.share).
3592 setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
Andrei Stingaceanu7f0c5bd2015-04-14 17:12:08 +01003593 }
3594
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003595 updateSelectAllItem(menu);
Clara Bayarri13152d12015-04-09 12:02:04 +01003596 updateReplaceItem(menu);
Gilles Debunned88876a2012-03-16 17:34:04 -07003597 }
3598
3599 @Override
3600 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003601 updateSelectAllItem(menu);
Clara Bayarri13152d12015-04-09 12:02:04 +01003602 updateReplaceItem(menu);
3603
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003604 Callback customCallback = getCustomCallback();
3605 if (customCallback != null) {
3606 return customCallback.onPrepareActionMode(mode, menu);
Gilles Debunned88876a2012-03-16 17:34:04 -07003607 }
3608 return true;
3609 }
3610
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003611 private void updateSelectAllItem(Menu menu) {
3612 boolean canSelectAll = mTextView.canSelectAllText();
3613 boolean selectAllItemExists = menu.findItem(TextView.ID_SELECT_ALL) != null;
3614 if (canSelectAll && !selectAllItemExists) {
3615 menu.add(Menu.NONE, TextView.ID_SELECT_ALL, MENU_ITEM_ORDER_SELECT_ALL,
3616 com.android.internal.R.string.selectAll)
3617 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
3618 } else if (!canSelectAll && selectAllItemExists) {
3619 menu.removeItem(TextView.ID_SELECT_ALL);
3620 }
3621 }
3622
Clara Bayarri13152d12015-04-09 12:02:04 +01003623 private void updateReplaceItem(Menu menu) {
Keisuke Kuroyanagifd3eff22015-07-06 18:20:41 +09003624 boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions()
3625 && !(mTextView.isInExtractedMode() && mTextView.hasSelection());
Clara Bayarri13152d12015-04-09 12:02:04 +01003626 boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
3627 if (canReplace && !replaceItemExists) {
Clara Bayarri3b69fd82015-06-03 21:52:02 +01003628 menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
3629 com.android.internal.R.string.replace)
3630 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
Clara Bayarri13152d12015-04-09 12:02:04 +01003631 } else if (!canReplace && replaceItemExists) {
3632 menu.removeItem(TextView.ID_REPLACE);
3633 }
3634 }
3635
Gilles Debunned88876a2012-03-16 17:34:04 -07003636 @Override
3637 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07003638 if (mProcessTextIntentActionsHandler.performMenuItemAction(item)) {
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00003639 return true;
3640 }
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003641 Callback customCallback = getCustomCallback();
3642 if (customCallback != null && customCallback.onActionItemClicked(mode, item)) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003643 return true;
3644 }
3645 return mTextView.onTextContextMenuItem(item.getItemId());
3646 }
3647
3648 @Override
3649 public void onDestroyActionMode(ActionMode mode) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003650 Callback customCallback = getCustomCallback();
3651 if (customCallback != null) {
3652 customCallback.onDestroyActionMode(mode);
Gilles Debunned88876a2012-03-16 17:34:04 -07003653 }
Adam Powell057a5852012-05-11 10:28:38 -07003654
3655 /*
3656 * If we're ending this mode because we're detaching from a window,
3657 * we still have selection state to preserve. Don't clear it, we'll
3658 * bring back the selection mode when (if) we get reattached.
3659 */
3660 if (!mPreserveDetachedSelection) {
3661 Selection.setSelection((Spannable) mTextView.getText(),
3662 mTextView.getSelectionEnd());
3663 mTextView.setHasTransientState(false);
3664 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003665
3666 if (mSelectionModifierCursorController != null) {
3667 mSelectionModifierCursorController.hide();
3668 }
3669
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003670 mTextActionMode = null;
Gilles Debunned88876a2012-03-16 17:34:04 -07003671 }
Clara Bayarriea4f1502015-03-18 00:25:01 +00003672
3673 @Override
3674 public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
3675 if (!view.equals(mTextView) || mTextView.getLayout() == null) {
3676 super.onGetContentRect(mode, view, outRect);
3677 return;
3678 }
3679 if (mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
3680 // We have a selection.
3681 mSelectionPath.reset();
3682 mTextView.getLayout().getSelectionPath(
3683 mTextView.getSelectionStart(), mTextView.getSelectionEnd(), mSelectionPath);
3684 mSelectionPath.computeBounds(mSelectionBounds, true);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003685 mSelectionBounds.bottom += mHandleHeight;
Clara Bayarrib7419dd2015-04-09 15:24:58 +01003686 } else if (mCursorCount == 2) {
3687 // We have a split cursor. In this case, we take the rectangle that includes both
3688 // parts of the cursor to ensure we don't obscure either of them.
3689 Rect firstCursorBounds = mCursorDrawable[0].getBounds();
3690 Rect secondCursorBounds = mCursorDrawable[1].getBounds();
3691 mSelectionBounds.set(
3692 Math.min(firstCursorBounds.left, secondCursorBounds.left),
3693 Math.min(firstCursorBounds.top, secondCursorBounds.top),
3694 Math.max(firstCursorBounds.right, secondCursorBounds.right),
3695 Math.max(firstCursorBounds.bottom, secondCursorBounds.bottom)
Clara Bayarri7938cdb2015-06-02 20:03:45 +01003696 + mHandleHeight);
Clara Bayarriea4f1502015-03-18 00:25:01 +00003697 } else {
3698 // We have a single cursor.
Mady Mellorff66ca52015-07-08 12:31:45 -07003699 Layout layout = getActiveLayout();
3700 int line = layout.getLineForOffset(mTextView.getSelectionStart());
Clara Bayarriea4f1502015-03-18 00:25:01 +00003701 float primaryHorizontal =
Mady Mellorff66ca52015-07-08 12:31:45 -07003702 layout.getPrimaryHorizontal(mTextView.getSelectionStart());
Clara Bayarriea4f1502015-03-18 00:25:01 +00003703 mSelectionBounds.set(
3704 primaryHorizontal,
Mady Mellorff66ca52015-07-08 12:31:45 -07003705 layout.getLineTop(line),
Clara Bayarrif95ed102015-08-12 19:46:47 +01003706 primaryHorizontal,
Mady Mellorff66ca52015-07-08 12:31:45 -07003707 layout.getLineTop(line + 1) + mHandleHeight);
Clara Bayarriea4f1502015-03-18 00:25:01 +00003708 }
3709 // Take TextView's padding and scroll into account.
3710 int textHorizontalOffset = mTextView.viewportToContentHorizontalOffset();
3711 int textVerticalOffset = mTextView.viewportToContentVerticalOffset();
3712 outRect.set(
3713 (int) Math.floor(mSelectionBounds.left + textHorizontalOffset),
3714 (int) Math.floor(mSelectionBounds.top + textVerticalOffset),
3715 (int) Math.ceil(mSelectionBounds.right + textHorizontalOffset),
3716 (int) Math.ceil(mSelectionBounds.bottom + textVerticalOffset));
3717 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003718 }
3719
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003720 /**
3721 * A listener to call {@link InputMethodManager#updateCursorAnchorInfo(View, CursorAnchorInfo)}
3722 * while the input method is requesting the cursor/anchor position. Does nothing as long as
3723 * {@link InputMethodManager#isWatchingCursor(View)} returns false.
3724 */
3725 private final class CursorAnchorInfoNotifier implements TextViewPositionListener {
Yohei Yukawac46b5f02014-06-10 12:26:34 +09003726 final CursorAnchorInfo.Builder mSelectionInfoBuilder = new CursorAnchorInfo.Builder();
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003727 final int[] mTmpIntOffset = new int[2];
3728 final Matrix mViewToScreenMatrix = new Matrix();
3729
3730 @Override
3731 public void updatePosition(int parentPositionX, int parentPositionY,
3732 boolean parentPositionChanged, boolean parentScrolled) {
3733 final InputMethodState ims = mInputMethodState;
3734 if (ims == null || ims.mBatchEditNesting > 0) {
3735 return;
3736 }
3737 final InputMethodManager imm = InputMethodManager.peekInstance();
3738 if (null == imm) {
3739 return;
3740 }
Yohei Yukawa0023d0e2014-07-11 04:13:03 +09003741 if (!imm.isActive(mTextView)) {
3742 return;
3743 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003744 // Skip if the IME has not requested the cursor/anchor position.
Yohei Yukawa0023d0e2014-07-11 04:13:03 +09003745 if (!imm.isCursorAnchorInfoEnabled()) {
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003746 return;
3747 }
3748 Layout layout = mTextView.getLayout();
3749 if (layout == null) {
3750 return;
3751 }
3752
Yohei Yukawac46b5f02014-06-10 12:26:34 +09003753 final CursorAnchorInfo.Builder builder = mSelectionInfoBuilder;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003754 builder.reset();
3755
3756 final int selectionStart = mTextView.getSelectionStart();
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003757 builder.setSelectionRange(selectionStart, mTextView.getSelectionEnd());
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003758
3759 // Construct transformation matrix from view local coordinates to screen coordinates.
3760 mViewToScreenMatrix.set(mTextView.getMatrix());
3761 mTextView.getLocationOnScreen(mTmpIntOffset);
3762 mViewToScreenMatrix.postTranslate(mTmpIntOffset[0], mTmpIntOffset[1]);
3763 builder.setMatrix(mViewToScreenMatrix);
3764
3765 final float viewportToContentHorizontalOffset =
3766 mTextView.viewportToContentHorizontalOffset();
3767 final float viewportToContentVerticalOffset =
3768 mTextView.viewportToContentVerticalOffset();
3769
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003770 final CharSequence text = mTextView.getText();
3771 if (text instanceof Spannable) {
3772 final Spannable sp = (Spannable) text;
3773 int composingTextStart = EditableInputConnection.getComposingSpanStart(sp);
3774 int composingTextEnd = EditableInputConnection.getComposingSpanEnd(sp);
3775 if (composingTextEnd < composingTextStart) {
3776 final int temp = composingTextEnd;
3777 composingTextEnd = composingTextStart;
3778 composingTextStart = temp;
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003779 }
Yohei Yukawa81f4cb32014-05-13 22:20:35 +09003780 final boolean hasComposingText =
3781 (0 <= composingTextStart) && (composingTextStart < composingTextEnd);
3782 if (hasComposingText) {
3783 final CharSequence composingText = text.subSequence(composingTextStart,
3784 composingTextEnd);
3785 builder.setComposingText(composingTextStart, composingText);
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003786
3787 final int minLine = layout.getLineForOffset(composingTextStart);
3788 final int maxLine = layout.getLineForOffset(composingTextEnd - 1);
3789 for (int line = minLine; line <= maxLine; ++line) {
3790 final int lineStart = layout.getLineStart(line);
3791 final int lineEnd = layout.getLineEnd(line);
3792 final int offsetStart = Math.max(lineStart, composingTextStart);
3793 final int offsetEnd = Math.min(lineEnd, composingTextEnd);
3794 final boolean ltrLine =
3795 layout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT;
3796 final float[] widths = new float[offsetEnd - offsetStart];
3797 layout.getPaint().getTextWidths(text, offsetStart, offsetEnd, widths);
3798 final float top = layout.getLineTop(line);
3799 final float bottom = layout.getLineBottom(line);
3800 for (int offset = offsetStart; offset < offsetEnd; ++offset) {
3801 final float charWidth = widths[offset - offsetStart];
3802 final boolean isRtl = layout.isRtlCharAt(offset);
3803 final float primary = layout.getPrimaryHorizontal(offset);
3804 final float secondary = layout.getSecondaryHorizontal(offset);
3805 // TODO: This doesn't work perfectly for text with custom styles and
3806 // TAB chars.
3807 final float left;
3808 final float right;
3809 if (ltrLine) {
3810 if (isRtl) {
3811 left = secondary - charWidth;
3812 right = secondary;
3813 } else {
3814 left = primary;
3815 right = primary + charWidth;
3816 }
3817 } else {
3818 if (!isRtl) {
3819 left = secondary;
3820 right = secondary + charWidth;
3821 } else {
3822 left = primary - charWidth;
3823 right = primary;
3824 }
3825 }
3826 // TODO: Check top-right and bottom-left as well.
3827 final float localLeft = left + viewportToContentHorizontalOffset;
3828 final float localRight = right + viewportToContentHorizontalOffset;
3829 final float localTop = top + viewportToContentVerticalOffset;
3830 final float localBottom = bottom + viewportToContentVerticalOffset;
3831 final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop);
3832 final boolean isBottomRightVisible =
3833 isPositionVisible(localRight, localBottom);
3834 int characterBoundsFlags = 0;
3835 if (isTopLeftVisible || isBottomRightVisible) {
3836 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3837 }
Andreas Gampe4976e2d2015-03-17 16:08:43 -07003838 if (!isTopLeftVisible || !isBottomRightVisible) {
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003839 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3840 }
3841 if (isRtl) {
3842 characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3843 }
3844 // Here offset is the index in Java chars.
3845 builder.addCharacterBounds(offset, localLeft, localTop, localRight,
3846 localBottom, characterBoundsFlags);
3847 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003848 }
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003849 }
3850 }
3851
3852 // Treat selectionStart as the insertion point.
3853 if (0 <= selectionStart) {
3854 final int offset = selectionStart;
3855 final int line = layout.getLineForOffset(offset);
3856 final float insertionMarkerX = layout.getPrimaryHorizontal(offset)
3857 + viewportToContentHorizontalOffset;
3858 final float insertionMarkerTop = layout.getLineTop(line)
3859 + viewportToContentVerticalOffset;
3860 final float insertionMarkerBaseline = layout.getLineBaseline(line)
3861 + viewportToContentVerticalOffset;
3862 final float insertionMarkerBottom = layout.getLineBottom(line)
3863 + viewportToContentVerticalOffset;
Yohei Yukawacc24e2b2014-08-29 20:21:10 -07003864 final boolean isTopVisible =
3865 isPositionVisible(insertionMarkerX, insertionMarkerTop);
3866 final boolean isBottomVisible =
3867 isPositionVisible(insertionMarkerX, insertionMarkerBottom);
3868 int insertionMarkerFlags = 0;
3869 if (isTopVisible || isBottomVisible) {
3870 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
3871 }
3872 if (!isTopVisible || !isBottomVisible) {
3873 insertionMarkerFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
3874 }
Yohei Yukawa5f183f02014-09-02 14:18:40 -07003875 if (layout.isRtlCharAt(offset)) {
3876 insertionMarkerFlags |= CursorAnchorInfo.FLAG_IS_RTL;
3877 }
Yohei Yukawa0b01e7f2014-07-08 15:29:51 +09003878 builder.setInsertionMarkerLocation(insertionMarkerX, insertionMarkerTop,
Yohei Yukawacc24e2b2014-08-29 20:21:10 -07003879 insertionMarkerBaseline, insertionMarkerBottom, insertionMarkerFlags);
Yohei Yukawa83b68ba2014-05-12 15:46:25 +09003880 }
3881
3882 imm.updateCursorAnchorInfo(mTextView, builder.build());
3883 }
3884 }
3885
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003886 @VisibleForTesting
3887 public abstract class HandleView extends View implements TextViewPositionListener {
Gilles Debunned88876a2012-03-16 17:34:04 -07003888 protected Drawable mDrawable;
3889 protected Drawable mDrawableLtr;
3890 protected Drawable mDrawableRtl;
3891 private final PopupWindow mContainer;
3892 // Position with respect to the parent TextView
3893 private int mPositionX, mPositionY;
3894 private boolean mIsDragging;
3895 // Offset from touch position to mPosition
3896 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY;
3897 protected int mHotspotX;
Adam Powell3fceabd2014-08-19 18:28:04 -07003898 protected int mHorizontalGravity;
Gilles Debunned88876a2012-03-16 17:34:04 -07003899 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
3900 private float mTouchOffsetY;
3901 // Where the touch position should be on the handle to ensure a maximum cursor visibility
3902 private float mIdealVerticalOffset;
3903 // Parent's (TextView) previous position in window
3904 private int mLastParentX, mLastParentY;
Gilles Debunned88876a2012-03-16 17:34:04 -07003905 // Previous text character offset
Mady Mellorc2225b92015-04-01 15:59:20 -07003906 protected int mPreviousOffset = -1;
Gilles Debunned88876a2012-03-16 17:34:04 -07003907 // Previous text character offset
3908 private boolean mPositionHasChanged = true;
Adam Powell3fceabd2014-08-19 18:28:04 -07003909 // Minimum touch target size for handles
3910 private int mMinSize;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08003911 // Indicates the line of text that the handle is on.
Mady Mellora6a0f782015-07-10 16:43:32 -07003912 protected int mPrevLine = UNSET_LINE;
3913 // Indicates the line of text that the user was touching. This can differ from mPrevLine
3914 // when selecting text when the handles jump to the end / start of words which may be on
3915 // a different line.
3916 protected int mPreviousLineTouched = UNSET_LINE;
Gilles Debunned88876a2012-03-16 17:34:04 -07003917
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003918 private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
Gilles Debunned88876a2012-03-16 17:34:04 -07003919 super(mTextView.getContext());
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09003920 setId(id);
Gilles Debunned88876a2012-03-16 17:34:04 -07003921 mContainer = new PopupWindow(mTextView.getContext(), null,
3922 com.android.internal.R.attr.textSelectHandleWindowStyle);
3923 mContainer.setSplitTouchEnabled(true);
3924 mContainer.setClippingEnabled(false);
3925 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
Keisuke Kuroyanagi7340be72015-02-27 17:57:49 +09003926 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
3927 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
Gilles Debunned88876a2012-03-16 17:34:04 -07003928 mContainer.setContentView(this);
3929
3930 mDrawableLtr = drawableLtr;
3931 mDrawableRtl = drawableRtl;
Adam Powell3fceabd2014-08-19 18:28:04 -07003932 mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
3933 com.android.internal.R.dimen.text_handle_min_size);
Gilles Debunned88876a2012-03-16 17:34:04 -07003934
3935 updateDrawable();
3936
Adam Powell3fceabd2014-08-19 18:28:04 -07003937 final int handleHeight = getPreferredHeight();
Gilles Debunned88876a2012-03-16 17:34:04 -07003938 mTouchOffsetY = -0.3f * handleHeight;
3939 mIdealVerticalOffset = 0.7f * handleHeight;
3940 }
3941
Mady Mellor7a936442015-05-20 10:05:52 -07003942 public float getIdealVerticalOffset() {
3943 return mIdealVerticalOffset;
3944 }
3945
Gilles Debunned88876a2012-03-16 17:34:04 -07003946 protected void updateDrawable() {
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09003947 if (mIsDragging) {
3948 // Don't update drawable during dragging.
3949 return;
3950 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003951 final int offset = getCurrentCursorOffset();
3952 final boolean isRtlCharAtOffset = mTextView.getLayout().isRtlCharAt(offset);
Keisuke Kuroyanagi33f81ac2015-05-14 20:10:57 +09003953 final Drawable oldDrawable = mDrawable;
Gilles Debunned88876a2012-03-16 17:34:04 -07003954 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr;
3955 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset);
Adam Powell3fceabd2014-08-19 18:28:04 -07003956 mHorizontalGravity = getHorizontalGravity(isRtlCharAtOffset);
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09003957 final Layout layout = mTextView.getLayout();
3958 if (layout != null && oldDrawable != mDrawable && isShowing()) {
3959 // Update popup window position.
Siyamed Sinir217c0f72016-02-01 18:30:02 -08003960 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX -
3961 getHorizontalOffset() + getCursorOffset();
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09003962 mPositionX += mTextView.viewportToContentHorizontalOffset();
3963 mPositionHasChanged = true;
3964 updatePosition(mLastParentX, mLastParentY, false, false);
Keisuke Kuroyanagi33f81ac2015-05-14 20:10:57 +09003965 postInvalidate();
3966 }
Gilles Debunned88876a2012-03-16 17:34:04 -07003967 }
3968
3969 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun);
Adam Powell3fceabd2014-08-19 18:28:04 -07003970 protected abstract int getHorizontalGravity(boolean isRtlRun);
Gilles Debunned88876a2012-03-16 17:34:04 -07003971
3972 // Touch-up filter: number of previous positions remembered
3973 private static final int HISTORY_SIZE = 5;
3974 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150;
3975 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350;
3976 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE];
3977 private final int[] mPreviousOffsets = new int[HISTORY_SIZE];
3978 private int mPreviousOffsetIndex = 0;
3979 private int mNumberPreviousOffsets = 0;
3980
3981 private void startTouchUpFilter(int offset) {
3982 mNumberPreviousOffsets = 0;
3983 addPositionToTouchUpFilter(offset);
3984 }
3985
3986 private void addPositionToTouchUpFilter(int offset) {
3987 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE;
3988 mPreviousOffsets[mPreviousOffsetIndex] = offset;
3989 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis();
3990 mNumberPreviousOffsets++;
3991 }
3992
3993 private void filterOnTouchUp() {
3994 final long now = SystemClock.uptimeMillis();
3995 int i = 0;
3996 int index = mPreviousOffsetIndex;
3997 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE);
3998 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) {
3999 i++;
4000 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE;
4001 }
4002
4003 if (i > 0 && i < iMax &&
4004 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) {
4005 positionAtCursorOffset(mPreviousOffsets[index], false);
4006 }
4007 }
4008
4009 public boolean offsetHasBeenChanged() {
4010 return mNumberPreviousOffsets > 1;
4011 }
4012
4013 @Override
4014 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Powell3fceabd2014-08-19 18:28:04 -07004015 setMeasuredDimension(getPreferredWidth(), getPreferredHeight());
4016 }
4017
4018 private int getPreferredWidth() {
4019 return Math.max(mDrawable.getIntrinsicWidth(), mMinSize);
4020 }
4021
4022 private int getPreferredHeight() {
4023 return Math.max(mDrawable.getIntrinsicHeight(), mMinSize);
Gilles Debunned88876a2012-03-16 17:34:04 -07004024 }
4025
4026 public void show() {
4027 if (isShowing()) return;
4028
4029 getPositionListener().addSubscriber(this, true /* local position may change */);
4030
4031 // Make sure the offset is always considered new, even when focusing at same position
4032 mPreviousOffset = -1;
4033 positionAtCursorOffset(getCurrentCursorOffset(), false);
Gilles Debunned88876a2012-03-16 17:34:04 -07004034 }
4035
4036 protected void dismiss() {
4037 mIsDragging = false;
4038 mContainer.dismiss();
4039 onDetached();
4040 }
4041
4042 public void hide() {
4043 dismiss();
4044
4045 getPositionListener().removeSubscriber(this);
4046 }
4047
Gilles Debunned88876a2012-03-16 17:34:04 -07004048 public boolean isShowing() {
4049 return mContainer.isShowing();
4050 }
4051
4052 private boolean isVisible() {
4053 // Always show a dragging handle.
4054 if (mIsDragging) {
4055 return true;
4056 }
4057
4058 if (mTextView.isInBatchEditMode()) {
4059 return false;
4060 }
4061
Keisuke Kuroyanagi6cda1e22015-04-22 21:41:14 +09004062 return isPositionVisible(mPositionX + mHotspotX + getHorizontalOffset(), mPositionY);
Gilles Debunned88876a2012-03-16 17:34:04 -07004063 }
4064
4065 public abstract int getCurrentCursorOffset();
4066
4067 protected abstract void updateSelection(int offset);
4068
4069 public abstract void updatePosition(float x, float y);
4070
4071 protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4072 // A HandleView relies on the layout, which may be nulled by external methods
4073 Layout layout = mTextView.getLayout();
4074 if (layout == null) {
4075 // Will update controllers' state, hiding them and stopping selection mode if needed
4076 prepareCursorControllers();
4077 return;
4078 }
Mady Mellorff66ca52015-07-08 12:31:45 -07004079 layout = getActiveLayout();
Gilles Debunned88876a2012-03-16 17:34:04 -07004080
4081 boolean offsetChanged = offset != mPreviousOffset;
4082 if (offsetChanged || parentScrolled) {
4083 if (offsetChanged) {
4084 updateSelection(offset);
4085 addPositionToTouchUpFilter(offset);
4086 }
4087 final int line = layout.getLineForOffset(offset);
Mady Mellorb9bbbb12015-03-23 11:50:46 -07004088 mPrevLine = line;
Gilles Debunned88876a2012-03-16 17:34:04 -07004089
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004090 mPositionX = getCursorHorizontalPosition(layout, offset) - mHotspotX -
4091 getHorizontalOffset() + getCursorOffset();
Gilles Debunned88876a2012-03-16 17:34:04 -07004092 mPositionY = layout.getLineBottom(line);
4093
4094 // Take TextView's padding and scroll into account.
4095 mPositionX += mTextView.viewportToContentHorizontalOffset();
4096 mPositionY += mTextView.viewportToContentVerticalOffset();
4097
4098 mPreviousOffset = offset;
4099 mPositionHasChanged = true;
4100 }
4101 }
4102
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004103 /**
4104 * Return the clamped horizontal position for the first cursor.
4105 *
4106 * @param layout Text layout.
4107 * @param offset Character offset for the cursor.
4108 * @return The clamped horizontal position for the cursor.
4109 */
4110 int getCursorHorizontalPosition(Layout layout, int offset) {
4111 return (int) (layout.getPrimaryHorizontal(offset) - 0.5f);
4112 }
4113
Gilles Debunned88876a2012-03-16 17:34:04 -07004114 public void updatePosition(int parentPositionX, int parentPositionY,
4115 boolean parentPositionChanged, boolean parentScrolled) {
4116 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled);
4117 if (parentPositionChanged || mPositionHasChanged) {
4118 if (mIsDragging) {
4119 // Update touchToWindow offset in case of parent scrolling while dragging
4120 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) {
4121 mTouchToWindowOffsetX += parentPositionX - mLastParentX;
4122 mTouchToWindowOffsetY += parentPositionY - mLastParentY;
4123 mLastParentX = parentPositionX;
4124 mLastParentY = parentPositionY;
4125 }
4126
4127 onHandleMoved();
4128 }
4129
4130 if (isVisible()) {
4131 final int positionX = parentPositionX + mPositionX;
4132 final int positionY = parentPositionY + mPositionY;
4133 if (isShowing()) {
4134 mContainer.update(positionX, positionY, -1, -1);
4135 } else {
4136 mContainer.showAtLocation(mTextView, Gravity.NO_GRAVITY,
4137 positionX, positionY);
4138 }
4139 } else {
4140 if (isShowing()) {
4141 dismiss();
4142 }
4143 }
4144
4145 mPositionHasChanged = false;
4146 }
4147 }
4148
4149 @Override
4150 protected void onDraw(Canvas c) {
Adam Powell3fceabd2014-08-19 18:28:04 -07004151 final int drawWidth = mDrawable.getIntrinsicWidth();
4152 final int left = getHorizontalOffset();
4153
4154 mDrawable.setBounds(left, 0, left + drawWidth, mDrawable.getIntrinsicHeight());
Gilles Debunned88876a2012-03-16 17:34:04 -07004155 mDrawable.draw(c);
4156 }
4157
Adam Powell3fceabd2014-08-19 18:28:04 -07004158 private int getHorizontalOffset() {
4159 final int width = getPreferredWidth();
4160 final int drawWidth = mDrawable.getIntrinsicWidth();
4161 final int left;
4162 switch (mHorizontalGravity) {
4163 case Gravity.LEFT:
4164 left = 0;
4165 break;
4166 default:
4167 case Gravity.CENTER:
4168 left = (width - drawWidth) / 2;
4169 break;
4170 case Gravity.RIGHT:
4171 left = width - drawWidth;
4172 break;
4173 }
4174 return left;
4175 }
4176
4177 protected int getCursorOffset() {
4178 return 0;
4179 }
4180
Gilles Debunned88876a2012-03-16 17:34:04 -07004181 @Override
4182 public boolean onTouchEvent(MotionEvent ev) {
Abodunrinwa Tokifd3a3a12015-05-05 20:04:34 +01004183 updateFloatingToolbarVisibility(ev);
4184
Gilles Debunned88876a2012-03-16 17:34:04 -07004185 switch (ev.getActionMasked()) {
4186 case MotionEvent.ACTION_DOWN: {
4187 startTouchUpFilter(getCurrentCursorOffset());
4188 mTouchToWindowOffsetX = ev.getRawX() - mPositionX;
4189 mTouchToWindowOffsetY = ev.getRawY() - mPositionY;
4190
4191 final PositionListener positionListener = getPositionListener();
4192 mLastParentX = positionListener.getPositionX();
4193 mLastParentY = positionListener.getPositionY();
4194 mIsDragging = true;
Mady Mellora6a0f782015-07-10 16:43:32 -07004195 mPreviousLineTouched = UNSET_LINE;
Gilles Debunned88876a2012-03-16 17:34:04 -07004196 break;
4197 }
4198
4199 case MotionEvent.ACTION_MOVE: {
4200 final float rawX = ev.getRawX();
4201 final float rawY = ev.getRawY();
4202
4203 // Vertical hysteresis: vertical down movement tends to snap to ideal offset
4204 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY;
4205 final float currentVerticalOffset = rawY - mPositionY - mLastParentY;
4206 float newVerticalOffset;
4207 if (previousVerticalOffset < mIdealVerticalOffset) {
4208 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset);
4209 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset);
4210 } else {
4211 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset);
4212 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset);
4213 }
4214 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY;
4215
Keisuke Kuroyanagibc89a5c2015-05-18 14:49:29 +09004216 final float newPosX =
4217 rawX - mTouchToWindowOffsetX + mHotspotX + getHorizontalOffset();
Gilles Debunned88876a2012-03-16 17:34:04 -07004218 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY;
4219
4220 updatePosition(newPosX, newPosY);
4221 break;
4222 }
4223
4224 case MotionEvent.ACTION_UP:
4225 filterOnTouchUp();
4226 mIsDragging = false;
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004227 updateDrawable();
Gilles Debunned88876a2012-03-16 17:34:04 -07004228 break;
4229
4230 case MotionEvent.ACTION_CANCEL:
4231 mIsDragging = false;
Keisuke Kuroyanagidbe2c292015-05-27 19:49:34 +09004232 updateDrawable();
Gilles Debunned88876a2012-03-16 17:34:04 -07004233 break;
4234 }
4235 return true;
4236 }
4237
4238 public boolean isDragging() {
4239 return mIsDragging;
4240 }
4241
Clara Bayarri6351e662015-03-16 23:17:59 +00004242 void onHandleMoved() {}
Gilles Debunned88876a2012-03-16 17:34:04 -07004243
Clara Bayarri6351e662015-03-16 23:17:59 +00004244 public void onDetached() {}
Gilles Debunned88876a2012-03-16 17:34:04 -07004245 }
4246
Mady Mellorff66ca52015-07-08 12:31:45 -07004247 /**
4248 * Returns the active layout (hint or text layout). Note that the text layout can be null.
4249 */
4250 private Layout getActiveLayout() {
4251 Layout layout = mTextView.getLayout();
4252 Layout hintLayout = mTextView.getHintLayout();
4253 if (TextUtils.isEmpty(layout.getText()) && hintLayout != null &&
4254 !TextUtils.isEmpty(hintLayout.getText())) {
4255 layout = hintLayout;
4256 }
4257 return layout;
4258 }
4259
Gilles Debunned88876a2012-03-16 17:34:04 -07004260 private class InsertionHandleView extends HandleView {
4261 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
4262 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds
4263
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004264 // Used to detect taps on the insertion handle, which will affect the insertion action mode
Gilles Debunned88876a2012-03-16 17:34:04 -07004265 private float mDownPositionX, mDownPositionY;
4266 private Runnable mHider;
4267
4268 public InsertionHandleView(Drawable drawable) {
Keisuke Kuroyanagida79ee62015-11-25 16:15:15 +09004269 super(drawable, drawable, com.android.internal.R.id.insertion_handle);
Gilles Debunned88876a2012-03-16 17:34:04 -07004270 }
4271
4272 @Override
4273 public void show() {
4274 super.show();
4275
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004276 final long durationSinceCutOrCopy =
Andrei Stingaceanu77b9c382015-05-06 13:25:19 +01004277 SystemClock.uptimeMillis() - TextView.sLastCutCopyOrTextChangedTime;
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004278
4279 // Cancel the single tap delayed runnable.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004280 if (mInsertionActionModeRunnable != null
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004281 && ((mTapState == TAP_STATE_DOUBLE_TAP)
4282 || (mTapState == TAP_STATE_TRIPLE_CLICK)
4283 || isCursorInsideEasyCorrectionSpan())) {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004284 mTextView.removeCallbacks(mInsertionActionModeRunnable);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004285 }
4286
4287 // Prepare and schedule the single tap runnable to run exactly after the double tap
4288 // timeout has passed.
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004289 if ((mTapState != TAP_STATE_DOUBLE_TAP) && (mTapState != TAP_STATE_TRIPLE_CLICK)
4290 && !isCursorInsideEasyCorrectionSpan()
Andrei Stingaceanu373816e2015-05-28 11:26:28 +01004291 && (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION)) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004292 if (mTextActionMode == null) {
4293 if (mInsertionActionModeRunnable == null) {
4294 mInsertionActionModeRunnable = new Runnable() {
4295 @Override
4296 public void run() {
4297 startInsertionActionMode();
4298 }
4299 };
4300 }
4301 mTextView.postDelayed(
4302 mInsertionActionModeRunnable,
4303 ViewConfiguration.getDoubleTapTimeout() + 1);
Andrei Stingaceanufae270c2015-04-29 14:39:40 +01004304 }
4305
Gilles Debunned88876a2012-03-16 17:34:04 -07004306 }
4307
4308 hideAfterDelay();
4309 }
4310
Gilles Debunned88876a2012-03-16 17:34:04 -07004311 private void hideAfterDelay() {
4312 if (mHider == null) {
4313 mHider = new Runnable() {
4314 public void run() {
4315 hide();
4316 }
4317 };
4318 } else {
4319 removeHiderCallback();
4320 }
4321 mTextView.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT);
4322 }
4323
4324 private void removeHiderCallback() {
4325 if (mHider != null) {
4326 mTextView.removeCallbacks(mHider);
4327 }
4328 }
4329
4330 @Override
4331 protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
4332 return drawable.getIntrinsicWidth() / 2;
4333 }
4334
4335 @Override
Adam Powell3fceabd2014-08-19 18:28:04 -07004336 protected int getHorizontalGravity(boolean isRtlRun) {
4337 return Gravity.CENTER_HORIZONTAL;
4338 }
4339
4340 @Override
4341 protected int getCursorOffset() {
4342 int offset = super.getCursorOffset();
4343 final Drawable cursor = mCursorCount > 0 ? mCursorDrawable[0] : null;
4344 if (cursor != null) {
4345 cursor.getPadding(mTempRect);
4346 offset += (cursor.getIntrinsicWidth() - mTempRect.left - mTempRect.right) / 2;
4347 }
4348 return offset;
4349 }
4350
4351 @Override
Siyamed Sinir217c0f72016-02-01 18:30:02 -08004352 int getCursorHorizontalPosition(Layout layout, int offset) {
4353 final Drawable drawable = mCursorCount > 0 ? mCursorDrawable[0] : null;
4354 if (drawable != null) {
4355 final float horizontal = layout.getPrimaryHorizontal(offset);
4356 return clampCursorHorizontalPosition(drawable, horizontal) + mTempRect.left;
4357 }
4358 return super.getCursorHorizontalPosition(layout, offset);
4359 }
4360
4361 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07004362 public boolean onTouchEvent(MotionEvent ev) {
4363 final boolean result = super.onTouchEvent(ev);
4364
4365 switch (ev.getActionMasked()) {
4366 case MotionEvent.ACTION_DOWN:
4367 mDownPositionX = ev.getRawX();
4368 mDownPositionY = ev.getRawY();
4369 break;
4370
4371 case MotionEvent.ACTION_UP:
4372 if (!offsetHasBeenChanged()) {
4373 final float deltaX = mDownPositionX - ev.getRawX();
4374 final float deltaY = mDownPositionY - ev.getRawY();
4375 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
4376
4377 final ViewConfiguration viewConfiguration = ViewConfiguration.get(
4378 mTextView.getContext());
4379 final int touchSlop = viewConfiguration.getScaledTouchSlop();
4380
4381 if (distanceSquared < touchSlop * touchSlop) {
Clara Bayarrib71dddd2015-06-04 23:17:30 +01004382 // Tapping on the handle toggles the insertion action mode.
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004383 if (mTextActionMode != null) {
4384 mTextActionMode.finish();
Gilles Debunned88876a2012-03-16 17:34:04 -07004385 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004386 startInsertionActionMode();
Gilles Debunned88876a2012-03-16 17:34:04 -07004387 }
4388 }
Abodunrinwa Tokibcdf0ab2015-04-25 00:11:25 +01004389 } else {
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004390 if (mTextActionMode != null) {
4391 mTextActionMode.invalidateContentRect();
Abodunrinwa Tokibcdf0ab2015-04-25 00:11:25 +01004392 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004393 }
4394 hideAfterDelay();
4395 break;
4396
4397 case MotionEvent.ACTION_CANCEL:
4398 hideAfterDelay();
4399 break;
4400
4401 default:
4402 break;
4403 }
4404
4405 return result;
4406 }
4407
4408 @Override
4409 public int getCurrentCursorOffset() {
4410 return mTextView.getSelectionStart();
4411 }
4412
4413 @Override
4414 public void updateSelection(int offset) {
4415 Selection.setSelection((Spannable) mTextView.getText(), offset);
4416 }
4417
4418 @Override
4419 public void updatePosition(float x, float y) {
Mady Melloree3821e2015-06-05 11:12:01 -07004420 Layout layout = mTextView.getLayout();
4421 int offset;
4422 if (layout != null) {
Mady Mellora6a0f782015-07-10 16:43:32 -07004423 if (mPreviousLineTouched == UNSET_LINE) {
4424 mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4425 }
4426 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
Mady Melloree3821e2015-06-05 11:12:01 -07004427 offset = mTextView.getOffsetAtCoordinate(currLine, x);
Mady Mellora6a0f782015-07-10 16:43:32 -07004428 mPreviousLineTouched = currLine;
Mady Melloree3821e2015-06-05 11:12:01 -07004429 } else {
4430 offset = mTextView.getOffsetForPosition(x, y);
4431 }
4432 positionAtCursorOffset(offset, false);
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004433 if (mTextActionMode != null) {
4434 mTextActionMode.invalidate();
Clara Bayarri1baed512015-05-11 15:29:16 +01004435 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004436 }
4437
4438 @Override
4439 void onHandleMoved() {
4440 super.onHandleMoved();
4441 removeHiderCallback();
4442 }
4443
4444 @Override
4445 public void onDetached() {
4446 super.onDetached();
4447 removeHiderCallback();
4448 }
4449 }
4450
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004451 @Retention(RetentionPolicy.SOURCE)
4452 @IntDef({HANDLE_TYPE_SELECTION_START, HANDLE_TYPE_SELECTION_END})
4453 public @interface HandleType {}
4454 public static final int HANDLE_TYPE_SELECTION_START = 0;
4455 public static final int HANDLE_TYPE_SELECTION_END = 1;
4456
4457 private class SelectionHandleView extends HandleView {
4458 // Indicates the handle type, selection start (HANDLE_TYPE_SELECTION_START) or selection
4459 // end (HANDLE_TYPE_SELECTION_END).
4460 @HandleType
4461 private final int mHandleType;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004462 // Indicates whether the cursor is making adjustments within a word.
4463 private boolean mInWord = false;
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004464 // Difference between touch position and word boundary position.
4465 private float mTouchWordDelta;
Mady Mellore264ac32015-06-22 16:46:29 -07004466 // X value of the previous updatePosition call.
4467 private float mPrevX;
4468 // Indicates if the handle has moved a boundary between LTR and RTL text.
4469 private boolean mLanguageDirectionChanged = false;
Mady Mellor42390aa2015-07-24 13:08:42 -07004470 // Distance from edge of horizontally scrolling text view
4471 // to use to switch to character mode.
4472 private final float mTextViewEdgeSlop;
4473 // Used to save text view location.
4474 private final int[] mTextViewLocation = new int[2];
Gilles Debunned88876a2012-03-16 17:34:04 -07004475
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004476 public SelectionHandleView(Drawable drawableLtr, Drawable drawableRtl, int id,
4477 @HandleType int handleType) {
4478 super(drawableLtr, drawableRtl, id);
4479 mHandleType = handleType;
4480 ViewConfiguration viewConfiguration = ViewConfiguration.get(mTextView.getContext());
Mady Mellor42390aa2015-07-24 13:08:42 -07004481 mTextViewEdgeSlop = viewConfiguration.getScaledTouchSlop() * 4;
Gilles Debunned88876a2012-03-16 17:34:04 -07004482 }
4483
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004484 private boolean isStartHandle() {
4485 return mHandleType == HANDLE_TYPE_SELECTION_START;
4486 }
4487
Gilles Debunned88876a2012-03-16 17:34:04 -07004488 @Override
4489 protected int getHotspotX(Drawable drawable, boolean isRtlRun) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004490 if (isRtlRun == isStartHandle()) {
Mady Mellor709386f2015-05-14 12:41:18 -07004491 return drawable.getIntrinsicWidth() / 4;
4492 } else {
4493 return (drawable.getIntrinsicWidth() * 3) / 4;
4494 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004495 }
4496
4497 @Override
Adam Powell3fceabd2014-08-19 18:28:04 -07004498 protected int getHorizontalGravity(boolean isRtlRun) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004499 return (isRtlRun == isStartHandle()) ? Gravity.LEFT : Gravity.RIGHT;
Adam Powell3fceabd2014-08-19 18:28:04 -07004500 }
4501
4502 @Override
Gilles Debunned88876a2012-03-16 17:34:04 -07004503 public int getCurrentCursorOffset() {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004504 return isStartHandle() ? mTextView.getSelectionStart() : mTextView.getSelectionEnd();
Gilles Debunned88876a2012-03-16 17:34:04 -07004505 }
4506
4507 @Override
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004508 protected void updateSelection(int offset) {
4509 if (isStartHandle()) {
4510 Selection.setSelection((Spannable) mTextView.getText(), offset,
4511 mTextView.getSelectionEnd());
4512 } else {
4513 Selection.setSelection((Spannable) mTextView.getText(),
4514 mTextView.getSelectionStart(), offset);
4515 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004516 updateDrawable();
Clara Bayarri7938cdb2015-06-02 20:03:45 +01004517 if (mTextActionMode != null) {
4518 mTextActionMode.invalidate();
Clara Bayarri13152d12015-04-09 12:02:04 +01004519 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004520 }
4521
4522 @Override
4523 public void updatePosition(float x, float y) {
Mady Mellor81fa3e82015-05-14 09:17:41 -07004524 final Layout layout = mTextView.getLayout();
Mady Mellorcc65c372015-06-17 09:25:19 -07004525 if (layout == null) {
4526 // HandleView will deal appropriately in positionAtCursorOffset when
4527 // layout is null.
Mady Mellor42390aa2015-07-24 13:08:42 -07004528 positionAndAdjustForCrossingHandles(mTextView.getOffsetForPosition(x, y));
Mady Mellorcc65c372015-06-17 09:25:19 -07004529 return;
4530 }
4531
Mady Mellora6a0f782015-07-10 16:43:32 -07004532 if (mPreviousLineTouched == UNSET_LINE) {
4533 mPreviousLineTouched = mTextView.getLineAtCoordinate(y);
4534 }
4535
Mady Mellorb9bbbb12015-03-23 11:50:46 -07004536 boolean positionCursor = false;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004537 final int anotherHandleOffset =
4538 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
Mady Mellora6a0f782015-07-10 16:43:32 -07004539 int currLine = getCurrentLineAdjustedForSlop(layout, mPreviousLineTouched, y);
Mady Mellorcc65c372015-06-17 09:25:19 -07004540 int initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
Mady Mellor81fa3e82015-05-14 09:17:41 -07004541
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004542 if (isStartHandle() && initialOffset >= anotherHandleOffset
4543 || !isStartHandle() && initialOffset <= anotherHandleOffset) {
4544 // Handles have crossed, bound it to the first selected line and
Mady Mellor81fa3e82015-05-14 09:17:41 -07004545 // adjust by word / char as normal.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004546 currLine = layout.getLineForOffset(anotherHandleOffset);
Mady Mellor81fa3e82015-05-14 09:17:41 -07004547 initialOffset = mTextView.getOffsetAtCoordinate(currLine, x);
4548 }
4549
4550 int offset = initialOffset;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004551 final int wordEnd = getWordEnd(offset);
4552 final int wordStart = getWordStart(offset);
Gilles Debunned88876a2012-03-16 17:34:04 -07004553
Mady Mellore264ac32015-06-22 16:46:29 -07004554 if (mPrevX == UNSET_X_VALUE) {
4555 mPrevX = x;
4556 }
4557
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004558 final int currentOffset = getCurrentCursorOffset();
4559 final boolean rtlAtCurrentOffset = layout.isRtlCharAt(currentOffset);
Mady Mellore264ac32015-06-22 16:46:29 -07004560 final boolean atRtl = layout.isRtlCharAt(offset);
4561 final boolean isLvlBoundary = layout.isLevelBoundary(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004562
4563 // We can't determine if the user is expanding or shrinking the selection if they're
4564 // on a bi-di boundary, so until they've moved past the boundary we'll just place
4565 // the cursor at the current position.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004566 if (isLvlBoundary || (rtlAtCurrentOffset && !atRtl) || (!rtlAtCurrentOffset && atRtl)) {
Mady Mellore264ac32015-06-22 16:46:29 -07004567 // We're on a boundary or this is the first direction change -- just update
4568 // to the current position.
4569 mLanguageDirectionChanged = true;
4570 mTouchWordDelta = 0.0f;
Mady Mellor42390aa2015-07-24 13:08:42 -07004571 positionAndAdjustForCrossingHandles(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004572 return;
4573 } else if (mLanguageDirectionChanged && !isLvlBoundary) {
4574 // We've just moved past the boundary so update the position. After this we can
4575 // figure out if the user is expanding or shrinking to go by word or character.
Mady Mellor42390aa2015-07-24 13:08:42 -07004576 positionAndAdjustForCrossingHandles(offset);
Mady Mellore264ac32015-06-22 16:46:29 -07004577 mTouchWordDelta = 0.0f;
4578 mLanguageDirectionChanged = false;
4579 return;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004580 }
4581
4582 boolean isExpanding;
4583 final float xDiff = x - mPrevX;
Keisuke Kuroyanagi26454142015-12-02 15:04:57 -08004584 if (isStartHandle()) {
4585 isExpanding = currLine < mPreviousLineTouched;
Mady Mellore264ac32015-06-22 16:46:29 -07004586 } else {
Keisuke Kuroyanagi26454142015-12-02 15:04:57 -08004587 isExpanding = currLine > mPreviousLineTouched;
4588 }
4589 if (atRtl == isStartHandle()) {
4590 isExpanding |= xDiff > 0;
4591 } else {
4592 isExpanding |= xDiff < 0;
Mady Mellore264ac32015-06-22 16:46:29 -07004593 }
4594
Mady Mellor42390aa2015-07-24 13:08:42 -07004595 if (mTextView.getHorizontallyScrolling()) {
4596 if (positionNearEdgeOfScrollingView(x, atRtl)
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004597 && ((isStartHandle() && mTextView.getScrollX() != 0)
4598 || (!isStartHandle()
4599 && mTextView.canScrollHorizontally(atRtl ? -1 : 1)))
4600 && ((isExpanding && ((isStartHandle() && offset < currentOffset)
4601 || (!isStartHandle() && offset > currentOffset)))
4602 || !isExpanding)) {
4603 // If we're expanding ensure that the offset is actually expanding compared to
4604 // the current offset, if the handle snapped to the word, the finger position
Mady Mellor42390aa2015-07-24 13:08:42 -07004605 // may be out of sync and we don't want the selection to jump back.
4606 mTouchWordDelta = 0.0f;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004607 final int nextOffset = (atRtl == isStartHandle())
4608 ? layout.getOffsetToRightOf(mPreviousOffset)
Mady Mellor42390aa2015-07-24 13:08:42 -07004609 : layout.getOffsetToLeftOf(mPreviousOffset);
4610 positionAndAdjustForCrossingHandles(nextOffset);
4611 return;
4612 }
4613 }
4614
Mady Mellore264ac32015-06-22 16:46:29 -07004615 if (isExpanding) {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004616 // User is increasing the selection.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004617 final boolean snapToWord = !mInWord
4618 || (isStartHandle() ? currLine < mPrevLine : currLine > mPrevLine);
4619 if (snapToWord) {
Mady Mellora5266832015-06-26 14:28:12 -07004620 // Sometimes words can be broken across lines (Chinese, hyphenation).
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004621 // We still snap to the word boundary but we only use the letters on the
Mady Mellora5266832015-06-26 14:28:12 -07004622 // current line to determine if the user is far enough into the word to snap.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004623 int wordBoundary = isStartHandle() ? wordStart : wordEnd;
4624 if (layout != null && layout.getLineForOffset(wordBoundary) != currLine) {
4625 wordBoundary = isStartHandle() ?
4626 layout.getLineStart(currLine) : layout.getLineEnd(currLine);
Mady Mellora5266832015-06-26 14:28:12 -07004627 }
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004628 final int offsetThresholdToSnap = isStartHandle()
4629 ? wordEnd - ((wordEnd - wordBoundary) / 2)
4630 : wordStart + ((wordBoundary - wordStart) / 2);
4631 if (isStartHandle()
4632 && (offset <= offsetThresholdToSnap || currLine < mPrevLine)) {
4633 // User is far enough into the word or on a different line so we expand by
4634 // word.
4635 offset = wordStart;
4636 } else if (!isStartHandle()
4637 && (offset >= offsetThresholdToSnap || currLine > mPrevLine)) {
4638 // User is far enough into the word or on a different line so we expand by
4639 // word.
4640 offset = wordEnd;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004641 } else {
Mady Mellorc2225b92015-04-01 15:59:20 -07004642 offset = mPreviousOffset;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004643 }
4644 }
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004645 if (layout != null && (isStartHandle() && offset < initialOffset)
4646 || (!isStartHandle() && offset > initialOffset)) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004647 final float adjustedX = layout.getPrimaryHorizontal(offset);
4648 mTouchWordDelta =
4649 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
Keisuke Kuroyanagi50a927c2015-05-07 17:34:21 +09004650 } else {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004651 mTouchWordDelta = 0.0f;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004652 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004653 positionCursor = true;
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004654 } else {
4655 final int adjustedOffset =
4656 mTextView.getOffsetAtCoordinate(currLine, x - mTouchWordDelta);
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004657 final boolean shrinking = isStartHandle()
4658 ? adjustedOffset > mPreviousOffset || currLine > mPrevLine
4659 : adjustedOffset < mPreviousOffset || currLine < mPrevLine;
4660 if (shrinking) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004661 // User is shrinking the selection.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004662 if (currLine != mPrevLine) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004663 // We're on a different line, so we'll snap to word boundaries.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004664 offset = isStartHandle() ? wordStart : wordEnd;
4665 if (layout != null && (isStartHandle() && offset < initialOffset)
4666 || (!isStartHandle() && offset > initialOffset)) {
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004667 final float adjustedX = layout.getPrimaryHorizontal(offset);
4668 mTouchWordDelta =
4669 mTextView.convertToLocalHorizontalCoordinate(x) - adjustedX;
4670 } else {
4671 mTouchWordDelta = 0.0f;
4672 }
4673 } else {
4674 offset = adjustedOffset;
4675 }
4676 positionCursor = true;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004677 } else if ((isStartHandle() && adjustedOffset < mPreviousOffset)
4678 || (!isStartHandle() && adjustedOffset > mPreviousOffset)) {
4679 // Handle has jumped to the word boundary, and the user is moving
Mady Mellor43fd2f42015-06-08 14:03:34 -07004680 // their finger towards the handle, the delta should be updated.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004681 mTouchWordDelta = mTextView.convertToLocalHorizontalCoordinate(x) -
4682 layout.getPrimaryHorizontal(mPreviousOffset);
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004683 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004684 }
4685
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004686 if (positionCursor) {
Mady Mellora6a0f782015-07-10 16:43:32 -07004687 mPreviousLineTouched = currLine;
Mady Mellor42390aa2015-07-24 13:08:42 -07004688 positionAndAdjustForCrossingHandles(offset);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004689 }
Mady Mellore264ac32015-06-22 16:46:29 -07004690 mPrevX = x;
Gilles Debunned88876a2012-03-16 17:34:04 -07004691 }
4692
Yoshiki Iguchi9582e152015-10-15 13:34:41 +09004693 /**
4694 * @param offset Cursor offset. Must be in [-1, length].
4695 * @param parentScrolled If the parent has been scrolled or not.
4696 */
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004697 @Override
Mady Mellor36d5a7b2015-05-22 10:31:12 -07004698 protected void positionAtCursorOffset(int offset, boolean parentScrolled) {
4699 super.positionAtCursorOffset(offset, parentScrolled);
Yoshiki Iguchi9582e152015-10-15 13:34:41 +09004700 mInWord = (offset != -1) && !getWordIteratorWithText().isBoundary(offset);
Mady Mellor36d5a7b2015-05-22 10:31:12 -07004701 }
4702
4703 @Override
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004704 public boolean onTouchEvent(MotionEvent event) {
4705 boolean superResult = super.onTouchEvent(event);
Mady Mellora6a0f782015-07-10 16:43:32 -07004706 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
4707 // Reset the touch word offset and x value when the user
4708 // re-engages the handle.
Keisuke Kuroyanagi0138e4c2015-05-12 12:51:26 +09004709 mTouchWordDelta = 0.0f;
Mady Mellore264ac32015-06-22 16:46:29 -07004710 mPrevX = UNSET_X_VALUE;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004711 }
4712 return superResult;
4713 }
Mady Mellor42390aa2015-07-24 13:08:42 -07004714
Mady Mellor42390aa2015-07-24 13:08:42 -07004715 private void positionAndAdjustForCrossingHandles(int offset) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004716 final int anotherHandleOffset =
4717 isStartHandle() ? mTextView.getSelectionEnd() : mTextView.getSelectionStart();
4718 if ((isStartHandle() && offset >= anotherHandleOffset)
4719 || (!isStartHandle() && offset <= anotherHandleOffset)) {
Mady Mellor42390aa2015-07-24 13:08:42 -07004720 // Handles can not cross and selection is at least one character.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004721 offset = getNextCursorOffset(anotherHandleOffset, !isStartHandle());
Mady Mellor42390aa2015-07-24 13:08:42 -07004722 mTouchWordDelta = 0.0f;
4723 }
4724 positionAtCursorOffset(offset, false);
4725 }
4726
Mady Mellor42390aa2015-07-24 13:08:42 -07004727 private boolean positionNearEdgeOfScrollingView(float x, boolean atRtl) {
4728 mTextView.getLocationOnScreen(mTextViewLocation);
4729 boolean nearEdge;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004730 if (atRtl == isStartHandle()) {
Mady Mellor42390aa2015-07-24 13:08:42 -07004731 int rightEdge = mTextViewLocation[0] + mTextView.getWidth()
4732 - mTextView.getPaddingRight();
4733 nearEdge = x > rightEdge - mTextViewEdgeSlop;
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004734 } else {
4735 int leftEdge = mTextViewLocation[0] + mTextView.getPaddingLeft();
4736 nearEdge = x < leftEdge + mTextViewEdgeSlop;
Mady Mellor42390aa2015-07-24 13:08:42 -07004737 }
4738 return nearEdge;
4739 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004740 }
4741
Mady Mellorcc65c372015-06-17 09:25:19 -07004742 private int getCurrentLineAdjustedForSlop(Layout layout, int prevLine, float y) {
Mady Mellor80679072015-07-09 16:05:36 -07004743 final int trueLine = mTextView.getLineAtCoordinate(y);
Mady Mellorcc65c372015-06-17 09:25:19 -07004744 if (layout == null || prevLine > layout.getLineCount()
4745 || layout.getLineCount() <= 0 || prevLine < 0) {
4746 // Invalid parameters, just return whatever line is at y.
Mady Mellor80679072015-07-09 16:05:36 -07004747 return trueLine;
4748 }
4749
4750 if (Math.abs(trueLine - prevLine) >= 2) {
4751 // Only stick to lines if we're within a line of the previous selection.
4752 return trueLine;
Mady Mellorcc65c372015-06-17 09:25:19 -07004753 }
4754
4755 final float verticalOffset = mTextView.viewportToContentVerticalOffset();
4756 final int lineCount = layout.getLineCount();
4757 final float slop = mTextView.getLineHeight() * LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS;
4758
4759 final float firstLineTop = layout.getLineTop(0) + verticalOffset;
4760 final float prevLineTop = layout.getLineTop(prevLine) + verticalOffset;
4761 final float yTopBound = Math.max(prevLineTop - slop, firstLineTop + slop);
4762
4763 final float lastLineBottom = layout.getLineBottom(lineCount - 1) + verticalOffset;
4764 final float prevLineBottom = layout.getLineBottom(prevLine) + verticalOffset;
4765 final float yBottomBound = Math.min(prevLineBottom + slop, lastLineBottom - slop);
4766
4767 // Determine if we've moved lines based on y position and previous line.
4768 int currLine;
4769 if (y <= yTopBound) {
4770 currLine = Math.max(prevLine - 1, 0);
4771 } else if (y >= yBottomBound) {
4772 currLine = Math.min(prevLine + 1, lineCount - 1);
4773 } else {
4774 currLine = prevLine;
4775 }
4776 return currLine;
4777 }
4778
Gilles Debunned88876a2012-03-16 17:34:04 -07004779 /**
4780 * A CursorController instance can be used to control a cursor in the text.
4781 */
4782 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
4783 /**
4784 * Makes the cursor controller visible on screen.
4785 * See also {@link #hide()}.
4786 */
4787 public void show();
4788
4789 /**
4790 * Hide the cursor controller from screen.
4791 * See also {@link #show()}.
4792 */
4793 public void hide();
4794
4795 /**
4796 * Called when the view is detached from window. Perform house keeping task, such as
4797 * stopping Runnable thread that would otherwise keep a reference on the context, thus
4798 * preventing the activity from being recycled.
4799 */
4800 public void onDetached();
4801 }
4802
4803 private class InsertionPointCursorController implements CursorController {
4804 private InsertionHandleView mHandle;
4805
4806 public void show() {
4807 getHandle().show();
Andrei Stingaceanu35c550c2015-05-07 16:49:49 +01004808
4809 if (mSelectionModifierCursorController != null) {
4810 mSelectionModifierCursorController.hide();
4811 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004812 }
4813
Gilles Debunned88876a2012-03-16 17:34:04 -07004814 public void hide() {
4815 if (mHandle != null) {
4816 mHandle.hide();
4817 }
4818 }
4819
4820 public void onTouchModeChanged(boolean isInTouchMode) {
4821 if (!isInTouchMode) {
4822 hide();
4823 }
4824 }
4825
4826 private InsertionHandleView getHandle() {
4827 if (mSelectHandleCenter == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004828 mSelectHandleCenter = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004829 mTextView.mTextSelectHandleRes);
4830 }
4831 if (mHandle == null) {
4832 mHandle = new InsertionHandleView(mSelectHandleCenter);
4833 }
4834 return mHandle;
4835 }
4836
4837 @Override
4838 public void onDetached() {
4839 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
4840 observer.removeOnTouchModeChangeListener(this);
4841
4842 if (mHandle != null) mHandle.onDetached();
4843 }
4844 }
4845
4846 class SelectionModifierCursorController implements CursorController {
Gilles Debunned88876a2012-03-16 17:34:04 -07004847 // The cursor controller handles, lazily created when shown.
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004848 private SelectionHandleView mStartHandle;
4849 private SelectionHandleView mEndHandle;
Gilles Debunned88876a2012-03-16 17:34:04 -07004850 // The offsets of that last touch down event. Remembered to start selection there.
4851 private int mMinTouchOffset, mMaxTouchOffset;
4852
Gilles Debunned88876a2012-03-16 17:34:04 -07004853 private float mDownPositionX, mDownPositionY;
4854 private boolean mGestureStayedInTapRegion;
4855
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004856 // Where the user first starts the drag motion.
4857 private int mStartOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004858
Mady Mellor7a936442015-05-20 10:05:52 -07004859 private boolean mHaventMovedEnoughToStartDrag;
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07004860 // The line that a selection happened most recently with the drag accelerator.
4861 private int mLineSelectionIsOn = -1;
4862 // Whether the drag accelerator has selected past the initial line.
4863 private boolean mSwitchedLines = false;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004864
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004865 // Indicates the drag accelerator mode that the user is currently using.
4866 private int mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
4867 // Drag accelerator is inactive.
4868 private static final int DRAG_ACCELERATOR_MODE_INACTIVE = 0;
4869 // Character based selection by dragging. Only for mouse.
4870 private static final int DRAG_ACCELERATOR_MODE_CHARACTER = 1;
4871 // Word based selection by dragging. Enabled after long pressing or double tapping.
4872 private static final int DRAG_ACCELERATOR_MODE_WORD = 2;
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09004873 // Paragraph based selection by dragging. Enabled after mouse triple click.
4874 private static final int DRAG_ACCELERATOR_MODE_PARAGRAPH = 3;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004875
Gilles Debunned88876a2012-03-16 17:34:04 -07004876 SelectionModifierCursorController() {
4877 resetTouchOffsets();
4878 }
4879
4880 public void show() {
4881 if (mTextView.isInBatchEditMode()) {
4882 return;
4883 }
4884 initDrawables();
4885 initHandles();
Gilles Debunned88876a2012-03-16 17:34:04 -07004886 }
4887
4888 private void initDrawables() {
4889 if (mSelectHandleLeft == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004890 mSelectHandleLeft = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004891 mTextView.mTextSelectHandleLeftRes);
4892 }
4893 if (mSelectHandleRight == null) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08004894 mSelectHandleRight = mTextView.getContext().getDrawable(
Gilles Debunned88876a2012-03-16 17:34:04 -07004895 mTextView.mTextSelectHandleRightRes);
4896 }
4897 }
4898
4899 private void initHandles() {
4900 // Lazy object creation has to be done before updatePosition() is called.
4901 if (mStartHandle == null) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004902 mStartHandle = new SelectionHandleView(mSelectHandleLeft, mSelectHandleRight,
4903 com.android.internal.R.id.selection_start_handle,
4904 HANDLE_TYPE_SELECTION_START);
Gilles Debunned88876a2012-03-16 17:34:04 -07004905 }
4906 if (mEndHandle == null) {
Keisuke Kuroyanagi5d7657e2015-11-26 13:59:05 +09004907 mEndHandle = new SelectionHandleView(mSelectHandleRight, mSelectHandleLeft,
4908 com.android.internal.R.id.selection_end_handle,
4909 HANDLE_TYPE_SELECTION_END);
Gilles Debunned88876a2012-03-16 17:34:04 -07004910 }
4911
4912 mStartHandle.show();
4913 mEndHandle.show();
4914
Gilles Debunned88876a2012-03-16 17:34:04 -07004915 hideInsertionPointCursorController();
4916 }
4917
4918 public void hide() {
4919 if (mStartHandle != null) mStartHandle.hide();
4920 if (mEndHandle != null) mEndHandle.hide();
4921 }
4922
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004923 public void enterDrag(int dragAcceleratorMode) {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004924 // Just need to init the handles / hide insertion cursor.
4925 show();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004926 mDragAcceleratorMode = dragAcceleratorMode;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004927 // Start location of selection.
4928 mStartOffset = mTextView.getOffsetForPosition(mLastDownPositionX,
4929 mLastDownPositionY);
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07004930 mLineSelectionIsOn = mTextView.getLineAtCoordinate(mLastDownPositionY);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004931 // Don't show the handles until user has lifted finger.
4932 hide();
4933
4934 // This stops scrolling parents from intercepting the touch event, allowing
4935 // the user to continue dragging across the screen to select text; TextView will
4936 // scroll as necessary.
4937 mTextView.getParent().requestDisallowInterceptTouchEvent(true);
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004938 mTextView.cancelLongPress();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08004939 }
4940
Gilles Debunned88876a2012-03-16 17:34:04 -07004941 public void onTouchEvent(MotionEvent event) {
4942 // This is done even when the View does not have focus, so that long presses can start
4943 // selection and tap can move cursor from this tap position.
Mady Mellor7a936442015-05-20 10:05:52 -07004944 final float eventX = event.getX();
4945 final float eventY = event.getY();
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004946 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
Gilles Debunned88876a2012-03-16 17:34:04 -07004947 switch (event.getActionMasked()) {
4948 case MotionEvent.ACTION_DOWN:
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004949 if (extractedTextModeWillBeStarted()) {
4950 // Prevent duplicating the selection handles until the mode starts.
4951 hide();
4952 } else {
4953 // Remember finger down position, to be able to start selection from there.
4954 mMinTouchOffset = mMaxTouchOffset = mTextView.getOffsetForPosition(
4955 eventX, eventY);
Gilles Debunned88876a2012-03-16 17:34:04 -07004956
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004957 // Double tap detection
4958 if (mGestureStayedInTapRegion) {
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004959 if (mTapState == TAP_STATE_DOUBLE_TAP
4960 || mTapState == TAP_STATE_TRIPLE_CLICK) {
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004961 final float deltaX = eventX - mDownPositionX;
4962 final float deltaY = eventY - mDownPositionY;
4963 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
Gilles Debunned88876a2012-03-16 17:34:04 -07004964
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004965 ViewConfiguration viewConfiguration = ViewConfiguration.get(
4966 mTextView.getContext());
4967 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop();
4968 boolean stayedInArea =
4969 distanceSquared < doubleTapSlop * doubleTapSlop;
Gilles Debunned88876a2012-03-16 17:34:04 -07004970
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08004971 if (stayedInArea && (isMouse || isPositionOnText(eventX, eventY))) {
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004972 if (mTapState == TAP_STATE_DOUBLE_TAP) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09004973 selectCurrentWordAndStartDrag();
Keisuke Kuroyanagi155aecb2015-11-05 19:10:07 +09004974 } else if (mTapState == TAP_STATE_TRIPLE_CLICK) {
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09004975 selectCurrentParagraphAndStartDrag();
4976 }
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004977 mDiscardNextActionUp = true;
4978 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004979 }
4980 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004981
Andrei Stingaceanu838307272015-06-19 17:58:47 +01004982 mDownPositionX = eventX;
4983 mDownPositionY = eventY;
4984 mGestureStayedInTapRegion = true;
4985 mHaventMovedEnoughToStartDrag = true;
4986 }
Gilles Debunned88876a2012-03-16 17:34:04 -07004987 break;
4988
4989 case MotionEvent.ACTION_POINTER_DOWN:
4990 case MotionEvent.ACTION_POINTER_UP:
4991 // Handle multi-point gestures. Keep min and max offset positions.
4992 // Only activated for devices that correctly handle multi-touch.
4993 if (mTextView.getContext().getPackageManager().hasSystemFeature(
4994 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) {
4995 updateMinAndMaxOffsets(event);
4996 }
4997 break;
4998
4999 case MotionEvent.ACTION_MOVE:
Mady Mellor7a936442015-05-20 10:05:52 -07005000 final ViewConfiguration viewConfig = ViewConfiguration.get(
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005001 mTextView.getContext());
Mady Mellor7a936442015-05-20 10:05:52 -07005002 final int touchSlop = viewConfig.getScaledTouchSlop();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005003
Mady Mellor7a936442015-05-20 10:05:52 -07005004 if (mGestureStayedInTapRegion || mHaventMovedEnoughToStartDrag) {
5005 final float deltaX = eventX - mDownPositionX;
5006 final float deltaY = eventY - mDownPositionY;
Gilles Debunned88876a2012-03-16 17:34:04 -07005007 final float distanceSquared = deltaX * deltaX + deltaY * deltaY;
5008
Mady Mellor7a936442015-05-20 10:05:52 -07005009 if (mGestureStayedInTapRegion) {
5010 int doubleTapTouchSlop = viewConfig.getScaledDoubleTapTouchSlop();
5011 mGestureStayedInTapRegion =
5012 distanceSquared <= doubleTapTouchSlop * doubleTapTouchSlop;
5013 }
5014 if (mHaventMovedEnoughToStartDrag) {
5015 // We don't start dragging until the user has moved enough.
5016 mHaventMovedEnoughToStartDrag =
5017 distanceSquared <= touchSlop * touchSlop;
Gilles Debunned88876a2012-03-16 17:34:04 -07005018 }
5019 }
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005020
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005021 if (isMouse && !isDragAcceleratorActive()) {
5022 final int offset = mTextView.getOffsetForPosition(eventX, eventY);
Keisuke Kuroyanagie8760852015-12-21 18:30:19 +09005023 if (mTextView.hasSelection()
5024 && (!mHaventMovedEnoughToStartDrag || mStartOffset != offset)
5025 && offset >= mTextView.getSelectionStart()
5026 && offset <= mTextView.getSelectionEnd()) {
5027 startDragAndDrop();
5028 break;
5029 }
5030
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005031 if (mStartOffset != offset) {
5032 // Start character based drag accelerator.
5033 if (mTextActionMode != null) {
5034 mTextActionMode.finish();
5035 }
5036 enterDrag(DRAG_ACCELERATOR_MODE_CHARACTER);
5037 mDiscardNextActionUp = true;
5038 mHaventMovedEnoughToStartDrag = false;
5039 }
5040 }
5041
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005042 if (mStartHandle != null && mStartHandle.isShowing()) {
5043 // Don't do the drag if the handles are showing already.
5044 break;
5045 }
5046
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005047 updateSelection(event);
Gilles Debunned88876a2012-03-16 17:34:04 -07005048 break;
5049
5050 case MotionEvent.ACTION_UP:
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005051 if (!isDragAcceleratorActive()) {
5052 break;
5053 }
5054 updateSelection(event);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005055
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005056 // No longer dragging to select text, let the parent intercept events.
5057 mTextView.getParent().requestDisallowInterceptTouchEvent(false);
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005058
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005059 int startOffset = mTextView.getSelectionStart();
5060 int endOffset = mTextView.getSelectionEnd();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005061
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005062 // Since we don't let drag handles pass once they're visible, we need to
5063 // make sure the start / end locations are correct because the user *can*
5064 // switch directions during the initial drag.
5065 if (endOffset < startOffset) {
5066 int tmp = endOffset;
5067 endOffset = startOffset;
5068 startOffset = tmp;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005069
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005070 // Also update the selection with the right offsets in this case.
5071 Selection.setSelection((Spannable) mTextView.getText(),
5072 startOffset, endOffset);
5073 }
5074 if (startOffset != endOffset) {
Andrei Stingaceanu2aaeefe2015-10-20 19:11:23 +01005075 startSelectionActionMode();
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005076 }
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005077
5078 // No longer the first dragging motion, reset.
5079 resetDragAcceleratorState();
Gilles Debunned88876a2012-03-16 17:34:04 -07005080 break;
5081 }
5082 }
5083
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005084 private void updateSelection(MotionEvent event) {
5085 if (mTextView.getLayout() != null) {
5086 switch (mDragAcceleratorMode) {
5087 case DRAG_ACCELERATOR_MODE_CHARACTER:
5088 updateCharacterBasedSelection(event);
5089 break;
5090 case DRAG_ACCELERATOR_MODE_WORD:
5091 updateWordBasedSelection(event);
5092 break;
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005093 case DRAG_ACCELERATOR_MODE_PARAGRAPH:
5094 updateParagraphBasedSelection(event);
5095 break;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005096 }
5097 }
5098 }
5099
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005100 /**
5101 * If the TextView allows text selection, selects the current paragraph and starts a drag.
5102 *
5103 * @return true if the drag was started.
5104 */
5105 private boolean selectCurrentParagraphAndStartDrag() {
5106 if (mInsertionActionModeRunnable != null) {
5107 mTextView.removeCallbacks(mInsertionActionModeRunnable);
5108 }
5109 if (mTextActionMode != null) {
5110 mTextActionMode.finish();
5111 }
5112 if (!selectCurrentParagraph()) {
5113 return false;
5114 }
5115 enterDrag(SelectionModifierCursorController.DRAG_ACCELERATOR_MODE_PARAGRAPH);
5116 return true;
5117 }
5118
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005119 private void updateCharacterBasedSelection(MotionEvent event) {
5120 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5121 Selection.setSelection((Spannable) mTextView.getText(), mStartOffset, offset);
5122 }
5123
5124 private void updateWordBasedSelection(MotionEvent event) {
5125 if (mHaventMovedEnoughToStartDrag) {
5126 return;
5127 }
5128 final boolean isMouse = event.isFromSource(InputDevice.SOURCE_MOUSE);
5129 final ViewConfiguration viewConfig = ViewConfiguration.get(
5130 mTextView.getContext());
5131 final float eventX = event.getX();
5132 final float eventY = event.getY();
5133 final int currLine;
5134 if (isMouse) {
5135 // No need to offset the y coordinate for mouse input.
5136 currLine = mTextView.getLineAtCoordinate(eventY);
5137 } else {
5138 float y = eventY;
5139 if (mSwitchedLines) {
5140 // Offset the finger by the same vertical offset as the handles.
5141 // This improves visibility of the content being selected by
5142 // shifting the finger below the content, this is applied once
5143 // the user has switched lines.
5144 final int touchSlop = viewConfig.getScaledTouchSlop();
5145 final float fingerOffset = (mStartHandle != null)
5146 ? mStartHandle.getIdealVerticalOffset()
5147 : touchSlop;
5148 y = eventY - fingerOffset;
5149 }
5150
5151 currLine = getCurrentLineAdjustedForSlop(mTextView.getLayout(), mLineSelectionIsOn,
5152 y);
5153 if (!mSwitchedLines && currLine != mLineSelectionIsOn) {
5154 // Break early here, we want to offset the finger position from
5155 // the selection highlight, once the user moved their finger
5156 // to a different line we should apply the offset and *not* switch
5157 // lines until recomputing the position with the finger offset.
5158 mSwitchedLines = true;
5159 return;
5160 }
5161 }
5162
5163 int startOffset;
5164 int offset = mTextView.getOffsetAtCoordinate(currLine, eventX);
5165 // Snap to word boundaries.
5166 if (mStartOffset < offset) {
5167 // Expanding with end handle.
5168 offset = getWordEnd(offset);
5169 startOffset = getWordStart(mStartOffset);
5170 } else {
5171 // Expanding with start handle.
5172 offset = getWordStart(offset);
5173 startOffset = getWordEnd(mStartOffset);
5174 }
5175 mLineSelectionIsOn = currLine;
5176 Selection.setSelection((Spannable) mTextView.getText(),
5177 startOffset, offset);
5178 }
Keisuke Kuroyanagi4368d052015-11-05 18:51:00 +09005179
5180 private void updateParagraphBasedSelection(MotionEvent event) {
5181 final int offset = mTextView.getOffsetForPosition(event.getX(), event.getY());
5182
5183 final int start = Math.min(offset, mStartOffset);
5184 final int end = Math.max(offset, mStartOffset);
5185 final long paragraphsRange = getParagraphsRange(start, end);
5186 final int selectionStart = TextUtils.unpackRangeStartFromLong(paragraphsRange);
5187 final int selectionEnd = TextUtils.unpackRangeEndFromLong(paragraphsRange);
5188 Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
5189 }
5190
Gilles Debunned88876a2012-03-16 17:34:04 -07005191 /**
5192 * @param event
5193 */
5194 private void updateMinAndMaxOffsets(MotionEvent event) {
5195 int pointerCount = event.getPointerCount();
5196 for (int index = 0; index < pointerCount; index++) {
5197 int offset = mTextView.getOffsetForPosition(event.getX(index), event.getY(index));
5198 if (offset < mMinTouchOffset) mMinTouchOffset = offset;
5199 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset;
5200 }
5201 }
5202
5203 public int getMinTouchOffset() {
5204 return mMinTouchOffset;
5205 }
5206
5207 public int getMaxTouchOffset() {
5208 return mMaxTouchOffset;
5209 }
5210
5211 public void resetTouchOffsets() {
5212 mMinTouchOffset = mMaxTouchOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005213 resetDragAcceleratorState();
5214 }
5215
5216 private void resetDragAcceleratorState() {
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005217 mStartOffset = -1;
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005218 mDragAcceleratorMode = DRAG_ACCELERATOR_MODE_INACTIVE;
Mady Mellorf9f8aeb2015-06-17 09:46:01 -07005219 mSwitchedLines = false;
Gilles Debunned88876a2012-03-16 17:34:04 -07005220 }
5221
5222 /**
5223 * @return true iff this controller is currently used to move the selection start.
5224 */
5225 public boolean isSelectionStartDragged() {
5226 return mStartHandle != null && mStartHandle.isDragging();
5227 }
5228
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005229 /**
5230 * @return true if the user is selecting text using the drag accelerator.
5231 */
5232 public boolean isDragAcceleratorActive() {
Keisuke Kuroyanagi97af6732015-12-04 16:56:38 -08005233 return mDragAcceleratorMode != DRAG_ACCELERATOR_MODE_INACTIVE;
Mady Mellor2ff2cd82015-03-02 10:37:01 -08005234 }
5235
Gilles Debunned88876a2012-03-16 17:34:04 -07005236 public void onTouchModeChanged(boolean isInTouchMode) {
5237 if (!isInTouchMode) {
5238 hide();
5239 }
5240 }
5241
5242 @Override
5243 public void onDetached() {
5244 final ViewTreeObserver observer = mTextView.getViewTreeObserver();
5245 observer.removeOnTouchModeChangeListener(this);
5246
5247 if (mStartHandle != null) mStartHandle.onDetached();
5248 if (mEndHandle != null) mEndHandle.onDetached();
5249 }
5250 }
5251
5252 private class CorrectionHighlighter {
5253 private final Path mPath = new Path();
Chris Craik6a49dde2015-05-12 10:28:14 -07005254 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Gilles Debunned88876a2012-03-16 17:34:04 -07005255 private int mStart, mEnd;
5256 private long mFadingStartTime;
5257 private RectF mTempRectF;
5258 private final static int FADE_OUT_DURATION = 400;
5259
5260 public CorrectionHighlighter() {
5261 mPaint.setCompatibilityScaling(mTextView.getResources().getCompatibilityInfo().
5262 applicationScale);
5263 mPaint.setStyle(Paint.Style.FILL);
5264 }
5265
5266 public void highlight(CorrectionInfo info) {
5267 mStart = info.getOffset();
5268 mEnd = mStart + info.getNewText().length();
5269 mFadingStartTime = SystemClock.uptimeMillis();
5270
5271 if (mStart < 0 || mEnd < 0) {
5272 stopAnimation();
5273 }
5274 }
5275
5276 public void draw(Canvas canvas, int cursorOffsetVertical) {
5277 if (updatePath() && updatePaint()) {
5278 if (cursorOffsetVertical != 0) {
5279 canvas.translate(0, cursorOffsetVertical);
5280 }
5281
5282 canvas.drawPath(mPath, mPaint);
5283
5284 if (cursorOffsetVertical != 0) {
5285 canvas.translate(0, -cursorOffsetVertical);
5286 }
5287 invalidate(true); // TODO invalidate cursor region only
5288 } else {
5289 stopAnimation();
5290 invalidate(false); // TODO invalidate cursor region only
5291 }
5292 }
5293
5294 private boolean updatePaint() {
5295 final long duration = SystemClock.uptimeMillis() - mFadingStartTime;
5296 if (duration > FADE_OUT_DURATION) return false;
5297
5298 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION;
5299 final int highlightColorAlpha = Color.alpha(mTextView.mHighlightColor);
5300 final int color = (mTextView.mHighlightColor & 0x00FFFFFF) +
5301 ((int) (highlightColorAlpha * coef) << 24);
5302 mPaint.setColor(color);
5303 return true;
5304 }
5305
5306 private boolean updatePath() {
5307 final Layout layout = mTextView.getLayout();
5308 if (layout == null) return false;
5309
5310 // Update in case text is edited while the animation is run
5311 final int length = mTextView.getText().length();
5312 int start = Math.min(length, mStart);
5313 int end = Math.min(length, mEnd);
5314
5315 mPath.reset();
5316 layout.getSelectionPath(start, end, mPath);
5317 return true;
5318 }
5319
5320 private void invalidate(boolean delayed) {
5321 if (mTextView.getLayout() == null) return;
5322
5323 if (mTempRectF == null) mTempRectF = new RectF();
5324 mPath.computeBounds(mTempRectF, false);
5325
5326 int left = mTextView.getCompoundPaddingLeft();
5327 int top = mTextView.getExtendedPaddingTop() + mTextView.getVerticalOffset(true);
5328
5329 if (delayed) {
5330 mTextView.postInvalidateOnAnimation(
5331 left + (int) mTempRectF.left, top + (int) mTempRectF.top,
5332 left + (int) mTempRectF.right, top + (int) mTempRectF.bottom);
5333 } else {
5334 mTextView.postInvalidate((int) mTempRectF.left, (int) mTempRectF.top,
5335 (int) mTempRectF.right, (int) mTempRectF.bottom);
5336 }
5337 }
5338
5339 private void stopAnimation() {
5340 Editor.this.mCorrectionHighlighter = null;
5341 }
5342 }
5343
5344 private static class ErrorPopup extends PopupWindow {
5345 private boolean mAbove = false;
5346 private final TextView mView;
5347 private int mPopupInlineErrorBackgroundId = 0;
5348 private int mPopupInlineErrorAboveBackgroundId = 0;
5349
5350 ErrorPopup(TextView v, int width, int height) {
5351 super(v, width, height);
5352 mView = v;
5353 // 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 -08005354 // shown and positioned. Initialized with below background, which should have
Gilles Debunned88876a2012-03-16 17:34:04 -07005355 // dimensions identical to the above version for this to work (and is more likely).
5356 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5357 com.android.internal.R.styleable.Theme_errorMessageBackground);
5358 mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
5359 }
5360
5361 void fixDirection(boolean above) {
5362 mAbove = above;
5363
5364 if (above) {
5365 mPopupInlineErrorAboveBackgroundId =
5366 getResourceId(mPopupInlineErrorAboveBackgroundId,
5367 com.android.internal.R.styleable.Theme_errorMessageAboveBackground);
5368 } else {
5369 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
5370 com.android.internal.R.styleable.Theme_errorMessageBackground);
5371 }
5372
5373 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId :
5374 mPopupInlineErrorBackgroundId);
5375 }
5376
5377 private int getResourceId(int currentId, int index) {
5378 if (currentId == 0) {
5379 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes(
5380 R.styleable.Theme);
5381 currentId = styledAttributes.getResourceId(index, 0);
5382 styledAttributes.recycle();
5383 }
5384 return currentId;
5385 }
5386
5387 @Override
5388 public void update(int x, int y, int w, int h, boolean force) {
5389 super.update(x, y, w, h, force);
5390
5391 boolean above = isAboveAnchor();
5392 if (above != mAbove) {
5393 fixDirection(above);
5394 }
5395 }
5396 }
5397
5398 static class InputContentType {
5399 int imeOptions = EditorInfo.IME_NULL;
5400 String privateImeOptions;
5401 CharSequence imeActionLabel;
5402 int imeActionId;
5403 Bundle extras;
5404 OnEditorActionListener onEditorActionListener;
5405 boolean enterDown;
Yohei Yukawad469f212016-01-21 12:38:09 -08005406 LocaleList imeHintLocales;
Gilles Debunned88876a2012-03-16 17:34:04 -07005407 }
5408
5409 static class InputMethodState {
Gilles Debunnec62589c2012-04-12 14:50:23 -07005410 ExtractedTextRequest mExtractedTextRequest;
5411 final ExtractedText mExtractedText = new ExtractedText();
Gilles Debunned88876a2012-03-16 17:34:04 -07005412 int mBatchEditNesting;
5413 boolean mCursorChanged;
5414 boolean mSelectionModeChanged;
5415 boolean mContentChanged;
5416 int mChangedStart, mChangedEnd, mChangedDelta;
5417 }
Satoshi Kataoka0e3849a2012-12-13 14:37:19 +09005418
James Cookf59152c2015-02-26 18:03:58 -08005419 /**
James Cook471559f2015-02-27 10:31:20 -08005420 * @return True iff (start, end) is a valid range within the text.
5421 */
5422 private static boolean isValidRange(CharSequence text, int start, int end) {
5423 return 0 <= start && start <= end && end <= text.length();
5424 }
5425
Seigo Nonakaa60160b2015-08-19 12:38:35 -07005426 @VisibleForTesting
5427 public SuggestionsPopupWindow getSuggestionsPopupWindowForTesting() {
5428 return mSuggestionsPopupWindow;
5429 }
5430
James Cook471559f2015-02-27 10:31:20 -08005431 /**
James Cookf59152c2015-02-26 18:03:58 -08005432 * An InputFilter that monitors text input to maintain undo history. It does not modify the
5433 * text being typed (and hence always returns null from the filter() method).
5434 */
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005435 public static class UndoInputFilter implements InputFilter {
James Cookf59152c2015-02-26 18:03:58 -08005436 private final Editor mEditor;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005437
James Cook48e0fac2015-02-25 15:44:51 -08005438 // Whether the current filter pass is directly caused by an end-user text edit.
5439 private boolean mIsUserEdit;
5440
James Cookd2026682015-03-03 14:40:14 -08005441 // Whether the text field is handling an IME composition. Must be parceled in case the user
5442 // rotates the screen during composition.
5443 private boolean mHasComposition;
James Cook48e0fac2015-02-25 15:44:51 -08005444
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005445 public UndoInputFilter(Editor editor) {
5446 mEditor = editor;
5447 }
5448
James Cookd2026682015-03-03 14:40:14 -08005449 public void saveInstanceState(Parcel parcel) {
5450 parcel.writeInt(mIsUserEdit ? 1 : 0);
5451 parcel.writeInt(mHasComposition ? 1 : 0);
5452 }
5453
5454 public void restoreInstanceState(Parcel parcel) {
5455 mIsUserEdit = parcel.readInt() != 0;
5456 mHasComposition = parcel.readInt() != 0;
5457 }
5458
James Cook48e0fac2015-02-25 15:44:51 -08005459 /**
5460 * Signals that a user-triggered edit is starting.
5461 */
5462 public void beginBatchEdit() {
5463 if (DEBUG_UNDO) Log.d(TAG, "beginBatchEdit");
5464 mIsUserEdit = true;
James Cook48e0fac2015-02-25 15:44:51 -08005465 }
5466
5467 public void endBatchEdit() {
5468 if (DEBUG_UNDO) Log.d(TAG, "endBatchEdit");
5469 mIsUserEdit = false;
5470 }
5471
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005472 @Override
5473 public CharSequence filter(CharSequence source, int start, int end,
5474 Spanned dest, int dstart, int dend) {
5475 if (DEBUG_UNDO) {
James Cook471559f2015-02-27 10:31:20 -08005476 Log.d(TAG, "filter: source=" + source + " (" + start + "-" + end + ") " +
5477 "dest=" + dest + " (" + dstart + "-" + dend + ")");
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005478 }
James Cookf1dad1e2015-02-27 11:00:01 -08005479
James Cook48e0fac2015-02-25 15:44:51 -08005480 // Check to see if this edit should be tracked for undo.
5481 if (!canUndoEdit(source, start, end, dest, dstart, dend)) {
James Cookf1dad1e2015-02-27 11:00:01 -08005482 return null;
5483 }
5484
James Cookd2026682015-03-03 14:40:14 -08005485 // Check for and handle IME composition edits.
5486 if (handleCompositionEdit(source, start, end, dstart)) {
5487 return null;
5488 }
5489
5490 // Handle keyboard edits.
5491 handleKeyboardEdit(source, start, end, dest, dstart, dend);
5492 return null;
5493 }
5494
5495 /**
5496 * Returns true iff the edit was handled, either because it should be ignored or because
5497 * this function created an undo operation for it.
5498 */
5499 private boolean handleCompositionEdit(CharSequence source, int start, int end, int dstart) {
5500 // Ignore edits while the user is composing.
5501 if (isComposition(source)) {
5502 mHasComposition = true;
5503 return true;
5504 }
5505 final boolean hadComposition = mHasComposition;
5506 mHasComposition = false;
5507
5508 // Check for the transition out of the composing state.
5509 if (hadComposition) {
5510 // If there was no text the user canceled composition. Ignore the edit.
5511 if (start == end) {
5512 return true;
5513 }
5514
5515 // Otherwise the user inserted the composition.
5516 String newText = TextUtils.substring(source, start, end);
James Cook22054252015-03-25 14:04:01 -07005517 EditOperation edit = new EditOperation(mEditor, "", dstart, newText);
5518 recordEdit(edit, false /* forceMerge */);
James Cookd2026682015-03-03 14:40:14 -08005519 return true;
5520 }
5521
5522 // This was neither a composition event nor a transition out of composing.
5523 return false;
5524 }
5525
5526 private void handleKeyboardEdit(CharSequence source, int start, int end,
5527 Spanned dest, int dstart, int dend) {
James Cook48e0fac2015-02-25 15:44:51 -08005528 // An application may install a TextWatcher to provide additional modifications after
5529 // the initial input filters run (e.g. a credit card formatter that adds spaces to a
5530 // string). This results in multiple filter() calls for what the user considers to be
5531 // a single operation. Always undo the whole set of changes in one step.
James Cookd2026682015-03-03 14:40:14 -08005532 final boolean forceMerge = isInTextWatcher();
James Cook471559f2015-02-27 10:31:20 -08005533
5534 // Build a new operation with all the information from this edit.
James Cookd2026682015-03-03 14:40:14 -08005535 String newText = TextUtils.substring(source, start, end);
5536 String oldText = TextUtils.substring(dest, dstart, dend);
James Cook22054252015-03-25 14:04:01 -07005537 EditOperation edit = new EditOperation(mEditor, oldText, dstart, newText);
5538 recordEdit(edit, forceMerge);
James Cookd2026682015-03-03 14:40:14 -08005539 }
James Cook471559f2015-02-27 10:31:20 -08005540
James Cook22054252015-03-25 14:04:01 -07005541 /**
5542 * Fetches the last undo operation and checks to see if a new edit should be merged into it.
5543 * If forceMerge is true then the new edit is always merged.
5544 */
5545 private void recordEdit(EditOperation edit, boolean forceMerge) {
James Cook471559f2015-02-27 10:31:20 -08005546 // Fetch the last edit operation and attempt to merge in the new edit.
James Cook48e0fac2015-02-25 15:44:51 -08005547 final UndoManager um = mEditor.mUndoManager;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005548 um.beginUpdate("Edit text");
James Cook471559f2015-02-27 10:31:20 -08005549 EditOperation lastEdit = um.getLastOperation(
5550 EditOperation.class, mEditor.mUndoOwner, UndoManager.MERGE_MODE_UNIQUE);
5551 if (lastEdit == null) {
5552 // Add this as the first edit.
5553 if (DEBUG_UNDO) Log.d(TAG, "filter: adding first op " + edit);
5554 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook22054252015-03-25 14:04:01 -07005555 } else if (forceMerge) {
5556 // Forced merges take priority because they could be the result of a non-user-edit
5557 // change and this case should not create a new undo operation.
5558 if (DEBUG_UNDO) Log.d(TAG, "filter: force merge " + edit);
5559 lastEdit.forceMergeWith(edit);
James Cook48e0fac2015-02-25 15:44:51 -08005560 } else if (!mIsUserEdit) {
5561 // An application directly modified the Editable outside of a text edit. Treat this
5562 // as a new change and don't attempt to merge.
5563 if (DEBUG_UNDO) Log.d(TAG, "non-user edit, new op " + edit);
5564 um.commitState(mEditor.mUndoOwner);
5565 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook471559f2015-02-27 10:31:20 -08005566 } else if (lastEdit.mergeWith(edit)) {
5567 // Merge succeeded, nothing else to do.
5568 if (DEBUG_UNDO) Log.d(TAG, "filter: merge succeeded, created " + lastEdit);
James Cook3ac0bcb2015-02-26 10:53:41 -08005569 } else {
James Cook471559f2015-02-27 10:31:20 -08005570 // Could not merge with the last edit, so commit the last edit and add this edit.
5571 if (DEBUG_UNDO) Log.d(TAG, "filter: merge failed, adding " + edit);
5572 um.commitState(mEditor.mUndoOwner);
5573 um.addOperation(edit, UndoManager.MERGE_MODE_NONE);
James Cook3ac0bcb2015-02-26 10:53:41 -08005574 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005575 um.endUpdate();
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005576 }
James Cook48e0fac2015-02-25 15:44:51 -08005577
5578 private boolean canUndoEdit(CharSequence source, int start, int end,
5579 Spanned dest, int dstart, int dend) {
5580 if (!mEditor.mAllowUndo) {
5581 if (DEBUG_UNDO) Log.d(TAG, "filter: undo is disabled");
5582 return false;
5583 }
5584
5585 if (mEditor.mUndoManager.isInUndo()) {
5586 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping, currently performing undo/redo");
5587 return false;
5588 }
5589
5590 // Text filters run before input operations are applied. However, some input operations
5591 // are invalid and will throw exceptions when applied. This is common in tests. Don't
5592 // attempt to undo invalid operations.
5593 if (!isValidRange(source, start, end) || !isValidRange(dest, dstart, dend)) {
5594 if (DEBUG_UNDO) Log.d(TAG, "filter: invalid op");
5595 return false;
5596 }
5597
5598 // Earlier filters can rewrite input to be a no-op, for example due to a length limit
5599 // on an input field. Skip no-op changes.
5600 if (start == end && dstart == dend) {
5601 if (DEBUG_UNDO) Log.d(TAG, "filter: skipping no-op");
5602 return false;
5603 }
5604
5605 return true;
5606 }
James Cookd2026682015-03-03 14:40:14 -08005607
5608 private boolean isComposition(CharSequence source) {
5609 if (!(source instanceof Spannable)) {
5610 return false;
5611 }
5612 // This is a composition edit if the source has a non-zero-length composing span.
5613 Spannable text = (Spannable) source;
5614 int composeBegin = EditableInputConnection.getComposingSpanStart(text);
5615 int composeEnd = EditableInputConnection.getComposingSpanEnd(text);
5616 return composeBegin < composeEnd;
5617 }
5618
5619 private boolean isInTextWatcher() {
5620 CharSequence text = mEditor.mTextView.getText();
5621 return (text instanceof SpannableStringBuilder)
5622 && ((SpannableStringBuilder) text).getTextWatcherDepth() > 0;
5623 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005624 }
5625
James Cookf59152c2015-02-26 18:03:58 -08005626 /**
5627 * An operation to undo a single "edit" to a text view.
5628 */
James Cook471559f2015-02-27 10:31:20 -08005629 public static class EditOperation extends UndoOperation<Editor> {
5630 private static final int TYPE_INSERT = 0;
5631 private static final int TYPE_DELETE = 1;
5632 private static final int TYPE_REPLACE = 2;
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005633
James Cook471559f2015-02-27 10:31:20 -08005634 private int mType;
5635 private String mOldText;
5636 private int mOldTextStart;
5637 private String mNewText;
5638 private int mNewTextStart;
5639
5640 private int mOldCursorPos;
5641 private int mNewCursorPos;
5642
5643 /**
James Cookd2026682015-03-03 14:40:14 -08005644 * Constructs an edit operation from a text input operation on editor that replaces the
James Cook22054252015-03-25 14:04:01 -07005645 * oldText starting at dstart with newText.
James Cook471559f2015-02-27 10:31:20 -08005646 */
James Cook22054252015-03-25 14:04:01 -07005647 public EditOperation(Editor editor, String oldText, int dstart, String newText) {
James Cook471559f2015-02-27 10:31:20 -08005648 super(editor.mUndoOwner);
James Cookd2026682015-03-03 14:40:14 -08005649 mOldText = oldText;
5650 mNewText = newText;
James Cook471559f2015-02-27 10:31:20 -08005651
5652 // Determine the type of the edit and store where it occurred. Avoid storing
5653 // irrevelant data (e.g. mNewTextStart for a delete) because that makes the
5654 // merging logic more complex (e.g. merging deletes could lead to mNewTextStart being
5655 // outside the bounds of the final text).
5656 if (mNewText.length() > 0 && mOldText.length() == 0) {
5657 mType = TYPE_INSERT;
5658 mNewTextStart = dstart;
5659 } else if (mNewText.length() == 0 && mOldText.length() > 0) {
5660 mType = TYPE_DELETE;
5661 mOldTextStart = dstart;
5662 } else {
5663 mType = TYPE_REPLACE;
5664 mOldTextStart = mNewTextStart = dstart;
5665 }
5666
5667 // Store cursor data.
5668 mOldCursorPos = editor.mTextView.getSelectionStart();
James Cookd2026682015-03-03 14:40:14 -08005669 mNewCursorPos = dstart + mNewText.length();
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005670 }
5671
James Cook471559f2015-02-27 10:31:20 -08005672 public EditOperation(Parcel src, ClassLoader loader) {
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005673 super(src, loader);
James Cook471559f2015-02-27 10:31:20 -08005674 mType = src.readInt();
5675 mOldText = src.readString();
5676 mOldTextStart = src.readInt();
5677 mNewText = src.readString();
5678 mNewTextStart = src.readInt();
5679 mOldCursorPos = src.readInt();
5680 mNewCursorPos = src.readInt();
5681 }
5682
5683 @Override
5684 public void writeToParcel(Parcel dest, int flags) {
5685 dest.writeInt(mType);
5686 dest.writeString(mOldText);
5687 dest.writeInt(mOldTextStart);
5688 dest.writeString(mNewText);
5689 dest.writeInt(mNewTextStart);
5690 dest.writeInt(mOldCursorPos);
5691 dest.writeInt(mNewCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005692 }
5693
James Cook48e0fac2015-02-25 15:44:51 -08005694 private int getNewTextEnd() {
5695 return mNewTextStart + mNewText.length();
5696 }
5697
5698 private int getOldTextEnd() {
5699 return mOldTextStart + mOldText.length();
5700 }
5701
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005702 @Override
5703 public void commit() {
5704 }
5705
5706 @Override
5707 public void undo() {
James Cook471559f2015-02-27 10:31:20 -08005708 if (DEBUG_UNDO) Log.d(TAG, "undo");
5709 // Remove the new text and insert the old.
James Cook48e0fac2015-02-25 15:44:51 -08005710 Editor editor = getOwnerData();
5711 Editable text = (Editable) editor.mTextView.getText();
5712 modifyText(text, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5713 mOldCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005714 }
5715
5716 @Override
5717 public void redo() {
James Cook471559f2015-02-27 10:31:20 -08005718 if (DEBUG_UNDO) Log.d(TAG, "redo");
5719 // Remove the old text and insert the new.
James Cook48e0fac2015-02-25 15:44:51 -08005720 Editor editor = getOwnerData();
5721 Editable text = (Editable) editor.mTextView.getText();
5722 modifyText(text, mOldTextStart, getOldTextEnd(), mNewText, mNewTextStart,
5723 mNewCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005724 }
5725
James Cook471559f2015-02-27 10:31:20 -08005726 /**
5727 * Attempts to merge this existing operation with a new edit.
5728 * @param edit The new edit operation.
5729 * @return If the merge succeeded, returns true. Otherwise returns false and leaves this
5730 * object unchanged.
5731 */
5732 private boolean mergeWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005733 if (DEBUG_UNDO) {
5734 Log.d(TAG, "mergeWith old " + this);
5735 Log.d(TAG, "mergeWith new " + edit);
5736 }
James Cook471559f2015-02-27 10:31:20 -08005737 switch (mType) {
5738 case TYPE_INSERT:
5739 return mergeInsertWith(edit);
5740 case TYPE_DELETE:
5741 return mergeDeleteWith(edit);
5742 case TYPE_REPLACE:
5743 return mergeReplaceWith(edit);
5744 default:
5745 return false;
5746 }
5747 }
5748
5749 private boolean mergeInsertWith(EditOperation edit) {
James Cook471559f2015-02-27 10:31:20 -08005750 // Only merge continuous insertions.
5751 if (edit.mType != TYPE_INSERT) {
5752 return false;
5753 }
5754 // Only merge insertions that are contiguous.
5755 if (getNewTextEnd() != edit.mNewTextStart) {
5756 return false;
5757 }
5758 mNewText += edit.mNewText;
5759 mNewCursorPos = edit.mNewCursorPos;
5760 return true;
5761 }
5762
5763 // TODO: Support forward delete.
5764 private boolean mergeDeleteWith(EditOperation edit) {
James Cook471559f2015-02-27 10:31:20 -08005765 // Only merge continuous deletes.
5766 if (edit.mType != TYPE_DELETE) {
5767 return false;
5768 }
5769 // Only merge deletions that are contiguous.
5770 if (mOldTextStart != edit.getOldTextEnd()) {
5771 return false;
5772 }
5773 mOldTextStart = edit.mOldTextStart;
5774 mOldText = edit.mOldText + mOldText;
5775 mNewCursorPos = edit.mNewCursorPos;
5776 return true;
5777 }
5778
5779 private boolean mergeReplaceWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005780 // Replacements can merge only with adjacent inserts.
5781 if (edit.mType != TYPE_INSERT || getNewTextEnd() != edit.mNewTextStart) {
James Cook471559f2015-02-27 10:31:20 -08005782 return false;
5783 }
5784 mOldText += edit.mOldText;
5785 mNewText += edit.mNewText;
5786 mNewCursorPos = edit.mNewCursorPos;
5787 return true;
5788 }
5789
James Cook48e0fac2015-02-25 15:44:51 -08005790 /**
5791 * Forcibly creates a single merged edit operation by simulating the entire text
5792 * contents being replaced.
5793 */
James Cook22054252015-03-25 14:04:01 -07005794 public void forceMergeWith(EditOperation edit) {
James Cook48e0fac2015-02-25 15:44:51 -08005795 if (DEBUG_UNDO) Log.d(TAG, "forceMerge");
James Cookf59152c2015-02-26 18:03:58 -08005796 Editor editor = getOwnerData();
James Cook48e0fac2015-02-25 15:44:51 -08005797
5798 // Copy the text of the current field.
5799 // NOTE: Using StringBuilder instead of SpannableStringBuilder would be somewhat faster,
5800 // but would require two parallel implementations of modifyText() because Editable and
5801 // StringBuilder do not share an interface for replace/delete/insert.
5802 Editable editable = (Editable) editor.mTextView.getText();
5803 Editable originalText = new SpannableStringBuilder(editable.toString());
5804
5805 // Roll back the last operation.
5806 modifyText(originalText, mNewTextStart, getNewTextEnd(), mOldText, mOldTextStart,
5807 mOldCursorPos);
5808
5809 // Clone the text again and apply the new operation.
5810 Editable finalText = new SpannableStringBuilder(editable.toString());
5811 modifyText(finalText, edit.mOldTextStart, edit.getOldTextEnd(), edit.mNewText,
5812 edit.mNewTextStart, edit.mNewCursorPos);
5813
5814 // Convert this operation into a non-mergeable replacement of the entire string.
5815 mType = TYPE_REPLACE;
5816 mNewText = finalText.toString();
5817 mNewTextStart = 0;
5818 mOldText = originalText.toString();
5819 mOldTextStart = 0;
5820 mNewCursorPos = edit.mNewCursorPos;
5821 // mOldCursorPos is unchanged.
5822 }
5823
5824 private static void modifyText(Editable text, int deleteFrom, int deleteTo,
5825 CharSequence newText, int newTextInsertAt, int newCursorPos) {
James Cook471559f2015-02-27 10:31:20 -08005826 // Apply the edit if it is still valid.
5827 if (isValidRange(text, deleteFrom, deleteTo) &&
5828 newTextInsertAt <= text.length() - (deleteTo - deleteFrom)) {
5829 if (deleteFrom != deleteTo) {
5830 text.delete(deleteFrom, deleteTo);
5831 }
5832 if (newText.length() != 0) {
5833 text.insert(newTextInsertAt, newText);
5834 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005835 }
James Cook900185d2015-03-10 09:48:11 -07005836 // Restore the cursor position. If there wasn't an old cursor (newCursorPos == -1) then
5837 // don't explicitly set it and rely on SpannableStringBuilder to position it.
James Cook471559f2015-02-27 10:31:20 -08005838 // TODO: Select all the text that was undone.
James Cook900185d2015-03-10 09:48:11 -07005839 if (0 <= newCursorPos && newCursorPos <= text.length()) {
James Cook471559f2015-02-27 10:31:20 -08005840 Selection.setSelection(text, newCursorPos);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005841 }
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005842 }
5843
James Cook48e0fac2015-02-25 15:44:51 -08005844 private String getTypeString() {
5845 switch (mType) {
5846 case TYPE_INSERT:
5847 return "insert";
5848 case TYPE_DELETE:
5849 return "delete";
5850 case TYPE_REPLACE:
5851 return "replace";
5852 default:
5853 return "";
5854 }
5855 }
5856
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005857 @Override
James Cook471559f2015-02-27 10:31:20 -08005858 public String toString() {
James Cook48e0fac2015-02-25 15:44:51 -08005859 return "[mType=" + getTypeString() + ", " +
James Cook471559f2015-02-27 10:31:20 -08005860 "mOldText=" + mOldText + ", " +
5861 "mOldTextStart=" + mOldTextStart + ", " +
5862 "mNewText=" + mNewText + ", " +
5863 "mNewTextStart=" + mNewTextStart + ", " +
5864 "mOldCursorPos=" + mOldCursorPos + ", " +
5865 "mNewCursorPos=" + mNewCursorPos + "]";
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005866 }
5867
James Cook471559f2015-02-27 10:31:20 -08005868 public static final Parcelable.ClassLoaderCreator<EditOperation> CREATOR
5869 = new Parcelable.ClassLoaderCreator<EditOperation>() {
James Cookf59152c2015-02-26 18:03:58 -08005870 @Override
James Cook471559f2015-02-27 10:31:20 -08005871 public EditOperation createFromParcel(Parcel in) {
5872 return new EditOperation(in, null);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005873 }
5874
James Cookf59152c2015-02-26 18:03:58 -08005875 @Override
James Cook471559f2015-02-27 10:31:20 -08005876 public EditOperation createFromParcel(Parcel in, ClassLoader loader) {
5877 return new EditOperation(in, loader);
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005878 }
5879
James Cookf59152c2015-02-26 18:03:58 -08005880 @Override
James Cook471559f2015-02-27 10:31:20 -08005881 public EditOperation[] newArray(int size) {
5882 return new EditOperation[size];
Dianne Hackborn3aa49b62013-04-26 16:39:17 -07005883 }
5884 };
5885 }
Abodunrinwa Tokideaf0db2015-06-26 18:21:30 -07005886
5887 /**
5888 * A helper for enabling and handling "PROCESS_TEXT" menu actions.
5889 * These allow external applications to plug into currently selected text.
5890 */
5891 static final class ProcessTextIntentActionsHandler {
5892
5893 private final Editor mEditor;
5894 private final TextView mTextView;
5895 private final PackageManager mPackageManager;
5896 private final SparseArray<Intent> mAccessibilityIntents = new SparseArray<Intent>();
5897 private final SparseArray<AccessibilityNodeInfo.AccessibilityAction> mAccessibilityActions
5898 = new SparseArray<AccessibilityNodeInfo.AccessibilityAction>();
5899
5900 private ProcessTextIntentActionsHandler(Editor editor) {
5901 mEditor = Preconditions.checkNotNull(editor);
5902 mTextView = Preconditions.checkNotNull(mEditor.mTextView);
5903 mPackageManager = Preconditions.checkNotNull(
5904 mTextView.getContext().getPackageManager());
5905 }
5906
5907 /**
5908 * Adds "PROCESS_TEXT" menu items to the specified menu.
5909 */
5910 public void onInitializeMenu(Menu menu) {
5911 int i = 0;
5912 for (ResolveInfo resolveInfo : getSupportedActivities()) {
5913 menu.add(Menu.NONE, Menu.NONE,
5914 Editor.MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START + i++,
5915 getLabel(resolveInfo))
5916 .setIntent(createProcessTextIntentForResolveInfo(resolveInfo))
5917 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
5918 }
5919 }
5920
5921 /**
5922 * Performs a "PROCESS_TEXT" action if there is one associated with the specified
5923 * menu item.
5924 *
5925 * @return True if the action was performed, false otherwise.
5926 */
5927 public boolean performMenuItemAction(MenuItem item) {
5928 return fireIntent(item.getIntent());
5929 }
5930
5931 /**
5932 * Initializes and caches "PROCESS_TEXT" accessibility actions.
5933 */
5934 public void initializeAccessibilityActions() {
5935 mAccessibilityIntents.clear();
5936 mAccessibilityActions.clear();
5937 int i = 0;
5938 for (ResolveInfo resolveInfo : getSupportedActivities()) {
5939 int actionId = TextView.ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID + i++;
5940 mAccessibilityActions.put(
5941 actionId,
5942 new AccessibilityNodeInfo.AccessibilityAction(
5943 actionId, getLabel(resolveInfo)));
5944 mAccessibilityIntents.put(
5945 actionId, createProcessTextIntentForResolveInfo(resolveInfo));
5946 }
5947 }
5948
5949 /**
5950 * Adds "PROCESS_TEXT" accessibility actions to the specified accessibility node info.
5951 * NOTE: This needs a prior call to {@link #initializeAccessibilityActions()} to make the
5952 * latest accessibility actions available for this call.
5953 */
5954 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo) {
5955 for (int i = 0; i < mAccessibilityActions.size(); i++) {
5956 nodeInfo.addAction(mAccessibilityActions.valueAt(i));
5957 }
5958 }
5959
5960 /**
5961 * Performs a "PROCESS_TEXT" action if there is one associated with the specified
5962 * accessibility action id.
5963 *
5964 * @return True if the action was performed, false otherwise.
5965 */
5966 public boolean performAccessibilityAction(int actionId) {
5967 return fireIntent(mAccessibilityIntents.get(actionId));
5968 }
5969
5970 private boolean fireIntent(Intent intent) {
5971 if (intent != null && Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) {
5972 intent.putExtra(Intent.EXTRA_PROCESS_TEXT, mTextView.getSelectedText());
5973 mEditor.mPreserveDetachedSelection = true;
5974 mTextView.startActivityForResult(intent, TextView.PROCESS_TEXT_REQUEST_CODE);
5975 return true;
5976 }
5977 return false;
5978 }
5979
5980 private List<ResolveInfo> getSupportedActivities() {
5981 PackageManager packageManager = mTextView.getContext().getPackageManager();
5982 return packageManager.queryIntentActivities(createProcessTextIntent(), 0);
5983 }
5984
5985 private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) {
5986 return createProcessTextIntent()
5987 .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, !mTextView.isTextEditable())
5988 .setClassName(info.activityInfo.packageName, info.activityInfo.name);
5989 }
5990
5991 private Intent createProcessTextIntent() {
5992 return new Intent()
5993 .setAction(Intent.ACTION_PROCESS_TEXT)
5994 .setType("text/plain");
5995 }
5996
5997 private CharSequence getLabel(ResolveInfo resolveInfo) {
5998 return resolveInfo.loadLabel(mPackageManager);
5999 }
6000 }
Gilles Debunned88876a2012-03-16 17:34:04 -07006001}