From ef46ce8b52190d9bf3a450b04f9c32fd687667d2 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:31 +0300 Subject: [PATCH 01/14] Let the widget picker draw its preview again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The launcher's picker showed «Couldn't add widget.» on every launcher from API 31, because the preview layout's root was a plain , and RemoteViews inflates only the classes marked @RemoteView. It is a FrameLayout now, and RemoteViewsLayoutTest reads every layout the widget ships and refuses a tag RemoteViews will not inflate, so the next one is a failing test rather than a broken picker nobody opens. Seen on an API 37 emulator before and after. Closes #167 --- .../src/main/res/layout/widget_preview.xml | 6 +- .../lessons/widget/RemoteViewsLayoutTest.kt | 89 +++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/RemoteViewsLayoutTest.kt diff --git a/android/widget/src/main/res/layout/widget_preview.xml b/android/widget/src/main/res/layout/widget_preview.xml index ba238dcc..cc324ae7 100644 --- a/android/widget/src/main/res/layout/widget_preview.xml +++ b/android/widget/src/main/res/layout/widget_preview.xml @@ -40,7 +40,11 @@ android:textColor="@color/widget_preview_on_surface_variant" android:textSize="13sp" /> - + ` + * drawing a progress bar — and nothing on the JVM could see it, because nothing + * here inflates these files: Glance builds the live widget in code, and the two + * XML layouts are read only by a launcher. + * + * So the tags are read out of the source tree and compared with the list. It + * cannot say whether a layout *looks* right — a launcher on a device can — only + * whether a launcher will inflate it at all. + */ +class RemoteViewsLayoutTest { + + private val res = File("src/main/res") + + @Test + fun `every widget layout uses only classes RemoteViews will inflate`() { + val layouts = res.listFiles { dir -> dir.isDirectory && dir.name.startsWith("layout") } + .orEmpty() + .flatMap { it.listFiles { file -> file.extension == "xml" }.orEmpty().toList() } + assertTrue( + "No layouts under ${res.absolutePath} — the walk went wrong, not the layouts", + layouts.isNotEmpty(), + ) + + val refused = layouts.flatMap { file -> + tagsOf(file).filterNot { it in Inflatable }.map { "${file.parentFile?.name}/${file.name}: <$it>" } + } + assertTrue( + "RemoteViews refuses these, and the launcher draws «Couldn't add widget.» " + + "instead of the layout: $refused", + refused.isEmpty(), + ) + } + + @Test + fun `the preview is among the layouts read`() { + // The file whose one bad tag started this; if it moves, the test above + // must still be reading it rather than passing over an empty folder. + assertTrue(File(res, "layout/widget_preview.xml").isFile) + } + + private fun tagsOf(file: File): List { + val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file) + val all = document.getElementsByTagName("*") + return (0 until all.length).map { (all.item(it) as Element).tagName } + } + + private companion object { + /** + * `@RemoteView` classes, by the short name a layout uses. From API 31 the + * compound buttons join the list; this module's `minSdk` is 26, and a + * preview is read only from 31, but the initial layout is read from 26, + * so the older list is the one both are held to. + */ + val Inflatable = setOf( + "FrameLayout", + "LinearLayout", + "RelativeLayout", + "GridLayout", + "AnalogClock", + "Button", + "Chronometer", + "ImageButton", + "ImageView", + "ProgressBar", + "TextView", + "ViewFlipper", + "ListView", + "GridView", + "StackView", + "AdapterViewFlipper", + "ViewStub", + ) + } +} From a88f7f8a2155cf727d5b5e2befae6efbf3b9a534 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:31 +0300 Subject: [PATCH 02/14] Let the widget follow a redraw that arrives inside a live Glance session provideGlance read the snapshot once, before provideContent, and a Glance session stays alive for about 46 seconds after it. updateAll inside that window only recomposes the running composition, which still held the first snapshot: a second class switch made within the window left the widget drawing the class just left. WidgetRedraws counts the redraws asked for; the tick receiver bumps it before updateAll, and the live composition re-reads the snapshot whenever the count has moved past the one its first read was taken at. A redraw asked for between the read and the collection is not lost, and a newer one replaces a read still in progress. docs/widget.md says so, describes the picker's preview (#167), and names WidgetTickReceiver as the receiver of DATA_SYNCED, which it had wrong. Closes #168 --- android/widget/build.gradle.kts | 3 + .../lessons/widget/LessonsWidget.kt | 61 +++++++--- .../lessons/widget/WidgetRedraws.kt | 61 ++++++++++ .../lessons/widget/tick/WidgetTickReceiver.kt | 7 +- .../lessons/widget/WidgetRedrawsTest.kt | 107 ++++++++++++++++++ docs/widget.md | 22 +++- 6 files changed, 243 insertions(+), 18 deletions(-) create mode 100644 android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetRedraws.kt create mode 100644 android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetRedrawsTest.kt diff --git a/android/widget/build.gradle.kts b/android/widget/build.gradle.kts index 97e3d877..fb091977 100644 --- a/android/widget/build.gradle.kts +++ b/android/widget/build.gradle.kts @@ -69,4 +69,7 @@ dependencies { implementation(libs.kotlinx.coroutines.android) testImplementation(libs.junit) + // The same catalog entry :core:data and :app test with; WidgetRedrawsTest + // drives the re-read on a virtual clock. + testImplementation(libs.kotlinx.coroutines.test) } diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt index f7f2ab59..89cf5d85 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt @@ -4,6 +4,9 @@ import android.content.ComponentName import android.content.Context import android.content.Intent import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember import androidx.glance.GlanceId import androidx.glance.GlanceTheme import androidx.glance.LocalContext @@ -34,11 +37,14 @@ import kotlinx.coroutines.flow.first * * Two decisions define this class: * - * **All data is resolved before [provideContent].** The composable below is a - * pure function of the snapshot it is handed, which means it can be previewed, - * reasoned about, and unit-tested through [com.lumenpearson.lessons.widget.ui] - * helpers. Fetching inside the composition — the pattern the reference app uses - * — recomposes against a moving target and makes the tree impossible to test. + * **All data is resolved into one snapshot before it is drawn.** The composable + * below is a pure function of the snapshot it is handed, which means it can be + * previewed, reasoned about, and unit-tested through + * [com.lumenpearson.lessons.widget.ui] helpers. Fetching inside the composition + * — the pattern the reference app uses — recomposes against a moving target and + * makes the tree impossible to test. The snapshot is read once when a session + * starts and again for each redraw asked for while it lives ([WidgetRedraws]); + * never piece by piece. * * **The clock is read exactly once per render.** Reading `LocalDateTime.now()` * in several places within one draw can straddle a bell and produce a widget @@ -64,19 +70,31 @@ class LessonsWidget : GlanceAppWidget() { override val sizeMode: SizeMode = SizeMode.Responsive(WidgetSizeClass.breakpoints) override suspend fun provideGlance(context: Context, id: GlanceId) { - // A failed read must not become "Problem loading widget" on somebody's - // home screen. Anything thrown out of provideGlance — an uninitialised - // graph, a corrupt Room file, a DataStore IO error — makes Glance draw - // its error layout, permanently, where the honest empty state would - // have told the user what to do and offered them a tap to do it. - val snapshot = runCatching { loadSnapshot(context) }.getOrElse { unreadableSnapshot() } - - // Once per render, not once per string: the stored choice came back with - // the snapshot above, and localized() hands the context straight back on - // API 33+ and on "системный", where there is nothing to override. - val localized = AppLocale.localized(context, snapshot.language) + // Taken before the read, so a redraw asked for while it runs is still + // seen by the composition below; see [rereadsAfter]. + val readAt = WidgetRedraws.current.value + val first = readSafely(context) provideContent { + // Still one snapshot per render — the body below is a pure function + // of it — but no longer one per *session*. Glance keeps a session + // alive for most of a minute and answers `updateAll` inside it with a + // recomposition alone, so the snapshot read above used to be drawn + // again for every redraw in that minute: switching classes twice in + // quick succession left the widget on the class the phone had just + // left (#168). Each redraw bumps [WidgetRedraws], and that re-reads. + val snapshot by produceState(first) { + rereadsAfter(WidgetRedraws.current, readAt) { readSafely(context) } + .collect { value = it } + } + + // Once per snapshot, not once per string: the stored choice came back + // with the snapshot, and localized() hands the context straight back + // on API 33+ and on "системный", where there is nothing to override. + val localized = remember(snapshot.language) { + AppLocale.localized(context, snapshot.language) + } + CompositionLocalProvider(LocalContext provides localized) { GlanceTheme { LessonsWidgetBody( @@ -102,6 +120,17 @@ class LessonsWidget : GlanceAppWidget() { } } + /** + * A failed read must not become "Problem loading widget" on somebody's home + * screen. Anything thrown out of provideGlance — an uninitialised graph, a + * corrupt Room file, a DataStore IO error — makes Glance draw its error + * layout, permanently, where the honest empty state would have told the user + * what to do and offered them a tap to do it. A re-read inside a live + * session is held to the same rule: a throw there would end the session. + */ + private suspend fun readSafely(context: Context): Snapshot = + runCatching { loadSnapshot(context) }.getOrElse { unreadableSnapshot() } + /** * What to draw when the read itself failed. * diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetRedraws.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetRedraws.kt new file mode 100644 index 00000000..852e6060 --- /dev/null +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetRedraws.kt @@ -0,0 +1,61 @@ +package com.lumenpearson.lessons.widget + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.update + +/** + * How many redraws this process has been asked for, so that a widget already on + * screen can tell its snapshot is out of date (#168). + * + * [LessonsWidget] reads everything before `provideContent`, which is what keeps + * its composable a pure function of one snapshot. But Glance keeps a session + * alive for the better part of a minute after it starts, and `updateAll` on a + * live session only recomposes — `provideGlance` does not run again — so a + * redraw asked for inside that minute drew the snapshot the session started + * with. On a phone that switched from one class to another and back within + * seconds, the widget went on showing the class it had just left, for as long + * as nothing else asked; the sync of the class on screen answered `304` and a + * `304` asks nothing. + * + * The counter is the missing edge: every redraw bumps it, and a composition + * that is still alive re-reads when it moves. A redraw that starts a session + * instead reads the counter together with its first snapshot, so it does not + * read twice. + */ +internal object WidgetRedraws { + + private val generation = MutableStateFlow(0L) + + /** The number of redraws asked for so far; only ever grows. */ + val current: StateFlow = generation.asStateFlow() + + /** Called before every `updateAll`, whoever asked for it. */ + fun ask() { + generation.update { it + 1 } + } +} + +/** + * A fresh [read] for every redraw asked for after [readAt], and nothing for the + * one the snapshot on screen already answers. + * + * [readAt] is the value of [generation] taken *before* that snapshot was read, + * so a redraw that lands between the read and the collection is still seen: + * the state flow hands its latest value to a new collector, and that value is + * no longer [readAt]. A newer redraw cancels a read still in progress, because + * only the last answer is worth drawing. + */ +@OptIn(ExperimentalCoroutinesApi::class) +internal fun rereadsAfter( + generation: StateFlow, + readAt: Long, + read: suspend () -> T, +): Flow = generation + .filter { it != readAt } + .mapLatest { read() } diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/tick/WidgetTickReceiver.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/tick/WidgetTickReceiver.kt index 67f2a9a1..66937eb0 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/tick/WidgetTickReceiver.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/tick/WidgetTickReceiver.kt @@ -5,6 +5,7 @@ import android.content.Context import android.content.Intent import androidx.glance.appwidget.updateAll import com.lumenpearson.lessons.widget.LessonsWidget +import com.lumenpearson.lessons.widget.WidgetRedraws import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -40,7 +41,11 @@ class WidgetTickReceiver : BroadcastReceiver() { scope.launch { try { // Redraw first: the new state is what decides when the next - // wake-up should be. + // wake-up should be. Bumped before asking, because a session + // that is still alive answers `updateAll` by recomposing, and it + // is the bump that makes it read again rather than redraw what it + // read when it started (#168). + WidgetRedraws.ask() LessonsWidget().updateAll(appContext) } catch (error: Exception) { android.util.Log.w(TAG, "Tick handling failed", error) diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetRedrawsTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetRedrawsTest.kt new file mode 100644 index 00000000..ab289b38 --- /dev/null +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetRedrawsTest.kt @@ -0,0 +1,107 @@ +package com.lumenpearson.lessons.widget + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * A widget already on screen re-reads for every redraw asked for after its + * snapshot, and for no other (#168). + * + * What went wrong on a device: Glance answers a redraw inside a live session by + * recomposing, and the snapshot had been read once for the whole session, so a + * class switch ten seconds after another drew the class the phone had left. + * What this holds is the edge that fixes it — a counter the redraw bumps and a + * composition that re-reads when it moves. Whether Glance itself then pushes + * the new frame is the launcher's side and was checked on an emulator. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class WidgetRedrawsTest { + + @Test + fun `nothing is re-read until a redraw is asked for`() = runTest { + val generation = MutableStateFlow(7L) + var reads = 0 + val seen = mutableListOf() + + val job = launch(UnconfinedTestDispatcher(testScheduler)) { + rereadsAfter(generation, readAt = 7L) { ++reads }.toList(seen) + } + advanceUntilIdle() + + assertEquals("the snapshot on screen already answers generation 7", 0, reads) + job.cancel() + } + + @Test + fun `every redraw after the snapshot reads again`() = runTest { + val generation = MutableStateFlow(7L) + var reads = 0 + val seen = mutableListOf() + + val job = launch(UnconfinedTestDispatcher(testScheduler)) { + rereadsAfter(generation, readAt = 7L) { ++reads }.toList(seen) + } + generation.value = 8L + generation.value = 9L + advanceUntilIdle() + + assertEquals(listOf(1, 2), seen) + job.cancel() + } + + /** + * The race the counter is read *before* the snapshot for: a redraw that + * lands while the first read is still running, before anything collects. + */ + @Test + fun `a redraw between the read and the collection is not lost`() = runTest { + val generation = MutableStateFlow(7L) + val readAt = generation.value + generation.value = 8L // asked for while the first snapshot was being read + var reads = 0 + val seen = mutableListOf() + + val job = launch(UnconfinedTestDispatcher(testScheduler)) { + rereadsAfter(generation, readAt) { ++reads }.toList(seen) + } + advanceUntilIdle() + + assertEquals(listOf(1), seen) + job.cancel() + } + + @Test + fun `a newer redraw replaces a read still in progress`() = runTest { + val generation = MutableStateFlow(0L) + val slow = CompletableDeferred() + val seen = mutableListOf() + + val job = launch(UnconfinedTestDispatcher(testScheduler)) { + rereadsAfter(generation, readAt = 0L) { + if (generation.value == 1L) slow.await() else "generation ${generation.value}" + }.toList(seen) + } + generation.value = 1L // starts a read that hangs + generation.value = 2L // and this one supersedes it + slow.complete("stale") + advanceUntilIdle() + + assertEquals(listOf("generation 2"), seen) + job.cancel() + } + + @Test + fun `asking bumps the process-wide counter`() { + val before = WidgetRedraws.current.value + WidgetRedraws.ask() + assertEquals(before + 1, WidgetRedraws.current.value) + } +} diff --git a/docs/widget.md b/docs/widget.md index 7ccf04ea..1af7c6d0 100644 --- a/docs/widget.md +++ b/docs/widget.md @@ -169,13 +169,33 @@ better than a receiver that crashes and stops the chain for good. Alarms do not survive a reboot, so `WidgetTickReceiver` listens for `BOOT_COMPLETED`, `MY_PACKAGE_REPLACED`, `TIME_SET` and `TIMEZONE_CHANGED`. +**A redraw inside a live session reads again.** `LessonsWidget` reads one snapshot and +draws it — the body is a pure function of that snapshot. Glance, though, keeps a session +alive for most of a minute after it starts, and answers `updateAll` inside that minute by +recomposing alone, without running `provideGlance` again. So the snapshot read when the +session started used to be drawn for every redraw in that minute: two class switches ten +seconds apart left the widget on the class the phone had just left, and nothing redrew it +after, because the sync of the class on screen answered `304` (#168, seen on an emulator). +Every redraw now bumps `WidgetRedraws` before it asks, and a composition that is still alive +re-reads when the counter moves; a redraw that starts a session reads the counter with its +first snapshot and does not read twice. + +## The picker + +`previewLayout` is what the launcher's widget picker draws, from XML, without running a line +of our code — and RemoteViews inflates only the classes marked `@RemoteView`. A plain +`` drawing the preview's progress bar made the whole preview «Couldn't add widget.» on +every launcher from API 31 (#167); it is a `FrameLayout` now, and `RemoteViewsLayoutTest` +reads every layout in the module for a class the launcher would refuse. + ## Offline The widget reads only Room and DataStore — there is no network on the drawing path. That is exactly why the countdown keeps running in a school basement. After a successful sync, `SyncWorker` sends the internal broadcast -`com.lumenpearson.lessons.action.DATA_SYNCED`, which `LessonsWidgetReceiver` subscribes to. +`com.lumenpearson.lessons.action.DATA_SYNCED`, which `WidgetTickReceiver` receives — not the +exported `LessonsWidgetReceiver`, which would take the action from any app on the device. That is why `:core:data` does not depend on `:widget` — the dependency would otherwise be circular. From 801aae59e8b48eddafc56b141895c8fe013e6de2 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:32 +0300 Subject: [PATCH 03/14] Keep the other years' terms when one year is synced The class row carries its terms, and replaceWindow wrote the fetched row whole. The server answers with the terms of the year that was asked for, so a look at another school year took the current year's terms away, and a 304 on the next sync of the current year never put them back: the calendar lost its quarters until the cache was cleared. replaceWindow keeps every stored term that lies wholly outside the window it replaces and takes the window's own from the answer, and the terms decode in date order. TermsAcrossYearsTest fails without the DAO change. Closes #169 --- .../core/data/database/EntityMappers.kt | 23 ++++- .../core/data/database/TimetableDao.kt | 10 ++- .../data/database/TermsAcrossYearsTest.kt | 89 +++++++++++++++++++ 3 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/database/TermsAcrossYearsTest.kt diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/EntityMappers.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/EntityMappers.kt index 96a02a31..5a32dc5b 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/EntityMappers.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/EntityMappers.kt @@ -69,14 +69,35 @@ internal fun decodeTerms(raw: String): List = raw.lineSequence() ) }.getOrNull() } - .sortedBy { it.index } + // By date, and by index only to break a tie: the row holds the terms of + // every cached year (#169), and «1, 1, 2, 2…» by index would interleave two + // of them. Within one year the two orders are the same. + .sortedWith(TermOrder) .toList() +private val TermOrder = compareBy({ it.startsOn }, { it.index }) + /** @see decodeTerms */ internal fun encodeTerms(terms: List): String = terms.joinToString("\n") { term -> "${term.index}|${term.kind.name.lowercase()}|${term.startsOn}|${term.endsOn}" } +/** + * The terms a class row holds after one year has been synced: the ones the + * bundle brought for [window], and every stored one that lies wholly outside it. + * + * The server sends the terms of the year it was asked for and nothing else, so + * a sync of another year must not take the current year's away — which it did, + * and a `304` for the current year never wrote them back (#169). A stored term + * that so much as touches the window is the bundle's to replace: it is either + * this year's, or it was cut differently last time and the bundle is newer. + */ +internal fun termsAfterSync(stored: String?, fetched: String, window: SyncedWindowEntity): String { + val otherYears = decodeTerms(stored.orEmpty()) + .filter { it.endsOn < window.startsOn || it.startsOn > window.endsOn } + return encodeTerms((otherYears + decodeTerms(fetched)).sortedWith(TermOrder)) +} + /** * Flattens a day into the rows that represent it. * diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/TimetableDao.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/TimetableDao.kt index 63bfb1db..4947105e 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/TimetableDao.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/database/TimetableDao.kt @@ -394,7 +394,15 @@ internal abstract class TimetableDao { deleteLessonsBetween(classId, window.startsOn, window.endsOn) deleteDaysBetween(classId, window.startsOn, window.endsOn) if (nextSchoolDay != null) deleteLookaheadOf(classId) - insertSchoolClass(schoolClass) + // The class row is one row for every year, but the terms in a bundle + // are the terms of the year it was asked for. Written as they came, a + // look at last year replaced this year's quarters, and the refresh that + // followed answered `304` and wrote nothing back (#169). So the row + // keeps every stored term outside this window and takes this window's + // from the bundle — read inside the transaction, so two years syncing + // at once cannot each write the other's terms away. + val stored = schoolClass(classId)?.terms + insertSchoolClass(schoolClass.copy(terms = termsAfterSync(stored, schoolClass.terms, window))) (days + listOfNotNull(nextSchoolDay)).forEach { record -> // Re-stamped rather than trusted: the class row being written is // the one authority on whose window this is, so a record built for diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/database/TermsAcrossYearsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/database/TermsAcrossYearsTest.kt new file mode 100644 index 00000000..e197d975 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/database/TermsAcrossYearsTest.kt @@ -0,0 +1,89 @@ +package com.lumenpearson.lessons.core.data.database + +import com.lumenpearson.lessons.core.model.Term +import com.lumenpearson.lessons.core.model.TermKind +import java.time.LocalDate +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * A look at another school year does not take the current year's terms away (#169). + * + * The class row is one row for every year, and a bundle carries the terms of + * the year it was asked for. Written as they came, scrolling the calendar to + * 2025/26 put 2025/26's quarters in place of 2026/27's; the refresh of 2026/27 + * that followed answered `304`, which writes nothing, and the header of the + * current week said «21 сентября — 27 сентября» with no «1 четверть» after it + * for as long as the year's data stayed the same. Seen on an emulator and read + * out of the phone's own database before this was written. + * + * Through [TimetableDao.replaceWindow] itself, on the in-memory DAO, because the + * merge has to happen inside the transaction that writes the row. + */ +class TermsAcrossYearsTest { + + private val thisYear = listOf( + quarter(1, LocalDate.of(2026, 9, 1), LocalDate.of(2026, 10, 31)), + quarter(2, LocalDate.of(2026, 11, 1), LocalDate.of(2026, 12, 31)), + ) + + private val lastYear = listOf( + quarter(1, LocalDate.of(2025, 9, 1), LocalDate.of(2025, 10, 31)), + quarter(2, LocalDate.of(2025, 11, 1), LocalDate.of(2025, 12, 31)), + ) + + @Test + fun `syncing last year keeps this year's terms`() = runTest { + val dao = InMemoryTimetableDao() + dao.replaceYear(classRow(thisYear), days = emptyList(), nextSchoolDay = null, openingYear = 2026) + + dao.replaceYear(classRow(lastYear), days = emptyList(), nextSchoolDay = null, openingYear = 2025) + + assertEquals(lastYear + thisYear, storedTerms(dao)) + } + + @Test + fun `a year synced again replaces its own terms and only its own`() = runTest { + val dao = InMemoryTimetableDao() + dao.replaceYear(classRow(thisYear), days = emptyList(), nextSchoolDay = null, openingYear = 2026) + dao.replaceYear(classRow(lastYear), days = emptyList(), nextSchoolDay = null, openingYear = 2025) + // The admin cut 2026/27 into halves in the meantime. + val halves = listOf( + Term(1, TermKind.SEMESTER, LocalDate.of(2026, 9, 1), LocalDate.of(2026, 12, 28)), + Term(2, TermKind.SEMESTER, LocalDate.of(2027, 1, 9), LocalDate.of(2027, 5, 31)), + ) + + dao.replaceYear(classRow(halves), days = emptyList(), nextSchoolDay = null, openingYear = 2026) + + assertEquals(lastYear + halves, storedTerms(dao)) + } + + @Test + fun `a first sync with nothing stored is the bundle's terms`() = runTest { + val dao = InMemoryTimetableDao() + + dao.replaceYear(classRow(thisYear), days = emptyList(), nextSchoolDay = null, openingYear = 2026) + + assertEquals(thisYear, storedTerms(dao)) + } + + private suspend fun storedTerms(dao: InMemoryTimetableDao): List = + decodeTerms(checkNotNull(dao.schoolClass(CLASS_ID)).terms) + + private fun classRow(terms: List) = SchoolClassEntity( + id = CLASS_ID, + name = "9А", + school = null, + timeZoneId = "Europe/Moscow", + terms = encodeTerms(terms), + syncedAtEpochMillis = 0L, + ) + + private fun quarter(index: Int, start: LocalDate, end: LocalDate) = + Term(index, TermKind.QUARTER, start, end) + + private companion object { + const val CLASS_ID = 1L + } +} From d1616d0dd709094d6e799257b5b8c9b3c603296c Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:32 +0300 Subject: [PATCH 04/14] =?UTF-8?q?Read=20the=20server's=20=C2=ABunknown?= =?UTF-8?q?=C2=BB=20schema=20as=20no=20revision=20at=20all?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /api/v1/warmup answers "schema": "unknown" when it cannot read alembic_version, and the about card drew it as a revision: «Схема unknown». WarmupDto.revision treats a blank or «unknown» value as none, and both the healthy and the degraded answer read it, so no chip is drawn for a revision nobody knows. Closes #172 --- .../lessons/core/data/network/dto/JoinDto.kt | 18 +++++++++++- .../data/repository/SessionRepositoryImpl.kt | 4 +-- .../data/network/dto/WarmupRevisionTest.kt | 28 +++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/WarmupRevisionTest.kt diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt index 2d0e7c63..fc75daaa 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt @@ -93,4 +93,20 @@ internal data class WarmupDto( @SerialName("schema") val schema: String? = null, @SerialName("expected_schema") val expectedSchema: String? = null, @SerialName("detail") val detail: String? = null, -) +) { + /** + * The revision the database is at, or null when the server does not know one. + * + * The server spells «I have none» as the word `unknown` (`public.py`: + * `revision or "unknown"`), and taken as a revision it reached the about + * card as «Схема unknown» — English inside a Russian chip, naming a + * revision that does not exist (#172). Null draws no chip, and the badge + * beside it already says the database and the code have not met. + */ + val revision: String? + get() = schema?.takeUnless { it.isBlank() || it.equals(UNKNOWN_REVISION, ignoreCase = true) } + + private companion object { + const val UNKNOWN_REVISION = "unknown" + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt index dc007eb9..0e1c3f82 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt @@ -75,13 +75,13 @@ internal class SessionRepositoryImpl( try { val body = api.warmup() when (body.status) { - "ok" -> ServerStatus.Ok(apiVersion = body.apiVersion, schema = body.schema) + "ok" -> ServerStatus.Ok(apiVersion = body.apiVersion, schema = body.revision) // `degraded` and `down` are both «the server answered and said // it is not well», and the schema pair is what says which. // Anything else a future server invents lands here too, with // its own sentence, rather than being reported as healthy. else -> ServerStatus.Degraded( - schema = body.schema, + schema = body.revision, expected = body.expectedSchema, detail = body.detail, ) diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/WarmupRevisionTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/WarmupRevisionTest.kt new file mode 100644 index 00000000..1fe84727 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/WarmupRevisionTest.kt @@ -0,0 +1,28 @@ +package com.lumenpearson.lessons.core.data.network.dto + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * «I have no revision» is not a revision (#172). + * + * A server whose database was built by `create_all` answers + * `"schema": "unknown"`, and the about card drew it as «Схема unknown» the + * first time the badge met a real server. + */ +class WarmupRevisionTest { + + @Test + fun `the server's unknown is no revision at all`() { + assertNull(WarmupDto(status = "degraded", schema = "unknown").revision) + assertNull(WarmupDto(status = "degraded", schema = "UNKNOWN").revision) + assertNull(WarmupDto(status = "degraded", schema = " ").revision) + assertNull(WarmupDto(status = "degraded", schema = null).revision) + } + + @Test + fun `a real revision is passed on as it came`() { + assertEquals("0017", WarmupDto(status = "ok", schema = "0017").revision) + } +} From cbe2f6f03151e5e4c6d45ebfb431a8b75b1f12ac Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:32 +0300 Subject: [PATCH 05/14] =?UTF-8?q?Say=20=C2=AB=D0=9D=D0=B8=D1=87=D0=B5?= =?UTF-8?q?=D0=B3=D0=BE=20=D0=BD=D0=B5=20=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=C2=BB=20on=20the=20one-line=20widget=20rather=20than=20?= =?UTF-8?q?=C2=AB0=20=D0=BF=D1=80=D0=B5=D0=B4=D0=BC=D0=B5=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The homework line on the smallest sizes counted subjects through a plural, and zero is a number the plural words as «0 предметов». The count is worded in one place now, which says «Ничего не задано» for none, and the today row uses it too. Closes #173 --- .../lessons/widget/format/WidgetStrings.kt | 16 +++++- .../lessons/widget/ui/LessonsWidgetBody.kt | 6 +-- .../lessons/widget/format/SubjectCountTest.kt | 52 +++++++++++++++++++ 3 files changed, 67 insertions(+), 7 deletions(-) create mode 100644 android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/format/SubjectCountTest.kt diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/format/WidgetStrings.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/format/WidgetStrings.kt index 755aacaf..6e9d89db 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/format/WidgetStrings.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/format/WidgetStrings.kt @@ -281,9 +281,21 @@ internal object WidgetStrings { text.collapseWhitespace(), ).ellipsize(maxChars) - /** "5 предметов" — Russian needs one/few/many, so this goes through plurals. */ + /** + * "5 предметов" — Russian needs one/few/many, so this goes through plurals — + * and «Ничего не задано» when there is nothing. + * + * Zero is a sentence rather than a number because every taller size already + * said it that way, and the one-line sizes, which printed the plural as it + * came, read «ДЗ на послезавтра · 0 предметов» beside them on the same home + * screen (#173). One place decides it now, so the sizes cannot disagree. + */ fun subjectCount(context: Context, count: Int): String = - context.resources.getQuantityString(R.plurals.widget_subject_count, count, count) + if (count == 0) { + context.resources.getString(R.string.widget_homework_empty) + } else { + context.resources.getQuantityString(R.plurals.widget_subject_count, count, count) + } /** * The word beside the ticking figure. diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt index cbfca073..55162ddf 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt @@ -610,11 +610,7 @@ private fun TodayHomeworkLine( ) HSpace(6) CaptionText( - text = if (subjects == 0) { - context.getString(R.string.widget_homework_empty) - } else { - WidgetStrings.subjectCount(context, subjects) - }, + text = WidgetStrings.subjectCount(context, subjects), size = size, emphasised = subjects > 0, ) diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/format/SubjectCountTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/format/SubjectCountTest.kt new file mode 100644 index 00000000..7d6b9791 --- /dev/null +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/format/SubjectCountTest.kt @@ -0,0 +1,52 @@ +package com.lumenpearson.lessons.widget.format + +import android.content.ContextWrapper +import android.content.res.Resources +import com.lumenpearson.lessons.widget.R +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * Nothing set is a sentence on every size of the widget, never «0 предметов» (#173). + * + * The one-line sizes printed the plural as it came, so a home screen with two + * widgets on it said «ДЗ на послезавтра · 0 предметов» in one and «Ничего не + * задано» in the other. The rule lives in [WidgetStrings.subjectCount] now, and + * this holds it there. + * + * No Robolectric in this module, so the context is a stub whose only real part + * is `getResources()`: both words are read through it. + */ +class SubjectCountTest { + + @Suppress("DEPRECATION") // the only public constructor; the stub ignores its arguments + private val resources = object : Resources(null, null, null) { + override fun getString(id: Int): String { + check(id == R.string.widget_homework_empty) { "asked for string $id" } + return NOTHING + } + + override fun getQuantityString(id: Int, quantity: Int, vararg formatArgs: Any?): String { + check(id == R.plurals.widget_subject_count) { "asked for plural $id" } + return "$quantity предмета" + } + } + + private val context = object : ContextWrapper(null) { + override fun getResources(): Resources = this@SubjectCountTest.resources + } + + @Test + fun `nothing set reads as a sentence rather than a zero`() { + assertEquals(NOTHING, WidgetStrings.subjectCount(context, 0)) + } + + @Test + fun `anything set is still counted`() { + assertEquals("3 предмета", WidgetStrings.subjectCount(context, 3)) + } + + private companion object { + const val NOTHING = "Ничего не задано" + } +} From 28bd7ab51e37cae959522f430b7d0c0f3ebd4a9b Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:33 +0300 Subject: [PATCH 06/14] Word an unreachable server in the app's own sentences MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The join screen and the refresh snackbar put OkHttp's exception text inside «Не удалось подключиться: …» and «Не удалось обновить: …», so a Russian sentence ended in English from the network stack. An offline join is the screen's own refusal now, unless the server address is missing, which keeps its own message; a failed sync carries no detail and says the generic sentence. sync_error_failed, which only existed to carry the detail, is gone from both languages. JoinErrorTest asserted the defect as correct behaviour («anything else is still shown verbatim»); it now asserts the opposite, and keeps the one case that is meant to be verbatim, a server's own answer. Closes #177 --- .../lessons/ui/common/SyncMessage.kt | 18 ++++++---- .../lessons/ui/join/JoinViewModel.kt | 7 +++- .../app/src/main/res/values-en/strings.xml | 1 - android/app/src/main/res/values/strings.xml | 1 - .../lessons/ui/common/SyncMessageTest.kt | 33 +++++++++++++++++++ .../lessons/ui/join/JoinErrorTest.kt | 28 ++++++++++++---- 6 files changed, 72 insertions(+), 16 deletions(-) create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt index e434b3e9..81e7c78f 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/SyncMessage.kt @@ -29,10 +29,16 @@ sealed interface SyncMessage { /** * Anything else: no network, a 5xx, a malformed payload. * - * @property detail server-provided text, shown verbatim when present because - * it is usually more specific than anything this app could invent. + * No detail, on purpose. This carried one, documented as the server's own + * words, and nothing ever filled it with those: the repository's failures + * are OkHttp's messages, «Server returned HTTP 502» and exception class + * names, and a pull-to-refresh with the server down read «Не удалось + * обновить: Failed to connect to /127.0.0.1:8000» (#177). What a user can + * do about any of them is the same — try again later — and the sentence + * written for that says so. The repository still keeps its message for + * whoever reads a log. */ - data class Failed(val detail: String?) : SyncMessage + data object Failed : SyncMessage /** A bug report did not reach GitHub. Not a sync, but the same snackbar. */ data object IssueFailed : SyncMessage @@ -46,7 +52,7 @@ fun SyncResult.toMessageOrNull(): SyncMessage? = when (this) { SyncResult.Success -> null SyncResult.Unauthorised -> SyncMessage.Unauthorised SyncResult.NotConfigured -> SyncMessage.NotConfigured - is SyncResult.Failed -> SyncMessage.Failed(message) + is SyncResult.Failed -> SyncMessage.Failed } /** Localizes a [SyncMessage] at the point where it is actually rendered. */ @@ -54,8 +60,6 @@ fun SyncResult.toMessageOrNull(): SyncMessage? = when (this) { fun SyncMessage.asText(): String = when (this) { SyncMessage.Unauthorised -> correctedString(R.string.sync_error_unauthorised) SyncMessage.NotConfigured -> correctedString(R.string.sync_error_not_configured) - is SyncMessage.Failed -> - detail?.let { correctedString(R.string.sync_error_failed, it) } - ?: correctedString(R.string.sync_error_generic) + SyncMessage.Failed -> correctedString(R.string.sync_error_generic) SyncMessage.IssueFailed -> correctedString(R.string.issue_error_failed) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt index fff904d8..ecf7b90a 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt @@ -95,11 +95,16 @@ sealed interface JoinError { // unreachable: «Не удалось подключиться: Could not reach the // server» went on a Russian screen, and the Russian sentence // written for exactly that case was never shown again. + // Nothing answered, so there is nothing to repeat: the exception's + // own message is OkHttp's, and it reached a Russian screen as + // «Не удалось подключиться: failed to connect to /10.0.2.2 (port + // 8000) from /10.0.2.16 …» (#177). The screen's own sentence is + // the answer to a server that cannot be reached. is JoinFailure.Offline -> if (classified.reason.causes().any { it is ServerAddressMissingException }) { NoServer } else { - Rejected(classified.reason.message?.takeIf { it.isNotBlank() }) + Rejected(null) } is JoinFailure.Rejected -> Rejected(classified.reason?.message?.takeIf { it.isNotBlank() }) diff --git a/android/app/src/main/res/values-en/strings.xml b/android/app/src/main/res/values-en/strings.xml index d11b97a0..6b2f6139 100644 --- a/android/app/src/main/res/values-en/strings.xml +++ b/android/app/src/main/res/values-en/strings.xml @@ -142,7 +142,6 @@ The phone keeps an access key and copies of the timetable and the diary, so the %1$d h Access to the class was revoked. Join again. No server address — set one in the settings. - Could not update: %1$s Could not update the timetable diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index df1edf55..58d71c0b 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -131,7 +131,6 @@ %1$d ч Доступ к классу отозван. Подключитесь заново. Не указан адрес сервера — задайте его в настройках. - Не удалось обновить: %1$s Не удалось обновить расписание diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt new file mode 100644 index 00000000..85169533 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/common/SyncMessageTest.kt @@ -0,0 +1,33 @@ +package com.lumenpearson.lessons.ui.common + +import com.lumenpearson.lessons.core.data.repository.SyncResult +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * A failed refresh is worded by the app, never by the exception (#177). + * + * The repository's failure message is for a log — OkHttp's «Failed to connect + * to /127.0.0.1:8000», «Server returned HTTP 502» — and it used to reach the + * snackbar after «Не удалось обновить:». Whatever it says, the screen gets the + * one sentence written for a refresh that did not happen. + */ +class SyncMessageTest { + + @Test + fun `a transport failure's own message does not reach the screen`() { + assertEquals( + SyncMessage.Failed, + SyncResult.Failed("Failed to connect to /127.0.0.1:8000").toMessageOrNull(), + ) + assertEquals(SyncMessage.Failed, SyncResult.Failed("Server returned HTTP 502").toMessageOrNull()) + } + + @Test + fun `the cases with a remedy keep their own sentences`() { + assertEquals(SyncMessage.Unauthorised, SyncResult.Unauthorised.toMessageOrNull()) + assertEquals(SyncMessage.NotConfigured, SyncResult.NotConfigured.toMessageOrNull()) + assertNull(SyncResult.Success.toMessageOrNull()) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt index 25e34a33..32e576f9 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt @@ -64,16 +64,32 @@ class JoinErrorTest { } /** - * Everything else keeps the server's own message under «Не удалось - * подключиться: …», which is what this screen did for every failure before - * the three above were split out. + * What a server said is kept under «Не удалось подключиться: …», which is + * what this screen did for every failure before the cases above were split + * out. */ @Test - fun `anything else is still shown verbatim`() { - val error = JoinError.of(JoinFailure.Offline(IOException("airplane mode"))) + fun `what the server said is still shown verbatim`() { + val error = JoinError.of(JoinFailure.Rejected(code = 502, reason = IOException("Bad gateway"))) assertTrue(error is JoinError.Rejected) - assertEquals("airplane mode", (error as JoinError.Rejected).detail) + assertEquals("Bad gateway", (error as JoinError.Rejected).detail) + } + + /** + * #177: when nothing answered there is nothing to repeat. This test used to + * assert the opposite — that «airplane mode» was shown verbatim — and on a + * device the verbatim text was OkHttp's: «Не удалось подключиться: failed + * to connect to /10.0.2.2 (port 8000) from /10.0.2.16 …». No message means + * the screen's own Russian sentence. + */ + @Test + fun `an unreachable server is worded by the screen, not by OkHttp`() { + val error = JoinError.of( + JoinFailure.Offline(IOException("failed to connect to /10.0.2.2 (port 8000) from /10.0.2.16")), + ) + + assertEquals(JoinError.Rejected(null), error) } /** From b43b14c4f384b63d1ea76c91c2d051647dc373f3 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:33 +0300 Subject: [PATCH 07/14] Let three tests pass on a Windows checkout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UnusedStringTest looked for "/src/" in a path Windows spells with backslashes, LegalBuildPropertyTest matched a blank line without the \r a Windows checkout gives it, and test_directory compared a relative path in the platform's separators with one written with «/». Each normalises now. CI runs on Linux and never saw any of it. The server suite on Windows also meets «database is locked» under -n auto now and then, from SQLite under load; that is noted on the issue and left alone. Closes #178 --- .../com/lumenpearson/lessons/LegalBuildPropertyTest.kt | 9 +++++++-- .../kotlin/com/lumenpearson/lessons/UnusedStringTest.kt | 7 +++++-- server/tests/test_directory.py | 4 +++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt index b36b8bd1..7b67b3ca 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt @@ -29,8 +29,13 @@ class LegalBuildPropertyTest { error("Could not find the Gradle root from ${File("").absolutePath}") } - private val buildScript by lazy { File(root, "android/app/build.gradle.kts").readText() } - private val workflow by lazy { File(root, ".github/workflows/apk.yml").readText() } + // Line endings normalised: Git for Windows checks text out with CRLF by + // default, and a block cut at a blank line found none there and threw + // (#178). The files are about what they say, not how they end a line. + private val buildScript by lazy { File(root, "android/app/build.gradle.kts").readText().unixLines() } + private val workflow by lazy { File(root, ".github/workflows/apk.yml").readText().unixLines() } + + private fun String.unixLines(): String = replace("\r\n", "\n") @Test fun `the build reads the property under both of its names`() { diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/UnusedStringTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/UnusedStringTest.kt index aab8feb5..0034b428 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/UnusedStringTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/UnusedStringTest.kt @@ -36,10 +36,13 @@ class UnusedStringTest { private val fromKotlin = Regex("""R\.(?:string|plurals|array)\.([A-Za-z0-9_]+)""") private val fromXml = Regex("""@(?:string|plurals|array)/([A-Za-z0-9_]+)""") - // Relative to `:app`'s own directory, which is where a unit test runs. + // Relative to `:app`'s own directory, which is where a unit test runs. Both + // path tests read the normalised path: on Windows `File.path` has + // backslashes, and a `/src/` matched against it kept no file at all, so + // every string in the app was reported unused there (#178). private fun sources(module: String): List = File("../$module").walkTopDown() - .filter { it.isFile && it.path.contains("/src/") } + .filter { it.isFile && "/src/" in it.path.replace(File.separatorChar, '/') } .filter { it.extension in setOf("kt", "xml") } .filter { "/res/values" !in it.path.replace(File.separatorChar, '/') } .toList() diff --git a/server/tests/test_directory.py b/server/tests/test_directory.py index b860bc97..42250035 100644 --- a/server/tests/test_directory.py +++ b/server/tests/test_directory.py @@ -507,7 +507,9 @@ def _throttles_built_in_app() -> list[tuple[str, ast.Call]]: continue name = getattr(node.func, "id", None) or getattr(node.func, "attr", None) if name == "JoinThrottle": - found.append((str(path.relative_to(APP)), node)) + # as_posix: on Windows str() of a relative path has backslashes, + # and the list below is written with slashes (#178). + found.append((path.relative_to(APP).as_posix(), node)) return found From 60c7728855aa385b62dacbd4caf7e51ccd02238e Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:33 +0300 Subject: [PATCH 08/14] Declare the time-zone database for a server run on Windows zoneinfo reads the system's database, and Windows has none: the server did not start at all there (ZoneInfoNotFoundError on the first class's zone). tzdata is declared for win32 only, and the mirror test lists it among the packages the Vercel bundle deliberately goes without, since Linux has the database already. Closes #170 --- server/pyproject.toml | 8 ++++++++ server/tests/test_requirements_mirror.py | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/server/pyproject.toml b/server/pyproject.toml index 24087a50..37c03d78 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -55,6 +55,14 @@ dependencies = [ # workstation against the database, never from inside a request, and the # function bundle is smaller without it. "alembic>=1.13", + # The time-zone database, on Windows only (#170). `zoneinfo` reads the + # operating system's, and Windows has none: without this the server does + # not even import there — `ZoneInfo("Europe/Moscow")` in + # providers/petersburg/client.py raises ZoneInfoNotFoundError on the way + # in. Linux, the Docker image and Vercel all ship /usr/share/zoneinfo, so + # the marker keeps it out of every deployment, and requirements.txt does + # not carry it (tests/test_requirements_mirror.py says why). + "tzdata>=2026.4; sys_platform == 'win32'", ] # Spelled out because the repository is a flat layout and now has more than one diff --git a/server/tests/test_requirements_mirror.py b/server/tests/test_requirements_mirror.py index 8683829c..76c527e5 100644 --- a/server/tests/test_requirements_mirror.py +++ b/server/tests/test_requirements_mirror.py @@ -26,8 +26,9 @@ #: where it is left out. ``uvicorn`` is the local server and Vercel brings its #: own; ``aiosqlite`` is the local database and the serverless one is Postgres; #: ``alembic`` runs from a workstation against the database, never from inside -#: a request. -DEPLOYED_WITHOUT = {"uvicorn", "aiosqlite", "alembic"} +#: a request; ``tzdata`` is the time-zone database for Windows, which is the one +#: platform without its own, and Vercel runs Linux (#170). +DEPLOYED_WITHOUT = {"uvicorn", "aiosqlite", "alembic", "tzdata"} _NAME = re.compile(r"^[A-Za-z0-9._-]+") From 07d330d61af46a7d2777cb1f9a77957290c288a9 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:33 +0300 Subject: [PATCH 09/14] Say that the crash reports' backup exclusion has been seen through bmgr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BackupRulesTest proves the rule files; what it could not say is whether a real backup leaves the reports out. On 26 September 2026 a crash report and two probe files went through bmgr's local transport, plain and flagged as a device transfer: the probes came back, the report did not. The test's note says so, and what it still cannot ask — Google's own transport to a real account. Closes #156 --- .../test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt index c205fbb2..d151c9a0 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt @@ -26,7 +26,11 @@ import org.w3c.dom.Element * The folder name is read out of `CrashReporter` itself rather than typed here, * so renaming the folder there fails this instead of quietly letting the new * folder into the backup. What this cannot say is whether a real phone obeys - * the rules: that needs a device and `bmgr`, and has not been done. + * the rules. That was asked once, on 26 September 2026, of an API 37 emulator + * through `bmgr` and the local transport: a report written by a real crash was + * not restored, while a file beside it in the same `external` domain was, for + * the cloud rules and again with the transport flagged as a device transfer. + * A later change to these files is back to being proved in XML only. */ class BackupRulesTest { From 01dc7fd51b869680f68703b73cf0ec5cbd902fe1 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:34 +0300 Subject: [PATCH 10/14] Let the tab bar be arranged in one touch, and closed from anywhere The owner's requests about the bar, one file between them, so one commit: - A tab's press and focus highlight is a circle (#179). The clickable keeps the whole box for the press and draws no indication; the ripple is drawn inside the Surface, whose CircleShape clips it. - A dropped tab no longer flashes the old order for a frame (#180). The tabs are keyed by label and animate where they are rather than their offset from a slot, and the shell reads the selected tab from the one it is keeping the pager on rather than from the pager's index, which names the old order until the pager has moved. - The long press that opens the arranging mode also picks the tab up (#181): one detector on the initial pass, ahead of the clickable, which consumes the pointer once it holds a tab so the lift is never a tap. Inside the mode a sideways move picks a tab up; the long press stays a TalkBack action. - A touch anywhere but the bar closes the mode, and reaches nothing under it (#182): ArrangingDismissLayer, between the page and the bar. - A section scrolled out of the guide's bar goes under the pill's round end (#183). Material pads the pill by 8 dp and scrolls its content inside that padding, so everything was cut by a straight edge 8 dp in. The side padding is inside the rows now, and the pill's own clip is what cuts. Checking #181 on the emulator found two things this branch had broken on its way, fixed here: the label that folds as the mode opens bounced below nothing and carried a neighbour out of the pill mid-drag (it folds on a spring without a bounce now), and keying the tabs took the gap after each one with it, so a drop could land 8 dp short (the gap belongs to the slot, as ToolbarGap). Every change has a Robolectric test that fails on the code before it. ToolbarShellCallerTest puts the bar under a caller shaped like the shell's and asks for one commit and a row that stays where it was dropped. The in-app guide says how to arrange the tabs, and its manifest is version 6. Closes #179 Closes #180 Closes #181 Closes #182 Closes #183 --- .../lessons/navigation/LessonsApp.kt | 33 +- .../component/ArrangingDismissLayer.kt | 48 +++ .../designsystem/component/FloatingToolbar.kt | 361 ++++++++++++------ .../component/ToolbarArrangeGesture.kt | 103 +++++ .../component/ArrangingDismissLayerTest.kt | 140 +++++++ .../designsystem/component/ToolbarDragTest.kt | 102 ++++- .../designsystem/component/ToolbarGestures.kt | 55 +++ .../component/ToolbarOverflowTest.kt | 39 ++ .../component/ToolbarReorderModeTest.kt | 40 +- .../component/ToolbarShellCallerTest.kt | 98 +++++ docs/app/guide.en.md | 2 + docs/app/guide.ru.md | 2 + docs/app/manifest.json | 4 +- 13 files changed, 900 insertions(+), 127 deletions(-) create mode 100644 android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayer.kt create mode 100644 android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarArrangeGesture.kt create mode 100644 android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayerTest.kt create mode 100644 android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarShellCallerTest.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt index 9651db1a..a49a6b0a 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt @@ -68,6 +68,7 @@ import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.repository.AppSettings import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.core.designsystem.component.ArrangingDismissLayer import com.lumenpearson.lessons.core.designsystem.component.LessonsFloatingToolbar import com.lumenpearson.lessons.core.designsystem.component.LessonsLoadingIndicator import com.lumenpearson.lessons.core.designsystem.component.ToolbarAction @@ -474,12 +475,15 @@ private fun HomeShell( var keepOnTab by remember { mutableStateOf(null) } LaunchedEffect(tabs) { val tab = keepOnTab ?: return@LaunchedEffect - keepOnTab = null val target = tabs.indexOf(tab) // `scrollToPage`, never the animated one: the page did not go // anywhere, the index under it did, and an animation here is a screen // visibly sliding to a place it never left. if (target >= 0 && target != pagerState.currentPage) pagerState.scrollToPage(target) + // Let go only once the pager is on it: the bar reads this tab as the + // selected one until then, and releasing it first left a frame in which + // the selection came from an index that still meant the old order. + keepOnTab = null } // A widget tap lands here. Closing the settings layers first, because the @@ -713,7 +717,15 @@ private fun HomeShell( ShellPage.Tabs -> if (home == ShellHome.DIARY) { diaryTab?.ordinal ?: 0 } else { - tabs.getOrNull(pagerState.currentPage) + // The tab being kept on, while there is one. A + // drop writes the new order, and the frame it + // arrives in still has the pager on the old + // *index* — the keyed pager moves it during its + // own measure, after this was read — so the + // index named the tab that had moved into it, + // and the selected circle hopped to that tab + // for a frame and back (#180). + (keepOnTab ?: tabs.getOrNull(pagerState.currentPage)) ?.let(barTabs::indexOf) ?: -1 } @@ -811,6 +823,15 @@ private fun HomeShell( ), ) }, + // Read against the page, like `reordering` above: the page + // sliding away must not keep a layer that swallows touches. + onTouchOutsideBar = if ( + reordering && page == ShellPage.Tabs && home == ShellHome.TIMETABLE + ) { + ::stopArranging + } else { + null + }, ) { when (page) { ShellPage.Tabs -> if (diaryViewModel != null) { @@ -986,6 +1007,10 @@ private val ShellPage.destination: ShellDestination * The cost of that is one measurement per page instead of one for the app, and * that is deliberate too: during a slide there are two toolbars, and a single * shared height would be written twice per frame by two different bars. + * + * @param onTouchOutsideBar while the tabs are being arranged, what a touch + * anywhere but the bar does; see [ArrangingDismissLayer]. Null the rest of the + * time, when there is no layer and the page takes its own touches. */ @Composable private fun ShellScaffold( @@ -993,6 +1018,7 @@ private fun ShellScaffold( statusBarHeightPx: Float, offset: ScrollOffsetHolder, toolbar: @Composable (Modifier) -> Unit, + onTouchOutsideBar: (() -> Unit)? = null, content: @Composable () -> Unit, ) { val density = LocalDensity.current @@ -1044,6 +1070,9 @@ private fun ShellScaffold( } } + // Between the page and the bar, so it takes every touch but the bar's. + if (onTouchOutsideBar != null) ArrangingDismissLayer(onDismiss = onTouchOutsideBar) + toolbar( Modifier .align(Alignment.BottomCenter) diff --git a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayer.kt b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayer.kt new file mode 100644 index 00000000..1e9eab45 --- /dev/null +++ b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayer.kt @@ -0,0 +1,48 @@ +package com.lumenpearson.lessons.core.designsystem.component + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.pointer.pointerInput + +/** + * Everything around the bar while its tabs are being arranged: a touch anywhere + * here closes the mode, and reaches nothing underneath (#182). + * + * Drawn above the page and below the bar. Compose hit-tests siblings from the + * top down and stops at the first one that takes the pointer, so the bar keeps + * its own gestures — a tap on a tab still closes the mode, a drag still carries + * one — and the page gets no touch at all while the mode is open. That is the + * point rather than a side effect: a tap meant to close the mode must not also + * open the lesson it landed on, and a swipe must not slide the pager out from + * under the icons being arranged. + * + * The mode closes when the finger lifts, as a tap does, rather than when it + * lands. A drag that starts here is swallowed whole and closes it the same way, + * because the alternative is a touch that does nothing at all. + */ +@Composable +fun ArrangingDismissLayer(onDismiss: () -> Unit, modifier: Modifier = Modifier) { + // Read through a state: the detector below is started once and never + // restarted, and would otherwise go on calling the first lambda it saw. + val currentOnDismiss by rememberUpdatedState(onDismiss) + Box( + modifier = modifier + .fillMaxSize() + .pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false).consume() + do { + val event = awaitPointerEvent() + event.changes.forEach { it.consume() } + } while (event.changes.any { it.pressed }) + currentOnDismiss() + } + }, + ) +} diff --git a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/FloatingToolbar.kt b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/FloatingToolbar.kt index 2291b451..2c84a26a 100644 --- a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/FloatingToolbar.kt +++ b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/FloatingToolbar.kt @@ -15,11 +15,12 @@ import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.gestures.detectHorizontalDragGestures -import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.indication +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer @@ -51,9 +52,11 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface +import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -67,6 +70,8 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.onLongClick +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview @@ -289,7 +294,12 @@ fun LessonsFloatingToolbar( label = "toolbar_mode", ) { backMode -> if (backMode) { - Row(verticalAlignment = Alignment.CenterVertically) { + Row( + // Material's horizontal padding, moved in here; see + // [PillContentPadding]. + modifier = Modifier.padding(horizontal = PillEndPadding), + verticalAlignment = Alignment.CenterVertically, + ) { BackAndTitle(title = title, onBackClick = onBackClick ?: {}) } } else { @@ -328,6 +338,7 @@ fun LessonsFloatingToolbar( modifier = pillModifier, expanded = expanded, colors = colors, + contentPadding = PillContentPadding, scrollBehavior = scrollBehavior, floatingActionButton = actionButton, content = content, @@ -337,6 +348,7 @@ fun LessonsFloatingToolbar( modifier = pillModifier, expanded = expanded, colors = colors, + contentPadding = PillContentPadding, scrollBehavior = scrollBehavior, content = content, ) @@ -443,8 +455,13 @@ private fun ToolbarItems( Modifier .widthIn(max = scrollingItemsMaxWidth(hasAction)) .horizontalScroll(scrollState) + // After the scroll, so it is the scrolling content that is + // padded and the window it scrolls in reaches the pill's edge: + // a section scrolled half out of view goes under the pill's + // round end rather than being cut off 8 dp inside it (#183). + .padding(horizontal = PillEndPadding) } else { - Modifier + Modifier.padding(horizontal = PillEndPadding) }, verticalAlignment = Alignment.CenterVertically, ) { @@ -454,68 +471,82 @@ private fun ToolbarItems( // the held tab follows the finger, and everything between it and // where it is going slides one slot the other way to open the gap. val shift = if (held >= 0) shiftSlots(slot, held, landing) else 0 - ToolbarTab( - item = item, - selected = original == selectedIndex, - isLast = slot == working.lastIndex, - expanded = expanded, - hideLabel = hideLabel, - jigglePhase = slot, - reordering = reordering, - held = slot == held, - offsetPx = if (slot == held) dragPx else shift * slotPx, - onLongPress = if (reorderable && !reordering) { - { + // Keyed by the tab, not by the slot it is in. Composed by position, + // a tab's animated offset belonged to its *slot*: the drop reordered + // the row and cleared the offsets in one frame, so every slot that + // changed hands drew its new tab at the old tab's offset and then + // sprang it home — the dropped tab visibly jumped away from where + // the finger left it before settling there (#180). Keyed, the state + // travels with the tab, and `ToolbarTab` animates where the tab + // *is* rather than how far it is from its slot. + key(item.label) { + ToolbarTab( + item = item, + selected = original == selectedIndex, + expanded = expanded, + hideLabel = hideLabel, + // The tab's own index, not its slot's: a phase that followed + // the slot would jump every time the tab changed places. + jigglePhase = original, + reordering = reordering, + held = slot == held, + slot = slot, + slotPx = slotPx, + offsetPx = if (slot == held) dragPx else shift * slotPx, + arrangeable = reorderable, + onOpenArranging = { // The press that opens the mode, and the only haptic in // it: `tap` rather than `press`, because this is a state // change and not a button, and the two should not feel // the same. LessonsHaptics.tap(view) onReorderingChange(true) - } - } else { - null - }, - onExitReorder = { onReorderingChange(false) }, - onDragStart = { - held = slot - dragPx = 0f - }, - onDrag = { delta -> dragPx += delta }, - onDragEnd = { - val from = held - val to = landing - held = -1 - dragPx = 0f - if (from >= 0 && to != from) { - // A notch as it lands, so a drop that changed the order - // feels different from one that did not. - LessonsHaptics.tick(view) - working = moveItem(working, from, to) - onReorder(working) - } - }, - ) + }, + onExitReorder = { onReorderingChange(false) }, + onDragStart = { + held = slot + dragPx = 0f + }, + onDrag = { delta -> dragPx += delta }, + onDragEnd = { + val from = held + val to = landing + held = -1 + dragPx = 0f + if (from >= 0 && to != from) { + // A notch as it lands, so a drop that changed the + // order feels different from one that did not. + LessonsHaptics.tick(view) + working = moveItem(working, from, to) + onReorder(working) + } + }, + ) + } + // Keyed by the slot, as the tab is by itself: see [ToolbarGap]. + if (slot < working.lastIndex) key(GapKey to slot) { ToolbarGap(expanded) } } } } +/** Keeps a gap's key from ever equalling a tab's, which is its label. */ +private const val GapKey = "toolbar_gap" + /** * The widest the scrolling row may be before the button beside it is pushed off * the screen. * * Measured from the window rather than from the parent's constraints because it * has to be known *before* the row is measured: the row is the thing being - * capped. Every term is deliberately generous — the pill's own content padding - * and the gap to the button are Material's and not ours — since the cost of - * over-reserving is one fewer icon visible, and the cost of under-reserving is - * a toolbar wider than the phone. + * capped. Every term is deliberately generous — the gap to the button is + * Material's and not ours — since the cost of over-reserving is one fewer icon + * visible, and the cost of under-reserving is a toolbar wider than the phone. */ @Composable private fun scrollingItemsMaxWidth(hasAction: Boolean): Dp { val screenWidth = LocalConfiguration.current.screenWidthDp.dp val reserved = ToolbarSideMargin * 2 + - PillContentPadding * 2 + + PillSlack * 2 + if (hasAction) ItemSize + ItemGap * 2 else 0.dp return (screenWidth - reserved).coerceAtLeast(ItemSize) } @@ -523,45 +554,75 @@ private fun scrollingItemsMaxWidth(hasAction: Boolean): Dp { /** The [LessonsFloatingToolbar] Box's own horizontal padding. */ private val ToolbarSideMargin: Dp = 16.dp -/** A generous estimate of Material's own padding inside the pill. */ -private val PillContentPadding: Dp = 16.dp +/** + * Material's padding inside the pill, less its two ends (#183). + * + * `FloatingToolbarDefaults.ContentPadding` is 8 dp all round, and in the layout + * with a button beside the pill Material scrolls its content inside it. A + * scroll container clips to a rectangle along its axis, so anything reaching + * an end — a documentation section scrolled half out of view, a held tab drawn + * larger, a jiggling one — was cut off by a straight edge 8 dp in from the + * pill's curve, and the round end the pill clips itself to was never reached. + * The ends' padding is [PillEndPadding] instead, inside every row, so the rows + * sit exactly where they did and everything that leaves them goes under the + * pill's own round end. + */ +private val PillContentPadding = PaddingValues(vertical = 8.dp) + +/** The two ends of Material's padding, drawn inside the rows; see above. */ +private val PillEndPadding: Dp = 8.dp + +/** + * What the cap on the scrolling row keeps back on each side of it beyond the + * margins. It was a generous 16 dp estimate of Material's padding, when that + * sat outside the row; [PillEndPadding] is now inside, so this is only what + * the estimate had to spare, and the pill is exactly as wide as it was. + */ +private val PillSlack: Dp = 8.dp /** * One tab: an icon that grows into an inverted pill with a label when selected. * - * ### The two gestures, and why they are two + * ### One gesture, as on an iOS home screen * - * On an iOS home screen one long press both opens the arranging mode and picks - * the icon up, so the finger never lifts. Here it is two: the long press opens - * the mode, and the drag that follows is a second touch. + * A long press opens the arranging mode **and picks the tab up**: the finger + * that pressed goes on to drag, without lifting (#181). Inside the mode a + * sideways move past the touch slop picks a tab up too, and a tap still closes + * the mode. * - * That is a real difference and it is deliberate. Making it one gesture means a - * tap detector and a long-press-drag detector on the same node, and which of - * them sees an event depends on which consumes the initial press — behaviour - * that cannot be settled by reading and that no test in this project can - * exercise, because it needs a real pointer and this module has no - * instrumentation. Two detectors that never overlap can be reasoned about, and - * the cost is one touch in a gesture nobody performs twice a day. + * It used to be two touches, on the ground that one gesture means a tap + * detector and a long-press-drag detector on one node, and which of them sees + * an event turns on which consumes it first. That is true, and it is settled + * here rather than avoided: the arranging detector is the outermost modifier and + * reads on [PointerEventPass.Initial], which reaches it before the + * `combinedClickable` inside, and the moment it has picked a tab up it consumes + * every change of that pointer — so the clickable sees a consumed stream, + * cancels its press and fires no tap on the lift. The clickable keeps no long + * press of its own, which is what used to swallow the rest of the gesture + * (`consumeUntilUp`); the long press stays reachable by TalkBack as a semantics + * action. Checked on an emulator with a real pointer. * * @param held whether this is the tab under the finger right now. It is drawn * above its neighbours and does not jiggle: an object you are holding is * steady, and everything else is what is loose. + * @param slot where the row has this tab now, and [slotPx] the row's pitch. * @param offsetPx where to draw it, along the row, relative to its slot. - * @param onLongPress non-null only while the mode can be *opened*; inside the - * mode the long press has nothing left to do. + * @param arrangeable whether a long press on it may open the arranging mode. */ @Composable private fun ToolbarTab( item: ToolbarItem, selected: Boolean, - isLast: Boolean, expanded: Boolean, hideLabel: Boolean, jigglePhase: Int = 0, reordering: Boolean = false, held: Boolean = false, + slot: Int = 0, + slotPx: Float = 0f, offsetPx: Float = 0f, - onLongPress: (() -> Unit)? = null, + arrangeable: Boolean = false, + onOpenArranging: () -> Unit = {}, onExitReorder: () -> Unit = {}, onDragStart: () -> Unit = {}, onDrag: (Float) -> Unit = {}, @@ -576,8 +637,8 @@ private fun ToolbarTab( // This is not ceremony. `Modifier.pointerInput` keyed on `Unit` starts its // coroutine once and never restarts it, and — because the element compares // equal on the key alone — the node is never even handed the newer lambda. - // Whatever `detectHorizontalDragGestures` closed over on the composition - // that opened the mode is what it still calls minutes later. `held` and + // Whatever the drag detector closed over on the composition that opened + // the mode is what it still calls minutes later. `held` and // `dragPx` survived that, being state reads; the landing slot did not, and // it is a plain `val` computed in the caller's composition. So every drop // reported the slot the tab had *before* the finger moved, which is no @@ -590,7 +651,8 @@ private fun ToolbarTab( // // Restarting the coroutine instead — a changing `pointerInput` key — would // cancel the gesture under the finger every time the drag moved a pixel. - val currentLongPress by rememberUpdatedState(onLongPress) + val currentReordering by rememberUpdatedState(reordering) + val currentOpenArranging by rememberUpdatedState(onOpenArranging) val currentDragStart by rememberUpdatedState(onDragStart) val currentDrag by rememberUpdatedState(onDrag) val currentDragEnd by rememberUpdatedState(onDragEnd) @@ -602,28 +664,51 @@ private fun ToolbarTab( ) val labelWidth by animateDpAsState( targetValue = if (selected && !hideLabel) LabelWidth else 0.dp, - animationSpec = toolbarSpring(), + // Without the bounce when the label goes because the tabs are being + // arranged. The long press that drops it is now also the start of a + // drag (#181), and a bouncing label dips below nothing: the tab is + // briefly narrower than an icon, and a neighbour already sliding over + // to open the gap is carried past the end of the row and out under the + // pill's edge, for a third of a second, mid-gesture. + animationSpec = if (reordering) toolbarSettleSpring() else toolbarSpring(), label = "toolbar_label_width", ) - // Collapses with the item beside it; see the note on LessonsFloatingToolbar. - val gap by animateDpAsState( - targetValue = if (expanded && !isLast) ItemGap else 0.dp, - animationSpec = toolbarSpring(), - label = "toolbar_item_gap", - ) if (itemWidth <= 0.dp && !selected) return - // Slides to its new slot on the same spring the widths use, so the row - // rearranging looks like the row rearranging rather than like icons - // teleporting. Not animated for the held tab: that one is following a - // finger, and a spring between the finger and the icon is lag. - val slide by animateFloatAsState( - targetValue = offsetPx, - animationSpec = if (held) snap() else toolbarOffsetSpring(), - label = "toolbar_item_offset", + // Where the tab *is* along the row, animated; not how far it is from its + // slot. The two are the same until the drop, and then only this one is + // continuous: the drop moves the tab to another slot and zeroes its offset + // in the same frame, so an animated offset started from the drag's last + // value on a slot that had just moved — and the tab jumped by the distance + // it had travelled before springing back (#180). An absolute position does + // not move when the slot and the offset trade places, and the offset the + // tab is drawn with is recovered from it below. + // + // Slides on the same spring the widths use while the tabs are being + // arranged, so the row rearranging looks like the row rearranging. Not for + // the held tab, which follows a finger — a spring between the finger and + // the icon is lag — and not outside the mode, where the pitch is not even + // (the selected tab wears its label) and an order that arrives from storage + // is a fact to draw, not a movement to show. + val position by animateFloatAsState( + targetValue = slot * slotPx + offsetPx, + animationSpec = if (held || !reordering) snap() else toolbarOffsetSpring(), + label = "toolbar_item_position", ) - val placement = if (held) offsetPx else slide + val placement = if (held) offsetPx else position - slot * slotPx + + // One source for the press and the highlight, which are deliberately two + // modifiers in two places. The press is read on the tab's whole box — a + // square on an icon, the pill on the selected tab — so a thumb landing in a + // corner still counts. The highlight is drawn inside the `Surface`, where + // its `CircleShape` clips it into a circle. While both were the one + // `combinedClickable`, the ripple and the focus layer were drawn before the + // Surface's clip, i.e. as the whole rectangle: a plain square under a tab in + // the middle of the bar, and a rounded one only at either end, where the + // bar's own pill happened to cut it. The ripple still grows from wherever the + // finger went down, corner included, and is clipped to the circle. + val interactionSource = remember { MutableInteractionSource() } // `Surface` and `combinedClickable` rather than `IconButton`, and the reason // is the long press. Material's `IconButton` has no `onLongClick`, and @@ -640,6 +725,35 @@ private fun ToolbarTab( color = if (selected) scheme.background else scheme.primary, contentColor = if (selected) scheme.primary else scheme.background, modifier = Modifier + // First in the chain, outside the layer that moves and scales the + // tab: the finger is measured in the row's coordinates, so the held + // tab follows it one to one rather than a tenth slower at + // [HeldScale], and nothing the tab does to itself feeds back into + // the drag. See the note above on the one gesture. + .then( + if (arrangeable) { + Modifier + .pointerInput(Unit) { + detectArrangeGesture( + arranging = { currentReordering }, + onOpen = { currentOpenArranging() }, + onStart = { currentDragStart() }, + onDrag = { currentDrag(it) }, + onEnd = { currentDragEnd() }, + ) + } + .semantics { + if (!reordering) { + onLongClick { + currentOpenArranging() + true + } + } + } + } else { + Modifier + }, + ) .graphicsLayer { translationX = placement // Above its neighbours while it is being carried, so the row @@ -651,51 +765,33 @@ private fun ToolbarTab( } .zIndex(if (held) 1f else 0f) .jiggling(active = reordering && !held, phase = jigglePhase) - .then( - if (onLongPress != null) { - Modifier.pointerInput(Unit) { - detectTapGestures(onLongPress = { currentLongPress?.invoke() }) - } - } else { - Modifier - }, - ) - .then( - if (reordering) { - Modifier.pointerInput(Unit) { - detectHorizontalDragGestures( - onDragStart = { currentDragStart() }, - onDragEnd = { currentDragEnd() }, - onDragCancel = { currentDragEnd() }, - onHorizontalDrag = { change, delta -> - change.consume() - currentDrag(delta) - }, - ) - } - } else { - Modifier - }, - ) .width(itemWidth + labelWidth) .height(ItemSize) .combinedClickable( + interactionSource = interactionSource, + // Drawn inside the Surface instead; see [interactionSource]. + indication = null, onClick = { LessonsHaptics.press(view) // A tap inside the mode is «done», not «go there» — the - // same thing tapping the wallpaper does on iOS, moved onto - // the one surface a thumb is already near. Navigating - // instead would leave the reader on a page they did not ask - // for, with the bar still wobbling behind them. + // same thing tapping the wallpaper does on iOS, which the + // caller's [ArrangingDismissLayer] does for the rest of the + // window. Navigating instead would leave the reader on a + // page they did not ask for, with the bar still wobbling + // behind them. if (reordering) onExitReorder() else item.onClick() }, - onLongClick = onLongPress, role = Role.Tab, ), ) { Row( modifier = Modifier .fillMaxSize() + // Inside the Surface, so its CircleShape clips the ripple and the + // focus layer to a circle on an icon and to the pill on the + // selected tab — never the square the box is. Before the padding, + // so it covers the whole of the shape. + .indication(interactionSource, ripple()) .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, @@ -731,10 +827,27 @@ private fun ToolbarTab( } } } +} - if (!isLast) { - Spacer(Modifier.width(gap)) - } +/** + * The space after a slot of the row, collapsing with the tabs; see the note on + * [LessonsFloatingToolbar]. + * + * Its own composable, owned by the slot, rather than the tail of each tab: the + * gap is between two places in the row, not a part of whichever tab is in the + * first of them. While each tab carried its own, keying the tabs (#180) made + * the gap travel with them — so a drop that moved the last tab into the middle + * grew its gap from nothing, and the tab behind it landed a gap short and slid + * the rest of the way. + */ +@Composable +private fun ToolbarGap(expanded: Boolean) { + val gap by animateDpAsState( + targetValue = if (expanded) ItemGap else 0.dp, + animationSpec = toolbarSpring(), + label = "toolbar_item_gap", + ) + Spacer(Modifier.width(gap)) } /** @@ -829,13 +942,29 @@ private fun BackAndTitle( * The one spring the toolbar animates with. * * Bouncy and slow, which is what gives the selected pill its overshoot; every - * width in the component shares it so they cannot arrive at different times. + * width in the component shares it so they cannot arrive at different times — + * all but the one that changes on its own, the label going as the tabs start + * to be arranged, which is [toolbarSettleSpring]'s. */ private fun toolbarSpring() = spring( dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow, ) +/** + * The spring the selected tab's label goes on as the arranging mode opens. + * + * [toolbarSpring]'s pace without its bounce. The long press that opens the mode + * is also the start of a drag (#181), and the drag counts in slots of one + * pitch: a label that overshot on its way out made its tab narrower than an + * icon for a moment, which carried a neighbour already sliding into the gap + * past the end of the row. + */ +private fun toolbarSettleSpring() = spring( + dampingRatio = Spring.DampingRatioNoBouncy, + stiffness = Spring.StiffnessLow, +) + /** * The spring the pill's width follows while it morphs between its two modes. * diff --git a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarArrangeGesture.kt b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarArrangeGesture.kt new file mode 100644 index 00000000..8572095b --- /dev/null +++ b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarArrangeGesture.kt @@ -0,0 +1,103 @@ +package com.lumenpearson.lessons.core.designsystem.component + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.ui.input.pointer.AwaitPointerEventScope +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerId +import androidx.compose.ui.input.pointer.PointerInputChange +import androidx.compose.ui.input.pointer.PointerInputScope + +/** + * Picking a tab up and carrying it, in one touch (#181). + * + * Outside the arranging mode the tab is picked up by holding still for a long + * press, which also opens the mode ([onOpen] runs first, then [onStart]); inside + * it, by moving sideways past the touch slop. Either way the same pointer then + * drags ([onDrag], in pixels along the row) until it lifts or is cancelled + * ([onEnd], always, in a `finally`, so a gesture cut off by the node leaving + * the composition still puts the row back). + * + * Everything is read on [PointerEventPass.Initial], which reaches this detector + * before the tab's own `combinedClickable`, and once a tab is picked up every + * change of that pointer is consumed — the lift included. That is what keeps a + * long press from ending in a tap: the clickable sees a consumed stream, + * cancels its press, and does not navigate or close the mode on the lift. + * Until a tab is picked up nothing is consumed, so a plain tap is the + * clickable's to handle exactly as before. + * + * @param arranging read on every touch, not captured, because the mode opens + * and closes under a detector that is never restarted. + */ +internal suspend fun PointerInputScope.detectArrangeGesture( + arranging: () -> Boolean, + onOpen: () -> Unit, + onStart: () -> Unit, + onDrag: (Float) -> Unit, + onEnd: () -> Unit, +) = awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + val pickedUp = if (arranging()) { + awaitSideways(down) + } else { + awaitHold(down).also { if (it) onOpen() } + } + if (!pickedUp) return@awaitEachGesture + + onStart() + try { + while (true) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes + .firstOrNull { it.id == down.id } ?: break + val dx = change.position.x - change.previousPosition.x + val lifted = !change.pressed + change.consume() + if (lifted) break + if (dx != 0f) onDrag(dx) + } + } finally { + onEnd() + } +} + +/** + * True when [down] was held without lifting or wandering for the long-press + * timeout; false when it lifted (a tap) or moved first (not a hold). + */ +private suspend fun AwaitPointerEventScope.awaitHold(down: PointerInputChange): Boolean { + val settled = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) { + while (true) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes + .firstOrNull { it.id == down.id } ?: return@withTimeoutOrNull + if (!change.pressed || change.isConsumed) return@withTimeoutOrNull + if (travelled(change, down) > viewConfiguration.touchSlop) return@withTimeoutOrNull + } + } + // `null` is the timeout firing with the finger still down and still: a hold. + return settled == null && isStillDown(down.id) +} + +/** True once [down] has moved past the touch slop; false if it lifted first. */ +private suspend fun AwaitPointerEventScope.awaitSideways(down: PointerInputChange): Boolean { + while (true) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes + .firstOrNull { it.id == down.id } ?: return false + if (!change.pressed || change.isConsumed) return false + if (travelled(change, down) > viewConfiguration.touchSlop) { + change.consume() + return true + } + } +} + +private fun travelled(change: PointerInputChange, down: PointerInputChange): Float = + (change.position - down.position).getDistance() + +/** + * Whether the pointer is still pressed as of the last event this scope saw. + * + * Asked after the timeout, because the timeout and a lift can arrive in the same + * frame and only the event says which came first. + */ +private fun AwaitPointerEventScope.isStillDown(id: PointerId): Boolean = + currentEvent.changes.firstOrNull { it.id == id }?.pressed ?: false diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayerTest.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayerTest.kt new file mode 100644 index 00000000..6e0b5355 --- /dev/null +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ArrangingDismissLayerTest.kt @@ -0,0 +1,140 @@ +package com.lumenpearson.lessons.core.designsystem.component + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.click +import androidx.compose.ui.test.down +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.moveBy +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.up +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * The layer that closes the arranging mode from anywhere but the bar (#182), + * asked with the real bar on top of it and a page underneath that counts its + * own taps — because what can go wrong here is not the layer on its own but + * which of the three a touch reaches. + */ +@RunWith(RobolectricTestRunner::class) +class ArrangingDismissLayerTest { + + @get:Rule + val compose = createComposeRule() + + @Before + fun holdTheClock() { + // The jiggle and `MarqueeText` run for ever; see `MarqueeClockTest`. + compose.mainClock.autoAdvance = false + } + + private val labels = listOf("Сегодня", "Календарь", "Задания") + + private var dismissed = 0 + private var pageTapped = false + private var reordering by mutableStateOf(true) + private var reported: List? = null + + @Test + fun `a tap on the page closes the mode and does not reach the page`() { + setShell() + + compose.onNodeWithTag(Page).performTouchInput { click(Offset(20f, 20f)) } + compose.settle() + + assertEquals("the tap outside the bar did not close the mode", 1, dismissed) + assertFalse("the tap reached the page under the layer", pageTapped) + } + + @Test + fun `a drag on the page closes the mode when it lifts, not when it lands`() { + setShell() + + compose.onNodeWithTag(Page).performTouchInput { + down(Offset(20f, 20f)) + moveBy(Offset(0f, 300f)) + } + compose.settle() + assertEquals("the mode closed while the finger was still down", 0, dismissed) + + compose.onNodeWithTag(Page).performTouchInput { up() } + compose.settle() + assertEquals(1, dismissed) + } + + @Test + fun `a tap on a tab is still the bar's, and the layer does not see it`() { + // The bar closes the mode on a tap of its own; the layer raising a + // second close for the same tap would be harmless today and a double + // action the day closing does anything more than flip a flag. + setShell() + + compose.onNodeWithContentDescription(labels[1]).performClick() + compose.settle() + + assertFalse("the bar's own tap did not close the mode", reordering) + assertEquals("the layer also took a tap that landed on the bar", 0, dismissed) + } + + @Test + fun `a tab can still be carried with the layer under the bar`() { + setShell() + + compose.dragFarRight(labels[0]) + + assertEquals(listOf(1, 2, 0), reported) + assertEquals("the layer took a drag that started on the bar", 0, dismissed) + } + + private fun setShell() { + compose.setContent { + LessonsTheme { + Box(Modifier.fillMaxSize()) { + Box( + Modifier + .fillMaxSize() + .testTag(Page) + .clickable { pageTapped = true }, + ) + if (reordering) ArrangingDismissLayer(onDismiss = { dismissed++ }) + LessonsFloatingToolbar( + modifier = Modifier.align(Alignment.BottomCenter), + items = labels.map { label -> + ToolbarItem(icon = Icons.Rounded.Settings, label = label) {} + }, + selectedIndex = 0, + reorderable = true, + reordering = reordering, + onReorderingChange = { reordering = it }, + onReorder = { reported = it }, + ) + } + } + } + compose.settle() + } + + private companion object { + const val Page = "page" + } +} diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarDragTest.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarDragTest.kt index 9f4e63d9..67ea1cdc 100644 --- a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarDragTest.kt +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarDragTest.kt @@ -5,9 +5,16 @@ import androidx.compose.material.icons.rounded.Settings import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.test.down +import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.up import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test @@ -126,13 +133,101 @@ class ToolbarDragTest { assertEquals(order, compose.drawnOrder(labels)) } - private fun setBar(onReorder: (List) -> Unit = {}) { + @Test + fun `a long press carries straight on into a drag, in the same touch`() { + // #181. It used to take two touches: the tab's clickable kept the long + // press for itself and consumed the rest of the gesture, and the drag + // detector was only added once the mode it belonged to was open, so it + // never saw the press that opened it. The finger lifted, pressed again + // and only then carried anything. + var reported: List? = null + var tapped = false + val reordering = setBar(open = false, onReorder = { reported = it }, onTap = { tapped = true }) + + compose.longPressAndDragFarRight(labels[0]) + + assertTrue("the long press did not open the mode", reordering()) + assertEquals("the same touch did not carry the tab", listOf(1, 2, 0), reported) + assertEquals(listOf(labels[1], labels[2], labels[0]), compose.drawnOrder(labels)) + assertFalse("the lift that ended the drag was taken for a tap", tapped) + } + + @Test + fun `on the frame of the drop every tab is still where it was drawn`() { + // #180. The row composed its tabs by position, so a tab's animated + // offset belonged to its slot: the drop reordered the row and zeroed + // the offsets in one frame, and every slot that changed hands drew its + // new tab from the old tab's offset, for a frame, before springing + // home — the flash of the row in the wrong order that the reader saw. + // Against that code the carried tab itself was read here thousands of + // dp from where the finger had left it. + // + // Centres, not edges, and to a dp and a half. What the drop may change + // on that frame is the carried tab's scale and the jiggle's phase, and + // both turn about the tab's centre and move no centre sideways; an + // edge moves with the scale, and the quarter of a tab that allowed for + // it also let through the gap that travelled with its tab (see + // `ToolbarGap`), which was a jump of 8 dp. + setBar() + compose.holdFarRight(labels[0]) + val before = compose.drawnCentres(labels) + + compose.lift(labels[0]) + val after = compose.drawnCentres(labels) + + for (label in labels) { + assertEquals( + "«$label» was drawn somewhere else on the frame of the drop", + before.getValue(label), + after.getValue(label), + 1.5f, + ) + } + } + + @Test + fun `as the mode opens, the tab being picked up is never narrower than an icon`() { + // The label goes as the mode opens, on the bar's bouncy spring, and a + // bounce on the way to nothing is a dip below it: the tab was briefly + // narrower than its own icon. That was invisible while the mode opened + // on one touch and the drag began on another; since the long press also + // picks the tab up (#181), the neighbour already sliding into the gap + // rode the dip past the end of the row and out under the pill's edge. + val reordering = setBar(open = false) + compose.onNodeWithContentDescription(labels[0]).performTouchInput { down(center) } + var waited = 0 + while (!reordering() && waited++ < 200) compose.settle(frames = 1) + assertTrue("the long press never opened the mode", reordering()) + + val widths = List(90) { + compose.settle(frames = 1) + val bounds = compose.onNodeWithContentDescription(labels[0]).getUnclippedBoundsInRoot() + (bounds.right - bounds.left).value + } + compose.onNodeWithContentDescription(labels[0]).performTouchInput { up() } + compose.settle() + + assertTrue( + "the tab dipped to ${widths.min()} dp on its way to ${widths.last()} dp", + widths.min() >= widths.last() - 0.5f, + ) + } + + /** + * The bar, with its mode opened by a long press unless [open] is false. + * Returns a reading of whether the mode is open now. + */ + private fun setBar( + open: Boolean = true, + onReorder: (List) -> Unit = {}, + onTap: () -> Unit = {}, + ): () -> Boolean { var reordering by mutableStateOf(false) compose.setContent { LessonsTheme { LessonsFloatingToolbar( items = labels.map { label -> - ToolbarItem(icon = Icons.Rounded.Settings, label = label) {} + ToolbarItem(icon = Icons.Rounded.Settings, label = label) { onTap() } }, selectedIndex = 0, reorderable = true, @@ -143,6 +238,7 @@ class ToolbarDragTest { } } compose.settle() - compose.longPress(labels[0]) + if (open) compose.longPress(labels[0]) + return { reordering } } } diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarGestures.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarGestures.kt index c08560ad..70fe2bfb 100644 --- a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarGestures.kt +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarGestures.kt @@ -82,6 +82,61 @@ internal fun ComposeContentTestRule.dragFarRight(label: String) { settle(frames = 120) } +/** + * A long press that goes straight on into a drag off the end of the bar, without + * the finger lifting in between: the one gesture that opens the arranging mode + * and carries a tab (#181). + * + * The wait is on the composition's clock for the same reason as in [longPress], + * and the move comes after it, so what is asked is whether a pointer that has + * already been a long press is still the drag's. + */ +internal fun ComposeContentTestRule.longPressAndDragFarRight(label: String) { + onNodeWithContentDescription(label).performTouchInput { down(center) } + settle() + mainClock.advanceTimeBy(LongPressMillis) + settle() + onNodeWithContentDescription(label).performTouchInput { + moveBy(Offset(SlopPx, 0f)) + moveBy(Offset(FarPx, 0f)) + } + settle() + onNodeWithContentDescription(label).performTouchInput { up() } + settle(frames = 120) +} + +/** + * Carries a tab off the end of the bar and keeps the finger down, with the row + * given time to settle around the gap, so that what is drawn is the last frame + * before a drop. [lift] ends it; the two are apart so that a test can read the + * row in between. + */ +internal fun ComposeContentTestRule.holdFarRight(label: String) { + onNodeWithContentDescription(label).performTouchInput { + down(center) + moveBy(Offset(SlopPx, 0f)) + moveBy(Offset(FarPx, 0f)) + } + settle(frames = 120) +} + +/** Lifts the finger [holdFarRight] left down, and draws exactly one frame. */ +internal fun ComposeContentTestRule.lift(label: String) { + onNodeWithContentDescription(label).performTouchInput { up() } + settle(frames = 1) +} + +/** + * Where each tab's centre is drawn along the row, the layer that moves it + * included. The centre rather than an edge, because the held tab's scale and + * the jiggle both turn about it. + */ +internal fun SemanticsNodeInteractionsProvider.drawnCentres(labels: List): Map = + labels.associateWith { label -> + val bounds = onNodeWithContentDescription(label).getUnclippedBoundsInRoot() + (bounds.left.value + bounds.right.value) / 2 + } + /** The tabs left to right, by the slot each was laid out in. */ internal fun SemanticsNodeInteractionsProvider.drawnOrder(labels: List): List = labels.sortedBy { onNodeWithContentDescription(it).getUnclippedBoundsInRoot().left.value } diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarOverflowTest.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarOverflowTest.kt index 1cf653d1..d2303ed0 100644 --- a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarOverflowTest.kt +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarOverflowTest.kt @@ -5,9 +5,12 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Settings import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onRoot +import androidx.compose.ui.unit.dp import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme import org.junit.Assert.assertTrue import org.junit.Rule @@ -69,6 +72,42 @@ class ToolbarOverflowTest { compose.onNodeWithContentDescription(ActionLabel).assertExists() } + /** + * A section scrolled half out of view goes under the pill's round end (#183). + * + * Every scroll container clips to a rectangle along its axis, and there are + * two here — Material scrolls the content of a pill with a button beside it, + * and the row scrolls its sections — so the edge a section is cut by is the + * nearer of their two windows. While Material's padding sat outside both, + * both windows began exactly where the first section did: 8 dp inside the + * pill, a straight line, and the round end the pill clips itself to was + * never reached. Asked of the windows rather than of the pixels, because a + * JVM test does not draw. + */ + @Test + fun `no scroll window cuts the row short of the pill's end`() { + showToolbar(selectedIndex = 0) + + val first = compose.onNodeWithContentDescription("Раздел 0").fetchSemanticsNode().boundsInRoot + val windows = compose + .onAllNodes( + SemanticsMatcher.keyIsDefined(SemanticsProperties.HorizontalScrollAxisRange), + useUnmergedTree = true, + ) + .fetchSemanticsNodes() + val endPadding = with(compose.density) { 8.dp.toPx() } + + assertTrue("found no scrolling window to ask", windows.isNotEmpty()) + for (window in windows) { + val before = first.left - window.boundsInRoot.left + assertTrue( + "A scroll window begins $before px before the first section, " + + "inside the pill's $endPadding px end, and cuts it with a straight edge", + before >= endPadding - 0.5f, + ) + } + } + private fun showToolbar(selectedIndex: Int) { compose.setContent { LessonsTheme { diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarReorderModeTest.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarReorderModeTest.kt index 136d2443..11f18f2e 100644 --- a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarReorderModeTest.kt +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarReorderModeTest.kt @@ -5,9 +5,11 @@ import androidx.compose.material.icons.rounded.Settings import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performSemanticsAction import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -69,6 +71,36 @@ class ToolbarReorderModeTest { assertEquals("a long press has to open the mode", true, reordering) } + @Test + fun `the lift that ends a long press is not a tap`() { + // The tab's clickable no longer has a long press of its own (#181), and + // a clickable with none takes a press of any length for a tap. What + // keeps the long press from also navigating is the arranging detector + // consuming the pointer once it has picked the tab up — this is the + // test that it does. + var tapped: String? = null + setBar(reorderingNow = false, onTap = { tapped = it }) + + compose.longPress(labels[1]) + + assertNull("the long press navigated as well", tapped) + } + + @Test + fun `a screen reader can still open the mode`() { + // The long press moved from the clickable into a detector of the bar's + // own, which a screen reader cannot perform; it is offered to TalkBack + // as the node's long-click action instead. + var reordering: Boolean? = null + setBar(reorderingNow = false, onReordering = { reordering = it }) + + compose.onNodeWithContentDescription(labels[1]) + .performSemanticsAction(SemanticsActions.OnLongClick) + compose.settle() + + assertEquals("the long-click action did not open the mode", true, reordering) + } + @Test fun `a long press does nothing when the caller has not asked for it`() { // The documentation's bar uses the same component, and its order is the @@ -85,10 +117,10 @@ class ToolbarReorderModeTest { @Test fun `inside the mode a tap closes it rather than navigating`() { - // The iOS gesture is a tap on the wallpaper; there is no wallpaper - // under a floating bar, so the bar takes the tap. Navigating instead - // would land the reader on a page they did not ask for, with the bar - // still wobbling. + // The iOS gesture is a tap on the wallpaper, which the rest of the + // window answers through `ArrangingDismissLayer`; on the bar itself a + // tab takes the tap. Navigating instead would land the reader on a page + // they did not ask for, with the bar still wobbling. var reordering: Boolean? = null var tapped: String? = null setBar(reorderingNow = true, onReordering = { reordering = it }, onTap = { tapped = it }) diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarShellCallerTest.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarShellCallerTest.kt new file mode 100644 index 00000000..6118f4f5 --- /dev/null +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/ToolbarShellCallerTest.kt @@ -0,0 +1,98 @@ +package com.lumenpearson.lessons.core.designsystem.component + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.createComposeRule +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * The bar under a caller shaped like the shell's, on the one-touch gesture. + * + * `LessonsApp` does three things no other test's caller does: it latches the + * list the mode opened with, it writes the new order to storage and gets it + * back a few frames later, and it names the selected tab by what it is rather + * than by an index. A drop on an emulator once looked as if it had been + * committed twice; this is the same arrangement without the emulator, where + * nobody else's finger can be on the screen, and it asks for exactly one + * commit and a row that stays where it was dropped. + */ +@RunWith(RobolectricTestRunner::class) +class ToolbarShellCallerTest { + + @get:Rule + val compose = createComposeRule() + + @Before + fun holdTheClock() { + compose.mainClock.autoAdvance = false + } + + private val calendar = "Календарь" + private val homework = "Задания" + private val today = "Сегодня" + + private var stored by mutableStateOf(listOf(calendar, homework, today)) + private var arranging by mutableStateOf?>(null) + private var keepOn by mutableStateOf(null) + private val commits = mutableListOf>() + + @Test + fun `one touch commits once, and the row stays as it was dropped`() { + showShell() + + compose.longPressAndDragFarRight(calendar) + compose.settle(frames = 200) + + val expected = listOf(homework, today, calendar) + assertEquals("the order was committed other than once", listOf(expected), commits) + assertEquals(expected, stored) + assertEquals(expected, compose.drawnOrder(expected)) + } + + private fun showShell() { + compose.setContent { + val scope = rememberCoroutineScope() + val barTabs = arranging ?: stored + // The shell lets go of the tab it kept the pager on once the new + // order is back out of storage. + LaunchedEffect(stored) { keepOn = null } + LessonsTheme { + LessonsFloatingToolbar( + items = barTabs.map { ToolbarItem(icon = Icons.Rounded.Settings, label = it) {} }, + selectedIndex = (keepOn ?: calendar).let(barTabs::indexOf), + reorderable = true, + reordering = arranging != null, + onReorderingChange = { on -> arranging = if (on) stored else null }, + onReorder = { moved -> + keepOn = calendar + val next = moved.map { barTabs[it] } + commits += next + // A round trip through DataStore: a few frames, not none. + scope.launch { + delay(StorageMillis) + stored = next + } + }, + ) + } + } + compose.settle() + } + + private companion object { + const val StorageMillis = 48L + } +} diff --git a/docs/app/guide.en.md b/docs/app/guide.en.md index d5d26bf7..8567b7e2 100644 --- a/docs/app/guide.en.md +++ b/docs/app/guide.en.md @@ -51,6 +51,8 @@ Three tabs under one floating toolbar; swipe between them or tap an icon in the - “Calendar” — the timetable as a week, a month or a single day, with rooms, replacements and cancellations; the day has two readings, “Ribbon” and “List”. - “Homework” — assignments grouped by the day they are due on. +The order of the tabs is yours: press and hold an icon in the bar and, without lifting your finger, carry it to its new place. While the icons wobble you can go on rearranging them; to finish, tap anywhere on the screen or go back. + “Homework” shows only what is still ahead. The “All” button opens the past ones too, and says how many were hidden. Settings holds nine sections, each one a page of its own: appearance, interaction, content, notifications, sync, class, diary, updates and “about”. An administrator of the class has a tenth — “Managing the class”. diff --git a/docs/app/guide.ru.md b/docs/app/guide.ru.md index 15e0b127..de79ea58 100644 --- a/docs/app/guide.ru.md +++ b/docs/app/guide.ru.md @@ -51,6 +51,8 @@ - «Календарь» — расписание неделей, месяцем или днём, с кабинетами, заменами и отменами; у «Дня» два чтения — «Лента» и «Список». - «Задания» — домашние задания, сгруппированные по дню, к которому они заданы. +Порядок вкладок можно поменять: зажмите значок в шторке и, не отпуская пальца, перенесите его на новое место. Пока значки покачиваются, их можно переставлять дальше; чтобы закончить, коснитесь любого места экрана или сделайте жест «назад». + Во вкладке «Задания» по умолчанию показаны только будущие. Кнопка «Все» открывает и прошлые и заодно говорит, сколько их было спрятано. Внутри настроек девять разделов, в каждый проваливаются отдельно: оформление, взаимодействие, содержимое, уведомления, синхронизация, класс, дневник, обновления и «о приложении». У администратора класса есть десятый — «Управление классом». diff --git a/docs/app/manifest.json b/docs/app/manifest.json index db200fbc..38819f62 100644 --- a/docs/app/manifest.json +++ b/docs/app/manifest.json @@ -1,6 +1,6 @@ { - "version": 5, - "updated": "2026-09-25", + "version": 6, + "updated": "2026-09-27", "appVersion": "0.6.0", "files": { "ru": "guide.ru.md", From a01ceb1da2cc1c15837b2412b2efad20a075fc69 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:34 +0300 Subject: [PATCH 11/14] Space a picker's segments by its tray's inset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In a tray the segments sat 2 dp apart, Material's connected gap, while the tray's edge was 4 dp from them: crowded together inside a wider frame, in «Неделя / Месяц / День» and every other picker drawn in a tray. The gap is the tray's inset now, the one number its corners were already derived from; a picker with no tray keeps the connected gap. SegmentedPickerGapTest reads it as geometry and fails on the old gap. Closes #184 --- .../designsystem/component/SegmentedPicker.kt | 21 +++- .../component/SegmentedPickerGapTest.kt | 103 ++++++++++++++++++ docs/design.md | 8 ++ 3 files changed, 128 insertions(+), 4 deletions(-) create mode 100644 android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPickerGapTest.kt diff --git a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPicker.kt b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPicker.kt index 788972b6..703277a1 100644 --- a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPicker.kt +++ b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPicker.kt @@ -66,9 +66,13 @@ private val SegmentFadeWidth = 8.dp * translation-editor plumbing — that component carries a long-press gesture * that opens a string-editing sheet, which is a feature of that app rather than * of the design system. What is kept is what makes it look right: Material's - * connected leading/middle/trailing shapes, the `ConnectedSpaceBetween` gap, the - * row of equal weights and the marquee on labels too long for their segment. + * connected leading/middle/trailing shapes, the `ConnectedSpaceBetween` gap + * (widened to the tray's inset when there is a tray), the row of equal weights + * and the marquee on labels too long for their segment. * + * @param contentPadding the tray's inset around the segments, when + * [containerColor] draws one. Its top is the one number the tray's corners + * and the gaps between segments are both derived from. * @param labelProvider the visible text of an option; also its accessibility name. * @param iconProvider optional glyph, drawn before the label. */ @@ -100,9 +104,10 @@ fun SegmentedPicker( // outer corner is the one the tray has to follow; `topStart` is that // corner. The trailing segment is its mirror, so one reading does both // ends. + val inset = contentPadding.calculateTopPadding() val shape = ConcentricShape( inner = ButtonGroupDefaults.connectedLeadingButtonShape, - inset = contentPadding.calculateTopPadding(), + inset = inset, ) Row( @@ -111,7 +116,15 @@ fun SegmentedPicker( .clip(shape) .background(containerColor) .padding(contentPadding), - horizontalArrangement = Arrangement.spacedBy(ButtonGroupDefaults.ConnectedSpaceBetween), + // In a tray, the tray's inset: each segment then sits as far from its + // neighbour as from the tray's edge (#184). It was Material's connected + // gap, 2 dp inside a 4 dp tray, whose corners were already derived from + // the inset and whose gaps never were — the segments looked crowded + // together in a frame wider than the space between them. Standing alone + // there is no inset to match, and the connected gap is the design. + horizontalArrangement = Arrangement.spacedBy( + maxOf(inset, ButtonGroupDefaults.ConnectedSpaceBetween), + ), ) { items.forEachIndexed { index, item -> val selected = item == selectedItem diff --git a/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPickerGapTest.kt b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPickerGapTest.kt new file mode 100644 index 00000000..c0786988 --- /dev/null +++ b/android/core/designsystem/src/test/kotlin/com/lumenpearson/lessons/core/designsystem/component/SegmentedPickerGapTest.kt @@ -0,0 +1,103 @@ +package com.lumenpearson.lessons.core.designsystem.component + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import com.lumenpearson.lessons.core.designsystem.theme.rowContainer +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * The space around a segment in a tray is one number (#184). + * + * Asked as geometry rather than as a constant, because the defect was two + * numbers that each looked right in their own file: the callers' 4 dp tray and + * Material's 2 dp connected gap. What the reader sees is the distance from one + * backing to the next against the distance from a backing to the tray's edge, + * so that is what is measured. + */ +@RunWith(RobolectricTestRunner::class) +class SegmentedPickerGapTest { + + @get:Rule + val compose = createComposeRule() + + @Before + fun holdTheClock() { + // The labels are `MarqueeText`; see `MarqueeClockTest`. + compose.mainClock.autoAdvance = false + } + + private val items = listOf("Неделя", "Месяц", "День") + + @Test + fun `in a tray, segments are as far apart as they are from its edge`() { + showPicker(inset = 4) + + val tray = compose.onNodeWithTag(Tray).getUnclippedBoundsInRoot() + val segments = segmentBounds() + + assertEquals("from the tray's edge", 4f, (segments[0].left - tray.left).value, 0.5f) + for (i in 1 until segments.size) { + assertEquals( + "between «${items[i - 1]}» and «${items[i]}»", + 4f, + (segments[i].left - segments[i - 1].right).value, + 0.5f, + ) + } + } + + @Test + fun `standing alone, segments keep the connected gap`() { + // No tray, no inset to match: the settings rows draw the picker bare, + // and there Material's connected group is the design. + showPicker(inset = 0) + + val segments = segmentBounds() + + assertEquals(2f, (segments[1].left - segments[0].right).value, 0.5f) + } + + /** In the merged tree the node holding a label's text is its whole segment. */ + private fun segmentBounds() = items + .map { compose.onNodeWithText(it).getUnclippedBoundsInRoot() } + .sortedBy { it.left.value } + + private fun showPicker(inset: Int) { + compose.setContent { + LessonsTheme { + SegmentedPicker( + items = items, + selectedItem = items[1], + onItemSelected = {}, + labelProvider = { it }, + containerColor = if (inset > 0) { + MaterialTheme.colorScheme.rowContainer + } else { + Color.Transparent + }, + contentPadding = PaddingValues(inset.dp), + modifier = Modifier.testTag(Tray), + ) + } + } + compose.settle() + } + + private companion object { + const val Tray = "tray" + } +} diff --git a/docs/design.md b/docs/design.md index e9268ca5..c46b37df 100644 --- a/docs/design.md +++ b/docs/design.md @@ -54,6 +54,14 @@ tray simply becomes a capsule. The picker used to be clipped at the call site wi arithmetic rather than on a screen, which is the only way either could be checked at all: Glance builds `RemoteViews` and there is no frame loop to draw them into. +**The same inset is the gap between two segments.** A tray is the space around its +backings, and it reads as even only when a backing is as far from its neighbour as from the +edge. The picker's corners followed the 4 dp inset while its segments kept Material's 2 dp +connected gap, so they looked crowded together inside a wider frame (#184). In a tray the +gap is the inset now; a picker with no tray keeps the connected gap, because there is no +edge to match. The floating toolbar keeps the same rule with 8 dp for both: its pill's inset +and the gap between tabs. `SegmentedPickerGapTest` reads it as geometry. + **The widget derives every inner corner from the rung it is on.** Its `innerCorner()` is the 24 dp surface less that rung's own padding, floored at 6 dp. It was a flat 18 dp — "one step tighter than the surface" — which would have been right for exactly From 387f98b800d05ed23ab7ea94fb8d7f29b8cd7a02 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:34 +0300 Subject: [PATCH 12/14] Add the extra source folders through directories, which AGP 9.4 asks for Every Gradle sync warned six times that srcDirs(vararg) is deprecated in favour of AndroidSourceDirectorySet.directories: once for the legal documents in :app, and five times in :core:data for Room's schemas, the guide, the region catalog and the sign-in vectors. A deprecated DSL call goes in a later major, and on that day the APK would stop carrying a folder without saying so. Each folder is added to directories with the same path; like srcDirs, it adds to the defaults rather than replacing them. LegalBuildPropertyTest matches the new line. The keystore notice in the same sync output is the build's own and stays. Closes #185 --- android/app/build.gradle.kts | 5 +++- .../lessons/LegalBuildPropertyTest.kt | 3 ++- android/core/data/build.gradle.kts | 24 ++++++++++++------- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8e040639..57a8c71f 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -210,7 +210,10 @@ android { // rather than a second one kept level by hand. The names cannot collide // with the guide's at the asset root: `legal.json`, not `manifest.json`, // and LegalDocumentsTest holds that for every folder mounted there. - getByName("main").assets.srcDirs(rootProject.layout.projectDirectory.dir("../docs/legal")) + // + // `directories`, not `srcDirs(...)`, which AGP 9.4 deprecates (#185). + getByName("main").assets.directories += + rootProject.layout.projectDirectory.dir("../docs/legal").asFile.path } androidResources { diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt index 7b67b3ca..d7624c89 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt @@ -92,7 +92,8 @@ class LegalBuildPropertyTest { assertTrue( "app/build.gradle.kts must mount docs/legal as an asset folder, or an " + "offline reader is told the document could not be opened", - buildScript.contains("""assets.srcDirs(rootProject.layout.projectDirectory.dir("../docs/legal"))"""), + Regex("""assets\.directories \+=\s+rootProject\.layout\.projectDirectory\.dir\("\.\./docs/legal"\)\.asFile\.path""") + .containsMatchIn(buildScript), ) val folder = File(root, "docs/legal") listOf("terms.ru.md", "terms.en.md", "privacy.ru.md", "privacy.en.md", "legal.json").forEach { name -> diff --git a/android/core/data/build.gradle.kts b/android/core/data/build.gradle.kts index 49a74aae..ef406562 100644 --- a/android/core/data/build.gradle.kts +++ b/android/core/data/build.gradle.kts @@ -4,6 +4,10 @@ plugins { alias(libs.plugins.ksp) } +/** A folder of the repository outside `android/`, as the path `directories` takes. */ +fun inRepository(path: String): String = + rootProject.layout.projectDirectory.dir("../$path").asFile.path + android { namespace = "com.lumenpearson.lessons.core.data" compileSdk = 37 @@ -42,9 +46,13 @@ android { // instead of being written blind. // fallback: if AGP ever drops the `test` android source set, keeping only the // `androidTest` line below is enough for Room's MigrationTestHelper. + // + // Every folder below is added through `directories`, a set of paths, rather + // than `srcDirs(...)`, which AGP 9.4 deprecates (#185); both add to the + // defaults rather than replace them. sourceSets { - getByName("test").assets.srcDirs(files("$projectDir/schemas")) - getByName("androidTest").assets.srcDirs(files("$projectDir/schemas")) + getByName("test").assets.directories += "$projectDir/schemas" + getByName("androidTest").assets.directories += "$projectDir/schemas" // The guide the app draws, shipped in the APK as it is written in the // repository — `docs/app/` itself is the asset folder, rather than a @@ -52,23 +60,21 @@ android { // copy of that text, which is the point: the app fetches these same // files from GitHub, and a bundled copy that had drifted from them // would show a reader a guide nobody wrote. - getByName("main").assets.srcDirs(rootProject.layout.projectDirectory.dir("../docs/app")) + getByName("main").assets.directories += inRepository("docs/app") // The region catalog, bundled as the server's generator wrote it — the // same one file the server reads, never a copy, because the phone takes // every host it will ever send a password to from this file and a // second allow-list is a second answer to «may I talk to this host». - getByName("main").assets.srcDirs( - rootProject.layout.projectDirectory.dir("../server/app/catalog/data"), - ) + getByName("main").assets.directories += inRepository("server/app/catalog/data") // The known answers both sign-in implementations are held to, read in // place from the server's tests so there is one file and not two that // agree until somebody edits one. The catalog rides along so a JVM test // can load it from the classpath the way the app loads it from assets. - getByName("test").resources.srcDirs( - rootProject.layout.projectDirectory.dir("../server/tests/vectors"), - rootProject.layout.projectDirectory.dir("../server/app/catalog/data"), + getByName("test").resources.directories += listOf( + inRepository("server/tests/vectors"), + inRepository("server/app/catalog/data"), ) } } From c1c3acf4955b49e08cb63011a79bb6a143fcef9d Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:35 +0300 Subject: [PATCH 13/14] Share the Android gates as Studio run configurations, and say how to run the app on an emulator .run/ holds five Gradle configurations that point at android/: the unit tests CI runs, both assembles, an install of the debug build, the pure model's tests and lint (labelled as not a gate). docs/build.md says how to open the repository in Android Studio, how an emulator reaches a local server (adb reverse and 127.0.0.1, because 10.0.2.2 did not answer here), and that a server on Windows needs tzdata (#170). --- .run/Android assemble.run.xml | 25 ++++++++++++ .run/Android core model tests.run.xml | 24 +++++++++++ .run/Android install debug.run.xml | 24 +++++++++++ .run/Android lint.run.xml | 24 +++++++++++ .run/Android unit tests.run.xml | 24 +++++++++++ docs/build.md | 58 +++++++++++++++++++++++++++ 6 files changed, 179 insertions(+) create mode 100644 .run/Android assemble.run.xml create mode 100644 .run/Android core model tests.run.xml create mode 100644 .run/Android install debug.run.xml create mode 100644 .run/Android lint.run.xml create mode 100644 .run/Android unit tests.run.xml diff --git a/.run/Android assemble.run.xml b/.run/Android assemble.run.xml new file mode 100644 index 00000000..be6754ed --- /dev/null +++ b/.run/Android assemble.run.xml @@ -0,0 +1,25 @@ + + + + + + + true + true + false + false + + + diff --git a/.run/Android core model tests.run.xml b/.run/Android core model tests.run.xml new file mode 100644 index 00000000..b2fbd889 --- /dev/null +++ b/.run/Android core model tests.run.xml @@ -0,0 +1,24 @@ + + + + + + + true + true + false + true + + + diff --git a/.run/Android install debug.run.xml b/.run/Android install debug.run.xml new file mode 100644 index 00000000..c75d9d37 --- /dev/null +++ b/.run/Android install debug.run.xml @@ -0,0 +1,24 @@ + + + + + + + true + true + false + false + + + diff --git a/.run/Android lint.run.xml b/.run/Android lint.run.xml new file mode 100644 index 00000000..36cbe063 --- /dev/null +++ b/.run/Android lint.run.xml @@ -0,0 +1,24 @@ + + + + + + + true + true + false + false + + + diff --git a/.run/Android unit tests.run.xml b/.run/Android unit tests.run.xml new file mode 100644 index 00000000..acb82e02 --- /dev/null +++ b/.run/Android unit tests.run.xml @@ -0,0 +1,24 @@ + + + + + + + true + true + false + true + + + diff --git a/docs/build.md b/docs/build.md index 07ebee5d..5f2921f4 100644 --- a/docs/build.md +++ b/docs/build.md @@ -684,6 +684,46 @@ licence, so a typeface cannot be swapped without its licence following it. The wrapper and its jar are in the repository, so `./gradlew` works on a fresh clone with no Gradle installed, and nothing else has to be on the machine. +## Android Studio + +**Open the repository root, and link `android/` as the Gradle project** (the Gradle tool +window's «+», or the prompt Studio shows for a folder with a build in it). The root is what +shows `server/`, `docs/` and the rest beside the app, and it is the only place Studio reads +`.run/` from: the shared run configurations there are written against the root, with the +Gradle project at `$PROJECT_DIR$/android`. Opening `android/` on its own builds the app just +as well and shows none of them. + +The configurations in `.run/` are Gradle ones only, because they are the only kind that +assume nothing about the machine: the two CI gates (`test`; `assembleDebug assembleRelease`), +`:core:model:test`, `:app:installDebug`, and `lint`, which is not a gate. Studio makes its own +«app» configuration on the first sync. The server's commands stay in the terminal, as the +README gives them: a Python configuration needs a Python plugin and an interpreter somebody +else's Studio may not have. + +**Gradle JDK: 21**, which is what CI runs. In Studio that is Settings → Build, Execution, +Deployment → Build Tools → Gradle → Gradle JDK; `#GRADLE_LOCAL_JAVA_HOME` reads +`android/.gradle/config.properties`, which is not committed: + +```properties +java.home=C:/Program Files/Eclipse Adoptium/jdk-21.0.11.10-hotspot +``` + +The JetBrains Runtime Studio ships with (25 at the time of writing) builds this project too; +21 is recommended because it is what CI gates on. + +**On Windows**, Git checks text out with CRLF unless told otherwise (`core.autocrlf`), and +three tests used to fail on such a checkout while passing on CI — two read paths with `/` and +one looked for a blank line without `\r` (#178). They pass now. The server suite under +`-n auto` can hit `database is locked` from SQLite on a loaded Windows machine; the same +tests pass on their own. + +**Logs.** Logcat's filter `package:com.lumenpearson.lessons` catches both the release build +and the debug one, whose package ends in `.debug`; `package:com.lumenpearson.lessons.debug` +is the debug build alone. The widget draws in the launcher's process and wakes in ours, so +its story is `tag:WidgetTick | tag:GlanceSessionManager | tag:WM-WorkerWrapper` under the +package filter, and a layout the launcher refuses is `tag:AppWidgetHostView` in the +launcher's own log — which is how #167 was found. + ## Pointing the app at a server The app needs an address the **phone** can reach, not the computer. `localhost` and @@ -720,6 +760,24 @@ The app needs an address the **phone** can reach, not the computer. `localhost` The bot hands out a class code with `/code`, and `python -m scripts.seed_demo` creates a demo class with the code `DEMO24`. +### On the emulator + +An emulator reaches the computer at `10.0.2.2`, in principle. On the Windows machine this +was first tried on it did not: «failed to connect to /10.0.2.2 (port 8000)» with uvicorn +listening on `0.0.0.0`. What works everywhere is a tunnel through `adb`, after which the +emulator's own loopback *is* the computer's: + +```bash +adb reverse tcp:8000 tcp:8000 # again after every emulator restart +``` + +and `http://127.0.0.1:8000` as the address in the app. The tunnel survives airplane mode, +so switching the network off does not cut the app from this server; to see how the app +behaves with the server gone, remove the tunnel instead (`adb reverse --remove tcp:8000`). + +On Windows the server needs one package Linux does not: the time-zone database. It is +declared in `pyproject.toml` for Windows only (#170), so `pip install -e ".[dev]"` brings it. + ### Why HTTP and not HTTPS Since Android 9 the system blocks `http://` by default. The app allows it through From 073dbe7af30368d3f057bd5b055702652486e5f6 Mon Sep 17 00:00:00 2001 From: leather147 Date: Sun, 27 Sep 2026 00:21:35 +0300 Subject: [PATCH 14/14] Record the first walk of the app on a device, and what it left HANDOVER.md opens on #186 and gains the batch: what was seen on the emulator by issue, the defects filed before their fixes, the owner's requests about the bar, the pickers and the sync warnings, what the recording could not settle because the emulator was shared, the machine's own costs, and the gates. Sections 5 and 7 say what the batch answered and what is the owner's now: the keystore's passwords, space on C: and a restart of Studio. README.md's honest status says what one walkthrough on an emulator saw. docs/architecture.md keeps the class row's terms across years (#169) and carries the new test counts, per module. --- HANDOVER.md | 436 +++++++++++++++++++++++++++++++++---------- README.md | 56 ++++-- docs/architecture.md | 14 +- 3 files changed, 385 insertions(+), 121 deletions(-) diff --git a/HANDOVER.md b/HANDOVER.md index 04aaaa95..f3e2be63 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -4,43 +4,51 @@ A working document, not part of the reference set in `docs/`. It describes **the the moment of handover**, so that a new session — human or agent — continues from the same place without reopening or redoing anything. -Last updated: **26 September 2026**. **PRs #63 through #85, #128, #129, #133 and #134 are -merged**; `main` is at `fa4fe0c`, the merge of #134. `dev` is still at `a43c6e8`, the merge -of #129, because #133 and #134 each went in from a branch of their own, and #140 is on one -too. It is behind `main` and has nothing `main` lacks, so bringing it level is a -fast-forward. **The only thing open is the pull request carrying this paragraph, #140**, from -`claude/school-diary-api-routes-cc4o1n`, on milestone 10, -`v0.9.0 — NetSchool e-diary, onboarding via the school's diary`. It is no longer a draft: -the owner created that milestone on 25 September and renamed the other nine the same day -(the table, with what each was called before, is under «And before that: nothing on a -screen is cut off»). Both reviews of its code have finished, and every confirmed finding is -fixed on the branch. The last one, **#165**, was a product decision. The owner decided it on -26 September: corrections are shared per child. It is fixed in `e01443d`, with a third -revision, `0017`. With no known defect left, `0015`, `0016` and `0017` went onto the -production database on 26 September 2026 at 12:26 UTC, as the owner's condition allowed. -What stands between #140 and the merge is only the `github-pr` skill's checklist on the -exact head. +Last updated: **27 September 2026**, night. **PRs #63 through #85, #128, #129, #133, #134, +#140 and #166 are merged**; `main` is at `bd7c816`, the merge of #166 (Dependabot's +`android-actions/setup-android` 4.0.1 → 4.0.4), and #140 went in before it as `4f506c2`. +`dev` is still at `a43c6e8`, the merge of #129: behind `main`, with nothing `main` lacks, so +bringing it level is a fast-forward. **The only thing open is the pull request carrying this +paragraph, #186**, from `agents/uncovered-device-scenarios-c8618d`, on milestone 9, +`v0.8.0 — On-device checks, 89-region e-diary survey`. It is the first batch made on a +machine with an emulator: it walked the app on an API 37 emulator against a local server and +production, with the live bot beside it, found twelve defects, filed each before fixing it +(#167–#178), fixed nine, and carries the seven things the owner asked for over the evening +and the night (#179–#185): the tab bar's round highlight, a drop that no longer flashes the +old order, a tab picked up by the same touch that opens the arranging mode, a tap anywhere to +close it, a scrolled bar cut by its round end, even gaps in every segmented picker's tray, +and a Gradle sync without AGP 9.4's deprecation warnings. The section «What the last session added» below is that batch. The SHA of its own merge is for the next close-out to write. -**Code moved on both halves, and the schema with it.** #140 carries two batches. The first -(#139, `4c34cb5` to `42fdf0a`) reads a second electronic diary, «Сетевой город» (ИРТех -NetSchool), on the server, behind a provider-neutral seam that Петербург went behind -unchanged. The second (#141, from `17c0473`) is the owner's request of 25 September: a first -run with two ways in — the class code, or the family's own school's diary — on which the -password goes from the phone to the diary and never to this server, and a phone that reads -only its diary gets a home of its own. Both halves' gates were run rather than quoted: -server **2024** tests, Android **1408**. - -**Once #140 merges, twenty-five issues are meant to close and twenty-four stay open.** Meant to -close: #136–#139, #141, #145–#155 and #157–#165. Staying open: **#156**, whose fix is in -`ce9c749` but which waits for a phone's backup to be read (`needs:device`); **#135**, the -owner's decision about the second diary, which the code has now answered but which is theirs -to close; **#142**, **#143** and **#144**, this batch's deliberate follow-ups, on no -milestone; **#109–#117**, the device epic and its children on milestone 9; **#118–#122**, -the owner's alone; and #123–#127, `status:someday`. What a merge closes is decided by the -`Closes` lines in the pull request body and in the commit messages, not by this paragraph — -read them against this list before merging. +**What #186 moves.** Android: the widget picker's preview draws again (#167); the widget +follows a class switch made inside a live Glance session (#168); a look at another school +year no longer takes the current year's terms away (#169); a server that cannot be reached +is worded by the app, not by OkHttp, on the join screen and in the refresh snackbar (#177); +«Схема unknown» is gone from the about card (#172); the one-line widget sizes say «Ничего не +задано» rather than «0 предметов» (#173); a toolbar tab's highlight is a circle (#179); a +dropped tab is drawn where the finger left it, not for a frame where it came from (#180); the +long press that opens the arranging mode also picks the tab up (#181); a touch anywhere but +the bar closes the mode and reaches nothing underneath (#182); a section scrolled out of the +guide's bar goes under the pill's round end instead of a straight cut inside it (#183); +segments in a picker's tray are as far apart as they are from its edge (#184). The in-app +guide says how to arrange the tabs (manifest version 6). The build scripts add their six +extra source folders through `directories` rather than the deprecated `srcDirs` (#185). Server: `tzdata` is declared for Windows, where the server did not start at all (#170). +Tests: three that failed on a Windows checkout pass there now (#178). Project: shared Gradle +run configurations in `.run/`, and `docs/build.md` says how to open the repository in +Android Studio. No schema change; `EXPECTED_REVISION` is still `0017`. + +**Once #186 merges, twenty-one issues are meant to close:** #167, #168, #169, #170, #172, +#173 and #177–#185 by their fixes; **#156** and **#119** by what the walkthrough read (#156's +backup through `bmgr`, #119's warmup and `/start`; see «What the last session added»); and, +of the device epic, **#114**, **#115**, **#116** and **#117**, whose emulator answers are in +their own threads. Filed and left open, each saying why: **#171** (a join fetches the year +twice), **#174** (two small widget sizes cut the wrong text), **#175** (the sign-in form +repeats a sentence) and **#176** (a stale join error, which did not reproduce the second +time). **#113** and **#111** stay open for what only a phone can say, and **#110** and +**#112** were not started. What a merge closes is decided by the `Closes` +lines in the pull request body and in the commit messages, not by this paragraph — read them +against this list before merging. **The code expects head `0017`, and production is at `0017` since 26 September 2026 at 12:26 UTC.** `EXPECTED_REVISION` in `app/db.py` is `0017`, pinned to the real head by @@ -48,28 +56,27 @@ read them against this list before merging. needs. `0016` creates `usage_counters`, the anonymous school directory's daily count of DaData requests. `0017` files the diary corrections under the child rather than a login, and it is data only. All three went on through the Neon connector (the project named `lessons`) -**before** the merge, in one transaction; «Schema» in the section on #140 below says what the -database said. The `0014` chapter still holds: #83's -pinned table of the enum column widths fails when a `SAEnum` member's **name** outgrows its -`VARCHAR`, which SQLite cannot see and production Postgres finds at the moment somebody marks -a day. - -Production was read after #60 and again after #61, rather than assumed: `/api/v1/warmup` — -which opens a real connection, so it answers for the database as well as the code — -answered `{"status":"ok","api_version":1,"schema":"0013"}`. **It has not been re-read since, -and #83 found out why.** The deployments sit behind Vercel's Deployment Protection and -answer a redirect to a login page, so `/api/v1/warmup` cannot be read from a session here at -all. It still wants reading, by the owner's browser or with a bypass token (#119). Once #140 -has merged and deployed it should answer `"schema":"0017"`; in the window between the -migrations and the merge it answers `degraded` with «База впереди кода…», which is the -window the correct order creates rather than a fault. That single line is the cheapest check -that the migrations and the code actually met. +**before** #140's merge, in one transaction; «Schema» in the section on #140 below says what +the database said. The `0014` chapter still holds: #83's pinned table of the enum column +widths fails when a `SAEnum` member's **name** outgrows its `VARCHAR`, which SQLite cannot +see and production Postgres finds at the moment somebody marks a day. + +**Production was read after #140 deployed, and the schema and the code met.** On 26 September +2026 at 17:05 UTC the production deployment of `bd7c816` answered `/api/v1/warmup` with +`{"status":"ok","api_version":1,"schema":"0017"}`. It was read through the Vercel connector's +`web_fetch_vercel_url`, which carries the owner's access through Deployment Protection — the +thing that made #83 call it unreachable from a session. The project's production alias +`lessons-ruddy-zeta.vercel.app` is **not** behind that protection (`/api/v1/health` answers +`200`), while the per-deployment URLs and `lessons-codeilluminators.vercel.app` redirect to +Vercel's sign-in; a phone is pointed at the first. The bot answered `/start` in the owner's +chat the same day. Both halves of #119 are therefore read, and it closes. **Two things changed about how this project is tracked, and they are the reason to read on before planning anything.** **The work moves to a local machine.** Everything up to #85 was built with no emulator, no -`adb` and no device, and so were #133, #134 and #140. The section «Where the work happens +`adb` and no device, and so were #133, #134 and #140; #186 is the first batch made with +one. The section «Where the work happens from here» below says what that unlocks and what it still cannot do; **#109** is the epic. #140 is the first batch since that decision to change screens, so nearly everything it adds to section 5 is a question a device answers. @@ -99,8 +106,9 @@ beside them. What that unlocks, in the order it is worth: PNGs. Every «nobody has looked at this» item in section 5 becomes answerable. 2. **Instrumented tests.** There is **no `androidTest` source set anywhere in this project** — not in any of the five modules, and no `espresso`, `uiautomator` or - `androidx.test` in the version catalog. That is why the reorder gesture is two touches - rather than one, and why its threshold is asserted in arithmetic rather than under a + `androidx.test` in the version catalog. It is why the reorder gesture was two touches + until #181, which made it one with a Robolectric test driving the pointer under a held + clock instead, and why its threshold is asserted in arithmetic rather than under a finger. 3. **Frame timing.** `dumpsys gfxinfo … framestats` costs nothing and works today; Perfetto plus `trace_processor` answers «which composable recomposed» in SQL; Macrobenchmark's @@ -140,7 +148,198 @@ next, someday, done) and `needs:` (device, owner). **A session cannot create a G Project board** — Projects v2 is GraphQL-only and the toolset here is REST — so the board is the owner's to make, and these labels are what its views filter on. -## What the last session added: «Сетевой город» on the server, and a way in through your own school's diary +## What the last session added: the first walk of the app on a device, and the twelve defects it found + +**The first batch made on a machine with an emulator (#109).** On 26 September 2026 the owner +handed the session Android Studio, an emulator and the live Telegram bot, and asked for every +«nobody has looked at this» to be looked at. It was walked on the AVD `Pixel_10_Pro_XL` +(API 37, `google_apis_playstore`, x86_64, 1344×2992 at 480 dpi, the emulator's GPU through the +host's RTX 3070), against a local server (`seed_demo`, «9А», plus a second class «10Б» in +Asia/Yekaterinburg) and against production, whose «11А» was driven from the bot in the +owner's own chat. Two builds were used side by side: the debug build from this branch, and +the release build the APK workflow made from `bd7c816`, already installed and joined to +«11А». + +### What was seen, by issue + +- **#156, crash reports and the backup — confirmed.** A real crash (`am crash`) wrote + `crash_reports/crash_…_00.log`; `bmgr backupnow` through the local transport, the files + deleted, `bmgr restore`: a probe file in `files/` and one in the `external` domain came back, + the report did not. Again with the transport flagged `is_device_transfer=true`: the same. + The Google transport was put back afterwards. The issue closes on this. +- **#119, warmup and `/start` — read.** See the opening paragraph. Closes. +- **#114, arranging the tabs.** The long press opens the mode (labels fold, the icons wobble); + a second touch dragging «Задания» to the first slot lands there; the reader stays on + «Календарь», which moves with its tab; back leaves the mode, not the app; the order + survives a force-stop. That was the build before #181; since it, the long press carries on + into the drag, and a recording of one injected touch shows the mode opening and the same + touch carrying «Календарь» a slot. **Not answerable on an emulator:** whether half a slot + is right under a thumb, and whether the haptic lands with the mode. +- **#115, the correction mode.** Outlines sit on the app's labels and never on subjects, + times or rooms; a long press on a row with a switch opens «Исправить строку» and leaves the + switch as it was; «Установлена v0.1.0» opens as `Установлена %1$s`; a long press inside the + editor does nothing. The editor lists two keys where two rows share one Russian text + (`settings_debug`, `debug_reports_open`) — by design, not filed. +- **#116, two classes and the join modes.** Joined, listed with «Показывается сейчас», both + ways out named. The widget follows a switch — and did **not** follow a second switch made + inside a live Glance session (#168, fixed). The production class «11А» turned out to be + invite-only already; its class code gets `403` «Этот класс принимает только по личному + приглашению из бота», the release phone that joined it earlier still syncs, and the app + words the refusal as «Этот класс подключает телефоны только по личному приглашению…». A + personal code from the live bot's «📱 Подключить телефон» (a spoiler, fifteen minutes, one + phone) linked the release build: «Телефон привязан · Роль: Владелец · можно + редактировать»; replaying the spent code answered `404`. The `429` was seen for the first + time: «Слишком много попыток. Попробуйте через 15 минут.» (`Retry-After: 866`). +- **#117, the upgrade path.** A debug build of `fa4fe0c` (before #140) was set up — old first + run, «9А», tabs rearranged — and `bd7c816` installed over it with `install -r`: the class + stayed, the first run did not come back, the tab order held, and the first sync was a + `304`. A later install over a build with a widget on the home screen kept the widget + drawing without re-adding it. The same APK re-signed with a fresh debug keystore was + refused with `INSTALL_FAILED_UPDATE_INCOMPATIBLE: … signatures do not match newer version`, + and the installed app was untouched — which is the sentence `docs/build.md` asserts. Both + builds were signed with this machine's debug key: the release keystore lives in CI. +- **#113, the widget's sizes.** Four launcher sizes, not twelve rungs, because the launcher + resizes by cells and the home screen had neighbours: 2×1 «ДЗ на послезавтра · 3 предмета»; + 2×2, about 195×226 dp, which lands on LARGE and cuts «Алгебра в 08:…»; 4×1; 4×2. At font + scale 2.0 the 4×1 still fits and the 2×1 reads «Д… 3 предмета» (#174). The picker's + preview was broken on every launcher from API 31 (#167, fixed). Stays open for the other + rungs and for the corner radii on a real launcher. +- **#111, the ribbon's cost — relative only.** Twelve flings of Monday's ribbon, `gfxinfo`: + debug SHADER p50 200 ms / NONE 250 ms; release SHADER 150 / NONE 200; the system Settings + app scrolled the same way at p50 150 ms, 88 % janky. The shader adds nothing measurable + above this emulator's floor; the floor itself is the emulator. With no lesson running the + ribbon renders one frame in ten seconds, so nothing redraws per frame when idle. Stays open + for a phone. +- **The first run, both ways in.** All five steps in Russian and in English; the legal links + online (GitHub, the English terms) and offline (the bundled «Privacy policy, Edition 1 of + September 25, 2026»). The diary way: the region list; Алтайский край's Госуслуги-only hand-off + to `netschool.edu22.info`; Амурская область's school search, which asked that region's live + «Сетевой город» server over TLS **from the phone** and got its real schools back — + kindergartens included; the «Моя школа» hand-off to `gosuslugi.ru/school`; the password form + with its host and the `http://` warning. No password was typed anywhere. +- **The calendar.** Week, month, the day's ribbon and list, «Подробно», the year picker, and + 2025/26 fetched on demand with «Загружаю год». The ribbon did not crash (#79's defect). +- **Offline and the server badge.** The cache stays on screen when the server goes away; the + about card's badge met a real server for the first time («Сервер: база и код разошлись» + on a `create_all` database, correctly). +- **Studio's Logcat**, read on the owner's request: the release build's periodic + `SyncWorker` ran eleven seconds against production, cold start included; WorkManager's + «onNetworkChanged() not implemented in … SystemJobService» on API 37 is the library's, not + ours; «Davey! duration=1046ms» opening a lesson sheet is a debug build's JIT on this + emulator's floor. + +### The defects, each filed before its fix + +| # | What was wrong | What it does now | +| --- | --- | --- | +| #167 | The picker's preview was «Couldn't add widget.»: a plain `` in `widget_preview.xml` | `FrameLayout`; `RemoteViewsLayoutTest` refuses any class RemoteViews will not inflate | +| #168 | Two redraws inside one Glance session drew the first snapshot: the widget stayed on the class just left | `WidgetRedraws` counts redraws, and a live composition re-reads when it moves | +| #169 | A sync of another year replaced the class row's terms; a `304` never put them back | `replaceWindow` keeps other years' terms and takes the window's own | +| #170 | The server did not start on Windows: no time-zone database | `tzdata` declared for Windows only, and left out of the bundle on purpose | +| #172 | «Схема unknown» on the about card | the server's sentinel is no revision, and draws no chip | +| #173 | «0 предметов» on the one-line widget sizes | «Ничего не задано», from the one place that words the count | +| #177 | OkHttp's English inside «Не удалось подключиться: …» and «Не удалось обновить: …» | the app's own sentences; `SyncMessage.Failed` carries no detail | +| #178 | Three tests failed on a Windows checkout (paths with `/`, a blank line without `\r`) | normalised; `JoinErrorTest` no longer asserts the #177 defect as correct | +| #179 | (the owner's request) a tab's press and focus highlight was a square | drawn inside the tab's `CircleShape`; the press still takes the whole box | +| #180 | (the owner's report) a dropped tab was drawn for a frame in the wrong place: tabs composed by position, and the selection read from the pager's index | tabs keyed by label and animated by where they are; the selection read from the tab being kept on | +| #181 | (the owner's request) picking a tab up took a second touch after the long press | one detector on the initial pass opens the mode and carries the tab; the long press stays a TalkBack action | +| #182 | (the owner's request) a tap outside the bar did not close the mode, and reached the page | `ArrangingDismissLayer` between the page and the bar | +| #183 | (the owner's report) a scrolled section was cut by a straight edge 8 dp inside the pill | Material's side padding moved inside the rows, so the pill's own round clip is what cuts | +| #184 | (the owner's report) segments in a tray 2 dp apart, 4 dp from its edge | the gap is the tray's inset; bare pickers keep Material's connected 2 dp | +| #185 | (the owner's screenshot of a sync) six warnings that `srcDirs` is deprecated in AGP 9.4 | `directories +=` with the same paths; `LegalBuildPropertyTest` matches the new line | + +Left open, with their reasons in the issue: **#171** (a join fetches the year twice, three +times once; seen on the build before #140 too), **#174** (small widget sizes), **#175** +(a repeated sentence on the sign-in form), **#176** (a stale join error that did not +reproduce the second time). + +Every fix was checked again on the emulator it was found on, except #173's wording, which +the widget at its current size does not draw (`SubjectCountTest` holds it), and #180–#184 — +see the next section. + +### The owner's toolbar, checked on the emulator while the owner used it + +#180–#184 came in one at a time over the evening and the night, each as a sentence and +most with a screenshot. Each has a Robolectric test that fails on the code before it: the +drop is read on its first frame (horizontal centres, to a dp and a half — the scale and the +jiggle both turn about the centre), the one-touch gesture is driven with the long-press wait +on the composition's clock, the layer is asked with the real bar on top of a page that counts +its own taps, and the two gaps are read as geometry. `ToolbarShellCallerTest` puts the bar +under a caller shaped like `LessonsApp` — the list latched, the order written and read back +some frames later — and asks for one commit and a row that stays where it was dropped. + +On the emulator, the check was a screen recording of one injected touch, cut into frames +with `ffmpeg`. It showed the one-touch pickup working, the round end of the pill clipping a +tab that slid out, and **two defects in this branch's own unmerged code**, fixed before the +merge and so not filed: the label that folds as the mode opens was on the bar's bouncy +spring, and with the drag already under way its dip below nothing carried a neighbour out +under the pill's edge for a third of a second (it now folds on `toolbarSettleSpring`); and +keying the tabs had taken the gap after each tab along with it, so a drop that moved the last +tab into the middle landed the tab behind it 8 dp short (the gap is `ToolbarGap` now, owned by +the slot). + +It also showed what could not be settled there: **the owner was using the emulator at the +same time.** The injected touch was once cancelled by the system for another device's +(«Canceling pointers for device 4»), the tab order changed between two screenshots with no +command of this session's in between, the guide was open where the calendar had been, and +Google Calendar came to the front mid-check. The final order that recording left in storage +was one no single drag of the injected touch could produce, and the same arrangement in the +JVM gives exactly one commit — so the device run is not evidence either way, and the session +stopped driving the emulator rather than fight for it. **Not seen on the device:** the drop +without its flash (#180), a tap outside closing the mode (#182), and #184. + +### The machine, and what it cost + +- **The emulator image's SystemUI crash-looped** on `SecurityException: Need + android.permission.BLUETOOTH_CONNECT` — its runtime permissions had been revoked — which is + also the Bluetooth crash in the owner's note to the bot. `pm grant` for every denied + permission fixed the running session; **the Quick Boot snapshot still held the revoked + state**, so every quick boot brought the crash back, and the long press on the launcher + stayed dead until a reboot. Saving a new snapshot with `adb emu avd snapshot save` froze + the emulator — it stalled writing `textures.bin` — and the stuck process had to be stopped; + the next start was a cold boot and came up healthy, with the grants in place. That freeze + briefly blocked the owner's own «Run» from Studio. +- **The Quick Boot revert.** A restart of the emulator mid-session quick-booted from a + snapshot taken before this session, which took back the debug app, its data, the widgets and + the permission grants: a build installed afterwards met a fresh first run. The release build + predates that snapshot and kept «11А», probably without the personal-code link made later. +- **C: had about 2 GB free**, which is why the emulator refused to start once («Your device + does not have enough disk space to run avd»). The AVD alone is 12 GB, 8.5 GB of it the + Quick Boot RAM image; `./gradlew clean` in this worktree gave back what its builds took. +- **Android Studio is set up** (none of it in this repository, all of it the owner's + machine): the repository root opened with `android/` linked as a Gradle project on JDK 21 + (`android/.gradle/config.properties`), `.claude/worktrees`, the venvs and the caches + excluded from indexing, a `server/.venv` for the Python plugin, local run configurations + for uvicorn, the seed, pytest as CI runs it (no source roots on `sys.path`), ruff and mypy, + Logcat favourites for this project, Kotlin auto-import, a project dictionary, and a 4 GB + heap (`studio64.exe.vmoptions` in the config directory). **Waiting for the next restart of + the IDE:** registering `server/.venv` as the Python SDK, turning the root module into a + Python one (which quiets «Unsupported Modules Detected»), and disabling the third-party + «Python Portable» plugin that fails to load on every start — the IDE rewrites those files + on exit, and the owner was using it. +- **The release keystore** (a folder on the owner's machine, handed over during the session) is PKCS12 + and came without its passwords, so nothing was signed with it and its certificate was not + compared with the build on the emulator. Before it replaces the key CI signs with: an APK + signed by a different key does not install over the one already on a phone (above, #117). + +### Gates + +At this branch's last commit before the close-out: `ruff check app tests scripts migrations` +clean; `pytest -q -n auto` **2024** passed (9 min 56 s here, against CI's four); +`python -m mypy` clean, 100 modules; `./gradlew test` **1438** (`:core:model` 125, +`:core:data` 537, `:core:designsystem` 112, `:widget` 113, `:app` 551); `assembleDebug` and +`assembleRelease` build, and a sync prints no deprecation. + +### What nobody has verified in this batch + +Everything in the list above that says «emulator» and is a question about a hand: the +threshold under a thumb, the haptics, TalkBack, a real GPU's frame times, Doze on a school +morning, the widget's other eight rungs. No diary was signed in to. Nothing was signed with +the release key. The Python SDK and the plugin change in the IDE wait for a restart. The +owner's toolbar requests are held by JVM tests and, on the device, only as far as the section +above says: #180, #182 and #184 were not seen there. + +## What the session before it added: «Сетевой город» on the server, and a way in through your own school's diary Open as PR #140, from `claude/school-diary-api-routes-cc4o1n`, on milestone 10 (`v0.9.0 — NetSchool e-diary, onboarding via the school's diary`). Twenty-two commits on @@ -411,7 +610,7 @@ Section 5 carries each of these with the reason it is unverifiable. In short: permission system refused a local server, so `0015`'s guard for a database that `0001` built is proven offline and on SQLite. -## What the session before it added: the electronic diary of every Russian region, and the routes each platform exposes +## What the batch before added: the electronic diary of every Russian region, and the routes each platform exposes Merged as PR #134 (`fa4fe0c`), from `claude/school-diary-api-routes-cc4o1n`, in the milestone then called `v0.8.0 — On a device`; it closed #130. **Documentation only.** No file under @@ -2352,8 +2551,8 @@ titles of their own time, which a search no longer finds; the third column maps | 6 | `v0.6.0 — Dishka DI, scrolling text, in-app guide from the repo` | `v0.6.0 — One container, and nothing cut off` | closed | PRs #60–#74; issues #96, #97, #99, #101, #103, #104 | | 7 | `Dependencies — dependabot bumps` | `Dependencies` | open, for good | every dependabot bump; deliberately not a version | | 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | `v0.7.0 — Оптимизация` | closed | PRs #75–#85, #128; issues #98, #100, #105–#108 | -| 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | `v0.8.0 — On a device` | open | PRs #129, #133, #134; issues #109–#117, #130–#132 — the first whose work needs an emulator or a phone | -| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PR #140; issues #135–#139, #141, #145–#160 — the one being worked on | +| 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | `v0.8.0 — On a device` | open | PRs #129, #133, #134, #186; issues #109–#117, #130–#132, #167–#185 — the first whose work needs an emulator or a phone, and #186 the first done on one | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PR #140 (merged); issues #135–#139, #141, #145–#165 | **#142, #143 and #144 are on no milestone, deliberately**: two follow-ups and a decision that #140 left alone on purpose, which belong to whichever version takes them up. @@ -2789,9 +2988,9 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 2024 tests, ~4 min (CI runs this) +cd server && pytest -q -n auto # 2024 tests, ~4 min on CI, ~10 on Windows cd server && python -m mypy # clean, 100 modules -cd android && ./gradlew test # 1408 tests across the five modules +cd android && ./gradlew test # 1438 tests across the five modules cd android && ./gradlew assembleDebug assembleRelease # both assembles ``` @@ -3189,6 +3388,10 @@ device on it. #140's additions below belong to #121 where they need a live diary merge. The prose here is kept because it says *why* each one is unverifiable, which an issue title cannot. +**#186 looked at a good part of this on an emulator** (26–27 September 2026; «What the last +session added» has the detail). The bullets it answered say so in place, and what an emulator +cannot answer — a thumb, a haptic, a real GPU, a real launcher's corners — is still here. + - **Not one route in `docs/diaries/` has been seen answering.** #134's 1916 routes were read from client code and two official apps, and cross-checked against each other. No diary host answers a cloud session, so none was ever called. A route marked *current* @@ -3218,21 +3421,25 @@ title cannot. retry. If that is what the first live session gets, the phone-registered path does not work for that diary and only the password routes remain. Whether «Сетевой город»'s four bootstrap calls fit inside Vercel's 30-second ceiling is unmeasured too. -- **Nothing of #140's phone half has run on a device.** Nothing composes `LessonsApp` in a - test, so the gate between the three homes, the hold on the first run through a join or a - registration, the swap to the right home and the resume after the process dies are proved - by the pure rules and the view models only. Nobody has seen the first run on a screen, - the wavy progress bar under real timings, the browser handoffs — the legal documents, ТОР - «Моя школа», the three Госуслуги-only regions — or the bundled fallback sheet, or heard - any of it through TalkBack. `diary.db` has not been written on a real phone. -- **TLS against the regional servers, and Android's own windows-1251, are inferred.** The - failure shapes `UpstreamHttp` classifies are the ones Conscrypt and the JVM are known to - throw, not ones seen on a device; the port carries its own windows-1251 table rather than +- **#140's phone half has run on an emulator, and only as far as a diary without a + password goes.** Nothing composes `LessonsApp` in a test, so the gate between the three + homes, the hold on the first run and the resume after the process dies are still proved by + the pure rules and the view models only. #186 walked the first run both ways in, in both + languages: the legal documents online and the bundled fallback offline, the region list, a + Госуслуги-only region's hand-off, ТОР «Моя школа»'s, a live school search and the password + form. Nobody has heard any of it through TalkBack, and `diary.db` has not been written, + because no password was typed. +- **TLS against the regional servers is seen succeeding once, and its failures and Android's + own windows-1251 are inferred.** #186's school search reached Амурская область's live + «Сетевой город» server over TLS from the emulator and got its schools back. The failure + shapes `UpstreamHttp` classifies are the ones Conscrypt and the JVM are known to throw, not + ones seen on a device; the port carries its own windows-1251 table rather than trusting the device's ICU, and whether the device's would have agreed is unasked. A `Retry-After` given as a date is read as no wait. -- **The backup exclusion of crash reports (#156) is proved in XML only.** `BackupRulesTest` - reads both rule files and the reporter's folder name; whether a real backup leaves the - reports out takes a phone and `bmgr`, which is why the issue stays open. +- **The backup exclusion of crash reports (#156) is seen on an emulator, not on a phone.** + `BackupRulesTest` reads both rule files; #186 ran `bmgr` through the local transport, plain + and flagged as a device transfer, and the report stayed out while a probe file came back. + Google's own transport to a real account has not been asked. - **The widget's third sentence has never been on a launcher.** Whether «Дневник — в приложении» and the new sentence for a phone with neither fit their rungs without a clip is judged by length only, and the redraw when the mode changes rests on a broadcast no test @@ -3247,15 +3454,15 @@ title cannot. describe what the code does and claim compliance with nothing: whether naming a GitHub account as operator satisfies 152-ФЗ, the transfer to hosting in Frankfurt, the age line and parental consent are open. -- **Nothing of the tab arranging has been seen on a phone, and it is a gesture.** #84 is a +- **The tab arranging has been seen on an emulator only, and it is a gesture.** #84 is a long press, a wobble and a drag; #85 is the drag actually reporting where it landed. What the 39 tests prove is arithmetic and contracts: where a drag of so many pixels lands, that the gesture reports the slot it computed, that a move is a permutation, that the stored order repairs itself, that the shell's one back rule leaves the mode before it leaves the - app. What nobody has felt: whether the wobble is plausible, whether half a slot is the - right threshold under a real thumb, whether the two-step gesture — press, then pick up — - reads as deliberate rather than as a gesture that failed the first time, and whether the - haptic lands where the mode opens. **The APK built for #84 predates the fix and does not + app. #186 saw it work on an emulator (#114), and made it one gesture (#181). What nobody + has felt: whether the wobble is plausible, whether half a slot is the right threshold + under a real thumb, whether a hold that picks the tab up at once is too eager for someone + who only meant to look, and whether the haptic lands where the mode opens. **The APK built for #84 predates the fix and does not rearrange anything**; the first install worth an evening is one built after #85 merges. - **The drag is driven from a test now, and how far it goes is the whole reason it can be.** #84 left it undriven on the ground that Robolectric reports its own densities, so a @@ -3263,9 +3470,10 @@ title cannot. batch: a drag of ten thousand pixels parks at the end under any density, which is what `ToolbarDragTest` does and what caught it. Anything *between* two slots is still not asked of a composition, and `ToolbarReorderTest` asks it in pixels instead. -- **There is a window of a frame or two after the drag, and it is inherent rather than a - defect:** between the drag ending and the preferences answering, the pager's index still - names the old order, and a `LaunchedEffect` on the arrived order is what closes it. The +- **There was a window of a frame or two after the drag, and it was written here as + inherent. It was not (#180):** between the drag ending and the preferences answering, the + pager's index still names the old order, and the bar read its selection from that index — + so the selected circle hopped for a frame. It reads the tab being kept on now. The other one — a frame of the pre-drag order at the moment the mode closes — was written down here as deliberate and is closed by #85. - **Nothing of the year scrolling has been looked at either.** What the tests prove is @@ -3289,7 +3497,9 @@ title cannot. happened. Three tests hold `AboutCard`; nothing holds the next one. Such a defect is invisible on a pull request by construction — `ci.yml` does not set the build properties and should not, because it does not produce an APK anybody installs. -- **The server badge has never been drawn against a real server.** `ServerStatus` has four +- **The server badge has been drawn against a real server once, on an emulator** — «Сервер: + база и код разошлись» from a local `create_all` database, correctly — and not yet from a + phone on a school's wifi. `ServerStatus` has four states and a test for each, all of them from a fake; nothing in the suite opens a socket. What that leaves unchecked is the shape of a real answer — whether `/api/v1/warmup` from a phone on a school's wifi resolves into `Ok`, `Degraded` or `Unreachable` as intended, @@ -3319,8 +3529,9 @@ title cannot. system font now fits the rung it lands on, whether the chips read as seven days, and whether the subject keeps its width beside a long teacher's name. Below API 31 the corner half of this does not arise at all — `cornerRadius` is a no-op there. -- **`/api/v1/warmup` has still not been read, and it is now known to be unreachable from a - session rather than merely not done.** The deployments are behind Vercel's Deployment +- **`/api/v1/warmup` was read on 26 September 2026** through the Vercel connector, which + carries the owner's access — `"schema":"0017"`; see the opening. What follows was true + until then. The deployments are behind Vercel's Deployment Protection and answer a redirect to a login page, so no `curl` from here can settle whether the schema — `0017` once #140 has deployed — and the code that needs it met. It needs the owner's browser or a bypass @@ -3388,21 +3599,25 @@ title cannot. goes. The last is the one that deletes data if you get it wrong: with one class, «Выйти» always meant "leave this one", and there used to be nothing to catch the day that row quietly started meaning "all of them". - Still seen by nobody: the switch with your eyes, the widget's redraw after it, and the - re-planning of the alarms — those are inferred from code that is called rather than - observed. + #186 held two on an emulator (#116): the switch was seen, and the widget's redraw after a + second switch inside one Glance session was found broken and fixed (#168). Still seen by + nobody: the re-planning of the alarms, which is inferred from code that is called rather + than observed. - **Nobody has switched the join mode on a live class** — but the switch is now pressed in tests: the confirmation appears only in the direction that takes something away, «Отмена» writes nothing, and restoring the class code writes straight away. It is covered lower down the stack too: the class code's refusal in `invite`, a personal code for one phone, a race between two requests for one code, a stale button, the sweeping, a `PATCH` in both directions, the log line, and that the column holds `OPEN` rather than `open`. **Not one - test presses the button.** Nobody has seen «📱 Подключить телефон» in a live bot, nor the - confirmation in the app, nor a screen with a code that has stopped working. -- **Nobody has ever seen the `429` on the code screen** — neither in its new form nor its - old. The limiter fires after thirty failures in fifteen minutes, and nobody in this - environment has got that far. -- **The upgrade path is verified by keys rather than by an installation.** An old install + test presses the button.** #186 saw «📱 Подключить телефон» in the live bot, its code link + a phone as «Владелец», the spent code answer `404`, and the invite-only class's own code + refused in words; nobody has flipped the switch on a live class or seen the confirmation + in the app. +- **The `429` on the code screen was seen once, on an emulator (#186):** «Слишком много + попыток. Попробуйте через 15 минут.», with `Retry-After: 866`. +- **The upgrade path has been installed over once, on an emulator (#117)**: a build of + `fa4fe0c` upgraded to `bd7c816` kept its class, its tab order and its first run done. What + follows is what held it before. An old install kept its class in four flat keys; a test builds exactly those keys and makes sure the class is found and the "introduction shown" flag is not reset. Nobody has upgraded a real installation of the previous version. If that is broken, the user sees the code field @@ -4090,10 +4305,29 @@ has a Cyrillic identifier: Kotlin has none at all. All of this is beyond an agent's reach: it needs a phone, a key or a live service. **These are issues now**, so that they can be closed rather than re-read: #118 the Preview -environment, #119 `/api/v1/warmup` and the bot's `/start`, #120 the external cron and -`DADATA_TOKEN`, #121 the real diary, #122 the widget's tick cadence and the diary -credential's bound, #135 the second diary, #144 a default server for a fresh install. Each -carries the label `needs:owner`; #156 carries `needs:device`. +environment, #120 the external cron and `DADATA_TOKEN`, #121 the real diary, #122 the +widget's tick cadence and the diary credential's bound, #135 the second diary, #144 a default +server for a fresh install. Each carries the label `needs:owner`. #119 (`/api/v1/warmup` and +`/start`) and #156 (the backup) were answered by #186 and close with it. + +**Give the release keystore its passwords, on your machine and nowhere else.** The keystore +handed over during #186 is PKCS12 and came without them, so nothing was signed +with it. A local release build reads `lessons.keystore.file`, `lessons.keystore.password`, +`lessons.key.alias` and `lessons.key.password` from `~/.gradle/gradle.properties` (or the +`LESSONS_KEYSTORE_*` and `LESSONS_KEY_*` variables); `docs/build.md` has the shape. Not in a +chat, not in the repository. And before that key replaces the one CI signs with: an APK +signed by a different key does not install over the one already on a phone — #117 showed the +refusal on the emulator. + +**Free some space on C:.** It had about 1.3 GB left on 27 September; the emulator refused to +start once below 2 GB, and the AVD's Quick Boot image alone is 8.5 GB. The worktrees under +`.claude/worktrees/` each carry their own Gradle build directories. + +**Restart Android Studio once, when it is free.** Three changes wait for it, because the IDE +rewrites those files on exit: `server/.venv` as the Python SDK, the root module as a Python +one (which quiets «Unsupported Modules Detected»), and the third-party «Python Portable» +plugin disabled, since it fails to load on every start. Everything else in the IDE's set-up +is already in place (see «What the last session added»). **The tenth milestone exists, and #140 is on it.** The owner created `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` on 25 September and renamed @@ -4110,9 +4344,8 @@ diary at all. It is #121's first live session, for both diaries at once. **Then walk the rest of the first run on that phone.** The class code as the other way in; leaving the last class with a diary signed in, which should land on the diary as the home -with «Выйти из дневника» still in settings (#151's path); the two legal links online and in -airplane mode; a ТОР region's hand-off to the official site. And read a backup with `bmgr` -for the crash reports — #156 closes only on that. +with «Выйти из дневника» still in settings (#151's path). The legal links, the ТОР hand-off +and the backup were seen on an emulator in #186; a phone adds the thumb, not the answer. **Decide #144: whether a fresh install gets a default server.** The diary path needs our server to register the session, and today a fresh install asks for its address where it is @@ -4154,7 +4387,10 @@ owner's.** `docs/diaries.md` is the map: Whichever platform comes next, the first step is one real session against it, as #121 is for Петербург. Not one route in `docs/diaries/` has been seen answering. -**Install one built after #85 and long-press a tab on the home screen.** The APK on #84's +**Install one built after #186 and long-press a tab on the home screen.** Since #181 the +long press picks the tab up in the same touch, and a tap anywhere closes the mode (#182). +#186 saw the gesture work on an emulator, but not by a hand — and the emulator was shared +with the owner at the time, so the drop was never watched undisturbed. The APK on #84's merge cannot rearrange anything — the drag reported the order unchanged — so it is the wrong build to judge the feature by. #84 and #85 together are the whole of a gesture and nothing in a session here could see any of it: whether the wobble reads as «иконки на diff --git a/README.md b/README.md index 12ac588b..ecd72bea 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ Read this before planning a release. | `ruff check app tests scripts migrations` | clean | | `python -m mypy` | clean, 100 modules — asks whether anything reaches for an attribute that does not exist | | `pytest -q -n auto` | 2024 tests, green, about four minutes — the command CI runs | -| `./gradlew test` | 1408 tests, green, all five modules | +| `./gradlew test` | 1438 tests, green, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | @@ -219,8 +219,22 @@ The server was checked live: brought up under uvicorn, answering `join` and `bun handing back substitutions, events, homework and `next_school_day`. The state engine was walked through all 1440 minutes of a school day and through all eleven Russian time zones. -**What nothing checks.** There is no `androidTest` directory in this project: not one test -has run on a device or an emulator. About two dozen of the app's screens, sheets and rows — +**What one walkthrough on an emulator saw.** On 26 September 2026 the app was walked by +hand on an API 37 emulator (Pixel 10 Pro XL image), against a local server and against +production, with the live bot beside it: the first run in both languages, both ways in as +far as the diary's password form, a wrong code, the `429`, the calendar's four views and the +year picker, rearranging the tabs, the correction mode, two classes and the switch between +them, the join modes and a personal code taken from the bot, the widget on the Pixel +launcher at four sizes and two font scales, an upgrade from the build before #140, a +refusal between two signing keys, and a real backup and restore through `bmgr`. It found +twelve defects (#167–#178), and the fixes were checked on the same emulator. The owner's six +requests of that night about the tab bar and the pickers (#179–#184) are held by JVM tests; +on the emulator, which the owner was using at the same time, only the one-touch pickup and +the pill's round end were seen. What it could not give is written in `HANDOVER.md`: a thumb, +haptics, a real GPU, Doze on a school morning, TalkBack, a real diary account. + +**What nothing checks automatically.** There is no `androidTest` directory in this project: +not one test runs on a device or an emulator. About two dozen of the app's screens, sheets and rows — the class list, the join mode, the connection errors, the first-run reveal and the terms line under its button, the diary home, the crash-report sheet, the calendar's header, its two sheets, its year picker and its day list, and the rest — are @@ -230,21 +244,23 @@ are exercised the same way. Nobody has pressed the rest of the interface or the widget: compilation proves that the types line up and says nothing about what happens on the screen. Covered by nothing: -* the widget drawn at each of its twelve sizes; +* the widget drawn at each of its twelve sizes — the walkthrough saw four launcher sizes, + not twelve rungs; * the accuracy of the `TickCadence` alarms in real Doze; -* the layout of the other screens, the dark theme, dynamic colours; -* the behaviour when the network drops and on the first sync; -* runtime crashes the compiler cannot see. +* the dark theme and dynamic colours beyond a glance, and the screens nobody opened; +* runtime crashes the compiler cannot see, beyond the ones a walkthrough happens to hit. Material 3 Expressive and Glance 1.3.0-alpha02 are alphas. They compile, but nobody has measured how they behave across Android versions. The electronic diary has never once been opened against a real server. Not Petersburg's dnevnik2.petersburgedu.ru — neither the sign-in page nor any screen of the app's diary — and -not «Сетевой город. Образование», the second provider, which **has never met a live regional -server**: its password sign-in (on the server and on the phone), its -keep-alive, its region allow-list and its weekly-diary mapping are read from open-source -clients and exercised on hand-written payloads, exactly as Petersburg's were. The tests run a hand-written stub in +not «Сетевой город. Образование», the second provider, whose **only contact with a live +regional server** is the phone's school search: on 26 September 2026 the emulator asked +Амурская область's server over TLS and got its real list of schools back. Its password +sign-in (on the server and on the phone), its keep-alive, its region allow-list and its +weekly-diary mapping are read from open-source clients and exercised on hand-written +payloads, exactly as Petersburg's were. The tests run a hand-written stub in place of each: that is the only honest way to check an integration with an undocumented service, but it says nothing about what that service actually answers. No browser has ever opened the sign-in page for either, and the first live session, for both, is the owner's @@ -266,8 +282,10 @@ nothing more.** The app now signs in to the diary itself and registers the sessi what it reads in a second database; imports two weeks of it and the term's marks at the first run, with a progress bar; and gives a phone with a diary and no class a home of its own, with the class sync disarmed there (#151, #152). All of it is held by pure rules, view models and -MockWebServer: not one step has run on a device, against a live diary or against a deployed -server. Nothing composes the shell in a test, so the gate, the hold through a join or a +MockWebServer. On an emulator the steps were walked as far as the password form — region, +school, the Госуслуги and «Моя школа» hand-offs to the browser — and no further: no password +was typed, so nothing has run against a live diary's sign-in or registered a session with a +deployed server. Nothing composes the shell in a test, so the gate, the hold through a join or a registration, the swap to the right home and the resume after a process death are proved by their rules alone. TLS to the regional servers, Room's `diary.db` on a device, the browser hand-offs to Госуслуги and to a diary's site, TalkBack on the new steps and the English text @@ -277,11 +295,13 @@ alerts (#142). **The terms and the privacy policy describe the code and have never been read by a lawyer.** The line under the first button opens them in the browser or, offline, from the copy in the -APK; that the default address resolves was checked on 25 September 2026 by fetching it, and no -link has been tapped on a phone. Phones that finished the first run before this build never -see the line — the documents stay reachable from «О приложении» — and the bot shows no link -to either. That crash reports are kept out of a phone's backup is in the backup rules and -their test only; it needs a phone to confirm (#156). +APK; on an emulator the link opened the English terms on GitHub online and the bundled +«Privacy policy, Edition 1 of September 25, 2026» sheet in airplane mode. Phones that +finished the first run before this build never see the line — the documents stay reachable +from «О приложении» — and the bot shows no link to either. That crash reports are kept out +of a phone's backup was confirmed on an emulator through `bmgr` and the local transport, +for the cloud rules and for a device transfer: a real crash report did not come back and a +file beside it did (#156). **Week parity was computed from the ISO week number, and that broke once every five or six years.** In an ISO year with 53 weeks, week 53 and week 1 stand next to each other and are diff --git a/docs/architecture.md b/docs/architecture.md index ba12cbb4..079a3810 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -168,6 +168,14 @@ scrolled into next September at all: while the cache held exactly one window and a sync wiped the class, arriving in another year would have destroyed the one being left. +The class row is the one thing every year shares, and it carries the terms. A +bundle brings the terms of the year it was asked for, so `replaceWindow` keeps +every stored term outside the window and takes the window's own from the bundle, +inside the transaction that writes the row. Written as they came, a look at last +year replaced this year's quarters, the next refresh of this year answered `304` +and wrote nothing, and the calendar's header lost «1 четверть» until the year's +data changed on the server (#169, found on an emulator). + `synced_window` is a table rather than something counted off the days present, because **a year fetched and genuinely empty has to be tellable from one never fetched**. A class made in March has no rows before it either way; counting @@ -715,9 +723,9 @@ with the host. ## Testing -2024 tests on the server, 1408 on Android; `pytest -q -n auto` and `./gradlew test`, both -offline, both in CI. On Android that is `:core:model` 125, `:core:data` 532, -`:core:designsystem` 99, `:widget` 104, `:app` 548. +2024 tests on the server, 1438 on Android; `pytest -q -n auto` and `./gradlew test`, both +offline, both in CI. On Android that is `:core:model` 125, `:core:data` 537, +`:core:designsystem` 112, `:widget` 113, `:app` 551. The table below is the load-bearing part of that rather than the whole of it: