-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditor.java
More file actions
5680 lines (4932 loc) · 233 KB
/
Copy pathEditor.java
File metadata and controls
5680 lines (4932 loc) · 233 KB
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 android.R;
import android.annotation.Nullable;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ClipData;
import android.content.ClipData.Item;
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.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
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.StaticLayout;
import android.text.TextUtils;
import android.text.method.KeyListener;
import android.text.method.MetaKeyKeyListener;
import android.text.method.MovementMethod;
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.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.DisplayListCanvas;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.RenderNode;
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.ViewTreeObserver;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
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.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.Drawables;
import android.widget.TextView.OnEditorActionListener;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.GrowingArrayUtils;
import com.android.internal.util.Preconditions;
import com.android.internal.widget.EditableInputConnection;
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
/**
* 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;
static final int BLINK = 500;
private static final float[] TEMP_POSITION = new float[2];
private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
private static final float LINE_SLOP_MULTIPLIER_FOR_HANDLEVIEWS = 0.5f;
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 MENU_ITEM_ORDER_CUT = 1;
private static final int MENU_ITEM_ORDER_COPY = 2;
private static final int MENU_ITEM_ORDER_PASTE = 3;
private static final int MENU_ITEM_ORDER_SHARE = 4;
private static final int MENU_ITEM_ORDER_SELECT_ALL = 5;
private static final int MENU_ITEM_ORDER_REPLACE = 6;
private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 10;
// 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;
// Cursor Controllers.
InsertionPointCursorController mInsertionPointCursorController;
SelectionModifierCursorController mSelectionModifierCursorController;
// Action mode used when text is selected or when actions on an insertion cursor are triggered.
ActionMode mTextActionMode;
boolean mInsertionControllerEnabled;
boolean mSelectionControllerEnabled;
// Used to highlight a word when it is corrected by the IME
CorrectionHighlighter mCorrectionHighlighter;
InputContentType mInputContentType;
InputMethodState mInputMethodState;
private static class TextRenderNode {
RenderNode renderNode;
boolean isDirty;
public TextRenderNode(String name) {
isDirty = true;
renderNode = RenderNode.create(name, null);
}
boolean needsRecord() { return isDirty || !renderNode.isValid(); }
}
TextRenderNode[] mTextRenderNodes;
boolean mFrozenWithFocus;
boolean mSelectionMoved;
boolean mTouchFocusSelected;
KeyListener mKeyListener;
int mInputType = EditorInfo.TYPE_NULL;
boolean mDiscardNextActionUp;
boolean mIgnoreActionUpEvent;
long mShowCursor;
Blink mBlink;
boolean mCursorVisible = true;
boolean mSelectAllOnFocus;
boolean mTextIsSelectable;
CharSequence mError;
boolean mErrorWasChanged;
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.
*/
boolean mShowErrorAfterAttach;
boolean mInBatchEditControllers;
boolean mShowSoftInputOnFocus = true;
boolean mPreserveDetachedSelection;
boolean mTemporaryDetach;
SuggestionsPopupWindow mSuggestionsPopupWindow;
SuggestionRangeSpan mSuggestionRangeSpan;
Runnable mShowSuggestionRunnable;
final Drawable[] mCursorDrawable = new Drawable[2];
int mCursorCount; // Current number of used mCursorDrawable: 0 (resource=0), 1 or 2 (split)
private Drawable mSelectHandleLeft;
private Drawable mSelectHandleRight;
private Drawable mSelectHandleCenter;
// Global listener that detects changes in the global position of the TextView
private PositionListener mPositionListener;
float mLastDownPositionX, mLastDownPositionY;
Callback mCustomSelectionActionModeCallback;
Callback mCustomInsertionActionModeCallback;
// Set when this TextView gained focus with some text selected. Will start selection mode.
boolean mCreatedWithASelection;
boolean mDoubleTap = false;
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;
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 TextView mTextView;
final ProcessTextIntentActionsHandler mProcessTextIntentActionsHandler;
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;
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);
}
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);
}
/**
* 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() {
int middle = (mTextView.getSelectionStart() + mTextView.getSelectionEnd()) / 2;
stopTextActionMode();
Selection.setSelection((Spannable) mTextView.getText(), middle);
showSuggestions();
}
void onAttachedToWindow() {
if (mShowErrorAfterAttach) {
showError();
mShowErrorAfterAttach = false;
}
mTemporaryDetach = false;
final ViewTreeObserver observer = mTextView.getViewTreeObserver();
// 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);
}
updateSpellCheckSpans(0, mTextView.getText().length(),
true /* create the spell checker if needed */);
if (mTextView.hasTransientState() &&
mTextView.getSelectionStart() != mTextView.getSelectionEnd()) {
// Since transient state is reference counted make sure it stays matched
// with our own calls to it for managing selection.
// The action mode callback will set this back again when/if the action mode starts.
mTextView.setHasTransientState(false);
// We had an active selection from before, start the selection mode.
startSelectionActionMode();
}
getPositionListener().addSubscriber(mCursorAnchorInfoNotifier, true);
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);
destroyDisplayListsData();
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;
}
mPreserveDetachedSelection = true;
hideCursorAndSpanControllers();
stopTextActionMode();
mPreserveDetachedSelection = false;
mTemporaryDetach = false;
}
private void destroyDisplayListsData() {
if (mTextRenderNodes != null) {
for (int i = 0; i < mTextRenderNodes.length; i++) {
RenderNode displayList = mTextRenderNodes[i] != null
? mTextRenderNodes[i].renderNode : null;
if (displayList != null && displayList.isValid()) {
displayList.destroyDisplayListData();
}
}
}
}
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());
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();
}
}
boolean isCursorVisible() {
// The default value is true, even when there is no associated Editor
return mCursorVisible && mTextView.isTextEditable();
}
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
|| windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW;
}
boolean enabled = windowSupportsHandles && mTextView.getLayout() != null;
mInsertionControllerEnabled = enabled && isCursorVisible();
mSelectionControllerEnabled = enabled && mTextView.textCanBeSelected();
if (!mInsertionControllerEnabled) {
hideInsertionPointCursorController();
if (mInsertionPointCursorController != null) {
mInsertionPointCursorController.onDetached();
mInsertionPointCursorController = null;
}
}
if (!mSelectionControllerEnabled) {
stopTextActionMode();
if (mSelectionModifierCursorController != null) {
mSelectionModifierCursorController.onDetached();
mSelectionModifierCursorController = null;
}
}
}
void hideInsertionPointCursorController() {
if (mInsertionPointCursorController != null) {
mInsertionPointCursorController.hide();
}
}
/**
* Hides the insertion and span controllers.
*/
void hideCursorAndSpanControllers() {
hideCursorControllers();
hideSpanControllers();
}
private void hideSpanControllers() {
if (mSpanController != null) {
mSpanController.hide();
}
}
private void hideCursorControllers() {
// When mTextView is not ExtractEditText, we need to distinguish two kinds of focus-lost.
// One is the true focus lost where suggestions pop-up (if any) should be dismissed, and the
// other is an side effect of showing the suggestions pop-up itself. We use isShowingUp()
// to distinguish one from the other.
if (mSuggestionsPopupWindow != null && ((mTextView.isInExtractedMode()) ||
!mSuggestionsPopupWindow.isShowingUp())) {
// Should be done before hide insertion point controller since it triggers a show of it
mSuggestionsPopupWindow.hide();
}
hideInsertionPointCursorController();
}
/**
* Create new SpellCheckSpans on the modified region.
*/
private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) {
// Remove spans whose adjacent characters are text not punctuation
mTextView.removeAdjacentSuggestionSpans(start);
mTextView.removeAdjacentSuggestionSpans(end);
if (mTextView.isTextEditable() && mTextView.isSuggestionsEnabled() &&
!(mTextView.isInExtractedMode())) {
if (mSpellChecker == null && createSpellChecker) {
mSpellChecker = new SpellChecker(mTextView);
}
if (mSpellChecker != null) {
mSpellChecker.spellCheck(start, end);
}
}
}
void onScreenStateChanged(int screenState) {
switch (screenState) {
case View.SCREEN_STATE_ON:
resumeBlink();
break;
case View.SCREEN_STATE_OFF:
suspendBlink();
break;
}
}
private void suspendBlink() {
if (mBlink != null) {
mBlink.cancel();
}
}
private void resumeBlink() {
if (mBlink != null) {
mBlink.uncancel();
makeBlink();
}
}
void adjustInputType(boolean password, boolean passwordInputType,
boolean webPasswordInputType, boolean numberPasswordInputType) {
// mInputType has been set from inputType, possibly modified by mInputMethod.
// Specialize mInputType to [web]password if we have a text class and the original input
// type was a password.
if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) {
if (password || passwordInputType) {
mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
| EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
}
if (webPasswordInputType) {
mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
| EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD;
}
} else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) {
if (numberPasswordInputType) {
mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION))
| EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
}
}
}
private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
int wid = tv.getPaddingLeft() + tv.getPaddingRight();
int ht = tv.getPaddingTop() + tv.getPaddingBottom();
int defaultWidthInPixels = mTextView.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.textview_error_popup_default_width);
Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels,
Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
float max = 0;
for (int i = 0; i < l.getLineCount(); i++) {
max = Math.max(max, l.getLineWidth(i));
}
/*
* Now set the popup size to be big enough for the text plus the border capped
* to DEFAULT_MAX_POPUP_WIDTH
*/
pop.setWidth(wid + (int) Math.ceil(max));
pop.setHeight(ht + l.getHeight());
}
void setFrame() {
if (mErrorPopup != null) {
TextView tv = (TextView) mErrorPopup.getContentView();
chooseSize(mErrorPopup, mError, tv);
mErrorPopup.update(mTextView, getErrorX(), getErrorY(),
mErrorPopup.getWidth(), mErrorPopup.getHeight());
}
}
private int getWordStart(int offset) {
// FIXME - For this and similar methods we're not doing anything to check if there's
// a LocaleSpan in the text, this may be something we should try handling or checking for.
int retOffset = getWordIteratorWithText().prevBoundary(offset);
if (getWordIteratorWithText().isOnPunctuation(retOffset)) {
// On punctuation boundary or within group of punctuation, find punctuation start.
retOffset = getWordIteratorWithText().getPunctuationBeginning(offset);
} else {
// Not on a punctuation boundary, find the word start.
retOffset = getWordIteratorWithText().getPrevWordBeginningOnTwoWordsBoundary(offset);
}
if (retOffset == BreakIterator.DONE) {
return offset;
}
return retOffset;
}
private int getWordEnd(int offset) {
int retOffset = getWordIteratorWithText().nextBoundary(offset);
if (getWordIteratorWithText().isAfterPunctuation(retOffset)) {
// On punctuation boundary or within group of punctuation, find punctuation end.
retOffset = getWordIteratorWithText().getPunctuationEnd(offset);
} else {
// Not on a punctuation boundary, find the word end.
retOffset = getWordIteratorWithText().getNextWordEndOnTwoWordBoundary(offset);
}
if (retOffset == BreakIterator.DONE) {
return offset;
}
return retOffset;
}
/**
* Adjusts selection to the word under last touch offset. Return true if the operation was
* successfully performed.
*/
private boolean selectCurrentWord() {
if (!mTextView.canSelectText()) {
return false;
}
if (mTextView.hasPasswordTransformationMethod()) {
// Always select all on a password field.
// Cut/copy menu entries are not available for passwords, but being able to select all
// is however useful to delete or paste to replace the entire content.
return mTextView.selectAllText();
}
int inputType = mTextView.getInputType();
int klass = inputType & InputType.TYPE_MASK_CLASS;
int variation = inputType & InputType.TYPE_MASK_VARIATION;
// Specific text field types: select the entire text for these
if (klass == InputType.TYPE_CLASS_NUMBER ||
klass == InputType.TYPE_CLASS_PHONE ||
klass == InputType.TYPE_CLASS_DATETIME ||
variation == InputType.TYPE_TEXT_VARIATION_URI ||
variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||
variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS ||
variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
return mTextView.selectAllText();
}
long lastTouchOffsets = getLastTouchOffsets();
final int minOffset = TextUtils.unpackRangeStartFromLong(lastTouchOffsets);
final int maxOffset = TextUtils.unpackRangeEndFromLong(lastTouchOffsets);
// Safety check in case standard touch event handling has been bypassed
if (minOffset < 0 || minOffset >= mTextView.getText().length()) return false;
if (maxOffset < 0 || maxOffset >= mTextView.getText().length()) return false;
int selectionStart, selectionEnd;
// If a URLSpan (web address, email, phone...) is found at that position, select it.
URLSpan[] urlSpans = ((Spanned) mTextView.getText()).
getSpans(minOffset, maxOffset, URLSpan.class);
if (urlSpans.length >= 1) {
URLSpan urlSpan = urlSpans[0];
selectionStart = ((Spanned) mTextView.getText()).getSpanStart(urlSpan);
selectionEnd = ((Spanned) mTextView.getText()).getSpanEnd(urlSpan);
} else {
// FIXME - We should check if there's a LocaleSpan in the text, this may be
// something we should try handling or checking for.
final WordIterator wordIterator = getWordIterator();
wordIterator.setCharSequence(mTextView.getText(), minOffset, maxOffset);
selectionStart = wordIterator.getBeginning(minOffset);
selectionEnd = wordIterator.getEnd(maxOffset);
if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE ||
selectionStart == selectionEnd) {
// Possible when the word iterator does not properly handle the text's language
long range = getCharClusterRange(minOffset);
selectionStart = TextUtils.unpackRangeStartFromLong(range);
selectionEnd = TextUtils.unpackRangeEndFromLong(range);
}
}
Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
return selectionEnd > selectionStart;
}
void onLocaleChanged() {
// Will be re-created on demand in getWordIterator with the proper new locale
mWordIterator = null;
mWordIteratorWithText = null;
}
/**
* @hide
*/
public WordIterator getWordIterator() {
if (mWordIterator == null) {
mWordIterator = new WordIterator(mTextView.getTextServicesLocale());
}
return mWordIterator;
}
private WordIterator getWordIteratorWithText() {
if (mWordIteratorWithText == null) {
mWordIteratorWithText = new WordIterator(mTextView.getTextServicesLocale());
mUpdateWordIteratorText = true;
}
if (mUpdateWordIteratorText) {
// FIXME - Shouldn't copy all of the text as only the area of the text relevant
// to the user's selection is needed. A possible solution would be to
// copy some number N of characters near the selection and then when the
// user approaches N then we'd do another copy of the next N characters.
CharSequence text = mTextView.getText();
mWordIteratorWithText.setCharSequence(text, 0, text.length());
mUpdateWordIteratorText = false;
}
return mWordIteratorWithText;
}
private int getNextCursorOffset(int offset, boolean findAfterGivenOffset) {
final Layout layout = mTextView.getLayout();
if (layout == null) return offset;
final CharSequence text = mTextView.getText();
final int nextOffset = layout.getPaint().getTextRunCursor(text, 0, text.length(),
layout.isRtlCharAt(offset) ? Paint.DIRECTION_RTL : Paint.DIRECTION_LTR,
offset, findAfterGivenOffset ? Paint.CURSOR_AFTER : Paint.CURSOR_BEFORE);
return nextOffset == -1 ? offset : nextOffset;
}
private long getCharClusterRange(int offset) {
final int textLength = mTextView.getText().length();
if (offset < textLength) {
return TextUtils.packRangeInLong(offset, getNextCursorOffset(offset, true));
}
if (offset - 1 >= 0) {
return TextUtils.packRangeInLong(getNextCursorOffset(offset, false), offset);
}
return TextUtils.packRangeInLong(offset, offset);
}
private boolean touchPositionIsInSelection() {
int selectionStart = mTextView.getSelectionStart();
int selectionEnd = mTextView.getSelectionEnd();
if (selectionStart == selectionEnd) {
return false;
}
if (selectionStart > selectionEnd) {
int tmp = selectionStart;
selectionStart = selectionEnd;
selectionEnd = tmp;
Selection.setSelection((Spannable) mTextView.getText(), selectionStart, selectionEnd);
}
SelectionModifierCursorController selectionController = getSelectionController();
int minOffset = selectionController.getMinTouchOffset();
int maxOffset = selectionController.getMaxTouchOffset();
return ((minOffset >= selectionStart) && (maxOffset < selectionEnd));
}
private PositionListener getPositionListener() {
if (mPositionListener == null) {
mPositionListener = new PositionListener();
}
return mPositionListener;
}
private interface TextViewPositionListener {
public void updatePosition(int parentPositionX, int parentPositionY,
boolean parentPositionChanged, boolean parentScrolled);
}
private boolean isPositionVisible(final float positionX, final float positionY) {
synchronized (TEMP_POSITION) {
final float[] position = TEMP_POSITION;
position[0] = positionX;
position[1] = positionY;
View view = mTextView;
while (view != null) {
if (view != mTextView) {
// Local scroll is already taken into account in positionX/Y
position[0] -= view.getScrollX();
position[1] -= view.getScrollY();
}
if (position[0] < 0 || position[1] < 0 ||
position[0] > view.getWidth() || position[1] > view.getHeight()) {
return false;
}
if (!view.getMatrix().isIdentity()) {
view.getMatrix().mapPoints(position);
}
position[0] += view.getLeft();
position[1] += view.getTop();
final ViewParent parent = view.getParent();
if (parent instanceof View) {
view = (View) parent;
} else {
// We've reached the ViewRoot, stop iterating
view = null;
}
}
}
// We've been able to walk up the view hierarchy and the position was never clipped
return true;
}
private boolean isOffsetVisible(int offset) {
Layout layout = mTextView.getLayout();
if (layout == null) return false;
final int line = layout.getLineForOffset(offset);
final int lineBottom = layout.getLineBottom(line);
final int primaryHorizontal = (int) layout.getPrimaryHorizontal(offset);
return isPositionVisible(primaryHorizontal + mTextView.viewportToContentHorizontalOffset(),
lineBottom + mTextView.viewportToContentVerticalOffset());
}
/** Returns true if the screen coordinates position (x,y) corresponds to a character displayed
* in the view. Returns false when the position is in the empty space of left/right of text.
*/
private boolean isPositionOnText(float x, float y) {
Layout layout = mTextView.getLayout();
if (layout == null) return false;
final int line = mTextView.getLineAtCoordinate(y);
x = mTextView.convertToLocalHorizontalCoordinate(x);
if (x < layout.getLineLeft(line)) return false;
if (x > layout.getLineRight(line)) return false;
return true;
}
public boolean performLongClick(boolean handled) {
// Long press in empty space moves cursor and starts the insertion action mode.
if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
mInsertionControllerEnabled) {
final int offset = mTextView.getOffsetForPosition(mLastDownPositionX,
mLastDownPositionY);
stopTextActionMode();
Selection.setSelection((Spannable) mTextView.getText(), offset);