From ac5c9a2b6e622b29480f2fe731809e39f3a321bd Mon Sep 17 00:00:00 2001 From: makhlwf Date: Sat, 11 Jul 2026 22:35:40 +0200 Subject: [PATCH 1/8] fix(editor): sync TalkBack focus with the text cursor The editor wraps Rosemoe's CodeEditor, a custom-drawn View. Its accessibility node reported the whole document as a single generic editable node (class name CodeEditor) and advertised no text-movement granularities, ACTION_SET_SELECTION or granularity actions. TalkBack therefore had no way to move the real text caret with the reading position: double-tapping a word/line placed the caret at the node's centre and subsequent typing landed on the wrong line. Make IDEEditor behave like a standard EditText for screen readers: - Report as android.widget.EditText and advertise CHARACTER/WORD/LINE movement granularities plus ACTION_SET_SELECTION and the next/previous-at-granularity actions. - Handle those actions by converting absolute char indices to (line, column) via the editor's Indexer and moving the real caret, then emit TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY so the spoken segment and caret stay in sync. - Track the last touch-exploration hover point and, on ACTION_CLICK, place the caret there so a double-tap lands on the explored word/line (only active while touch exploration is on, so sighted use is unaffected). Text-segment iteration lives in EditorAccessibilitySegments (character and word mirror the framework's AccessibilityIterators; line walks logical '\n'-separated lines) and is covered by unit tests. --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 208 +++++++++++++++++- .../utils/EditorAccessibilitySegments.kt | 192 ++++++++++++++++ .../utils/EditorAccessibilitySegmentsTest.kt | 175 +++++++++++++++ 3 files changed, 573 insertions(+), 2 deletions(-) create mode 100644 editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt create mode 100644 editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index e7d65d9a08..5cd620238d 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -26,8 +26,12 @@ import android.util.AttributeSet import android.view.KeyEvent import android.view.MotionEvent import android.view.View +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityManager +import android.view.accessibility.AccessibilityNodeInfo import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection +import android.widget.EditText import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import com.itsaky.androidide.editor.R @@ -49,6 +53,7 @@ import com.itsaky.androidide.editor.schemes.IDEColorSchemeProvider import com.itsaky.androidide.editor.snippets.AbstractSnippetVariableResolver import com.itsaky.androidide.editor.snippets.FileVariableResolver import com.itsaky.androidide.editor.snippets.WorkspaceVariableResolver +import com.itsaky.androidide.editor.utils.EditorAccessibilitySegments import com.itsaky.androidide.editor.utils.getOperatorRangeAt import com.itsaky.androidide.eventbus.events.editor.ChangeType import com.itsaky.androidide.eventbus.events.editor.ColorSchemeInvalidatedEvent @@ -652,6 +657,206 @@ open class IDEEditor } } + // region Accessibility (screen reader) cursor synchronization + // + // The base CodeEditor exposes its whole content to accessibility services as a single + // editable node, but does not advertise text-movement granularities, ACTION_SET_SELECTION + // or the granularity actions. As a result TalkBack cannot keep the real text cursor in sync + // with the reading position: navigating or double-tapping placed the cursor in the wrong + // location and typing landed on the wrong line. The overrides below make the editor behave + // like a standard EditText for screen readers. + + private val accessibilityManager: AccessibilityManager? by lazy { + context.getSystemService(Context.ACCESSIBILITY_SERVICE) as? AccessibilityManager + } + + // Last touch-exploration (hover) position, in view coordinates, used to place the cursor + // where the user double-taps under TalkBack. NaN means "no recent exploration". + private var lastHoverX = Float.NaN + private var lastHoverY = Float.NaN + + private val isTouchExplorationEnabled: Boolean + get() = accessibilityManager?.isTouchExplorationEnabled == true + + override fun getAccessibilityClassName(): CharSequence = EditText::class.java.name + + override fun createAccessibilityNodeInfo(): AccessibilityNodeInfo? { + val info = super.createAccessibilityNodeInfo() ?: return null + if (!isReleased && isEnabled && isEditable) { + // Report as an EditText so TalkBack engages its text-editing affordances and keeps + // the caret in sync with granular navigation. + info.className = EditText::class.java.name + info.movementGranularities = EditorAccessibilitySegments.SUPPORTED_GRANULARITIES + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_SELECTION) + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_NEXT_AT_MOVEMENT_GRANULARITY) + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY) + } + return info + } + + override fun dispatchHoverEvent(event: MotionEvent): Boolean { + // Remember where the user is exploring so ACTION_CLICK can place the caret there. + if (isTouchExplorationEnabled) { + lastHoverX = event.x + lastHoverY = event.y + } + return super.dispatchHoverEvent(event) + } + + override fun performAccessibilityAction( + action: Int, + arguments: Bundle?, + ): Boolean { + when (action) { + AccessibilityNodeInfo.ACTION_SET_SELECTION -> + if (handleAccessibilitySetSelection(arguments)) return true + + AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY -> + if (handleAccessibilityGranularityMove(action, arguments, forward = true)) return true + + AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY -> + if (handleAccessibilityGranularityMove(action, arguments, forward = false)) return true + + AccessibilityNodeInfo.ACTION_CLICK -> + if (handleAccessibilityClick()) return true + } + return super.performAccessibilityAction(action, arguments) + } + + /** + * Places the caret where the user last explored by touch. This makes a TalkBack double-tap + * on a word or line move the real text cursor to that spot instead of the node's center. + */ + private fun handleAccessibilityClick(): Boolean { + if (isReleased || !isEditable || !isTouchExplorationEnabled) return false + val x = lastHoverX + val y = lastHoverY + if (x.isNaN() || y.isNaN()) return false + return try { + if (!isFocused) requestFocus() + val packed = getPointPositionOnScreen(x, y) + val line = (packed ushr 32).toInt() + val column = (packed and 0xffffffffL).toInt() + if (line < 0 || column < 0) return false + setSelection(line, column) + true + } catch (e: Exception) { + log.error("Error placing cursor from accessibility click", e) + false + } + } + + /** Handles [AccessibilityNodeInfo.ACTION_SET_SELECTION] using absolute character indices. */ + private fun handleAccessibilitySetSelection(arguments: Bundle?): Boolean { + if (isReleased || !isEditable || arguments == null) return false + if (!arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) || + !arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT) + ) { + return false + } + val content = text + val length = content.length + val start = arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) + val end = arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT) + if (start < 0 || end < 0 || start > length || end > length) return false + return applySelectionFromIndices(start, end) + } + + /** + * Handles the move-by-granularity actions. Moves the real text cursor to the next/previous + * character, word or line and reports the traversed segment so the screen reader reads it, + * mirroring [EditText] behaviour. + */ + private fun handleAccessibilityGranularityMove( + action: Int, + arguments: Bundle?, + forward: Boolean, + ): Boolean { + if (isReleased || !isEditable || arguments == null) return false + val granularity = arguments.getInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + ) + val extendSelection = arguments.getBoolean( + AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, + false, + ) + val content = text + val cur = cursor ?: return false + val selStart = cur.left + val selEnd = cur.right + + val fromIndex = if (forward) selEnd else selStart + val segment = + if (forward) { + EditorAccessibilitySegments.following(content, granularity, fromIndex) + } else { + EditorAccessibilitySegments.preceding(content, granularity, fromIndex) + } ?: return false + + val segStart = segment[0] + val segEnd = segment[1] + val newCaret = if (forward) segEnd else segStart + + val applied = + if (extendSelection) { + val anchor = if (forward) selStart else selEnd + applySelectionFromIndices(minOf(anchor, newCaret), maxOf(anchor, newCaret)) + } else { + applySelectionFromIndices(newCaret, newCaret) + } + if (!applied) return false + + sendTextTraversedEvent(segStart, segEnd, action, granularity) + return true + } + + /** Converts absolute char indices to (line, column) positions and moves the selection. */ + private fun applySelectionFromIndices(start: Int, end: Int): Boolean { + val content = text + return try { + val indexer = content.indexer + val startPos = indexer.getCharPosition(start) + if (start == end) { + setSelection(startPos.line, startPos.column) + } else { + val endPos = indexer.getCharPosition(end) + setSelectionRegion(startPos.line, startPos.column, endPos.line, endPos.column) + } + true + } catch (e: Exception) { + log.error("Error applying accessibility selection [$start, $end]", e) + false + } + } + + /** + * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY] event so the + * screen reader announces the character/word/line the caret just traversed. + */ + @Suppress("DEPRECATION") // AccessibilityEvent(int) requires API 30; obtain() works on minSdk 28. + private fun sendTextTraversedEvent( + fromIndex: Int, + toIndex: Int, + action: Int, + granularity: Int, + ) { + val manager = accessibilityManager ?: return + if (!manager.isEnabled) return + val event = AccessibilityEvent.obtain( + AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, + ) + onInitializeAccessibilityEvent(event) + event.className = EditText::class.java.name + event.fromIndex = fromIndex + event.toIndex = toIndex + event.action = action + event.movementGranularity = granularity + // The reader substrings [fromIndex, toIndex] out of the event text. + event.text.add(text.toString()) + sendAccessibilityEventUnchecked(event) + } + // endregion Accessibility + override fun copyTextToClipboard( text: CharSequence, start: Int, @@ -1121,8 +1326,7 @@ open class IDEEditor content = text, file = currentFile, cursor = - text.cursor.apply { -// set(lineToProcess, text.getLine(lineToProcess).length) + text.cursor.apply {// set(lineToProcess, text.getLine(lineToProcess).length) }, ) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt new file mode 100644 index 0000000000..4c4a352e16 --- /dev/null +++ b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt @@ -0,0 +1,192 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.editor.utils + +import android.view.accessibility.AccessibilityNodeInfo +import java.text.BreakIterator + +/** + * Pure text-segment iteration used to keep the editor's text cursor in sync with a + * screen reader's "move by granularity" navigation, so the editor behaves like a + * standard [android.widget.EditText] under TalkBack. + * + * The editor exposes its whole content to accessibility services as a single flat + * [CharSequence]. Movement granularity actions therefore operate on absolute character + * indices into that flat text; the caller is responsible for mapping the returned + * indices back to (line, column) positions in the editor. + * + * The character and word implementations mirror the semantics of the framework's + * (hidden) `android.view.AccessibilityIterators`, so navigation matches what users + * already expect from an [android.widget.EditText]. Line navigation walks logical + * lines (separated by `'\n'`), which for source code is the natural unit. + * + * @author Code On The Go + */ +object EditorAccessibilitySegments { + + private const val DONE = BreakIterator.DONE + + /** + * The set of movement granularities that [following] and [preceding] can handle. + * Intended to be advertised via [AccessibilityNodeInfo.setMovementGranularities]. + */ + const val SUPPORTED_GRANULARITIES = + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER or + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD or + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE + + /** + * Returns the `[start, end]` range (end-exclusive) of the segment that follows + * [offset] for the given [granularity], or `null` when there is nothing after it. + */ + fun following( + text: CharSequence, + granularity: Int, + offset: Int, + ): IntArray? = + when (granularity) { + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterFollowing(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordFollowing(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> lineFollowing(text, offset) + else -> null + } + + /** + * Returns the `[start, end]` range (end-exclusive) of the segment that precedes + * [offset] for the given [granularity], or `null` when there is nothing before it. + */ + fun preceding( + text: CharSequence, + granularity: Int, + offset: Int, + ): IntArray? = + when (granularity) { + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterPreceding(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordPreceding(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> linePreceding(text, offset) + else -> null + } + + // --------------------------------------------------------------------------------------------- + // Character + // --------------------------------------------------------------------------------------------- + + private fun characterFollowing(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + val iterator = BreakIterator.getCharacterInstance().apply { setText(text.toString()) } + var start = if (offset < 0) 0 else offset + if (!iterator.isBoundary(start)) { + start = iterator.following(start) + if (start == DONE) return null + } + val end = iterator.following(start) + if (end == DONE) return null + return intArrayOf(start, end) + } + + private fun characterPreceding(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + val iterator = BreakIterator.getCharacterInstance().apply { setText(text.toString()) } + var end = if (offset > length) length else offset + if (!iterator.isBoundary(end)) { + end = iterator.preceding(end) + if (end == DONE) return null + } + val start = iterator.preceding(end) + if (start == DONE) return null + return intArrayOf(start, end) + } + + // --------------------------------------------------------------------------------------------- + // Word + // --------------------------------------------------------------------------------------------- + + private fun wordFollowing(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } + var start = if (offset < 0) 0 else offset + // Skip past any non-word characters (whitespace, punctuation) to the start of a word. + while (!isLetterOrDigit(text, start) && !isWordStart(text, start)) { + start = iterator.following(start) + if (start == DONE) return null + } + val end = iterator.following(start) + if (end == DONE || !isWordEnd(text, end)) return null + return intArrayOf(start, end) + } + + private fun wordPreceding(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } + var end = if (offset > length) length else offset + while (!isLetterOrDigit(text, end - 1) && !isWordEnd(text, end)) { + end = iterator.preceding(end) + if (end == DONE) return null + } + val start = iterator.preceding(end) + if (start == DONE || !isWordStart(text, start)) return null + return intArrayOf(start, end) + } + + private fun isWordStart(text: CharSequence, index: Int): Boolean = + isLetterOrDigit(text, index) && (index == 0 || !isLetterOrDigit(text, index - 1)) + + private fun isWordEnd(text: CharSequence, index: Int): Boolean = + (index > 0 && isLetterOrDigit(text, index - 1)) && + (index == text.length || !isLetterOrDigit(text, index)) + + private fun isLetterOrDigit(text: CharSequence, index: Int): Boolean = + index in 0 until text.length && Character.isLetterOrDigit(text[index]) + + // --------------------------------------------------------------------------------------------- + // Line (logical, '\n'-separated) + // --------------------------------------------------------------------------------------------- + + private fun lineFollowing(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + var start = if (offset < 0) 0 else offset + // When not already at a line start, advance to the beginning of the next line. + if (start > 0 && text[start - 1] != '\n') { + while (start < length && text[start] != '\n') start++ + if (start < length) start++ // step over the newline onto the next line + if (start >= length) return null + } + var end = start + while (end < length && text[end] != '\n') end++ + return intArrayOf(start, end) + } + + private fun linePreceding(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + var end = if (offset > length) length else offset + // If sitting on a line start, step back onto the previous line's newline. + if (text[end - 1] == '\n') end-- + if (end <= 0) return null + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + var lineEnd = start + while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ + return intArrayOf(start, lineEnd) + } +} diff --git a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt new file mode 100644 index 0000000000..e2e697ac65 --- /dev/null +++ b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt @@ -0,0 +1,175 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.editor.utils + +import android.view.accessibility.AccessibilityNodeInfo +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * Unit tests for [EditorAccessibilitySegments], which drives screen-reader cursor + * synchronization. The returned ranges are absolute char indices into the flat text. + */ +@RunWith(RobolectricTestRunner::class) +class EditorAccessibilitySegmentsTest { + + private val char = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER + private val word = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD + private val line = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE + + private fun following(text: String, granularity: Int, offset: Int) = + EditorAccessibilitySegments.following(text, granularity, offset)?.toList() + + private fun preceding(text: String, granularity: Int, offset: Int) = + EditorAccessibilitySegments.preceding(text, granularity, offset)?.toList() + + // --------------------------------------------------------------------------------------------- + // Character + // --------------------------------------------------------------------------------------------- + + @Test + fun `character following returns the next single character`() { + assertThat(following("abc", char, 0)).isEqualTo(listOf(0, 1)) + assertThat(following("abc", char, 1)).isEqualTo(listOf(1, 2)) + } + + @Test + fun `character following at end returns null`() { + assertThat(following("abc", char, 3)).isNull() + } + + @Test + fun `character preceding returns the previous single character`() { + assertThat(preceding("abc", char, 3)).isEqualTo(listOf(2, 3)) + assertThat(preceding("abc", char, 1)).isEqualTo(listOf(0, 1)) + } + + @Test + fun `character preceding at start returns null`() { + assertThat(preceding("abc", char, 0)).isNull() + } + + // --------------------------------------------------------------------------------------------- + // Word + // --------------------------------------------------------------------------------------------- + + @Test + fun `word following skips whitespace and returns whole words`() { + val text = "foo bar" + assertThat(following(text, word, 0)).isEqualTo(listOf(0, 3)) // foo + assertThat(following(text, word, 3)).isEqualTo(listOf(4, 7)) // bar + } + + @Test + fun `word following past last word returns null`() { + assertThat(following("foo bar", word, 7)).isNull() + } + + @Test + fun `word preceding returns previous word`() { + val text = "foo bar" + assertThat(preceding(text, word, 7)).isEqualTo(listOf(4, 7)) // bar + assertThat(preceding(text, word, 4)).isEqualTo(listOf(0, 3)) // foo + } + + @Test + fun `word navigation skips separator punctuation between identifiers`() { + // Simulates code like "x=y" — the identifiers are words, '=' is skipped. + val text = "x=y" + assertThat(following(text, word, 0)).isEqualTo(listOf(0, 1)) // x + assertThat(following(text, word, 1)).isEqualTo(listOf(2, 3)) // y + } + + @Test + fun `word navigation treats a dotted identifier as a single word`() { + // Matches EditText/BreakIterator semantics: "a.b" is one word, not three. + val text = "a.b" + assertThat(following(text, word, 0)).isEqualTo(listOf(0, 3)) + } + + // --------------------------------------------------------------------------------------------- + // Line + // --------------------------------------------------------------------------------------------- + + @Test + fun `line following returns the current line when at its start`() { + val text = "abc\ndef\nghi" + assertThat(following(text, line, 0)).isEqualTo(listOf(0, 3)) // abc + } + + @Test + fun `line following from mid-line advances to the next line`() { + val text = "abc\ndef\nghi" + // offset 5 is inside "def"; next line is "ghi". + assertThat(following(text, line, 5)).isEqualTo(listOf(8, 11)) + } + + @Test + fun `line following from end of a line moves to the next line`() { + val text = "abc\ndef" + // offset 3 is the '\n' after abc -> caret sits at end of line 0. + assertThat(following(text, line, 3)).isEqualTo(listOf(4, 7)) // def + } + + @Test + fun `line preceding returns the line the caret sits at the end of`() { + val text = "abc\ndef" + assertThat(preceding(text, line, 7)).isEqualTo(listOf(4, 7)) // def + } + + @Test + fun `line preceding from a line start moves to the previous line`() { + val text = "abc\ndef" + // offset 4 is the start of "def"; previous line is "abc". + assertThat(preceding(text, line, 4)).isEqualTo(listOf(0, 3)) + } + + @Test + fun `line handles empty lines`() { + val text = "abc\n\ndef" + // index 4 is the empty line between the two newlines. + assertThat(following(text, line, 4)).isEqualTo(listOf(4, 4)) + } + + // --------------------------------------------------------------------------------------------- + // Guards + // --------------------------------------------------------------------------------------------- + + @Test + fun `empty text yields no segments`() { + assertThat(following("", char, 0)).isNull() + assertThat(preceding("", word, 0)).isNull() + assertThat(following("", line, 0)).isNull() + } + + @Test + fun `unsupported granularity yields null`() { + assertThat(following("abc", 999, 0)).isNull() + assertThat(preceding("abc", 999, 3)).isNull() + } + + @Test + fun `supported granularities bitmask includes character word and line`() { + val mask = EditorAccessibilitySegments.SUPPORTED_GRANULARITIES + assertThat(mask and char).isEqualTo(char) + assertThat(mask and word).isEqualTo(word) + assertThat(mask and line).isEqualTo(line) + } +} From 57c9cabd58ed502f1f5123d9e3594ce6372133e6 Mon Sep 17 00:00:00 2001 From: makhlwf Date: Sat, 11 Jul 2026 23:46:32 +0200 Subject: [PATCH 2/8] fix(editor): address review feedback on a11y cursor sync - getAccessibilityClassName() now mirrors the !isReleased && isEnabled && isEditable guard used by createAccessibilityNodeInfo(), so a read-only or released editor is no longer announced as an "Edit box". - Word granularity navigation snaps a mid-word offset to the enclosing word's start/end, so navigation traverses the whole word (e.g. "hello"@2 -> [0,5]) instead of a truncated range. Adds regression tests for mid-word offsets. - Narrow the accessibility catch blocks to IndexOutOfBoundsException / IllegalArgumentException instead of a broad Exception, per project convention. --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 21 +++++++++++++++---- .../utils/EditorAccessibilitySegments.kt | 10 +++++++++ .../utils/EditorAccessibilitySegmentsTest.kt | 11 ++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index 5cd620238d..adc0f0bab5 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -678,7 +678,14 @@ open class IDEEditor private val isTouchExplorationEnabled: Boolean get() = accessibilityManager?.isTouchExplorationEnabled == true - override fun getAccessibilityClassName(): CharSequence = EditText::class.java.name + override fun getAccessibilityClassName(): CharSequence = + // Only advertise EditText semantics in the same states createAccessibilityNodeInfo() + // does, so a read-only or released editor is not announced as an "Edit box". + if (!isReleased && isEnabled && isEditable) { + EditText::class.java.name + } else { + super.getAccessibilityClassName() + } override fun createAccessibilityNodeInfo(): AccessibilityNodeInfo? { val info = super.createAccessibilityNodeInfo() ?: return null @@ -740,7 +747,10 @@ open class IDEEditor if (line < 0 || column < 0) return false setSelection(line, column) true - } catch (e: Exception) { + } catch (e: IndexOutOfBoundsException) { + log.error("Error placing cursor from accessibility click", e) + false + } catch (e: IllegalArgumentException) { log.error("Error placing cursor from accessibility click", e) false } @@ -823,7 +833,10 @@ open class IDEEditor setSelectionRegion(startPos.line, startPos.column, endPos.line, endPos.column) } true - } catch (e: Exception) { + } catch (e: IndexOutOfBoundsException) { + log.error("Error applying accessibility selection [$start, $end]", e) + false + } catch (e: IllegalArgumentException) { log.error("Error applying accessibility selection [$start, $end]", e) false } @@ -1638,4 +1651,4 @@ open class IDEEditor val (startCol, endCol) = range setSelectionRegion(line, startCol, line, endCol) } - } + } \ No newline at end of file diff --git a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt index 4c4a352e16..e733e52877 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt @@ -123,6 +123,11 @@ object EditorAccessibilitySegments { if (length <= 0 || offset >= length) return null val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } var start = if (offset < 0) 0 else offset + // If the offset lands inside a word, snap back to that word's start so the whole + // enclosing word is traversed instead of a truncated tail (e.g. "hello"@2 -> [0,5]). + if (isLetterOrDigit(text, start)) { + while (start > 0 && isLetterOrDigit(text, start - 1)) start-- + } // Skip past any non-word characters (whitespace, punctuation) to the start of a word. while (!isLetterOrDigit(text, start) && !isWordStart(text, start)) { start = iterator.following(start) @@ -138,6 +143,11 @@ object EditorAccessibilitySegments { if (length <= 0 || offset <= 0) return null val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } var end = if (offset > length) length else offset + // If the offset lands inside a word, snap forward to that word's end so the whole + // enclosing word is traversed instead of a truncated head (e.g. "hello"@2 -> [0,5]). + if (isLetterOrDigit(text, end - 1) && isLetterOrDigit(text, end)) { + while (end < length && isLetterOrDigit(text, end)) end++ + } while (!isLetterOrDigit(text, end - 1) && !isWordEnd(text, end)) { end = iterator.preceding(end) if (end == DONE) return null diff --git a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt index e2e697ac65..4189db3a75 100644 --- a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt +++ b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt @@ -82,6 +82,17 @@ class EditorAccessibilitySegmentsTest { assertThat(following("foo bar", word, 7)).isNull() } + @Test + fun `word following from inside a word snaps to the whole enclosing word`() { + // Offset 2 is inside "hello"; the whole word must be traversed, not a truncated tail. + assertThat(following("hello", word, 2)).isEqualTo(listOf(0, 5)) + } + + @Test + fun `word preceding from inside a word snaps to the whole enclosing word`() { + assertThat(preceding("hello", word, 2)).isEqualTo(listOf(0, 5)) + } + @Test fun `word preceding returns previous word`() { val text = "foo bar" From 2a994d30324187346c3c7a35de0b26d26e618ba8 Mon Sep 17 00:00:00 2001 From: makhlwf Date: Tue, 14 Jul 2026 00:01:08 +0200 Subject: [PATCH 3/8] fix(editor): add paragraph a11y granularity and text change/selection events Two TalkBack gaps surfaced in on-device testing: 1. Line and paragraph navigation didn't work. PARAGRAPH granularity was never advertised, and the editor never emitted TYPE_VIEW_TEXT_SELECTION_CHANGED, so the screen reader could not track the caret across the larger granularities. Advertise + implement PARAGRAPH (non-empty logical lines, blank lines skipped) and fire a selection-changed event on every selection change. 2. Inserted/deleted characters were not announced. Emit TYPE_VIEW_TEXT_CHANGED on content changes with fromIndex, added/removed counts and beforeText reconstructed from the change, so TalkBack speaks typed and deleted text like a standard EditText. Both event senders are no-ops when no accessibility service is enabled. Adds unit tests for paragraph navigation. --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 73 +++++++++++++++++++ .../utils/EditorAccessibilitySegments.kt | 35 ++++++++- .../utils/EditorAccessibilitySegmentsTest.kt | 32 ++++++++ 3 files changed, 139 insertions(+), 1 deletion(-) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index adc0f0bab5..b5a7094296 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -868,6 +868,73 @@ open class IDEEditor event.text.add(text.toString()) sendAccessibilityEventUnchecked(event) } + /** + * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED] event so the screen reader + * tracks the caret/selection as it moves — required for reliable movement-by-granularity + * navigation (lines/paragraphs in particular) and to mirror standard [EditText] behaviour. + * Called on every selection change; cheap no-op when no accessibility service is running. + */ + @Suppress("DEPRECATION") + fun sendSelectionChangedAccessibilityEvent() { + val manager = accessibilityManager ?: return + if (!manager.isEnabled) return + val cur = cursor ?: return + val event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) + onInitializeAccessibilityEvent(event) + event.className = EditText::class.java.name + val content = text.toString() + event.fromIndex = cur.left + event.toIndex = cur.right + event.itemCount = content.length + event.text.add(content) + sendAccessibilityEventUnchecked(event) + } + + /** + * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED] event so the screen reader announces + * inserted and deleted characters, like a standard [EditText]. TalkBack reconstructs the + * change from [AccessibilityEvent.getFromIndex], added/removed counts, the current text and + * [AccessibilityEvent.getBeforeText]. Cheap no-op when no accessibility service is running. + */ + @Suppress("DEPRECATION") + fun sendTextChangedAccessibilityEvent(changeEvent: ContentChangeEvent) { + val manager = accessibilityManager ?: return + if (!manager.isEnabled) return + val current = text.toString() + val length = current.length + val fromIndex = changeEvent.changeStart.index.coerceIn(0, length) + val changed = changeEvent.changedText + val changedLen = changed.length + + val event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) + onInitializeAccessibilityEvent(event) + event.className = EditText::class.java.name + event.fromIndex = fromIndex + when (changeEvent.action) { + ContentChangeEvent.ACTION_INSERT -> { + event.addedCount = changedLen + event.removedCount = 0 + // beforeText = current text with the just-inserted range removed. + val insertEnd = (fromIndex + changedLen).coerceIn(0, length) + event.beforeText = current.substring(0, fromIndex) + current.substring(insertEnd) + } + + ContentChangeEvent.ACTION_DELETE -> { + event.addedCount = 0 + event.removedCount = changedLen + // beforeText = current text with the just-deleted text put back. + event.beforeText = current.substring(0, fromIndex) + changed + current.substring(fromIndex) + } + + else -> { // ACTION_SET_NEW_TEXT and any other wholesale replacement + event.addedCount = length + event.removedCount = 0 + event.beforeText = "" + } + } + event.text.add(current) + sendAccessibilityEventUnchecked(event) + } // endregion Accessibility override fun copyTextToClipboard( @@ -1184,6 +1251,9 @@ open class IDEEditor return@subscribeEvent } + // Announce inserted/deleted characters to screen readers, like a standard EditText. + sendTextChangedAccessibilityEvent(event) + refreshModifiedState() // A pending inline suggestion is anchored to the pre-edit cursor position; any edit // invalidates it. The plugin re-issues one after its debounce. @@ -1204,6 +1274,9 @@ open class IDEEditor return@subscribeEvent } + // Keep the screen reader's caret in sync as the selection moves, like an EditText. + sendSelectionChangedAccessibilityEvent() + // Moving the cursor away from the anchor makes ghost text meaningless. dismissInlineSuggestion() diff --git a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt index e733e52877..ea8620d5d0 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt @@ -48,7 +48,8 @@ object EditorAccessibilitySegments { const val SUPPORTED_GRANULARITIES = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER or AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD or - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE or + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH /** * Returns the `[start, end]` range (end-exclusive) of the segment that follows @@ -63,6 +64,7 @@ object EditorAccessibilitySegments { AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterFollowing(text, offset) AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordFollowing(text, offset) AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> lineFollowing(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH -> paragraphFollowing(text, offset) else -> null } @@ -79,6 +81,7 @@ object EditorAccessibilitySegments { AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterPreceding(text, offset) AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordPreceding(text, offset) AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> linePreceding(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH -> paragraphPreceding(text, offset) else -> null } @@ -199,4 +202,34 @@ object EditorAccessibilitySegments { while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ return intArrayOf(start, lineEnd) } + + // --------------------------------------------------------------------------------------------- + // Paragraph (non-empty '\n'-separated lines; blank lines are skipped, as EditText does) + // --------------------------------------------------------------------------------------------- + + private fun paragraphFollowing(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + var start = if (offset < 0) 0 else offset + // Skip blank lines so navigation lands on the next non-empty line. + while (start < length && text[start] == '\n') start++ + if (start >= length) return null + // Snap to the start of the enclosing line. + while (start > 0 && text[start - 1] != '\n') start-- + var end = start + while (end < length && text[end] != '\n') end++ + return intArrayOf(start, end) + } + + private fun paragraphPreceding(text: CharSequence, offset: Int): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + var end = if (offset > length) length else offset + // Skip blank lines (trailing newlines) so we land on the previous non-empty line's end. + while (end > 0 && text[end - 1] == '\n') end-- + if (end <= 0) return null + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + return intArrayOf(start, end) + } } diff --git a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt index 4189db3a75..db82300ba8 100644 --- a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt +++ b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt @@ -33,6 +33,7 @@ class EditorAccessibilitySegmentsTest { private val char = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER private val word = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD private val line = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE + private val paragraph = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH private fun following(text: String, granularity: Int, offset: Int) = EditorAccessibilitySegments.following(text, granularity, offset)?.toList() @@ -159,6 +160,36 @@ class EditorAccessibilitySegmentsTest { assertThat(following(text, line, 4)).isEqualTo(listOf(4, 4)) } + // --------------------------------------------------------------------------------------------- + // Paragraph + // --------------------------------------------------------------------------------------------- + + @Test + fun `paragraph following returns the current non-empty line`() { + val text = "abc\ndef\nghi" + assertThat(following(text, paragraph, 0)).isEqualTo(listOf(0, 3)) // abc + } + + @Test + fun `paragraph following skips blank lines`() { + val text = "abc\n\ndef" + // From end of "abc" (index 3), the next paragraph is "def" — the blank line is skipped. + assertThat(following(text, paragraph, 3)).isEqualTo(listOf(5, 8)) + } + + @Test + fun `paragraph preceding skips blank lines`() { + val text = "abc\n\ndef" + // From the start of "def" (index 5), the previous paragraph is "abc". + assertThat(preceding(text, paragraph, 5)).isEqualTo(listOf(0, 3)) + } + + @Test + fun `paragraph preceding returns the line the caret sits at the end of`() { + val text = "abc\ndef" + assertThat(preceding(text, paragraph, 7)).isEqualTo(listOf(4, 7)) // def + } + // --------------------------------------------------------------------------------------------- // Guards // --------------------------------------------------------------------------------------------- @@ -182,5 +213,6 @@ class EditorAccessibilitySegmentsTest { assertThat(mask and char).isEqualTo(char) assertThat(mask and word).isEqualTo(word) assertThat(mask and line).isEqualTo(line) + assertThat(mask and paragraph).isEqualTo(paragraph) } } From 16e8667ff1695414501647ab64d517c6d51a711d Mon Sep 17 00:00:00 2001 From: makhlwf Date: Tue, 14 Jul 2026 01:09:37 +0200 Subject: [PATCH 4/8] fix(editor): correct mid-paragraph a11y navigation paragraphPreceding returned the raw offset as its end bound, so a mid-paragraph offset yielded a truncated range (e.g. "abc\ndef\nghi"@5 gave [4,5] instead of [4,7]). paragraphFollowing also snapped to the current line instead of advancing. Rework both to mirror lineFollowing/linePreceding (advance to the next line forward; return the whole enclosing line backward) while still skipping blank lines, and add mid-paragraph regression tests. --- .../editor/utils/EditorAccessibilitySegments.kt | 16 ++++++++++++---- .../utils/EditorAccessibilitySegmentsTest.kt | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt index ea8620d5d0..cd4a327305 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt @@ -211,11 +211,15 @@ object EditorAccessibilitySegments { val length = text.length if (length <= 0 || offset >= length) return null var start = if (offset < 0) 0 else offset + // Mirror lineFollowing: when not already at a line start, advance to the next line. + if (start > 0 && text[start - 1] != '\n') { + while (start < length && text[start] != '\n') start++ + if (start < length) start++ // step over the newline onto the next line + if (start >= length) return null + } // Skip blank lines so navigation lands on the next non-empty line. while (start < length && text[start] == '\n') start++ if (start >= length) return null - // Snap to the start of the enclosing line. - while (start > 0 && text[start - 1] != '\n') start-- var end = start while (end < length && text[end] != '\n') end++ return intArrayOf(start, end) @@ -225,11 +229,15 @@ object EditorAccessibilitySegments { val length = text.length if (length <= 0 || offset <= 0) return null var end = if (offset > length) length else offset - // Skip blank lines (trailing newlines) so we land on the previous non-empty line's end. + // Skip blank lines (trailing newlines) so we land on the previous non-empty line. while (end > 0 && text[end - 1] == '\n') end-- if (end <= 0) return null var start = end while (start > 0 && text[start - 1] != '\n') start-- - return intArrayOf(start, end) + // Mirror linePreceding: scan forward to the line end so a mid-paragraph offset returns + // the whole line instead of a truncated head. + var lineEnd = start + while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ + return intArrayOf(start, lineEnd) } } diff --git a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt index db82300ba8..c3163e7f22 100644 --- a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt +++ b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt @@ -190,6 +190,20 @@ class EditorAccessibilitySegmentsTest { assertThat(preceding(text, paragraph, 7)).isEqualTo(listOf(4, 7)) // def } + @Test + fun `paragraph following from a mid-paragraph offset advances to the next paragraph`() { + val text = "abc\ndef\nghi" + // offset 5 is inside "def"; next paragraph is "ghi". + assertThat(following(text, paragraph, 5)).isEqualTo(listOf(8, 11)) + } + + @Test + fun `paragraph preceding from a mid-paragraph offset returns the whole enclosing paragraph`() { + val text = "abc\ndef\nghi" + // offset 5 is inside "def"; the whole line must be returned, not a truncated head. + assertThat(preceding(text, paragraph, 5)).isEqualTo(listOf(4, 7)) + } + // --------------------------------------------------------------------------------------------- // Guards // --------------------------------------------------------------------------------------------- From 32ff0dbec6550037358afe5fdb543c45c284192e Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Tue, 20 Oct 2026 17:24:39 +0100 Subject: [PATCH 5/8] style(ADFA=4605): Spotless reformat --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 65 +-- .../utils/EditorAccessibilitySegments.kt | 432 ++++++++++-------- .../utils/EditorAccessibilitySegmentsTest.kt | 405 ++++++++-------- 3 files changed, 474 insertions(+), 428 deletions(-) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index b5a7094296..9bc075d869 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -715,25 +715,29 @@ open class IDEEditor arguments: Bundle?, ): Boolean { when (action) { - AccessibilityNodeInfo.ACTION_SET_SELECTION -> + AccessibilityNodeInfo.ACTION_SET_SELECTION -> { if (handleAccessibilitySetSelection(arguments)) return true + } - AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY -> + AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY -> { if (handleAccessibilityGranularityMove(action, arguments, forward = true)) return true + } - AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY -> + AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY -> { if (handleAccessibilityGranularityMove(action, arguments, forward = false)) return true + } - AccessibilityNodeInfo.ACTION_CLICK -> + AccessibilityNodeInfo.ACTION_CLICK -> { if (handleAccessibilityClick()) return true + } } return super.performAccessibilityAction(action, arguments) } /** - * Places the caret where the user last explored by touch. This makes a TalkBack double-tap - * on a word or line move the real text cursor to that spot instead of the node's center. - */ + * Places the caret where the user last explored by touch. This makes a TalkBack double-tap + * on a word or line move the real text cursor to that spot instead of the node's center. + */ private fun handleAccessibilityClick(): Boolean { if (isReleased || !isEditable || !isTouchExplorationEnabled) return false val x = lastHoverX @@ -773,23 +777,25 @@ open class IDEEditor } /** - * Handles the move-by-granularity actions. Moves the real text cursor to the next/previous - * character, word or line and reports the traversed segment so the screen reader reads it, - * mirroring [EditText] behaviour. - */ + * Handles the move-by-granularity actions. Moves the real text cursor to the next/previous + * character, word or line and reports the traversed segment so the screen reader reads it, + * mirroring [EditText] behaviour. + */ private fun handleAccessibilityGranularityMove( action: Int, arguments: Bundle?, forward: Boolean, ): Boolean { if (isReleased || !isEditable || arguments == null) return false - val granularity = arguments.getInt( - AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, - ) - val extendSelection = arguments.getBoolean( - AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, - false, - ) + val granularity = + arguments.getInt( + AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, + ) + val extendSelection = + arguments.getBoolean( + AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN, + false, + ) val content = text val cur = cursor ?: return false val selStart = cur.left @@ -821,7 +827,10 @@ open class IDEEditor } /** Converts absolute char indices to (line, column) positions and moves the selection. */ - private fun applySelectionFromIndices(start: Int, end: Int): Boolean { + private fun applySelectionFromIndices( + start: Int, + end: Int, + ): Boolean { val content = text return try { val indexer = content.indexer @@ -843,9 +852,9 @@ open class IDEEditor } /** - * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY] event so the - * screen reader announces the character/word/line the caret just traversed. - */ + * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY] event so the + * screen reader announces the character/word/line the caret just traversed. + */ @Suppress("DEPRECATION") // AccessibilityEvent(int) requires API 30; obtain() works on minSdk 28. private fun sendTextTraversedEvent( fromIndex: Int, @@ -855,9 +864,10 @@ open class IDEEditor ) { val manager = accessibilityManager ?: return if (!manager.isEnabled) return - val event = AccessibilityEvent.obtain( - AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, - ) + val event = + AccessibilityEvent.obtain( + AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, + ) onInitializeAccessibilityEvent(event) event.className = EditText::class.java.name event.fromIndex = fromIndex @@ -868,6 +878,7 @@ open class IDEEditor event.text.add(text.toString()) sendAccessibilityEventUnchecked(event) } + /** * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED] event so the screen reader * tracks the caret/selection as it moves — required for reliable movement-by-granularity @@ -1412,7 +1423,7 @@ open class IDEEditor content = text, file = currentFile, cursor = - text.cursor.apply {// set(lineToProcess, text.getLine(lineToProcess).length) + text.cursor.apply { // set(lineToProcess, text.getLine(lineToProcess).length) }, ) @@ -1724,4 +1735,4 @@ open class IDEEditor val (startCol, endCol) = range setSelectionRegion(line, startCol, line, endCol) } - } \ No newline at end of file + } diff --git a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt index cd4a327305..c6a21f5e56 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegments.kt @@ -38,206 +38,236 @@ import java.text.BreakIterator * @author Code On The Go */ object EditorAccessibilitySegments { + private const val DONE = BreakIterator.DONE - private const val DONE = BreakIterator.DONE - - /** - * The set of movement granularities that [following] and [preceding] can handle. - * Intended to be advertised via [AccessibilityNodeInfo.setMovementGranularities]. - */ - const val SUPPORTED_GRANULARITIES = - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER or - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD or - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE or - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH - - /** - * Returns the `[start, end]` range (end-exclusive) of the segment that follows - * [offset] for the given [granularity], or `null` when there is nothing after it. - */ - fun following( - text: CharSequence, - granularity: Int, - offset: Int, - ): IntArray? = - when (granularity) { - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterFollowing(text, offset) - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordFollowing(text, offset) - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> lineFollowing(text, offset) - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH -> paragraphFollowing(text, offset) - else -> null - } - - /** - * Returns the `[start, end]` range (end-exclusive) of the segment that precedes - * [offset] for the given [granularity], or `null` when there is nothing before it. - */ - fun preceding( - text: CharSequence, - granularity: Int, - offset: Int, - ): IntArray? = - when (granularity) { - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterPreceding(text, offset) - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordPreceding(text, offset) - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> linePreceding(text, offset) - AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH -> paragraphPreceding(text, offset) - else -> null - } - - // --------------------------------------------------------------------------------------------- - // Character - // --------------------------------------------------------------------------------------------- - - private fun characterFollowing(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset >= length) return null - val iterator = BreakIterator.getCharacterInstance().apply { setText(text.toString()) } - var start = if (offset < 0) 0 else offset - if (!iterator.isBoundary(start)) { - start = iterator.following(start) - if (start == DONE) return null - } - val end = iterator.following(start) - if (end == DONE) return null - return intArrayOf(start, end) - } - - private fun characterPreceding(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset <= 0) return null - val iterator = BreakIterator.getCharacterInstance().apply { setText(text.toString()) } - var end = if (offset > length) length else offset - if (!iterator.isBoundary(end)) { - end = iterator.preceding(end) - if (end == DONE) return null - } - val start = iterator.preceding(end) - if (start == DONE) return null - return intArrayOf(start, end) - } - - // --------------------------------------------------------------------------------------------- - // Word - // --------------------------------------------------------------------------------------------- - - private fun wordFollowing(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset >= length) return null - val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } - var start = if (offset < 0) 0 else offset - // If the offset lands inside a word, snap back to that word's start so the whole - // enclosing word is traversed instead of a truncated tail (e.g. "hello"@2 -> [0,5]). - if (isLetterOrDigit(text, start)) { - while (start > 0 && isLetterOrDigit(text, start - 1)) start-- - } - // Skip past any non-word characters (whitespace, punctuation) to the start of a word. - while (!isLetterOrDigit(text, start) && !isWordStart(text, start)) { - start = iterator.following(start) - if (start == DONE) return null - } - val end = iterator.following(start) - if (end == DONE || !isWordEnd(text, end)) return null - return intArrayOf(start, end) - } - - private fun wordPreceding(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset <= 0) return null - val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } - var end = if (offset > length) length else offset - // If the offset lands inside a word, snap forward to that word's end so the whole - // enclosing word is traversed instead of a truncated head (e.g. "hello"@2 -> [0,5]). - if (isLetterOrDigit(text, end - 1) && isLetterOrDigit(text, end)) { - while (end < length && isLetterOrDigit(text, end)) end++ - } - while (!isLetterOrDigit(text, end - 1) && !isWordEnd(text, end)) { - end = iterator.preceding(end) - if (end == DONE) return null - } - val start = iterator.preceding(end) - if (start == DONE || !isWordStart(text, start)) return null - return intArrayOf(start, end) - } - - private fun isWordStart(text: CharSequence, index: Int): Boolean = - isLetterOrDigit(text, index) && (index == 0 || !isLetterOrDigit(text, index - 1)) - - private fun isWordEnd(text: CharSequence, index: Int): Boolean = - (index > 0 && isLetterOrDigit(text, index - 1)) && - (index == text.length || !isLetterOrDigit(text, index)) - - private fun isLetterOrDigit(text: CharSequence, index: Int): Boolean = - index in 0 until text.length && Character.isLetterOrDigit(text[index]) - - // --------------------------------------------------------------------------------------------- - // Line (logical, '\n'-separated) - // --------------------------------------------------------------------------------------------- - - private fun lineFollowing(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset >= length) return null - var start = if (offset < 0) 0 else offset - // When not already at a line start, advance to the beginning of the next line. - if (start > 0 && text[start - 1] != '\n') { - while (start < length && text[start] != '\n') start++ - if (start < length) start++ // step over the newline onto the next line - if (start >= length) return null - } - var end = start - while (end < length && text[end] != '\n') end++ - return intArrayOf(start, end) - } - - private fun linePreceding(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset <= 0) return null - var end = if (offset > length) length else offset - // If sitting on a line start, step back onto the previous line's newline. - if (text[end - 1] == '\n') end-- - if (end <= 0) return null - var start = end - while (start > 0 && text[start - 1] != '\n') start-- - var lineEnd = start - while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ - return intArrayOf(start, lineEnd) - } - - // --------------------------------------------------------------------------------------------- - // Paragraph (non-empty '\n'-separated lines; blank lines are skipped, as EditText does) - // --------------------------------------------------------------------------------------------- - - private fun paragraphFollowing(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset >= length) return null - var start = if (offset < 0) 0 else offset - // Mirror lineFollowing: when not already at a line start, advance to the next line. - if (start > 0 && text[start - 1] != '\n') { - while (start < length && text[start] != '\n') start++ - if (start < length) start++ // step over the newline onto the next line - if (start >= length) return null - } - // Skip blank lines so navigation lands on the next non-empty line. - while (start < length && text[start] == '\n') start++ - if (start >= length) return null - var end = start - while (end < length && text[end] != '\n') end++ - return intArrayOf(start, end) - } - - private fun paragraphPreceding(text: CharSequence, offset: Int): IntArray? { - val length = text.length - if (length <= 0 || offset <= 0) return null - var end = if (offset > length) length else offset - // Skip blank lines (trailing newlines) so we land on the previous non-empty line. - while (end > 0 && text[end - 1] == '\n') end-- - if (end <= 0) return null - var start = end - while (start > 0 && text[start - 1] != '\n') start-- - // Mirror linePreceding: scan forward to the line end so a mid-paragraph offset returns - // the whole line instead of a truncated head. - var lineEnd = start - while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ - return intArrayOf(start, lineEnd) - } + /** + * The set of movement granularities that [following] and [preceding] can handle. + * Intended to be advertised via [AccessibilityNodeInfo.setMovementGranularities]. + */ + const val SUPPORTED_GRANULARITIES = + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER or + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD or + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE or + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH + + /** + * Returns the `[start, end]` range (end-exclusive) of the segment that follows + * [offset] for the given [granularity], or `null` when there is nothing after it. + */ + fun following( + text: CharSequence, + granularity: Int, + offset: Int, + ): IntArray? = + when (granularity) { + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterFollowing(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordFollowing(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> lineFollowing(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH -> paragraphFollowing(text, offset) + else -> null + } + + /** + * Returns the `[start, end]` range (end-exclusive) of the segment that precedes + * [offset] for the given [granularity], or `null` when there is nothing before it. + */ + fun preceding( + text: CharSequence, + granularity: Int, + offset: Int, + ): IntArray? = + when (granularity) { + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER -> characterPreceding(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD -> wordPreceding(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE -> linePreceding(text, offset) + AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH -> paragraphPreceding(text, offset) + else -> null + } + + // --------------------------------------------------------------------------------------------- + // Character + // --------------------------------------------------------------------------------------------- + + private fun characterFollowing( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + val iterator = BreakIterator.getCharacterInstance().apply { setText(text.toString()) } + var start = if (offset < 0) 0 else offset + if (!iterator.isBoundary(start)) { + start = iterator.following(start) + if (start == DONE) return null + } + val end = iterator.following(start) + if (end == DONE) return null + return intArrayOf(start, end) + } + + private fun characterPreceding( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + val iterator = BreakIterator.getCharacterInstance().apply { setText(text.toString()) } + var end = if (offset > length) length else offset + if (!iterator.isBoundary(end)) { + end = iterator.preceding(end) + if (end == DONE) return null + } + val start = iterator.preceding(end) + if (start == DONE) return null + return intArrayOf(start, end) + } + + // --------------------------------------------------------------------------------------------- + // Word + // --------------------------------------------------------------------------------------------- + + private fun wordFollowing( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } + var start = if (offset < 0) 0 else offset + // If the offset lands inside a word, snap back to that word's start so the whole + // enclosing word is traversed instead of a truncated tail (e.g. "hello"@2 -> [0,5]). + if (isLetterOrDigit(text, start)) { + while (start > 0 && isLetterOrDigit(text, start - 1)) start-- + } + // Skip past any non-word characters (whitespace, punctuation) to the start of a word. + while (!isLetterOrDigit(text, start) && !isWordStart(text, start)) { + start = iterator.following(start) + if (start == DONE) return null + } + val end = iterator.following(start) + if (end == DONE || !isWordEnd(text, end)) return null + return intArrayOf(start, end) + } + + private fun wordPreceding( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + val iterator = BreakIterator.getWordInstance().apply { setText(text.toString()) } + var end = if (offset > length) length else offset + // If the offset lands inside a word, snap forward to that word's end so the whole + // enclosing word is traversed instead of a truncated head (e.g. "hello"@2 -> [0,5]). + if (isLetterOrDigit(text, end - 1) && isLetterOrDigit(text, end)) { + while (end < length && isLetterOrDigit(text, end)) end++ + } + while (!isLetterOrDigit(text, end - 1) && !isWordEnd(text, end)) { + end = iterator.preceding(end) + if (end == DONE) return null + } + val start = iterator.preceding(end) + if (start == DONE || !isWordStart(text, start)) return null + return intArrayOf(start, end) + } + + private fun isWordStart( + text: CharSequence, + index: Int, + ): Boolean = isLetterOrDigit(text, index) && (index == 0 || !isLetterOrDigit(text, index - 1)) + + private fun isWordEnd( + text: CharSequence, + index: Int, + ): Boolean = + (index > 0 && isLetterOrDigit(text, index - 1)) && + (index == text.length || !isLetterOrDigit(text, index)) + + private fun isLetterOrDigit( + text: CharSequence, + index: Int, + ): Boolean = index in 0 until text.length && Character.isLetterOrDigit(text[index]) + + // --------------------------------------------------------------------------------------------- + // Line (logical, '\n'-separated) + // --------------------------------------------------------------------------------------------- + + private fun lineFollowing( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + var start = if (offset < 0) 0 else offset + // When not already at a line start, advance to the beginning of the next line. + if (start > 0 && text[start - 1] != '\n') { + while (start < length && text[start] != '\n') start++ + if (start < length) start++ // step over the newline onto the next line + if (start >= length) return null + } + var end = start + while (end < length && text[end] != '\n') end++ + return intArrayOf(start, end) + } + + private fun linePreceding( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + var end = if (offset > length) length else offset + // If sitting on a line start, step back onto the previous line's newline. + if (text[end - 1] == '\n') end-- + if (end <= 0) return null + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + var lineEnd = start + while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ + return intArrayOf(start, lineEnd) + } + + // --------------------------------------------------------------------------------------------- + // Paragraph (non-empty '\n'-separated lines; blank lines are skipped, as EditText does) + // --------------------------------------------------------------------------------------------- + + private fun paragraphFollowing( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset >= length) return null + var start = if (offset < 0) 0 else offset + // Mirror lineFollowing: when not already at a line start, advance to the next line. + if (start > 0 && text[start - 1] != '\n') { + while (start < length && text[start] != '\n') start++ + if (start < length) start++ // step over the newline onto the next line + if (start >= length) return null + } + // Skip blank lines so navigation lands on the next non-empty line. + while (start < length && text[start] == '\n') start++ + if (start >= length) return null + var end = start + while (end < length && text[end] != '\n') end++ + return intArrayOf(start, end) + } + + private fun paragraphPreceding( + text: CharSequence, + offset: Int, + ): IntArray? { + val length = text.length + if (length <= 0 || offset <= 0) return null + var end = if (offset > length) length else offset + // Skip blank lines (trailing newlines) so we land on the previous non-empty line. + while (end > 0 && text[end - 1] == '\n') end-- + if (end <= 0) return null + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + // Mirror linePreceding: scan forward to the line end so a mid-paragraph offset returns + // the whole line instead of a truncated head. + var lineEnd = start + while (lineEnd < length && text[lineEnd] != '\n') lineEnd++ + return intArrayOf(start, lineEnd) + } } diff --git a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt index c3163e7f22..2a3a6d9145 100644 --- a/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt +++ b/editor/src/test/java/com/itsaky/androidide/editor/utils/EditorAccessibilitySegmentsTest.kt @@ -29,204 +29,209 @@ import org.robolectric.RobolectricTestRunner */ @RunWith(RobolectricTestRunner::class) class EditorAccessibilitySegmentsTest { - - private val char = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER - private val word = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD - private val line = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE - private val paragraph = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH - - private fun following(text: String, granularity: Int, offset: Int) = - EditorAccessibilitySegments.following(text, granularity, offset)?.toList() - - private fun preceding(text: String, granularity: Int, offset: Int) = - EditorAccessibilitySegments.preceding(text, granularity, offset)?.toList() - - // --------------------------------------------------------------------------------------------- - // Character - // --------------------------------------------------------------------------------------------- - - @Test - fun `character following returns the next single character`() { - assertThat(following("abc", char, 0)).isEqualTo(listOf(0, 1)) - assertThat(following("abc", char, 1)).isEqualTo(listOf(1, 2)) - } - - @Test - fun `character following at end returns null`() { - assertThat(following("abc", char, 3)).isNull() - } - - @Test - fun `character preceding returns the previous single character`() { - assertThat(preceding("abc", char, 3)).isEqualTo(listOf(2, 3)) - assertThat(preceding("abc", char, 1)).isEqualTo(listOf(0, 1)) - } - - @Test - fun `character preceding at start returns null`() { - assertThat(preceding("abc", char, 0)).isNull() - } - - // --------------------------------------------------------------------------------------------- - // Word - // --------------------------------------------------------------------------------------------- - - @Test - fun `word following skips whitespace and returns whole words`() { - val text = "foo bar" - assertThat(following(text, word, 0)).isEqualTo(listOf(0, 3)) // foo - assertThat(following(text, word, 3)).isEqualTo(listOf(4, 7)) // bar - } - - @Test - fun `word following past last word returns null`() { - assertThat(following("foo bar", word, 7)).isNull() - } - - @Test - fun `word following from inside a word snaps to the whole enclosing word`() { - // Offset 2 is inside "hello"; the whole word must be traversed, not a truncated tail. - assertThat(following("hello", word, 2)).isEqualTo(listOf(0, 5)) - } - - @Test - fun `word preceding from inside a word snaps to the whole enclosing word`() { - assertThat(preceding("hello", word, 2)).isEqualTo(listOf(0, 5)) - } - - @Test - fun `word preceding returns previous word`() { - val text = "foo bar" - assertThat(preceding(text, word, 7)).isEqualTo(listOf(4, 7)) // bar - assertThat(preceding(text, word, 4)).isEqualTo(listOf(0, 3)) // foo - } - - @Test - fun `word navigation skips separator punctuation between identifiers`() { - // Simulates code like "x=y" — the identifiers are words, '=' is skipped. - val text = "x=y" - assertThat(following(text, word, 0)).isEqualTo(listOf(0, 1)) // x - assertThat(following(text, word, 1)).isEqualTo(listOf(2, 3)) // y - } - - @Test - fun `word navigation treats a dotted identifier as a single word`() { - // Matches EditText/BreakIterator semantics: "a.b" is one word, not three. - val text = "a.b" - assertThat(following(text, word, 0)).isEqualTo(listOf(0, 3)) - } - - // --------------------------------------------------------------------------------------------- - // Line - // --------------------------------------------------------------------------------------------- - - @Test - fun `line following returns the current line when at its start`() { - val text = "abc\ndef\nghi" - assertThat(following(text, line, 0)).isEqualTo(listOf(0, 3)) // abc - } - - @Test - fun `line following from mid-line advances to the next line`() { - val text = "abc\ndef\nghi" - // offset 5 is inside "def"; next line is "ghi". - assertThat(following(text, line, 5)).isEqualTo(listOf(8, 11)) - } - - @Test - fun `line following from end of a line moves to the next line`() { - val text = "abc\ndef" - // offset 3 is the '\n' after abc -> caret sits at end of line 0. - assertThat(following(text, line, 3)).isEqualTo(listOf(4, 7)) // def - } - - @Test - fun `line preceding returns the line the caret sits at the end of`() { - val text = "abc\ndef" - assertThat(preceding(text, line, 7)).isEqualTo(listOf(4, 7)) // def - } - - @Test - fun `line preceding from a line start moves to the previous line`() { - val text = "abc\ndef" - // offset 4 is the start of "def"; previous line is "abc". - assertThat(preceding(text, line, 4)).isEqualTo(listOf(0, 3)) - } - - @Test - fun `line handles empty lines`() { - val text = "abc\n\ndef" - // index 4 is the empty line between the two newlines. - assertThat(following(text, line, 4)).isEqualTo(listOf(4, 4)) - } - - // --------------------------------------------------------------------------------------------- - // Paragraph - // --------------------------------------------------------------------------------------------- - - @Test - fun `paragraph following returns the current non-empty line`() { - val text = "abc\ndef\nghi" - assertThat(following(text, paragraph, 0)).isEqualTo(listOf(0, 3)) // abc - } - - @Test - fun `paragraph following skips blank lines`() { - val text = "abc\n\ndef" - // From end of "abc" (index 3), the next paragraph is "def" — the blank line is skipped. - assertThat(following(text, paragraph, 3)).isEqualTo(listOf(5, 8)) - } - - @Test - fun `paragraph preceding skips blank lines`() { - val text = "abc\n\ndef" - // From the start of "def" (index 5), the previous paragraph is "abc". - assertThat(preceding(text, paragraph, 5)).isEqualTo(listOf(0, 3)) - } - - @Test - fun `paragraph preceding returns the line the caret sits at the end of`() { - val text = "abc\ndef" - assertThat(preceding(text, paragraph, 7)).isEqualTo(listOf(4, 7)) // def - } - - @Test - fun `paragraph following from a mid-paragraph offset advances to the next paragraph`() { - val text = "abc\ndef\nghi" - // offset 5 is inside "def"; next paragraph is "ghi". - assertThat(following(text, paragraph, 5)).isEqualTo(listOf(8, 11)) - } - - @Test - fun `paragraph preceding from a mid-paragraph offset returns the whole enclosing paragraph`() { - val text = "abc\ndef\nghi" - // offset 5 is inside "def"; the whole line must be returned, not a truncated head. - assertThat(preceding(text, paragraph, 5)).isEqualTo(listOf(4, 7)) - } - - // --------------------------------------------------------------------------------------------- - // Guards - // --------------------------------------------------------------------------------------------- - - @Test - fun `empty text yields no segments`() { - assertThat(following("", char, 0)).isNull() - assertThat(preceding("", word, 0)).isNull() - assertThat(following("", line, 0)).isNull() - } - - @Test - fun `unsupported granularity yields null`() { - assertThat(following("abc", 999, 0)).isNull() - assertThat(preceding("abc", 999, 3)).isNull() - } - - @Test - fun `supported granularities bitmask includes character word and line`() { - val mask = EditorAccessibilitySegments.SUPPORTED_GRANULARITIES - assertThat(mask and char).isEqualTo(char) - assertThat(mask and word).isEqualTo(word) - assertThat(mask and line).isEqualTo(line) - assertThat(mask and paragraph).isEqualTo(paragraph) - } + private val char = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER + private val word = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD + private val line = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE + private val paragraph = AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH + + private fun following( + text: String, + granularity: Int, + offset: Int, + ) = EditorAccessibilitySegments.following(text, granularity, offset)?.toList() + + private fun preceding( + text: String, + granularity: Int, + offset: Int, + ) = EditorAccessibilitySegments.preceding(text, granularity, offset)?.toList() + + // --------------------------------------------------------------------------------------------- + // Character + // --------------------------------------------------------------------------------------------- + + @Test + fun `character following returns the next single character`() { + assertThat(following("abc", char, 0)).isEqualTo(listOf(0, 1)) + assertThat(following("abc", char, 1)).isEqualTo(listOf(1, 2)) + } + + @Test + fun `character following at end returns null`() { + assertThat(following("abc", char, 3)).isNull() + } + + @Test + fun `character preceding returns the previous single character`() { + assertThat(preceding("abc", char, 3)).isEqualTo(listOf(2, 3)) + assertThat(preceding("abc", char, 1)).isEqualTo(listOf(0, 1)) + } + + @Test + fun `character preceding at start returns null`() { + assertThat(preceding("abc", char, 0)).isNull() + } + + // --------------------------------------------------------------------------------------------- + // Word + // --------------------------------------------------------------------------------------------- + + @Test + fun `word following skips whitespace and returns whole words`() { + val text = "foo bar" + assertThat(following(text, word, 0)).isEqualTo(listOf(0, 3)) // foo + assertThat(following(text, word, 3)).isEqualTo(listOf(4, 7)) // bar + } + + @Test + fun `word following past last word returns null`() { + assertThat(following("foo bar", word, 7)).isNull() + } + + @Test + fun `word following from inside a word snaps to the whole enclosing word`() { + // Offset 2 is inside "hello"; the whole word must be traversed, not a truncated tail. + assertThat(following("hello", word, 2)).isEqualTo(listOf(0, 5)) + } + + @Test + fun `word preceding from inside a word snaps to the whole enclosing word`() { + assertThat(preceding("hello", word, 2)).isEqualTo(listOf(0, 5)) + } + + @Test + fun `word preceding returns previous word`() { + val text = "foo bar" + assertThat(preceding(text, word, 7)).isEqualTo(listOf(4, 7)) // bar + assertThat(preceding(text, word, 4)).isEqualTo(listOf(0, 3)) // foo + } + + @Test + fun `word navigation skips separator punctuation between identifiers`() { + // Simulates code like "x=y" — the identifiers are words, '=' is skipped. + val text = "x=y" + assertThat(following(text, word, 0)).isEqualTo(listOf(0, 1)) // x + assertThat(following(text, word, 1)).isEqualTo(listOf(2, 3)) // y + } + + @Test + fun `word navigation treats a dotted identifier as a single word`() { + // Matches EditText/BreakIterator semantics: "a.b" is one word, not three. + val text = "a.b" + assertThat(following(text, word, 0)).isEqualTo(listOf(0, 3)) + } + + // --------------------------------------------------------------------------------------------- + // Line + // --------------------------------------------------------------------------------------------- + + @Test + fun `line following returns the current line when at its start`() { + val text = "abc\ndef\nghi" + assertThat(following(text, line, 0)).isEqualTo(listOf(0, 3)) // abc + } + + @Test + fun `line following from mid-line advances to the next line`() { + val text = "abc\ndef\nghi" + // offset 5 is inside "def"; next line is "ghi". + assertThat(following(text, line, 5)).isEqualTo(listOf(8, 11)) + } + + @Test + fun `line following from end of a line moves to the next line`() { + val text = "abc\ndef" + // offset 3 is the '\n' after abc -> caret sits at end of line 0. + assertThat(following(text, line, 3)).isEqualTo(listOf(4, 7)) // def + } + + @Test + fun `line preceding returns the line the caret sits at the end of`() { + val text = "abc\ndef" + assertThat(preceding(text, line, 7)).isEqualTo(listOf(4, 7)) // def + } + + @Test + fun `line preceding from a line start moves to the previous line`() { + val text = "abc\ndef" + // offset 4 is the start of "def"; previous line is "abc". + assertThat(preceding(text, line, 4)).isEqualTo(listOf(0, 3)) + } + + @Test + fun `line handles empty lines`() { + val text = "abc\n\ndef" + // index 4 is the empty line between the two newlines. + assertThat(following(text, line, 4)).isEqualTo(listOf(4, 4)) + } + + // --------------------------------------------------------------------------------------------- + // Paragraph + // --------------------------------------------------------------------------------------------- + + @Test + fun `paragraph following returns the current non-empty line`() { + val text = "abc\ndef\nghi" + assertThat(following(text, paragraph, 0)).isEqualTo(listOf(0, 3)) // abc + } + + @Test + fun `paragraph following skips blank lines`() { + val text = "abc\n\ndef" + // From end of "abc" (index 3), the next paragraph is "def" — the blank line is skipped. + assertThat(following(text, paragraph, 3)).isEqualTo(listOf(5, 8)) + } + + @Test + fun `paragraph preceding skips blank lines`() { + val text = "abc\n\ndef" + // From the start of "def" (index 5), the previous paragraph is "abc". + assertThat(preceding(text, paragraph, 5)).isEqualTo(listOf(0, 3)) + } + + @Test + fun `paragraph preceding returns the line the caret sits at the end of`() { + val text = "abc\ndef" + assertThat(preceding(text, paragraph, 7)).isEqualTo(listOf(4, 7)) // def + } + + @Test + fun `paragraph following from a mid-paragraph offset advances to the next paragraph`() { + val text = "abc\ndef\nghi" + // offset 5 is inside "def"; next paragraph is "ghi". + assertThat(following(text, paragraph, 5)).isEqualTo(listOf(8, 11)) + } + + @Test + fun `paragraph preceding from a mid-paragraph offset returns the whole enclosing paragraph`() { + val text = "abc\ndef\nghi" + // offset 5 is inside "def"; the whole line must be returned, not a truncated head. + assertThat(preceding(text, paragraph, 5)).isEqualTo(listOf(4, 7)) + } + + // --------------------------------------------------------------------------------------------- + // Guards + // --------------------------------------------------------------------------------------------- + + @Test + fun `empty text yields no segments`() { + assertThat(following("", char, 0)).isNull() + assertThat(preceding("", word, 0)).isNull() + assertThat(following("", line, 0)).isNull() + } + + @Test + fun `unsupported granularity yields null`() { + assertThat(following("abc", 999, 0)).isNull() + assertThat(preceding("abc", 999, 3)).isNull() + } + + @Test + fun `supported granularities bitmask includes character word and line`() { + val mask = EditorAccessibilitySegments.SUPPORTED_GRANULARITIES + assertThat(mask and char).isEqualTo(char) + assertThat(mask and word).isEqualTo(word) + assertThat(mask and line).isEqualTo(line) + assertThat(mask and paragraph).isEqualTo(paragraph) + } } From 3029c4bff0c2cd71530eca47179addc8e77480e4 Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Tue, 20 Oct 2026 22:40:10 +0100 Subject: [PATCH 6/8] fix(ADFA-4605): Update cursor on TalkBack tap and add speech and haptic feedback - Update handleAccessibilityClick() to place the text cursor at the explored touch position (or current cursor position if no hover event preceded) using SelectionChangeEvent.CAUSE_TAP and ensure the position is visible - Add haptic feedback (HapticFeedbackConstants.KEYBOARD_TAP) and dispatch TYPE_VIEW_CLICKED accessibility event on TalkBack double-tap/click - Announce line and column position along with line content when cursor moves due to tap - Announce line content during touch exploration hover events - Ensure accessibility node info and action dispatch use the editable property rather than isEditable so temporary background layoutBusy states do not strip EditText semantics or drop accessibility actions - Add IDEEditorAccessibilityTest covering node info actions, hover event coordinate retention, and accessibility click dispatch --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 166 +++++++++++++++--- .../editor/ui/IDEEditorAccessibilityTest.kt | 135 ++++++++++++++ 2 files changed, 281 insertions(+), 20 deletions(-) create mode 100644 editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index 9bc075d869..c714f3c00b 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -23,6 +23,7 @@ import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.AttributeSet +import android.view.HapticFeedbackConstants import android.view.KeyEvent import android.view.MotionEvent import android.view.View @@ -599,6 +600,10 @@ open class IDEEditor selectionChangeRunner?.also { selectionChangeHandler.removeCallbacks(it) } selectionChangeRunner = null + lastHoverX = Float.NaN + lastHoverY = Float.NaN + lastExploredLine = -1 + if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this) } @@ -674,6 +679,7 @@ open class IDEEditor // where the user double-taps under TalkBack. NaN means "no recent exploration". private var lastHoverX = Float.NaN private var lastHoverY = Float.NaN + private var lastExploredLine = -1 private val isTouchExplorationEnabled: Boolean get() = accessibilityManager?.isTouchExplorationEnabled == true @@ -681,7 +687,7 @@ open class IDEEditor override fun getAccessibilityClassName(): CharSequence = // Only advertise EditText semantics in the same states createAccessibilityNodeInfo() // does, so a read-only or released editor is not announced as an "Edit box". - if (!isReleased && isEnabled && isEditable) { + if (!isReleased && isEnabled && editable) { EditText::class.java.name } else { super.getAccessibilityClassName() @@ -689,11 +695,13 @@ open class IDEEditor override fun createAccessibilityNodeInfo(): AccessibilityNodeInfo? { val info = super.createAccessibilityNodeInfo() ?: return null - if (!isReleased && isEnabled && isEditable) { + if (!isReleased && isEnabled && editable) { // Report as an EditText so TalkBack engages its text-editing affordances and keeps // the caret in sync with granular navigation. info.className = EditText::class.java.name + info.isClickable = true info.movementGranularities = EditorAccessibilitySegments.SUPPORTED_GRANULARITIES + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_SELECTION) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_NEXT_AT_MOVEMENT_GRANULARITY) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY) @@ -701,15 +709,71 @@ open class IDEEditor return info } + override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) { + super.onInitializeAccessibilityNodeInfo(info) + if (!isReleased && isEnabled && editable) { + info.className = EditText::class.java.name + info.isClickable = true + info.movementGranularities = EditorAccessibilitySegments.SUPPORTED_GRANULARITIES + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK) + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_SELECTION) + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_NEXT_AT_MOVEMENT_GRANULARITY) + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY) + } + } + override fun dispatchHoverEvent(event: MotionEvent): Boolean { - // Remember where the user is exploring so ACTION_CLICK can place the caret there. - if (isTouchExplorationEnabled) { - lastHoverX = event.x - lastHoverY = event.y + if (!isTouchExplorationEnabled || isReleased) { + return super.dispatchHoverEvent(event) + } + + when (event.actionMasked) { + MotionEvent.ACTION_HOVER_ENTER, + MotionEvent.ACTION_HOVER_MOVE, + -> { + val x = event.x.coerceIn(0f, (width - 1).coerceAtLeast(0).toFloat()) + val y = event.y.coerceIn(0f, (height - 1).coerceAtLeast(0).toFloat()) + lastHoverX = x + lastHoverY = y + handleHoverExploration(x, y) + return true + } + + MotionEvent.ACTION_HOVER_EXIT -> { + // Reset the explored line tracker, but keep lastHoverX and lastHoverY intact + // so an ensuing ACTION_CLICK places the caret where the user explored. + lastExploredLine = -1 + return true + } } return super.dispatchHoverEvent(event) } + @Suppress("DEPRECATION") + private fun handleHoverExploration( + x: Float, + y: Float, + ) { + if (isReleased) return + val currentText = text + val count = currentText.lineCount + if (count <= 0) return + + val packed = getPointPositionOnScreen(x, y) + val line = (packed ushr 32).toInt().coerceIn(0, count - 1) + if (line != lastExploredLine) { + lastExploredLine = line + val lineContent = currentText.getLine(line).toString().trimEnd('\r', '\n') + val announcement = + if (lineContent.isBlank()) { + "Line ${line + 1}" + } else { + "Line ${line + 1}: $lineContent" + } + announceForAccessibility(announcement) + } + } + override fun performAccessibilityAction( action: Int, arguments: Bundle?, @@ -735,21 +799,38 @@ open class IDEEditor } /** - * Places the caret where the user last explored by touch. This makes a TalkBack double-tap - * on a word or line move the real text cursor to that spot instead of the node's center. + * Places the caret where the user last explored by touch or tapped. This makes a TalkBack + * double-tap on a word or line move the real text cursor to that spot and announce feedback. */ private fun handleAccessibilityClick(): Boolean { - if (isReleased || !isEditable || !isTouchExplorationEnabled) return false - val x = lastHoverX - val y = lastHoverY - if (x.isNaN() || y.isNaN()) return false + if (isReleased || !isEnabled) return false + + val currentText = text + val count = currentText.lineCount + if (count <= 0) return false + + val (targetLine, targetCol) = + if (!lastHoverX.isNaN() && !lastHoverY.isNaN()) { + val packed = getPointPositionOnScreen(lastHoverX, lastHoverY) + val line = (packed ushr 32).toInt().coerceIn(0, count - 1) + val maxCol = currentText.getColumnCount(line) + val col = (packed and 0xffffffffL).toInt().coerceIn(0, maxCol) + line to col + } else { + val cur = cursor + if (cur != null) { + cur.leftLine to cur.leftColumn + } else { + 0 to 0 + } + } + return try { if (!isFocused) requestFocus() - val packed = getPointPositionOnScreen(x, y) - val line = (packed ushr 32).toInt() - val column = (packed and 0xffffffffL).toInt() - if (line < 0 || column < 0) return false - setSelection(line, column) + setSelection(targetLine, targetCol, true, SelectionChangeEvent.CAUSE_TAP) + ensurePositionVisible(targetLine, targetCol) + sendClickAccessibilityEvent() + performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP) true } catch (e: IndexOutOfBoundsException) { log.error("Error placing cursor from accessibility click", e) @@ -762,7 +843,7 @@ open class IDEEditor /** Handles [AccessibilityNodeInfo.ACTION_SET_SELECTION] using absolute character indices. */ private fun handleAccessibilitySetSelection(arguments: Bundle?): Boolean { - if (isReleased || !isEditable || arguments == null) return false + if (isReleased || !isEnabled || arguments == null) return false if (!arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) || !arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT) ) { @@ -786,7 +867,7 @@ open class IDEEditor arguments: Bundle?, forward: Boolean, ): Boolean { - if (isReleased || !isEditable || arguments == null) return false + if (isReleased || !isEnabled || arguments == null) return false val granularity = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT, @@ -851,6 +932,23 @@ open class IDEEditor } } + /** + * Emits a [AccessibilityEvent.TYPE_VIEW_CLICKED] event so accessibility services receive + * click notifications regardless of view attachment state in unit tests. + */ + @Suppress("DEPRECATION") + private fun sendClickAccessibilityEvent() { + val manager = accessibilityManager ?: return + if (!manager.isEnabled) return + val event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_CLICKED) + onInitializeAccessibilityEvent(event) + if (parent != null) { + sendAccessibilityEventUnchecked(event) + } else { + manager.sendAccessibilityEvent(event) + } + } + /** * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY] event so the * screen reader announces the character/word/line the caret just traversed. @@ -946,6 +1044,30 @@ open class IDEEditor event.text.add(current) sendAccessibilityEventUnchecked(event) } + + /** + * Announces the current cursor position and line content to screen readers after a tap/click. + */ + @Suppress("DEPRECATION") + private fun announceCursorPosition( + line: Int, + column: Int, + ) { + if (isReleased) return + val manager = accessibilityManager ?: return + if (!manager.isEnabled) return + + val currentText = text + if (line !in 0 until currentText.lineCount) return + val lineContent = currentText.getLine(line).toString().trimEnd('\r', '\n') + val announcement = + if (lineContent.isBlank()) { + "Line ${line + 1}, column ${column + 1}" + } else { + "Line ${line + 1}, column ${column + 1}: $lineContent" + } + announceForAccessibility(announcement) + } // endregion Accessibility override fun copyTextToClipboard( @@ -1280,7 +1402,7 @@ open class IDEEditor } } - subscribeEvent(SelectionChangeEvent::class.java) { _, _ -> + subscribeEvent(SelectionChangeEvent::class.java) { event, _ -> if (isReleased) { return@subscribeEvent } @@ -1288,6 +1410,10 @@ open class IDEEditor // Keep the screen reader's caret in sync as the selection moves, like an EditText. sendSelectionChangedAccessibilityEvent() + if (accessibilityManager?.isEnabled == true && event.cause == SelectionChangeEvent.CAUSE_TAP) { + announceCursorPosition(event.left.line, event.left.column) + } + // Moving the cursor away from the anchor makes ghost text meaningless. dismissInlineSuggestion() diff --git a/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt new file mode 100644 index 0000000000..34970c097c --- /dev/null +++ b/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt @@ -0,0 +1,135 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.editor.ui + +import android.content.Context +import android.os.SystemClock +import android.view.MotionEvent +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityManager +import android.view.accessibility.AccessibilityNodeInfo +import android.widget.EditText +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.editor.utils.EditorAccessibilitySegments +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(application = BaseApplication::class) +class IDEEditorAccessibilityTest { + private lateinit var context: Context + private lateinit var editor: TestIDEEditor + private lateinit var a11yManager: AccessibilityManager + + private class TestIDEEditor( + context: Context, + ) : IDEEditor(context) { + public override fun dispatchHoverEvent(event: MotionEvent): Boolean = super.dispatchHoverEvent(event) + } + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + a11yManager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager + editor = TestIDEEditor(context) + editor.isWordwrap = false + editor.setText("Line 1: first\nLine 2: second\nLine 3: third") + shadowOf(android.os.Looper.getMainLooper()).idle() + } + + @After + fun tearDown() { + editor.release() + } + + @Test + fun `node reports as EditText with click and movement actions`() { + val info = editor.createAccessibilityNodeInfo() + assertThat(info).isNotNull() + assertThat(info!!.className).isEqualTo(EditText::class.java.name) + assertThat(info.isClickable).isTrue() + assertThat(info.movementGranularities).isEqualTo(EditorAccessibilitySegments.SUPPORTED_GRANULARITIES) + + val actions = info.actionList.map { it.id } + assertThat(actions).contains(AccessibilityNodeInfo.ACTION_CLICK) + assertThat(actions).contains(AccessibilityNodeInfo.ACTION_SET_SELECTION) + assertThat(actions).contains(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY) + assertThat(actions).contains(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY) + } + + @Suppress("DEPRECATION") + @Test + fun `onInitializeAccessibilityNodeInfo populates click and movement actions`() { + val info = AccessibilityNodeInfo.obtain() + editor.onInitializeAccessibilityNodeInfo(info) + + assertThat(info.className).isEqualTo(EditText::class.java.name) + assertThat(info.isClickable).isTrue() + val actions = info.actionList.map { it.id } + assertThat(actions).contains(AccessibilityNodeInfo.ACTION_CLICK) + assertThat(actions).contains(AccessibilityNodeInfo.ACTION_SET_SELECTION) + } + + @Test + fun `hover exit does not overwrite coordinates for subsequent accessibility click`() { + shadowOf(a11yManager).apply { + setEnabled(true) + setTouchExplorationEnabled(true) + } + + val downTime = SystemClock.uptimeMillis() + val enterEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_HOVER_ENTER, 50f, 10f, 0) + val moveEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_HOVER_MOVE, 60f, 15f, 0) + val exitEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_HOVER_EXIT, -1f, -1f, 0) + + assertThat(editor.dispatchHoverEvent(enterEvent)).isTrue() + assertThat(editor.dispatchHoverEvent(moveEvent)).isTrue() + assertThat(editor.dispatchHoverEvent(exitEvent)).isTrue() + + // An ensuing ACTION_CLICK should still succeed and place caret without crashing or failing + val clickHandled = editor.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, null) + assertThat(clickHandled).isTrue() + assertThat(editor.cursor).isNotNull() + + shadowOf(android.os.Looper.getMainLooper()).idle() + + // Verify click accessibility event was dispatched + val events = shadowOf(a11yManager).sentAccessibilityEvents + val clickedEvents = events.filter { it.eventType == AccessibilityEvent.TYPE_VIEW_CLICKED } + assertThat(clickedEvents).isNotEmpty() + } + + @Test + fun `accessibility click succeeds when no prior hover occurred`() { + shadowOf(a11yManager).apply { + setEnabled(true) + setTouchExplorationEnabled(true) + } + + val clickHandled = editor.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, null) + assertThat(clickHandled).isTrue() + assertThat(editor.cursor).isNotNull() + } +} From bff895d1c8b9fddf10ca738cf4e14d5273e056ee Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Tue, 20 Oct 2026 23:25:27 +0100 Subject: [PATCH 7/8] fix(ADFA-4605): Show keyboard when a line is double-tapped --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 38 +++++++++++++++++++ .../editor/ui/IDEEditorAccessibilityTest.kt | 12 ++++++ 2 files changed, 50 insertions(+) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index c714f3c00b..c0cfbcb199 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -32,6 +32,7 @@ import android.view.accessibility.AccessibilityManager import android.view.accessibility.AccessibilityNodeInfo import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting @@ -91,6 +92,7 @@ import com.itsaky.androidide.utils.FileUtils import com.itsaky.androidide.utils.dpToPx import com.itsaky.androidide.utils.flashError import io.github.rosemoe.sora.event.ContentChangeEvent +import io.github.rosemoe.sora.event.DoubleClickEvent import io.github.rosemoe.sora.event.SelectionChangeEvent import io.github.rosemoe.sora.lang.EmptyLanguage import io.github.rosemoe.sora.lang.Language @@ -662,6 +664,32 @@ open class IDEEditor } } + override fun showSoftInput() { + if (isReleased || !isEnabled || !editable) { + return + } + if (!isFocused) { + requestFocus() + } + super.showSoftInput() + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.showSoftInput(this, 0) + post { + if (!isReleased && isEnabled && editable) { + val manager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + manager?.showSoftInput(this, 0) + } + } + } + + override fun performClick(): Boolean { + val handled = super.performClick() + if (!isReleased && isEnabled && editable) { + showSoftInput() + } + return handled + } + // region Accessibility (screen reader) cursor synchronization // // The base CodeEditor exposes its whole content to accessibility services as a single @@ -829,6 +857,9 @@ open class IDEEditor if (!isFocused) requestFocus() setSelection(targetLine, targetCol, true, SelectionChangeEvent.CAUSE_TAP) ensurePositionVisible(targetLine, targetCol) + if (editable) { + showSoftInput() + } sendClickAccessibilityEvent() performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP) true @@ -1427,6 +1458,13 @@ open class IDEEditor } } + subscribeEvent(DoubleClickEvent::class.java) { _, _ -> + if (isReleased || !isEnabled || !editable) { + return@subscribeEvent + } + showSoftInput() + } + EventBus.getDefault().register(this) } diff --git a/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt index 34970c097c..e73687acc2 100644 --- a/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt +++ b/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt @@ -23,6 +23,7 @@ import android.view.MotionEvent import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import android.view.accessibility.AccessibilityNodeInfo +import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat @@ -132,4 +133,15 @@ class IDEEditorAccessibilityTest { assertThat(clickHandled).isTrue() assertThat(editor.cursor).isNotNull() } + + @Test + fun `accessibility click requests soft keyboard when editable`() { + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + + val clickHandled = editor.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, null) + assertThat(clickHandled).isTrue() + + shadowOf(android.os.Looper.getMainLooper()).idle() + assertThat(shadowOf(imm).isSoftInputVisible).isTrue() + } } From 063d985081b6f0e56827d768370ceb77365eac8e Mon Sep 17 00:00:00 2001 From: Dara Abijo Date: Thu, 29 Oct 2026 12:13:28 +0100 Subject: [PATCH 8/8] fix(ADFA-4605): Address PR comments --- .../itsaky/androidide/editor/ui/IDEEditor.kt | 65 +++++-------------- .../editor/ui/IDEEditorAccessibilityTest.kt | 1 + 2 files changed, 18 insertions(+), 48 deletions(-) diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index cfa6ca5151..f6720b7181 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -19,6 +19,7 @@ package com.itsaky.androidide.editor.ui import android.content.Context import android.graphics.Rect +import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper @@ -32,7 +33,6 @@ import android.view.accessibility.AccessibilityManager import android.view.accessibility.AccessibilityNodeInfo import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection -import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting @@ -92,10 +92,10 @@ import com.itsaky.androidide.utils.FileUtils import com.itsaky.androidide.utils.dpToPx import com.itsaky.androidide.utils.flashError import io.github.rosemoe.sora.event.ContentChangeEvent -import io.github.rosemoe.sora.event.DoubleClickEvent import io.github.rosemoe.sora.event.SelectionChangeEvent import io.github.rosemoe.sora.lang.EmptyLanguage import io.github.rosemoe.sora.lang.Language +import io.github.rosemoe.sora.util.IntPair import io.github.rosemoe.sora.widget.CodeEditor import io.github.rosemoe.sora.widget.EditorRenderer import io.github.rosemoe.sora.widget.EditorSearcher @@ -664,32 +664,6 @@ open class IDEEditor } } - override fun showSoftInput() { - if (isReleased || !isEnabled || !editable) { - return - } - if (!isFocused) { - requestFocus() - } - super.showSoftInput() - val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager - imm?.showSoftInput(this, 0) - post { - if (!isReleased && isEnabled && editable) { - val manager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager - manager?.showSoftInput(this, 0) - } - } - } - - override fun performClick(): Boolean { - val handled = super.performClick() - if (!isReleased && isEnabled && editable) { - showSoftInput() - } - return handled - } - // region Accessibility (screen reader) cursor synchronization // // The base CodeEditor exposes its whole content to accessibility services as a single @@ -777,7 +751,6 @@ open class IDEEditor return super.dispatchHoverEvent(event) } - @Suppress("DEPRECATION") private fun handleHoverExploration( x: Float, y: Float, @@ -788,7 +761,7 @@ open class IDEEditor if (count <= 0) return val packed = getPointPositionOnScreen(x, y) - val line = (packed ushr 32).toInt().coerceIn(0, count - 1) + val line = IntPair.getFirst(packed).coerceIn(0, count - 1) if (line != lastExploredLine) { lastExploredLine = line val lineContent = currentText.getLine(line).toString().trimEnd('\r', '\n') @@ -840,9 +813,9 @@ open class IDEEditor val (targetLine, targetCol) = if (!lastHoverX.isNaN() && !lastHoverY.isNaN()) { val packed = getPointPositionOnScreen(lastHoverX, lastHoverY) - val line = (packed ushr 32).toInt().coerceIn(0, count - 1) + val line = IntPair.getFirst(packed).coerceIn(0, count - 1) val maxCol = currentText.getColumnCount(line) - val col = (packed and 0xffffffffL).toInt().coerceIn(0, maxCol) + val col = IntPair.getSecond(packed).coerceIn(0, maxCol) line to col } else { val cur = cursor @@ -963,15 +936,22 @@ open class IDEEditor } } + private fun obtainAccessibilityEvent(eventType: Int): AccessibilityEvent = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + AccessibilityEvent(eventType) + } else { + @Suppress("DEPRECATION") + AccessibilityEvent.obtain(eventType) + } + /** * Emits a [AccessibilityEvent.TYPE_VIEW_CLICKED] event so accessibility services receive * click notifications regardless of view attachment state in unit tests. */ - @Suppress("DEPRECATION") private fun sendClickAccessibilityEvent() { val manager = accessibilityManager ?: return if (!manager.isEnabled) return - val event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_CLICKED) + val event = obtainAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED) onInitializeAccessibilityEvent(event) if (parent != null) { sendAccessibilityEventUnchecked(event) @@ -984,7 +964,6 @@ open class IDEEditor * Emits a [AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY] event so the * screen reader announces the character/word/line the caret just traversed. */ - @Suppress("DEPRECATION") // AccessibilityEvent(int) requires API 30; obtain() works on minSdk 28. private fun sendTextTraversedEvent( fromIndex: Int, toIndex: Int, @@ -994,7 +973,7 @@ open class IDEEditor val manager = accessibilityManager ?: return if (!manager.isEnabled) return val event = - AccessibilityEvent.obtain( + obtainAccessibilityEvent( AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, ) onInitializeAccessibilityEvent(event) @@ -1014,12 +993,11 @@ open class IDEEditor * navigation (lines/paragraphs in particular) and to mirror standard [EditText] behaviour. * Called on every selection change; cheap no-op when no accessibility service is running. */ - @Suppress("DEPRECATION") fun sendSelectionChangedAccessibilityEvent() { val manager = accessibilityManager ?: return if (!manager.isEnabled) return val cur = cursor ?: return - val event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) + val event = obtainAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) onInitializeAccessibilityEvent(event) event.className = EditText::class.java.name val content = text.toString() @@ -1036,7 +1014,6 @@ open class IDEEditor * change from [AccessibilityEvent.getFromIndex], added/removed counts, the current text and * [AccessibilityEvent.getBeforeText]. Cheap no-op when no accessibility service is running. */ - @Suppress("DEPRECATION") fun sendTextChangedAccessibilityEvent(changeEvent: ContentChangeEvent) { val manager = accessibilityManager ?: return if (!manager.isEnabled) return @@ -1046,7 +1023,7 @@ open class IDEEditor val changed = changeEvent.changedText val changedLen = changed.length - val event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) + val event = obtainAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) onInitializeAccessibilityEvent(event) event.className = EditText::class.java.name event.fromIndex = fromIndex @@ -1079,7 +1056,6 @@ open class IDEEditor /** * Announces the current cursor position and line content to screen readers after a tap/click. */ - @Suppress("DEPRECATION") private fun announceCursorPosition( line: Int, column: Int, @@ -1458,13 +1434,6 @@ open class IDEEditor } } - subscribeEvent(DoubleClickEvent::class.java) { _, _ -> - if (isReleased || !isEnabled || !editable) { - return@subscribeEvent - } - showSoftInput() - } - EventBus.getDefault().register(this) } diff --git a/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt b/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt index e73687acc2..37ec41ad23 100644 --- a/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt +++ b/editor/src/test/java/com/itsaky/androidide/editor/ui/IDEEditorAccessibilityTest.kt @@ -136,6 +136,7 @@ class IDEEditorAccessibilityTest { @Test fun `accessibility click requests soft keyboard when editable`() { + editor.isDisableSoftKbdIfHardKbdAvailable = false val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager val clickHandled = editor.performAccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, null)