From 7e1a0ade79733a4751e7798f60f78403badc9bf6 Mon Sep 17 00:00:00 2001 From: SessionHero01 <180888785+SessionHero01@users.noreply.github.com> Date: Tue, 24 Sep 2024 11:59:55 +1000 Subject: [PATCH] Fix crashes when removing spaces in mention texts --- .../conversation/v2/mention/MentionViewModel.kt | 10 +++++++--- .../securesms/conversation/v2/MentionViewModelTest.kt | 5 +++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/mention/MentionViewModel.kt b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/mention/MentionViewModel.kt index d4068a3e6c..e3e5df0458 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/mention/MentionViewModel.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/conversation/v2/mention/MentionViewModel.kt @@ -202,13 +202,17 @@ class MentionViewModel( val sb = StringBuilder() var offset = 0 for ((span, range) in spansWithRanges) { - // Add content before the mention span - sb.append(editable, offset, range.first) + // Add content before the mention span. There's a possibility of overlapping spans so we need to + // safe guard the start offset here to not go over our span's start. + val thisMentionStart = range.first + val lastMentionEnd = offset.coerceAtMost(thisMentionStart) + sb.append(editable, lastMentionEnd, thisMentionStart) // Replace the mention span with "@public key" sb.append('@').append(span.member.publicKey).append(' ') - offset = range.last + 1 + // Safe guard offset to not go over the end of the editable. + offset = (range.last + 1).coerceAtMost(editable.length) } // Add the remaining content diff --git a/app/src/test/java/org/thoughtcrime/securesms/conversation/v2/MentionViewModelTest.kt b/app/src/test/java/org/thoughtcrime/securesms/conversation/v2/MentionViewModelTest.kt index ea27128205..86bbaab5bc 100644 --- a/app/src/test/java/org/thoughtcrime/securesms/conversation/v2/MentionViewModelTest.kt +++ b/app/src/test/java/org/thoughtcrime/securesms/conversation/v2/MentionViewModelTest.kt @@ -179,6 +179,11 @@ class MentionViewModelTest { // Should have normalised message with selected candidate assertThat(mentionViewModel.normalizeMessageBody()) .isEqualTo("Hi @pubkey1 ") + + // Should have correct normalised message even with the last space deleted + editable.delete(editable.length - 1, editable.length) + assertThat(mentionViewModel.normalizeMessageBody()) + .isEqualTo("Hi @pubkey1 ") } } } \ No newline at end of file