This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
Editor.java
8325 lines (7347 loc) · 347 KB
/
Editor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import static android.view.ContentInfo.SOURCE_DRAG_AND_DROP;
import static android.widget.TextView.ACCESSIBILITY_ACTION_SMART_START_ID;
import static com.android.graphics.hwui.flags.Flags.highContrastTextSmallTextRect;
import android.R;
import android.animation.ValueAnimator;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AppGlobals;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.RemoteAction;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.UndoManager;
import android.content.UndoOperation;
import android.content.UndoOwner;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.RecordingCanvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.RenderNode;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.ParcelableParcel;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.DynamicLayout;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Layout;
import android.text.ParcelableSpan;
import android.text.Selection;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.StaticLayout;
import android.text.TextFlags;
import android.text.TextUtils;
import android.text.method.InsertModeTransformationMethod;
import android.text.method.KeyListener;
import android.text.method.MetaKeyKeyListener;
import android.text.method.MovementMethod;
import android.text.method.OffsetMapping;
import android.text.method.TransformationMethod;
import android.text.method.WordIterator;
import android.text.style.EasyEditSpan;
import android.text.style.SuggestionRangeSpan;
import android.text.style.SuggestionSpan;
import android.text.style.TextAppearanceSpan;
import android.text.style.URLSpan;
import android.util.ArraySet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.ContentInfo;
import android.view.ContextMenu;
import android.view.ContextThemeWrapper;
import android.view.DragAndDropPermissions;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OnReceiveContentListener;
import android.view.SubMenu;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.ViewRootImpl;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.CursorAnchorInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.view.textclassifier.TextClassification;
import android.view.textclassifier.TextClassificationManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.Drawables;
import android.widget.TextView.OnEditorActionListener;
import android.window.OnBackInvokedCallback;
import android.window.OnBackInvokedDispatcher;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.graphics.ColorUtils;
import com.android.internal.inputmethod.EditableInputConnection;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.GrowingArrayUtils;
import com.android.internal.util.Preconditions;
import com.android.internal.view.FloatingActionMode;
import com.android.text.flags.Flags;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Helper class used by TextView to handle editable text views.
*
* @hide
*/
public class Editor {
private static final String TAG = "Editor";
private static final boolean DEBUG_UNDO = false;
// Specifies whether to use the magnifier when pressing the insertion or selection handles.
private static final boolean FLAG_USE_MAGNIFIER = true;
// Specifies how far to make the cursor start float when drag the cursor away from the
// beginning or end of the line.
private static final int CURSOR_START_FLOAT_DISTANCE_PX = 20;
private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000;
private static final int RECENT_CUT_COPY_DURATION_MS = 15 * 1000; // 15 seconds in millis
static final int BLINK = 500;
private static final int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
private static final int UNSET_X_VALUE = -1;
private static final int UNSET_LINE = -1;
// Tag used when the Editor maintains its own separate UndoManager.
private static final String UNDO_OWNER_TAG = "Editor";
// Ordering constants used to place the Action Mode items in their menu.
private static final int ACTION_MODE_MENU_ITEM_ORDER_ASSIST = 0;
private static final int ACTION_MODE_MENU_ITEM_ORDER_CUT = 4;
private static final int ACTION_MODE_MENU_ITEM_ORDER_COPY = 5;
private static final int ACTION_MODE_MENU_ITEM_ORDER_PASTE = 6;
private static final int ACTION_MODE_MENU_ITEM_ORDER_SHARE = 7;
private static final int ACTION_MODE_MENU_ITEM_ORDER_SELECT_ALL = 8;
private static final int ACTION_MODE_MENU_ITEM_ORDER_REPLACE = 9;
private static final int ACTION_MODE_MENU_ITEM_ORDER_AUTOFILL = 10;
private static final int ACTION_MODE_MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 11;
private static final int ACTION_MODE_MENU_ITEM_ORDER_SECONDARY_ASSIST_ACTIONS_START = 50;
private static final int ACTION_MODE_MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 100;
private static final int CONTEXT_MENU_ITEM_ORDER_REPLACE = 11;
private static final int CONTEXT_MENU_GROUP_UNDO_REDO = Menu.FIRST;
private static final int CONTEXT_MENU_GROUP_CLIPBOARD = Menu.FIRST + 1;
private static final int CONTEXT_MENU_GROUP_MISC = Menu.FIRST + 2;
private static final int FLAG_MISSPELLED_OR_GRAMMAR_ERROR =
SuggestionSpan.FLAG_MISSPELLED | SuggestionSpan.FLAG_GRAMMAR_ERROR;
@IntDef({MagnifierHandleTrigger.SELECTION_START,
MagnifierHandleTrigger.SELECTION_END,
MagnifierHandleTrigger.INSERTION})
@Retention(RetentionPolicy.SOURCE)
private @interface MagnifierHandleTrigger {
int INSERTION = 0;
int SELECTION_START = 1;
int SELECTION_END = 2;
}
@IntDef({TextActionMode.SELECTION, TextActionMode.INSERTION, TextActionMode.TEXT_LINK})
@interface TextActionMode {
int SELECTION = 0;
int INSERTION = 1;
int TEXT_LINK = 2;
}
// Default content insertion handler.
private final TextViewOnReceiveContentListener mDefaultOnReceiveContentListener =
new TextViewOnReceiveContentListener();
// Each Editor manages its own undo stack.
private final UndoManager mUndoManager = new UndoManager();
private UndoOwner mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
final UndoInputFilter mUndoInputFilter = new UndoInputFilter(this);
boolean mAllowUndo = true;
private final MetricsLogger mMetricsLogger = new MetricsLogger();
// Cursor Controllers.
InsertionPointCursorController mInsertionPointCursorController;
SelectionModifierCursorController mSelectionModifierCursorController;
// Action mode used when text is selected or when actions on an insertion cursor are triggered.
private ActionMode mTextActionMode;
@UnsupportedAppUsage
private boolean mInsertionControllerEnabled;
@UnsupportedAppUsage
private boolean mSelectionControllerEnabled;
private final boolean mHapticTextHandleEnabled;
/** Handles OnBackInvokedCallback back dispatch */
private final OnBackInvokedCallback mBackCallback = this::stopTextActionMode;
private boolean mBackCallbackRegistered;
@Nullable
private MagnifierMotionAnimator mMagnifierAnimator;
private final Runnable mUpdateMagnifierRunnable = new Runnable() {
@Override
public void run() {
mMagnifierAnimator.update();
}
};
// Update the magnifier contents whenever anything in the view hierarchy is updated.
// Note: this only captures UI thread-visible changes, so it's a known issue that an animating
// VectorDrawable or Ripple animation will not trigger capture, since they're owned by
// RenderThread.
private final ViewTreeObserver.OnDrawListener mMagnifierOnDrawListener =
new ViewTreeObserver.OnDrawListener() {
@Override
public void onDraw() {
if (mMagnifierAnimator != null) {
// Posting the method will ensure that updating the magnifier contents will
// happen right after the rendering of the current frame.
mTextView.post(mUpdateMagnifierRunnable);
}
}
};
// Used to highlight a word when it is corrected by the IME
private CorrectionHighlighter mCorrectionHighlighter;
/**
* {@code true} when {@link TextView#setText(CharSequence, TextView.BufferType, boolean, int)}
* is being executed and {@link InputMethodManager#restartInput(View)} is scheduled to be
* called.
*
* <p>This is also used to avoid an unnecessary invocation of
* {@link InputMethodManager#updateSelection(View, int, int, int, int)} when
* {@link InputMethodManager#restartInput(View)} is scheduled to be called already
* See bug 186582769 for details.</p>
*
* <p>TODO(186582769): Come up with better way.</p>
*/
private boolean mHasPendingRestartInputForSetText = false;
InputContentType mInputContentType;
InputMethodState mInputMethodState;
private static class TextRenderNode {
// Render node has 3 recording states:
// 1. Recorded operations are valid.
// #needsRecord() returns false, but needsToBeShifted is false.
// 2. Recorded operations are not valid, but just the position needed to be updated.
// #needsRecord() returns false, but needsToBeShifted is true.
// 3. Recorded operations are not valid. Need to record operations. #needsRecord() returns
// true.
RenderNode renderNode;
boolean isDirty;
// Becomes true when recorded operations can be reused, but the position has to be updated.
boolean needsToBeShifted;
public TextRenderNode(String name) {
renderNode = RenderNode.create(name, null);
isDirty = true;
needsToBeShifted = true;
}
boolean needsRecord() {
return isDirty || !renderNode.hasDisplayList();
}
}
private TextRenderNode[] mTextRenderNodes;
boolean mFrozenWithFocus;
boolean mSelectionMoved;
boolean mTouchFocusSelected;
KeyListener mKeyListener;
int mInputType = EditorInfo.TYPE_NULL;
boolean mDiscardNextActionUp;
boolean mIgnoreActionUpEvent;
/**
* To set a custom cursor, you should use {@link TextView#setTextCursorDrawable(Drawable)}
* or {@link TextView#setTextCursorDrawable(int)}.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private long mShowCursor;
private boolean mRenderCursorRegardlessTiming;
private Blink mBlink;
// Whether to let magnifier draw cursor on its surface. This is for floating cursor effect.
// And it can only be true when |mNewMagnifierEnabled| is true.
private boolean mDrawCursorOnMagnifier;
boolean mCursorVisible = true;
boolean mSelectAllOnFocus;
boolean mTextIsSelectable;
CharSequence mError;
boolean mErrorWasChanged;
private ErrorPopup mErrorPopup;
/**
* This flag is set if the TextView tries to display an error before it
* is attached to the window (so its position is still unknown).
* It causes the error to be shown later, when onAttachedToWindow()
* is called.
*/
private boolean mShowErrorAfterAttach;
boolean mInBatchEditControllers;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
boolean mShowSoftInputOnFocus = true;
private boolean mPreserveSelection;
private boolean mRestartActionModeOnNextRefresh;
private boolean mRequestingLinkActionMode;
private SelectionActionModeHelper mSelectionActionModeHelper;
boolean mIsBeingLongClicked;
boolean mIsBeingLongClickedByAccessibility;
private SuggestionsPopupWindow mSuggestionsPopupWindow;
SuggestionRangeSpan mSuggestionRangeSpan;
private Runnable mShowSuggestionRunnable;
Drawable mDrawableForCursor = null;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Drawable mSelectHandleLeft;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Drawable mSelectHandleRight;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Drawable mSelectHandleCenter;
// Global listener that detects changes in the global position of the TextView
private PositionListener mPositionListener;
private float mContextMenuAnchorX, mContextMenuAnchorY;
Callback mCustomSelectionActionModeCallback;
Callback mCustomInsertionActionModeCallback;
// Set when this TextView gained focus with some text selected. Will start selection mode.
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
boolean mCreatedWithASelection;
// The button state as of the last time #onTouchEvent is called.
private int mLastButtonState;
private final EditorTouchState mTouchState = new EditorTouchState();
private Runnable mInsertionActionModeRunnable;
// The span controller helps monitoring the changes to which the Editor needs to react:
// - EasyEditSpans, for which we have some UI to display on attach and on hide
// - SelectionSpans, for which we need to call updateSelection if an IME is attached
private SpanController mSpanController;
private WordIterator mWordIterator;
SpellChecker mSpellChecker;
// This word iterator is set with text and used to determine word boundaries
// when a user is selecting text.
private WordIterator mWordIteratorWithText;
// Indicate that the text in the word iterator needs to be updated.
private boolean mUpdateWordIteratorText;
private Rect mTempRect;
private final TextView mTextView;
final ProcessTextIntentActionsHandler mProcessTextIntentActionsHandler;
private final CursorAnchorInfoNotifier mCursorAnchorInfoNotifier =
new CursorAnchorInfoNotifier();
private final Runnable mShowFloatingToolbar = new Runnable() {
@Override
public void run() {
if (mTextActionMode != null) {
mTextActionMode.hide(0); // hide off.
}
}
};
boolean mIsInsertionActionModeStartPending = false;
private final SuggestionHelper mSuggestionHelper = new SuggestionHelper();
private boolean mFlagCursorDragFromAnywhereEnabled;
private float mCursorDragDirectionMinXYRatio;
private boolean mFlagInsertionHandleGesturesEnabled;
// Specifies whether the new magnifier (with fish-eye effect) is enabled.
private final boolean mNewMagnifierEnabled;
// Line height range in DP for the new magnifier.
static private final int MIN_LINE_HEIGHT_FOR_MAGNIFIER = 20;
static private final int MAX_LINE_HEIGHT_FOR_MAGNIFIER = 32;
// Line height range in pixels for the new magnifier.
// - If the line height is bigger than the max, magnifier should be dismissed.
// - If the line height is smaller than the min, magnifier should apply a bigger zoom factor
// to make sure the text can be seen clearly.
private int mMinLineHeightForMagnifier;
private int mMaxLineHeightForMagnifier;
// The zoom factor initially configured.
// The actual zoom value may changes based on this initial zoom value.
private float mInitialZoom = 1f;
// For calculating the line change slops while moving cursor/selection.
// The slop value as ratio of the current line height. It indicates the tolerant distance to
// avoid the cursor jumps to upper/lower line when the hit point is moving vertically out of
// the current line.
private final float mLineSlopRatio;
// The slop max/min value include line height and the slop on the upper/lower line.
private static final int LINE_CHANGE_SLOP_MAX_DP = 45;
private static final int LINE_CHANGE_SLOP_MIN_DP = 8;
private int mLineChangeSlopMax;
private int mLineChangeSlopMin;
private boolean mUseNewContextMenu;
private final AccessibilitySmartActions mA11ySmartActions;
private InsertModeController mInsertModeController;
Editor(TextView textView) {
mTextView = textView;
// Synchronize the filter list, which places the undo input filter at the end.
mTextView.setFilters(mTextView.getFilters());
mProcessTextIntentActionsHandler = new ProcessTextIntentActionsHandler(this);
mA11ySmartActions = new AccessibilitySmartActions(mTextView);
mHapticTextHandleEnabled = mTextView.getContext().getResources().getBoolean(
com.android.internal.R.bool.config_enableHapticTextHandle);
mFlagCursorDragFromAnywhereEnabled = AppGlobals.getIntCoreSetting(
WidgetFlags.KEY_ENABLE_CURSOR_DRAG_FROM_ANYWHERE,
WidgetFlags.ENABLE_CURSOR_DRAG_FROM_ANYWHERE_DEFAULT ? 1 : 0) != 0;
final int cursorDragMinAngleFromVertical = AppGlobals.getIntCoreSetting(
WidgetFlags.KEY_CURSOR_DRAG_MIN_ANGLE_FROM_VERTICAL,
WidgetFlags.CURSOR_DRAG_MIN_ANGLE_FROM_VERTICAL_DEFAULT);
mCursorDragDirectionMinXYRatio = EditorTouchState.getXYRatio(
cursorDragMinAngleFromVertical);
mFlagInsertionHandleGesturesEnabled = AppGlobals.getIntCoreSetting(
WidgetFlags.KEY_ENABLE_INSERTION_HANDLE_GESTURES,
WidgetFlags.ENABLE_INSERTION_HANDLE_GESTURES_DEFAULT ? 1 : 0) != 0;
mNewMagnifierEnabled = AppGlobals.getIntCoreSetting(
WidgetFlags.KEY_ENABLE_NEW_MAGNIFIER,
WidgetFlags.ENABLE_NEW_MAGNIFIER_DEFAULT ? 1 : 0) != 0;
mLineSlopRatio = AppGlobals.getFloatCoreSetting(
WidgetFlags.KEY_LINE_SLOP_RATIO,
WidgetFlags.LINE_SLOP_RATIO_DEFAULT);
mUseNewContextMenu = AppGlobals.getIntCoreSetting(
TextFlags.KEY_ENABLE_NEW_CONTEXT_MENU,
TextFlags.ENABLE_NEW_CONTEXT_MENU_DEFAULT ? 1 : 0) != 0;
if (TextView.DEBUG_CURSOR) {
logCursor("Editor", "Cursor drag from anywhere is %s.",
mFlagCursorDragFromAnywhereEnabled ? "enabled" : "disabled");
logCursor("Editor", "Cursor drag min angle from vertical is %d (= %f x/y ratio)",
cursorDragMinAngleFromVertical, mCursorDragDirectionMinXYRatio);
logCursor("Editor", "Insertion handle gestures is %s.",
mFlagInsertionHandleGesturesEnabled ? "enabled" : "disabled");
logCursor("Editor", "New magnifier is %s.",
mNewMagnifierEnabled ? "enabled" : "disabled");
}
mLineChangeSlopMax = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, LINE_CHANGE_SLOP_MAX_DP,
mTextView.getContext().getResources().getDisplayMetrics());
mLineChangeSlopMin = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, LINE_CHANGE_SLOP_MIN_DP,
mTextView.getContext().getResources().getDisplayMetrics());
}
@VisibleForTesting
public boolean getFlagCursorDragFromAnywhereEnabled() {
return mFlagCursorDragFromAnywhereEnabled;
}
@VisibleForTesting
public void setFlagCursorDragFromAnywhereEnabled(boolean enabled) {
mFlagCursorDragFromAnywhereEnabled = enabled;
}
@VisibleForTesting
public void setCursorDragMinAngleFromVertical(int degreesFromVertical) {
mCursorDragDirectionMinXYRatio = EditorTouchState.getXYRatio(degreesFromVertical);
}
@VisibleForTesting
public boolean getFlagInsertionHandleGesturesEnabled() {
return mFlagInsertionHandleGesturesEnabled;
}
@VisibleForTesting
public void setFlagInsertionHandleGesturesEnabled(boolean enabled) {
mFlagInsertionHandleGesturesEnabled = enabled;
}
// Lazy creates the magnifier animator.
private MagnifierMotionAnimator getMagnifierAnimator() {
if (FLAG_USE_MAGNIFIER && mMagnifierAnimator == null) {
// Lazy creates the magnifier instance because it requires the text height which cannot
// be measured at the time of Editor instance being created.
final Magnifier.Builder builder = mNewMagnifierEnabled
? createBuilderWithInlineMagnifierDefaults()
: Magnifier.createBuilderWithOldMagnifierDefaults(mTextView);
mMagnifierAnimator = new MagnifierMotionAnimator(builder.build());
}
return mMagnifierAnimator;
}
private Magnifier.Builder createBuilderWithInlineMagnifierDefaults() {
final Magnifier.Builder params = new Magnifier.Builder(mTextView);
float zoom = AppGlobals.getFloatCoreSetting(
WidgetFlags.KEY_MAGNIFIER_ZOOM_FACTOR,
WidgetFlags.MAGNIFIER_ZOOM_FACTOR_DEFAULT);
float aspectRatio = AppGlobals.getFloatCoreSetting(
WidgetFlags.KEY_MAGNIFIER_ASPECT_RATIO,
WidgetFlags.MAGNIFIER_ASPECT_RATIO_DEFAULT);
// Avoid invalid/unsupported values.
if (zoom < 1.2f || zoom > 1.8f) {
zoom = 1.5f;
}
if (aspectRatio < 3 || aspectRatio > 8) {
aspectRatio = 5.5f;
}
mInitialZoom = zoom;
mMinLineHeightForMagnifier = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, MIN_LINE_HEIGHT_FOR_MAGNIFIER,
mTextView.getContext().getResources().getDisplayMetrics());
mMaxLineHeightForMagnifier = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, MAX_LINE_HEIGHT_FOR_MAGNIFIER,
mTextView.getContext().getResources().getDisplayMetrics());
final Layout layout = mTextView.getLayout();
final int line = layout.getLineForOffset(mTextView.getSelectionStartTransformed());
final int sourceHeight = layout.getLineBottom(line, /* includeLineSpacing= */ false)
- layout.getLineTop(line);
final int height = (int)(sourceHeight * zoom);
final int width = (int)(aspectRatio * Math.max(sourceHeight, mMinLineHeightForMagnifier));
params.setFishEyeStyle()
.setSize(width, height)
.setSourceSize(width, sourceHeight)
.setElevation(0)
.setInitialZoom(zoom)
.setClippingEnabled(false);
final Context context = mTextView.getContext();
final TypedArray a = context.obtainStyledAttributes(
null, com.android.internal.R.styleable.Magnifier,
com.android.internal.R.attr.magnifierStyle, 0);
params.setDefaultSourceToMagnifierOffset(
a.getDimensionPixelSize(
com.android.internal.R.styleable.Magnifier_magnifierHorizontalOffset, 0),
a.getDimensionPixelSize(
com.android.internal.R.styleable.Magnifier_magnifierVerticalOffset, 0));
a.recycle();
return params.setSourceBounds(
Magnifier.SOURCE_BOUND_MAX_VISIBLE,
Magnifier.SOURCE_BOUND_MAX_IN_SURFACE,
Magnifier.SOURCE_BOUND_MAX_VISIBLE,
Magnifier.SOURCE_BOUND_MAX_IN_SURFACE);
}
ParcelableParcel saveInstanceState() {
ParcelableParcel state = new ParcelableParcel(getClass().getClassLoader());
Parcel parcel = state.getParcel();
mUndoManager.saveInstanceState(parcel);
mUndoInputFilter.saveInstanceState(parcel);
return state;
}
void restoreInstanceState(ParcelableParcel state) {
Parcel parcel = state.getParcel();
mUndoManager.restoreInstanceState(parcel, state.getClassLoader());
mUndoInputFilter.restoreInstanceState(parcel);
// Re-associate this object as the owner of undo state.
mUndoOwner = mUndoManager.getOwner(UNDO_OWNER_TAG, this);
}
/**
* Returns the default handler for receiving content in an editable {@link TextView}. This
* listener impl is used to encapsulate the default behavior but it is not part of the public
* API. If an app wants to execute the default platform behavior for receiving content, it
* should call {@link View#onReceiveContent}. Alternatively, if an app implements a custom
* listener for receiving content and wants to delegate some of the content to be handled by
* the platform, it should return the corresponding content from its listener. See
* {@link View#setOnReceiveContentListener} and {@link OnReceiveContentListener} for more info.
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
@NonNull
public TextViewOnReceiveContentListener getDefaultOnReceiveContentListener() {
return mDefaultOnReceiveContentListener;
}
/**
* Forgets all undo and redo operations for this Editor.
*/
void forgetUndoRedo() {
UndoOwner[] owners = { mUndoOwner };
mUndoManager.forgetUndos(owners, -1 /* all */);
mUndoManager.forgetRedos(owners, -1 /* all */);
}
boolean canUndo() {
UndoOwner[] owners = { mUndoOwner };
return mAllowUndo && mUndoManager.countUndos(owners) > 0;
}
boolean canRedo() {
UndoOwner[] owners = { mUndoOwner };
return mAllowUndo && mUndoManager.countRedos(owners) > 0;
}
void undo() {
if (!mAllowUndo) {
return;
}
UndoOwner[] owners = { mUndoOwner };
mUndoManager.undo(owners, 1); // Undo 1 action.
}
void redo() {
if (!mAllowUndo) {
return;
}
UndoOwner[] owners = { mUndoOwner };
mUndoManager.redo(owners, 1); // Redo 1 action.
}
void replace() {
if (mSuggestionsPopupWindow == null) {
mSuggestionsPopupWindow = new SuggestionsPopupWindow();
}
hideCursorAndSpanControllers();
mSuggestionsPopupWindow.show();
int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
Selection.setSelection((Spannable) mTextView.getText(), middle);
}
void onAttachedToWindow() {
if (mShowErrorAfterAttach) {
showError();
mShowErrorAfterAttach = false;
}
final ViewTreeObserver observer = mTextView.getViewTreeObserver();
if (observer.isAlive()) {
// No need to create the controller.
// The get method will add the listener on controller creation.
if (mInsertionPointCursorController != null) {
observer.addOnTouchModeChangeListener(mInsertionPointCursorController);
}
if (mSelectionModifierCursorController != null) {
mSelectionModifierCursorController.resetTouchOffsets();
observer.addOnTouchModeChangeListener(mSelectionModifierCursorController);
}
if (FLAG_USE_MAGNIFIER) {
observer.addOnDrawListener(mMagnifierOnDrawListener);
}
}
updateSpellCheckSpans(0, mTextView.getText().length(),
true /* create the spell checker if needed */);
if (mTextView.hasSelection()) {
refreshTextActionMode();
}
getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true);
// Call resumeBlink here instead of makeBlink to ensure that if mBlink is not null the
// Blink object is uncancelled. This ensures when a view is removed and added back the
// cursor will resume blinking.
resumeBlink();
}
void onDetachedFromWindow() {
getPositionListener().removeSubscriber(mCursorAnchorInfoNotifier);
if (mError != null) {
hideError();
}
suspendBlink();
if (mInsertionPointCursorController != null) {
mInsertionPointCursorController.onDetached();
}
if (mSelectionModifierCursorController != null) {
mSelectionModifierCursorController.onDetached();
}
if (mShowSuggestionRunnable != null) {
mTextView.removeCallbacks(mShowSuggestionRunnable);
}
// Cancel the single tap delayed runnable.
if (mInsertionActionModeRunnable != null) {
mTextView.removeCallbacks(mInsertionActionModeRunnable);
}
mTextView.removeCallbacks(mShowFloatingToolbar);
discardTextDisplayLists();
if (mSpellChecker != null) {
mSpellChecker.closeSession();
// Forces the creation of a new SpellChecker next time this window is created.
// Will handle the cases where the settings has been changed in the meantime.
mSpellChecker = null;
}
if (FLAG_USE_MAGNIFIER) {
final ViewTreeObserver observer = mTextView.getViewTreeObserver();
if (observer.isAlive()) {
observer.removeOnDrawListener(mMagnifierOnDrawListener);
}
}
hideCursorAndSpanControllers();
stopTextActionModeWithPreservingSelection();
mDefaultOnReceiveContentListener.clearInputConnectionInfo();
unregisterOnBackInvokedCallback();
}
private void unregisterOnBackInvokedCallback() {
if (!mBackCallbackRegistered) {
return;
}
ViewRootImpl viewRootImpl = getTextView().getViewRootImpl();
if (viewRootImpl != null
&& viewRootImpl.getOnBackInvokedDispatcher().isOnBackInvokedCallbackEnabled()) {
viewRootImpl.getOnBackInvokedDispatcher()
.unregisterOnBackInvokedCallback(mBackCallback);
mBackCallbackRegistered = false;
}
}
private void registerOnBackInvokedCallback() {
if (mBackCallbackRegistered) {
return;
}
ViewRootImpl viewRootImpl = mTextView.getViewRootImpl();
if (viewRootImpl != null
&& viewRootImpl.getOnBackInvokedDispatcher().isOnBackInvokedCallbackEnabled()) {
viewRootImpl.getOnBackInvokedDispatcher().registerOnBackInvokedCallback(
OnBackInvokedDispatcher.PRIORITY_DEFAULT, mBackCallback);
mBackCallbackRegistered = true;
}
}
private void discardTextDisplayLists() {
if (mTextRenderNodes != null) {
for (int i = 0; i < mTextRenderNodes.length; i++) {
RenderNode displayList = mTextRenderNodes[i] != null
? mTextRenderNodes[i].renderNode : null;
if (displayList != null && displayList.hasDisplayList()) {
displayList.discardDisplayList();
}
}
}
}
private void showError() {
if (mTextView.getWindowToken() == null) {
mShowErrorAfterAttach = true;
return;
}
if (mErrorPopup == null) {
LayoutInflater inflater = LayoutInflater.from(mTextView.getContext());
final TextView err = (TextView) inflater.inflate(
com.android.internal.R.layout.textview_hint, null);
final float scale = mTextView.getResources().getDisplayMetrics().density;
mErrorPopup =
new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f));
mErrorPopup.setFocusable(false);
// The user is entering text, so the input method is needed. We
// don't want the popup to be displayed on top of it.
mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
}
TextView tv = (TextView) mErrorPopup.getContentView();
chooseSize(mErrorPopup, mError, tv);
tv.setText(mError);
mErrorPopup.showAsDropDown(mTextView, getErrorX(), getErrorY(),
Gravity.TOP | Gravity.LEFT);
mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor());
}
public void setError(CharSequence error, Drawable icon) {
mError = TextUtils.stringOrSpannedString(error);
mErrorWasChanged = true;
if (mError == null) {
setErrorIcon(null);
if (mErrorPopup != null) {
if (mErrorPopup.isShowing()) {
mErrorPopup.dismiss();
}
mErrorPopup = null;
}
mShowErrorAfterAttach = false;
} else {
setErrorIcon(icon);
if (mTextView.isFocused()) {
showError();
}
}
}
private void setErrorIcon(Drawable icon) {
Drawables dr = mTextView.mDrawables;
if (dr == null) {
mTextView.mDrawables = dr = new Drawables(mTextView.getContext());
}
dr.setErrorDrawable(icon, mTextView);
mTextView.resetResolvedDrawables();
mTextView.invalidate();
mTextView.requestLayout();
}
private void hideError() {
if (mErrorPopup != null) {
if (mErrorPopup.isShowing()) {
mErrorPopup.dismiss();
}
}
mShowErrorAfterAttach = false;
}
/**
* Returns the X offset to make the pointy top of the error point
* at the middle of the error icon.
*/
private int getErrorX() {
/*
* The "25" is the distance between the point and the right edge
* of the background
*/
final float scale = mTextView.getResources().getDisplayMetrics().density;
final Drawables dr = mTextView.mDrawables;
final int layoutDirection = mTextView.getLayoutDirection();
int errorX;
int offset;
switch (layoutDirection) {
default:
case View.LAYOUT_DIRECTION_LTR:
offset = -(dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f);
errorX = mTextView.getWidth() - mErrorPopup.getWidth()
- mTextView.getPaddingRight() + offset;
break;
case View.LAYOUT_DIRECTION_RTL:
offset = (dr != null ? dr.mDrawableSizeLeft : 0) / 2 - (int) (25 * scale + 0.5f);
errorX = mTextView.getPaddingLeft() + offset;
break;
}
return errorX;
}
/**
* Returns the Y offset to make the pointy top of the error point
* at the bottom of the error icon.
*/
private int getErrorY() {
/*
* Compound, not extended, because the icon is not clipped
* if the text height is smaller.
*/
final int compoundPaddingTop = mTextView.getCompoundPaddingTop();
int vspace = mTextView.getBottom() - mTextView.getTop()
- mTextView.getCompoundPaddingBottom() - compoundPaddingTop;
final Drawables dr = mTextView.mDrawables;
final int layoutDirection = mTextView.getLayoutDirection();
int height;
switch (layoutDirection) {
default:
case View.LAYOUT_DIRECTION_LTR:
height = (dr != null ? dr.mDrawableHeightRight : 0);
break;
case View.LAYOUT_DIRECTION_RTL:
height = (dr != null ? dr.mDrawableHeightLeft : 0);
break;
}
int icontop = compoundPaddingTop + (vspace - height) / 2;
/*
* The "2" is the distance between the point and the top edge
* of the background.
*/
final float scale = mTextView.getResources().getDisplayMetrics().density;
return icontop + height - mTextView.getHeight() - (int) (2 * scale + 0.5f);
}
void createInputContentTypeIfNeeded() {
if (mInputContentType == null) {
mInputContentType = new InputContentType();
}
}
void createInputMethodStateIfNeeded() {
if (mInputMethodState == null) {
mInputMethodState = new InputMethodState();
}
}
private boolean isCursorVisible() {
// The default value is true, even when there is no associated Editor
return mCursorVisible && mTextView.isTextEditable();
}
boolean shouldRenderCursor() {
if (!isCursorVisible()) {
return false;
}
if (mRenderCursorRegardlessTiming) {
return true;
}
final long showCursorDelta = SystemClock.uptimeMillis() - mShowCursor;
return showCursorDelta % (2 * BLINK) < BLINK;
}
void prepareCursorControllers() {
boolean windowSupportsHandles = false;
ViewGroup.LayoutParams params = mTextView.getRootView().getLayoutParams();
if (params instanceof WindowManager.LayoutParams) {
WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params;
windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW