Skip to content

Commit 0319537

Browse files
committed
fix: leave edit mode on the main thread
Leaving edit mode crashed every device-test run. Editing is left after the note has been saved, and a coroutine resumes on whichever thread completed that save: Room finishes its queries and transactions on its own executor, and the interceptor a Compose test installs is not a CoroutineDispatcher, so withContext cannot re-dispatch at all. Hiding the keyboard therefore reached the editor from a database thread and the view hierarchy rejected it. MarkdownEditText now brings focus and input-method calls back to the thread that owns the view instead of trusting its callers, and the note screen hides the keyboard and leaves edit mode as one main-thread step so the input method is still reachable when it is asked to close. Also fixes the tests that were failing or racing beside it: - renamingANoteShowsAndUploadsTheNewFileName still asserted that a rename leaves the content alone, which stopped being true when the 'Update heading 1' option was added and defaulted to on. It now covers renaming with the option off, and a new test covers the default. The checkbox row became toggleable, so the label is part of the target and the option is one node that can be read and switched. - Three tests asserted that text was gone right after the action that removes it. A list answered by a database query keeps the previous result until the new query emits, so the screen is idle while it still shows what the action is about to replace. They wait for it to go. - editorDraftIsPeriodicallyCheckpointed... raced the 500 ms idle save and the 1500 ms synchronization delay against a 2000 ms wait. It is now two tests: typing that never pauses long enough for the idle save to complete, and a checkpoint given longer than the synchronization delay to show that it starts no network work.
1 parent 81b1adc commit 0319537

6 files changed

Lines changed: 257 additions & 59 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1414
- An **About** menu item in the note list account menu shows the version number and short git
1515
commit hash. Both values link to the project's GitHub releases and commit page respectively.
1616
- Renaming a note can optionally update the first Markdown heading to match the new file name.
17-
The rename dialog includes an **Update heading 1** checkbox that is enabled by default.
17+
The rename dialog includes an **Update heading 1** checkbox that is enabled by default. The whole
18+
checkbox row is tappable, so the label is part of the target and screen readers announce one
19+
checked option instead of a box beside unrelated text.
1820

1921
### Changed
2022

@@ -25,6 +27,9 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
2527
### Fixed
2628

2729
- The onscreen keyboard now closes reliably when leaving Markdown edit mode.
30+
- Leaving edit mode no longer crashes. Editing is left after a note has been saved, and a coroutine
31+
resumes on whichever thread completed that save, so the keyboard and focus changes could reach
32+
the editor from a database thread and be rejected by the view hierarchy.
2833
- Local `media/` images in Nextcloud notes now use the versioned Notes attachment endpoint instead
2934
of failing to load as red placeholders.
3035
- Checkboxes in nested task lists can now be toggled in view mode; previously only top-level

‎app/src/androidTest/kotlin/org/qownnotes/mobile/AppLaunchTest.kt‎

Lines changed: 136 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import android.widget.TextView
99
import androidx.compose.ui.test.assertIsDisplayed
1010
import androidx.compose.ui.test.assertIsEnabled
1111
import androidx.compose.ui.test.assertIsNotEnabled
12+
import androidx.compose.ui.test.assertIsOff
13+
import androidx.compose.ui.test.assertIsOn
1214
import androidx.compose.ui.test.junit4.createAndroidComposeRule
1315
import androidx.compose.ui.test.longClick
1416
import androidx.compose.ui.test.onAllNodesWithTag
@@ -42,7 +44,6 @@ import kotlinx.coroutines.flow.first
4244
import kotlinx.coroutines.runBlocking
4345
import org.hamcrest.Matchers.containsString
4446
import org.junit.Assert.assertEquals
45-
import org.junit.Assert.assertFalse
4647
import org.junit.Assert.assertTrue
4748
import org.junit.Before
4849
import org.junit.Rule
@@ -348,8 +349,8 @@ class AppLaunchTest {
348349
composeRule.waitUntil(timeoutMillis = 10_000) {
349350
application.fakeBackend.deletedRemoteIds.toSet() == setOf(42L, 43L)
350351
}
351-
composeRule.onNodeWithText("First note").assertDoesNotExist()
352-
composeRule.onNodeWithText("Second note").assertDoesNotExist()
352+
composeRule.waitForTextToGo("First note")
353+
composeRule.waitForTextToGo("Second note")
353354
}
354355

355356
@Test
@@ -363,7 +364,7 @@ class AppLaunchTest {
363364
composeRule.onNodeWithTag("confirm-delete-note").performClick()
364365

365366
composeRule.waitForTag("note-list")
366-
composeRule.onNodeWithText("Existing note").assertDoesNotExist()
367+
composeRule.waitForTextToGo("Existing note")
367368
composeRule.waitUntil(timeoutMillis = 10_000) {
368369
application.fakeBackend.deletedRemoteIds == listOf(42L)
369370
}
@@ -435,7 +436,7 @@ class AppLaunchTest {
435436
}
436437
composeRule.waitForText("Filtered note")
437438
composeRule.onNodeWithTag("note-search").performTextInput("Visible")
438-
composeRule.onNodeWithText("Filtered note").assertDoesNotExist()
439+
composeRule.waitForTextToGo("Filtered note")
439440

440441
composeRule.onNodeWithTag("remote-trash").performClick()
441442

@@ -636,18 +637,12 @@ class AppLaunchTest {
636637
importAccount("alice", "Existing note", "etag-1", 10)
637638
composeRule.onNodeWithText("Existing note").performClick()
638639
composeRule.enterEditMode()
639-
lateinit var editor: TextView
640-
onView(withId(R.id.markdown_editor)).check { view, _ ->
641-
editor = view as TextView
642-
assertTrue(editor.hasFocus())
643-
}
640+
awaitEditorFocus(focused = true)
644641

645642
composeRule.onNodeWithTag("cancel-editing").performClick()
646643

647644
composeRule.waitForTag("markdown-view")
648-
composeRule.runOnIdle {
649-
assertFalse("leaving edit mode must release editor focus", editor.hasFocus())
650-
}
645+
awaitEditorFocus(focused = false)
651646
composeRule.onNodeWithTag("confirm-discard-changes").assertDoesNotExist()
652647
composeRule.onNodeWithTag("edit-note").assertIsDisplayed()
653648
}
@@ -908,33 +903,44 @@ class AppLaunchTest {
908903
composeRule.onNodeWithTag("delete-note").assertIsDisplayed()
909904
}
910905

911-
/** The name of a note is the name of the file holding it, so a rename has to be uploaded. */
906+
/**
907+
* The name of a note is the name of the file holding it, so a rename has to be uploaded.
908+
* Renaming without the heading option touches nothing but that name.
909+
*/
912910
@Test
913911
fun renamingANoteShowsAndUploadsTheNewFileName() {
914912
importAccount("alice", "Existing note", "etag-1", 10)
915913
composeRule.onNodeWithText("Existing note").performClick()
916914

917-
// Opening a note loads it from the repository, so its actions appear a recomposition later.
918-
composeRule.openNoteMenu()
919-
composeRule.onNodeWithTag("rename-note").performClick()
920-
composeRule.waitForTag("note-name-field")
921-
composeRule.onNodeWithTag("note-name-field").performTextReplacement("Grocery list")
922-
composeRule.onNodeWithTag("confirm-rename-note").performClick()
915+
renameNote("Grocery list", updateHeading = false)
923916

924917
composeRule.waitForText("Grocery list")
925918
composeRule.onNodeWithTag("back-to-note-list").performClick()
926919
composeRule.waitForText("Grocery list")
927920
composeRule.waitUntil(timeoutMillis = 10_000) {
928921
application.fakeBackend.pushedNotes.any { it.title == "Grocery list" }
929922
}
930-
assertTrue(
931-
runBlocking {
932-
application.component.noteRepository
933-
.observeNotes(testAccount("alice").localAccountId())
934-
.first()
935-
.all { it.content == "# Existing note" }
923+
assertEquals(listOf("# Existing note"), noteContents("alice"))
924+
}
925+
926+
/**
927+
* The heading a note opens with usually repeats its file name, so the rename dialog offers to
928+
* carry the new name into that heading, and does so unless the writer says otherwise.
929+
*/
930+
@Test
931+
fun renamingANoteAlsoRewritesTheFirstHeadingByDefault() {
932+
importAccount("alice", "Existing note", "etag-1", 10, content = "# Existing note\n\nBody")
933+
composeRule.onNodeWithText("Existing note").performClick()
934+
935+
renameNote("Grocery list")
936+
937+
composeRule.waitForText("Grocery list")
938+
composeRule.waitUntil(timeoutMillis = 10_000) {
939+
application.fakeBackend.pushedNotes.any {
940+
it.title == "Grocery list" && it.content == "# Grocery list\n\nBody"
936941
}
937-
)
942+
}
943+
assertEquals(listOf("# Grocery list\n\nBody"), noteContents("alice"))
938944
}
939945

940946
/** A name that holds nothing a file system accepts would leave the note unreachable. */
@@ -1053,24 +1059,59 @@ class AppLaunchTest {
10531059
composeRule.onNodeWithTag("note-find-field").assertDoesNotExist()
10541060
}
10551061

1062+
/**
1063+
* An editing session that never pauses must still reach storage. Every round of typing
1064+
* restarts the idle save, so it never completes and whatever the database ends up holding was
1065+
* written by the periodic checkpoint. What is stored is only checked for the shape of the
1066+
* typed text, not for the newest of it, because a checkpoint is a snapshot of a moment that
1067+
* the writer has already typed past by the time it can be read back.
1068+
*/
10561069
@Test
1057-
fun editorDraftIsPeriodicallyCheckpointedWithoutStartingNetworkWork() {
1070+
fun editorDraftIsPeriodicallyCheckpointedWhileTypingNeverPauses() {
10581071
importAccount("alice", "Existing note", "etag-1", 10)
10591072
val note = runBlocking { notesOf("alice").single() }
10601073
composeRule.onNodeWithText("Existing note").performClick()
10611074
composeRule.enterEditMode()
1062-
onView(withId(R.id.markdown_editor)).perform(
1063-
click(),
1064-
replaceText("# Edited\n\nPeriodic checkpoint")
1065-
)
1075+
onView(withId(R.id.markdown_editor)).perform(click())
10661076

1067-
composeRule.waitUntil(timeoutMillis = 2_000) {
1068-
runBlocking {
1069-
application.component.noteRepository.get(note.localId)?.content ==
1070-
"# Edited\n\nPeriodic checkpoint"
1071-
}
1077+
var round = 0
1078+
composeRule.waitUntil(timeoutMillis = 30_000) {
1079+
onView(withId(R.id.markdown_editor))
1080+
.perform(replaceText("# Edited\n\nPeriodic checkpoint ${round++}"))
1081+
runBlocking { application.component.noteRepository.get(note.localId)?.content }
1082+
?.startsWith("# Edited\n\nPeriodic checkpoint") == true
1083+
}
1084+
}
1085+
1086+
/**
1087+
* A checkpoint is a local safety net, not an edit the writer finished, so it must not start
1088+
* network work of its own. Waiting past the synchronization delay is what makes the absence of
1089+
* an upload mean anything.
1090+
*/
1091+
@Test
1092+
fun checkpointingADraftStartsNoNetworkWork() {
1093+
importAccount("alice", "Existing note", "etag-1", 10)
1094+
val note = runBlocking { notesOf("alice").single() }
1095+
val pullsBefore = application.fakeBackend.checkpoints.size
1096+
1097+
runBlocking {
1098+
application.component.checkpointDraft(note.localId, "# Edited\n\nCheckpoint")
10721099
}
1073-
assertTrue(application.fakeBackend.pushedNotes.isEmpty())
1100+
1101+
assertEquals(
1102+
"# Edited\n\nCheckpoint",
1103+
runBlocking { application.component.noteRepository.get(note.localId)?.content }
1104+
)
1105+
Thread.sleep(SYNC_DELAY_MILLIS * 2)
1106+
assertTrue(
1107+
"a checkpoint must not upload the note",
1108+
application.fakeBackend.pushedNotes.isEmpty()
1109+
)
1110+
assertEquals(
1111+
"a checkpoint must not refresh the account",
1112+
pullsBefore,
1113+
application.fakeBackend.checkpoints.size
1114+
)
10741115
}
10751116

10761117
@Test
@@ -1166,6 +1207,31 @@ class AppLaunchTest {
11661207
onNodeWithTag("note-menu").performClick()
11671208
}
11681209

1210+
/**
1211+
* Renames the open note. Opening a note loads it from the repository, so its actions appear a
1212+
* recomposition later, and the dialog is only reachable through the note menu.
1213+
*/
1214+
private fun renameNote(name: String, updateHeading: Boolean = true) {
1215+
composeRule.openNoteMenu()
1216+
composeRule.onNodeWithTag("rename-note").performClick()
1217+
composeRule.waitForTag("note-name-field")
1218+
composeRule.onNodeWithTag("note-name-field").performTextReplacement(name)
1219+
composeRule.onNodeWithTag("update-heading-checkbox").assertIsOn()
1220+
if (!updateHeading) {
1221+
composeRule.onNodeWithTag("update-heading-checkbox").performClick()
1222+
composeRule.onNodeWithTag("update-heading-checkbox").assertIsOff()
1223+
}
1224+
composeRule.onNodeWithTag("confirm-rename-note").performClick()
1225+
}
1226+
1227+
/** What the notes of an account hold, read from the repository rather than from the screen. */
1228+
private fun noteContents(user: String): List<String> = runBlocking {
1229+
application.component.noteRepository
1230+
.observeNotes(testAccount(user).localAccountId())
1231+
.first()
1232+
.map { it.content }
1233+
}
1234+
11691235
/**
11701236
* Pull to refresh reacts to how far a drag has travelled by the time it is released. The
11711237
* injected gesture and the state that measures it advance on separate coroutines, so on a
@@ -1189,6 +1255,20 @@ class AppLaunchTest {
11891255
throw AssertionError("pulling the note list down never reached the backend")
11901256
}
11911257

1258+
/**
1259+
* Waits for the editor to hold or release input focus. Focus is requested once the view has
1260+
* been attached and released as edit mode is left, so neither is true the moment the action
1261+
* that causes it returns. A released editor is gone from the hierarchy and holds no focus.
1262+
*/
1263+
private fun awaitEditorFocus(focused: Boolean) {
1264+
composeRule.waitUntil(timeoutMillis = 10_000) {
1265+
composeRule.runOnIdle {
1266+
composeRule.activity.findViewById<TextView>(R.id.markdown_editor)
1267+
?.hasFocus() == true
1268+
} == focused
1269+
}
1270+
}
1271+
11921272
/**
11931273
* Espresso injects key events into the input method, which commits the resulting characters
11941274
* back through an asynchronous input connection. Looping the main thread until it is idle does
@@ -1295,4 +1375,22 @@ class AppLaunchTest {
12951375
onAllNodesWithText(text, substring = substring).fetchSemanticsNodes().isNotEmpty()
12961376
}
12971377
}
1378+
1379+
/**
1380+
* Waits for text to go, for lists that are answered by a query rather than filtered in place.
1381+
* Searching starts a new database flow and the previous result stays on screen until that flow
1382+
* emits, so the screen is idle while it still shows what the search is about to replace.
1383+
*/
1384+
private fun androidx.compose.ui.test.junit4.AndroidComposeTestRule<*, *>.waitForTextToGo(
1385+
text: String
1386+
) {
1387+
waitUntil(timeoutMillis = 10_000) {
1388+
onAllNodesWithText(text).fetchSemanticsNodes().isEmpty()
1389+
}
1390+
}
1391+
1392+
private companion object {
1393+
/** How long `ApplicationComponent` lets a scheduled synchronization wait before it runs. */
1394+
const val SYNC_DELAY_MILLIS = 1_500L
1395+
}
12981396
}

‎app/src/main/kotlin/org/qownnotes/mobile/MainActivity.kt‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import androidx.compose.foundation.layout.width
3737
import androidx.compose.foundation.lazy.LazyColumn
3838
import androidx.compose.foundation.lazy.items
3939
import androidx.compose.foundation.rememberScrollState
40+
import androidx.compose.foundation.selection.toggleable
4041
import androidx.compose.foundation.text.selection.SelectionContainer
4142
import androidx.compose.foundation.verticalScroll
4243
import androidx.compose.material.icons.Icons
@@ -108,6 +109,7 @@ import androidx.compose.ui.layout.onSizeChanged
108109
import androidx.compose.ui.platform.LocalContext
109110
import androidx.compose.ui.platform.LocalDensity
110111
import androidx.compose.ui.platform.testTag
112+
import androidx.compose.ui.semantics.Role
111113
import androidx.compose.ui.semantics.contentDescription
112114
import androidx.compose.ui.semantics.selected
113115
import androidx.compose.ui.semantics.semantics
@@ -123,6 +125,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
123125
import com.nextcloud.android.sso.exceptions.AccountImportCancelledException
124126
import com.nextcloud.android.sso.model.SingleSignOnAccount
125127
import kotlin.math.roundToInt
128+
import kotlinx.coroutines.Dispatchers
126129
import kotlinx.coroutines.delay
127130
import kotlinx.coroutines.flow.flowOf
128131
import kotlinx.coroutines.launch
@@ -1190,10 +1193,23 @@ private fun NoteDetailScreen(
11901193
var selectionStart by rememberSaveable(localId) { mutableStateOf(0) }
11911194
var selectionEnd by rememberSaveable(localId) { mutableStateOf(0) }
11921195
var editor by remember { mutableStateOf<MarkdownEditText?>(null) }
1196+
// Hiding the keyboard and the state change that takes the editor away have to happen in one
1197+
// go on the main thread: the input method is only reachable while the editor still has a
1198+
// window token. Editing is left after a repository call, and a coroutine resumes on whichever
1199+
// thread completed that call, so this names the thread it needs instead of assuming one.
11931200
val leaveEditMode = {
1194-
// Hide the IME while the editor still has a valid window token, before Compose removes it.
1195-
editor?.releaseInputFocus()
1196-
editing = false
1201+
scope.launch(Dispatchers.Main.immediate) {
1202+
editor?.releaseInputFocus()
1203+
editing = false
1204+
}
1205+
Unit
1206+
}
1207+
val leaveNoteScreen = {
1208+
scope.launch(Dispatchers.Main.immediate) {
1209+
editor?.releaseInputFocus()
1210+
onBackToList()
1211+
}
1212+
Unit
11971213
}
11981214
val editorScrollState = rememberScrollState()
11991215
var editorViewportHeight by remember { mutableIntStateOf(0) }
@@ -1370,14 +1386,10 @@ private fun NoteDetailScreen(
13701386
val source = draft
13711387
if (editing && source != null) {
13721388
scope.launch {
1373-
if (component.saveDraft(localId, source)) {
1374-
editor?.releaseInputFocus()
1375-
onBackToList()
1376-
}
1389+
if (component.saveDraft(localId, source)) leaveNoteScreen()
13771390
}
13781391
} else {
1379-
editor?.releaseInputFocus()
1380-
onBackToList()
1392+
leaveNoteScreen()
13811393
}
13821394
},
13831395
modifier = Modifier.testTag("back-to-note-list")
@@ -2057,15 +2069,19 @@ private fun RenameNoteDialog(
20572069
.testTag("note-name-field")
20582070
)
20592071
Spacer(modifier = Modifier.height(8.dp))
2072+
// The whole row toggles, so the label is part of the target and the option
2073+
// reports one checked state rather than a box beside unrelated text.
20602074
Row(
20612075
verticalAlignment = Alignment.CenterVertically,
20622076
modifier = Modifier.fillMaxWidth()
2077+
.toggleable(
2078+
value = updateHeading,
2079+
onValueChange = onUpdateHeadingChange,
2080+
role = Role.Checkbox
2081+
)
20632082
.testTag("update-heading-checkbox")
20642083
) {
2065-
Checkbox(
2066-
checked = updateHeading,
2067-
onCheckedChange = onUpdateHeadingChange
2068-
)
2084+
Checkbox(checked = updateHeading, onCheckedChange = null)
20692085
Spacer(modifier = Modifier.width(8.dp))
20702086
Text("Update heading 1")
20712087
}

0 commit comments

Comments
 (0)