Fix crash when modifying Selection
The root of this bug was in the fact that Selection.removeSelection
removes two spans, the start index and end index of the selection.
Each span removal triggers Editor#onSpanRemoved, which in turn tries
to set a selection. This meant that if we started with selection
(100, 120), then removeSpan(start) was called, so we had (-1, 120),
then the onSpanRemoved code tried to set a selection so set it to
(120, 120), then removeSpan(end) was called, ending up in (120, -1).
There are two stages to this fix
1. A lot of our code assumes that when either start or end selection
are larger than -1, both are valid. Therefore when we have one of them
out of sync, we crash. Fixed this assumption in all the places I found
2. We didn't have a mechanism to use FLAG_INTERMEDIATE when removing
spans, only when adding them, so this CL adds a remove with flags. This
allows us to not trigger onSpanRemoved when only one of the selection
indexes is removed.
Because this is an added method to an interface, the default just
calls the existing method. The new method is implemented in
SpannableStringInternal and SpannableStringBuilder to read
FLAG_INTERMEDIATE and avoid sending a spans changed event.
Selection.removeSelection then uses FLAG_INTERMEDIATE when removing
the first of the two selection spans.
Note that 2. would be enough to fix the current bug, but we want to
avoid other implementations of Spannable from crashing in the wild.
In general, it seems like a good idea to verify both selection indexes
are valid whenever they are used.
Bug: 72101848
Test: atest FrameworksCoreTests:SpannableStringBuilderTest
Test: atest FrameworksCoreTests:SpannableStringTest
Test: atest CtsWidgetTestCases:TextViewTest
Test: atest CtsWidgetTestCases:EditTextTest
Test: atest android.text.cts.SelectionTest (note new test as well)
Test: atest android.view.inputmethod.cts.BaseInputConnectionTest
Test: atest android.text.DynamicLayoutTest
Change-Id: I0d647fad152d0bef0f2115a46c3d17ebd8642281
diff --git a/core/java/android/text/Spannable.java b/core/java/android/text/Spannable.java
index 39b78eb..8315b2a 100644
--- a/core/java/android/text/Spannable.java
+++ b/core/java/android/text/Spannable.java
@@ -46,6 +46,19 @@
public void removeSpan(Object what);
/**
+ * Remove the specified object from the range of text to which it
+ * was attached, if any. It is OK to remove an object that was never
+ * attached in the first place.
+ *
+ * See {@link Spanned} for an explanation of what the flags mean.
+ *
+ * @hide
+ */
+ default void removeSpan(Object what, int flags) {
+ removeSpan(what);
+ }
+
+ /**
* Factory used by TextView to create new {@link Spannable Spannables}. You can subclass
* it to provide something other than {@link SpannableString}.
*