Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 113 additions & 32 deletions HANDOVER.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | 1446 tests, green, all five modules |
| `./gradlew test` | 1459 tests, green, all five modules |
| `./gradlew assembleDebug` | the APK builds |
| `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass |
| `./gradlew :core:designsystem:connectedDebugAndroidTest` | 3 tests, green on an API 37 emulator — on demand only, never in CI, which has no device |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import com.lumenpearson.lessons.core.data.repository.DiarySessionStore
import com.lumenpearson.lessons.core.data.repository.DiaryTarget
import com.lumenpearson.lessons.core.data.repository.DiaryTargetCodec
import com.lumenpearson.lessons.core.data.repository.Session
import com.lumenpearson.lessons.core.data.repository.SettingsStore
import com.lumenpearson.lessons.core.data.repository.ShellMode
import com.lumenpearson.lessons.core.data.repository.ShellModeSource
import com.lumenpearson.lessons.core.data.repository.ShellState
Expand Down Expand Up @@ -70,7 +71,7 @@ private val Context.lessonsDataStore: DataStore<Preferences> by preferencesDataS
* screens, they are both tiny, and a single file means a single fsync and a
* single flow to observe.
*/
internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellModeSource {
internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellModeSource, SettingsStore {

private val dataStore = context.applicationContext.lessonsDataStore

Expand All @@ -89,13 +90,13 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo
/** Every class this device has joined, in the order they were joined. */
val sessions: Flow<List<Session>> = preferences.map { it.memberships() }.distinctUntilChanged()

val settings: Flow<AppSettings> = preferences.map { it.toSettings() }.distinctUntilChanged()
override val settings: Flow<AppSettings> = preferences.map { it.toSettings() }.distinctUntilChanged()

suspend fun currentSession(): Session? = preferences.first().activeMembership()

suspend fun currentSessions(): List<Session> = preferences.first().memberships()

suspend fun currentSettings(): AppSettings = preferences.first().toSettings()
override suspend fun currentSettings(): AppSettings = preferences.first().toSettings()

/**
* Stores a membership and makes it the one being shown.
Expand Down Expand Up @@ -266,7 +267,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo
}

/** Read-modify-write inside DataStore's transaction, so concurrent edits merge. */
suspend fun updateSettings(transform: (AppSettings) -> AppSettings) {
override suspend fun updateSettings(transform: (AppSettings) -> AppSettings) {
dataStore.edit { prefs ->
val updated = transform(prefs.toSettings())
prefs[KEY_BASE_URL] = updated.baseUrl.trim()
Expand Down Expand Up @@ -386,7 +387,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellMo
* few hundred bytes and DataStore serves every read after the first from
* memory, so this costs one disk read per process.
*/
fun languageBlocking(): AppLanguage = runBlocking { currentSettings().language }
override fun languageBlocking(): AppLanguage = runBlocking { currentSettings().language }

/**
* The shape of the cached schedule as of the previous sync.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,9 @@ class DefaultLessonsContainer(
// the one moment that also has to answer for what is already on
// the shade, and it is the only caller that may — see the KDoc.
onAlertsChanged = { SchoolAlerts.onAlertsChanged(appContext) },
// The same broadcast a sync that changed the data sends: the widget
// cannot be called from this module, and it already listens for it.
onWidgetSettingsChanged = { DataSyncBroadcast.send(appContext) },
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,29 @@ data class AppSettings(
}
}

/**
* The settings the home-screen widget draws, and nothing else.
*
* One value that both sides read. The widget takes its language and its options
* from here and from nowhere else in [AppSettings], and a settings change asks
* it to redraw when this, and only this, has moved (#188). A setting the widget
* starts to draw belongs here, or the widget will draw it and not be told when
* it changes.
*/
data class WidgetSettings(
val language: AppLanguage,
val showProgress: Boolean,
val showTeacher: Boolean,
)

/** @see WidgetSettings */
val AppSettings.drawnByWidget: WidgetSettings
get() = WidgetSettings(
language = language,
showProgress = widgetShowProgress,
showTeacher = showTeacher,
)

/**
* Outcome of a sync attempt.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,61 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

/**
* A thin pass-through to [LessonsPreferences], plus one side effect.
* Where the settings are kept: the part of [LessonsPreferences] this repository
* reads, so that a test can hand it a map instead of a DataStore file, which
* this module's JVM tests cannot open.
*/
internal interface SettingsStore {
val settings: Flow<AppSettings>

fun languageBlocking(): AppLanguage

suspend fun currentSettings(): AppSettings

suspend fun updateSettings(transform: (AppSettings) -> AppSettings)
}

/**
* A thin pass-through to [LessonsPreferences], plus two side effects.
*
* It exists anyway so that consumers depend on an interface in this package
* rather than on DataStore, which keeps the storage choice replaceable and keeps
* `Preferences` out of every ViewModel's imports.
*
* @param onAlertsChanged re-arms the notification alarm. It belongs here rather
* than in the settings screen because a preference has one owner: turning an
* alert on from anywhere — the first-run flow, the settings page, a future
* quick setting — has to arm the chain, and only this method sees all of them.
* It is called only when the alert block actually moved, so toggling the theme
* does not go near an `AlarmManager`.
* Both side effects belong here rather than in the settings screen because a
* preference has one owner: a change from anywhere — the first-run flow, the
* settings page, a future quick setting — comes through [update], and only this
* method sees all of them. Each is called only when its own part of the settings
* actually moved, so toggling the theme goes near neither.
*
* @param onAlertsChanged re-arms the notification alarm when the alert block
* moved.
* @param onWidgetSettingsChanged asks the widget to redraw when
* [AppSettings.drawnByWidget] moved. The widget redraws on a sync that changed
* the data and on its own tick, and a settings change is neither: switched to
* Russian, the widget went on drawing English until something else woke it,
* which on a day off is hours (#188).
*/
internal class SettingsRepositoryImpl(
private val preferences: LessonsPreferences,
private val preferences: SettingsStore,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val onAlertsChanged: () -> Unit = {},
private val onWidgetSettingsChanged: () -> Unit = {},
) : SettingsRepository {

override val settings: Flow<AppSettings> = preferences.settings

override fun languageBlocking(): AppLanguage = preferences.languageBlocking()

override suspend fun update(transform: (AppSettings) -> AppSettings) {
val before = preferences.currentSettings().alerts
val before = preferences.currentSettings()
preferences.updateSettings(transform)
val after = preferences.currentSettings().alerts
if (before != after) {
val after = preferences.currentSettings()
if (before.alerts != after.alerts) {
// Off the caller's thread: this is usually a view model scope on the
// main dispatcher, and rescheduling reads the cached timetable.
withContext(ioDispatcher) { onAlertsChanged() }
}
if (before.drawnByWidget != after.drawnByWidget) onWidgetSettingsChanged()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.lumenpearson.lessons.core.data.repository

import com.lumenpearson.lessons.core.model.AppLanguage
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test

/**
* A change to a setting the widget draws asks the widget to redraw (#188).
*
* Switched to Russian on the emulator, the app redrew at once and the widget
* went on drawing English: nothing but a sync that changed the data, or the
* widget's own tick, ever asked it to draw again, and on a day off the tick is
* hours away.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class WidgetSettingsRedrawTest {

private class MemoryStore : SettingsStore {
val current = MutableStateFlow(AppSettings())
override val settings: Flow<AppSettings> = current
override fun languageBlocking(): AppLanguage = current.value.language
override suspend fun currentSettings(): AppSettings = current.value
override suspend fun updateSettings(transform: (AppSettings) -> AppSettings) {
current.value = transform(current.value)
}
}

private var redraws = 0

private fun repository() = SettingsRepositoryImpl(
preferences = MemoryStore(),
ioDispatcher = UnconfinedTestDispatcher(),
onWidgetSettingsChanged = { redraws++ },
)

@Test
fun `every setting the widget draws asks it to redraw`() = runTest {
val repository = repository()

repository.update { it.copy(language = AppLanguage.RUSSIAN) }
repository.update { it.copy(widgetShowProgress = false) }
repository.update { it.copy(showTeacher = false) }

assertEquals(3, redraws)
}

@Test
fun `a setting the widget does not draw leaves it alone`() = runTest {
val repository = repository()

repository.update { it.copy(pitchBlack = true) }
repository.update { it.copy(hapticsEnabled = false) }
repository.update { it.copy(todayShowHero = false) }

assertEquals(0, redraws)
}

@Test
fun `writing the value it already has is not a change`() = runTest {
val repository = repository()

repository.update { it.copy(language = AppLanguage.SYSTEM) }

assertEquals(0, redraws)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import com.lumenpearson.lessons.core.data.di.Graph
import com.lumenpearson.lessons.core.data.locale.AppLocale
import com.lumenpearson.lessons.core.data.repository.ShellMode
import com.lumenpearson.lessons.core.data.repository.ShellModeSource
import com.lumenpearson.lessons.core.data.repository.drawnByWidget
import com.lumenpearson.lessons.core.model.AppLanguage
import com.lumenpearson.lessons.core.model.DayState
import com.lumenpearson.lessons.core.model.DeepLink
Expand Down Expand Up @@ -239,7 +240,10 @@ class LessonsWidget : GlanceAppWidget() {
val (mode, timetable) = readModeAndTimetable(container.shellMode) {
container.timetableRepository.snapshotAroundToday()
}
val settings = container.settingsRepository.settings.first()
// Through `drawnByWidget` and nothing wider: it is also what decides
// whether a settings change asks this widget to redraw (#188), so a
// setting read here from anywhere else would be drawn and never updated.
val settings = container.settingsRepository.settings.first().drawnByWidget

// The school's wall clock, not the phone's. These differ whenever the
// device has travelled, and permanently for anyone following a school
Expand All @@ -252,7 +256,7 @@ class LessonsWidget : GlanceAppWidget() {
now = now,
mode = mode,
options = WidgetOptions(
showProgress = settings.widgetShowProgress,
showProgress = settings.showProgress,
showTeacher = settings.showTeacher,
// Only one trailing detail fits a phone-width row, and the room
// outranks the teacher — so with both on, the teacher never
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,19 @@ enum class WidgetSizeClass(
* It used to match [SMALL] and leave a third of itself empty. The height
* buys the two lines a pupil asks for next: what comes after this, and
* whether anything is set for the next school day.
*
* Three homework rows, not [SMALL]'s two. The list is drawn only after
* school, under the state, the plan and the header, and in 190 dp that
* comes to about 130 with three one-line rows — 175 at the worst, with a
* note on the day off and the plan and the header each on two lines. With
* two, a 2×2 on a phone, which is this rung, drew two of three subjects over
* an empty lower half (#174). [NARROW], the only rung above this one at the
* same width, has three as well.
*/
SMALL_TALL(
breakpoint = DpSize(110.dp, 190.dp),
timelineRows = 0,
homeworkItems = 2,
homeworkItems = 3,
homeworkChars = 24,
showsSubject = true,
showsMeta = true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,22 @@ internal object WidgetStrings {
context.resources.getQuantityString(R.plurals.widget_subject_count, count, count)
}

/**
* The same count without its noun: «3», or «нет» when nothing is set.
*
* For the one-line size at an enlarged font, where the count and the label
* share one line and the label is the half that gives way — at the largest
* font «ДЗ на завтра · 3 предмета» came out as «Д… 3 предмета» (#174). Read
* after «ДЗ на завтра» the figure needs no noun, and «ДЗ на завтра нет» is a
* whole Russian sentence, so the day survives and the answer does too.
*/
fun subjectFigure(context: Context, count: Int): String =
if (count == 0) {
context.resources.getString(R.string.widget_homework_none_short)
} else {
count.toString()
}

/**
* The word beside the ticking figure.
*
Expand Down Expand Up @@ -328,15 +344,46 @@ internal object WidgetStrings {
fun lessonCount(context: Context, count: Int): String =
context.resources.getQuantityString(R.plurals.widget_lesson_count, count, count)

/** "6 уроков · Алгебра в 09:00". */
fun dayPlan(context: Context, lessons: Int, firstSubject: String, firstAt: LocalTime): String =
context.getString(
/**
* "6 уроков · Алгебра в 09:00", in at most [maxChars] characters.
*
* When it does not fit, the subject is what gives way. The count and the
* time are the facts the line exists for, and the subject is the one part of
* it that still reads shortened. Cut from the end as a whole, the line spent
* its budget on the subject and lost the time: a 2×2 on a phone, on the rung
* whose budget is 24, read «4 урока · Алгебра в 08:…» (#174).
*
* The subject keeps at least [MIN_PLAN_SUBJECT_CHARS] characters with its
* «…». A budget too small even for that is overrun rather than met by
* cutting the time, which is why the narrow rungs give this line two lines.
*/
fun dayPlan(
context: Context,
lessons: Int,
firstSubject: String,
firstAt: LocalTime,
maxChars: Int = Int.MAX_VALUE,
): String {
// Through `resources`, as `subjectCount` is: `Context.getString` is
// final, and in this module's unit tests a final framework method
// answers null instead of reaching a stub's resources.
fun line(subject: String) = context.resources.getString(
R.string.widget_next_day_summary,
lessonCount(context, lessons),
firstSubject,
subject,
time(firstAt),
)

val subject = firstSubject.collapseWhitespace()
val whole = line(subject)
if (whole.length <= maxChars) return whole
val room = subject.length - (whole.length - maxChars)
return line(subject.ellipsize(room.coerceAtLeast(MIN_PLAN_SUBJECT_CHARS)))
}

/** «Алг…»: three letters and the «…», the shortest a subject still reads as one. */
const val MIN_PLAN_SUBJECT_CHARS = 4

/** "каб. 214", or null when the timetable has no room for this lesson. */
fun room(context: Context, lesson: Lesson): String? =
lesson.room?.takeIf { it.isNotBlank() }?.let { context.getString(R.string.widget_room, it) }
Expand Down
Loading
Loading