39 changed files with 894 additions and 204 deletions

No files matched your search

+2 -1
View File
@@ -213,11 +213,12 @@ dependencies {
implementation("de.jeanlucmakiola.floret:core-locale")
implementation("de.jeanlucmakiola.floret:core-crash")
implementation("de.jeanlucmakiola.floret:core-prefs")
implementation("de.jeanlucmakiola.floret:core-backup")
implementation("de.jeanlucmakiola.floret:core-android")
implementation("de.jeanlucmakiola.floret:core-di")
implementation("de.jeanlucmakiola.floret:identity")
implementation("de.jeanlucmakiola.floret:components")
implementation("de.jeanlucmakiola.floret:glance")
implementation("de.jeanlucmakiola.floret:ring")
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
@@ -7,7 +7,6 @@ import android.os.Build
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.clockula.alarm.AlarmCapabilities
import de.jeanlucmakiola.clockula.domain.alarm.CapabilitySnapshot
import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent
import javax.inject.Inject
import javax.inject.Singleton
@@ -24,7 +23,7 @@ class AndroidAlarmCapabilities @Inject constructor(
override fun snapshot(): CapabilitySnapshot = CapabilitySnapshot(
canScheduleExactAlarms = canScheduleExactAlarms(),
canUseFullScreenIntent = context.canUseFullScreenIntent(),
canUseFullScreenIntent = canUseFullScreenIntent(),
notificationsEnabled = notifications().areNotificationsEnabled(),
)
@@ -35,6 +34,13 @@ class AndroidAlarmCapabilities @Inject constructor(
true
}
private fun canUseFullScreenIntent(): Boolean =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
notifications().canUseFullScreenIntent()
} else {
true
}
private fun notifications(): NotificationManager =
context.getSystemService(NotificationManager::class.java)
}
@@ -5,8 +5,8 @@ import android.content.Intent
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.clockula.alarm.AlarmEngine
import de.jeanlucmakiola.clockula.alarm.AlarmIntents
import de.jeanlucmakiola.clockula.ring.HandoffWakeLock
import de.jeanlucmakiola.floret.di.ApplicationScope
import de.jeanlucmakiola.floret.ring.RingWakeLock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.time.Instant
@@ -34,7 +34,7 @@ class AlarmFireReceiver : HiltBroadcastReceiver() {
val alarmId = intent.getLongExtra(AlarmIntents.EXTRA_ALARM_ID, 0L)
val action = intent.action ?: return
if (action == AlarmIntents.ACTION_FIRE) RingWakeLock.handOff(context, "clockula:alarm-fire")
if (action == AlarmIntents.ACTION_FIRE) HandoffWakeLock.acquire(context, "clockula:alarm-fire")
val pendingResult = goAsync()
scope.launch {
try {
@@ -6,7 +6,10 @@ import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.clockula.alarm.AlarmCapabilities
import de.jeanlucmakiola.clockula.alarm.AlarmEngine
@@ -18,10 +21,8 @@ import de.jeanlucmakiola.clockula.domain.ring.RingFallbackPolicy
import de.jeanlucmakiola.clockula.domain.ring.SilenceAfter
import de.jeanlucmakiola.clockula.ring.ForegroundRingScreen
import de.jeanlucmakiola.clockula.ring.RingAudioPlayer
import de.jeanlucmakiola.clockula.ring.RingVibrator
import de.jeanlucmakiola.clockula.ui.ring.AlarmRingActivity
import de.jeanlucmakiola.floret.ring.RingVibrator
import de.jeanlucmakiola.floret.ring.RingWakeLock
import de.jeanlucmakiola.floret.ring.startRingForeground
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -57,7 +58,7 @@ class AlarmRingService : Service() {
private val audio by lazy { RingAudioPlayer(this) }
private val vibrator by lazy { RingVibrator(this) }
private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, WAKE_LOCK_TIMEOUT_MILLIS) }
private var wakeLock: PowerManager.WakeLock? = null
private var ringing: Job? = null
/** The alarm this service last asked a ring screen for. */
@@ -93,7 +94,7 @@ class AlarmRingService : Service() {
// database read is not something to spend them on.
startForegroundPreparing()
// Also before the read: the fire broadcast's own wake lock is gone by now.
wakeLock.acquire()
acquireWakeLock()
ringing = scope.launch {
val session = engine.ringSession()
if (session == null) {
@@ -183,7 +184,26 @@ class AlarmRingService : Service() {
private fun startForeground(notification: Notification) {
posted = notification
startRingForeground(RingNotifications.RING_NOTIFICATION_ID, notification)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
// systemExempted: Android's own guidance names an app holding an
// exact-alarm permission and continuing an alarm in the background.
startForeground(
RingNotifications.RING_NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED,
)
} else {
startForeground(RingNotifications.RING_NOTIFICATION_ID, notification)
}
}
private fun acquireWakeLock() {
if (wakeLock != null) return
val power = getSystemService(PowerManager::class.java)
wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG).apply {
setReferenceCounted(false)
runCatching { acquire(WAKE_LOCK_TIMEOUT_MILLIS) }
}
}
private fun releaseRing() {
@@ -191,7 +211,8 @@ class AlarmRingService : Service() {
ringing = null
audio.stop()
vibrator.stop()
wakeLock.release()
wakeLock?.let { if (it.isHeld) runCatching { it.release() } }
wakeLock = null
}
private fun stop() {
@@ -1,8 +1,14 @@
package de.jeanlucmakiola.clockula.backup
import de.jeanlucmakiola.clockula.data.backup.BACKUP_MAX_BYTES
/** The fixed filename a backup is written to inside the user-chosen folder (`docs/PLAN.md` §7). */
const val BACKUP_FILE_NAME: String = "clockula-backup-v1.json"
/** A backup to read or write is over [BACKUP_MAX_BYTES]. */
class BackupTooLargeException(cause: Throwable? = null) :
java.io.IOException("backup exceeds $BACKUP_MAX_BYTES bytes", cause)
/**
* The on-device side of export/import: writing/reading the JSON text through
* SAF. [BackupEngine] does not know this is SAF — it only knows these two
@@ -12,6 +18,6 @@ interface BackupFiles {
/** Writes [content] as [BACKUP_FILE_NAME] inside the folder [treeUri] names, overwriting any existing one. */
suspend fun write(treeUri: String, content: String): Result<Unit>
/** Reads whatever text is at [documentUri]. */
/** Reads whatever text is at [documentUri]; fails with [BackupTooLargeException] past the size limit. */
suspend fun read(documentUri: String): Result<String>
}
@@ -6,10 +6,14 @@ import androidx.documentfile.provider.DocumentFile
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.clockula.backup.BACKUP_FILE_NAME
import de.jeanlucmakiola.clockula.backup.BackupFiles
import de.jeanlucmakiola.clockula.backup.BackupTooLargeException
import de.jeanlucmakiola.clockula.data.backup.BACKUP_MAX_BYTES
import de.jeanlucmakiola.floret.android.DocumentTooLargeException
import de.jeanlucmakiola.floret.android.readDocumentBytes
import de.jeanlucmakiola.floret.android.writeDocumentBytes
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.UUID
import javax.inject.Inject
@@ -30,16 +34,15 @@ class SafBackupFiles @Inject constructor(
override suspend fun write(treeUri: String, content: String): Result<Unit> = withContext(io) {
runCatching {
val bytes = content.toByteArray(Charsets.UTF_8)
if (bytes.size > MAX_BACKUP_BYTES) throw IOException("backup exceeds the 8 MiB limit")
if (bytes.size > BACKUP_MAX_BYTES) throw BackupTooLargeException()
val tree = DocumentFile.fromTreeUri(context, treeUri.toUri())
?: error("could not open the chosen folder")
val temporary = tree.createFile("application/json", "$BACKUP_FILE_NAME.${UUID.randomUUID()}.tmp")
?: throw IOException("could not create a temporary backup")
var keepTemporary = false
try {
val stream = context.contentResolver.openOutputStream(temporary.uri)
?: throw IOException("could not open an output stream for ${temporary.uri}")
stream.use { it.write(bytes) }
// Just created and empty: plain "w", as before, works on every provider.
context.contentResolver.writeDocumentBytes(temporary.uri, bytes, truncate = false)
val existing = tree.findFile(BACKUP_FILE_NAME)
if (existing != null && !existing.delete()) throw IOException("could not remove the previous backup")
// Some SAF providers cannot rename. Once the old file has been
@@ -57,25 +60,12 @@ class SafBackupFiles @Inject constructor(
override suspend fun read(documentUri: String): Result<String> = withContext(io) {
runCatching {
val stream = context.contentResolver.openInputStream(documentUri.toUri())
?: throw IOException("could not open an input stream for $documentUri")
stream.use { input ->
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
var total = 0
while (true) {
val count = input.read(buffer)
if (count < 0) break
total += count
if (total > MAX_BACKUP_BYTES) throw IOException("backup exceeds the 8 MiB limit")
output.write(buffer, 0, count)
}
output.toString(Charsets.UTF_8.name())
val bytes = try {
context.contentResolver.readDocumentBytes(documentUri.toUri(), BACKUP_MAX_BYTES)
} catch (e: DocumentTooLargeException) {
throw BackupTooLargeException(e)
}
bytes.toString(Charsets.UTF_8)
}
}
private companion object {
const val MAX_BACKUP_BYTES = 8 * 1024 * 1024
}
}
@@ -22,6 +22,11 @@ import de.jeanlucmakiola.clockula.domain.screensaver.ScreenSaverSettings
import de.jeanlucmakiola.clockula.domain.screensaver.ScreenSaverStyle
import de.jeanlucmakiola.clockula.domain.timer.TimerPresets
import de.jeanlucmakiola.clockula.domain.widget.parseQuickTimerDuration
import de.jeanlucmakiola.floret.backup.BackupFormat
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.backup.invalidBackup
import de.jeanlucmakiola.floret.backup.readBackup
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.floret.prefs.toEnum
import kotlinx.serialization.SerializationException
@@ -31,23 +36,6 @@ import java.time.format.DateTimeParseException
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Instant
/**
* Why a restore failed, in words a user can act on. The codec's own four, plus
* the two the caller meets around it: the file would not open, or the import
* itself failed after the file was valid.
*/
enum class BackupProblem { NOT_A_BACKUP, NEWER_VERSION, INVALID_DATA, TOO_LARGE, UNREADABLE, NOT_APPLIED }
/**
* The result of [BackupCodec.decode]: either a validated [BackupContent], or
* why not — [problem] for the user, [reason] the specific detail, in English,
* for tests and logs.
*/
sealed interface BackupResult {
data class Success(val content: BackupContent) : BackupResult
data class Failure(val problem: BackupProblem, val reason: String) : BackupResult
}
/**
* The JSON wire format ↔ [BackupContent]. Pure Kotlin — no Android import —
* so the round trip and every rejection path are JVM-unit-testable.
@@ -57,7 +45,17 @@ sealed interface BackupResult {
*/
object BackupCodec {
private const val MAX_DOCUMENT_CHARS = 8 * 1024 * 1024
/**
* floret's envelope rules (format name, version range, size, byte-order
* mark). The file is still stream-decoded into [BackupFile] in one pass,
* which skips unknown content without holding it.
*/
private val envelope = BackupFormat(
name = BACKUP_FORMAT,
version = BACKUP_VERSION,
minVersion = BACKUP_MIN_VERSION,
maxChars = BACKUP_MAX_BYTES,
)
private const val MAX_ALARMS = 10_000
private const val MAX_TIMERS = 10_000
private const val MAX_WORLD_CLOCKS = 1_000
@@ -70,25 +68,27 @@ object BackupCodec {
}
fun encode(content: BackupContent): String =
json.encodeToString(BackupDocument.serializer(), content.toDocument())
json.encodeToString(BackupFile.serializer(), content.toFile())
fun decode(text: String): BackupResult {
if (text.length > MAX_DOCUMENT_CHARS) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "backup exceeds the 8 MiB limit")
fun decode(input: String): BackupResult<BackupContent> {
val text = when (val prepared = envelope.prepare(input)) {
is BackupResult.Failure -> return prepared
is BackupResult.Success -> prepared.value
}
val document = try {
json.decodeFromString(BackupDocument.serializer(), text)
val file = try {
json.decodeFromString(BackupFile.serializer(), text)
} catch (e: SerializationException) {
return BackupResult.Failure(BackupProblem.NOT_A_BACKUP, "not a valid backup file: ${e.message}")
} catch (e: IllegalArgumentException) {
return BackupResult.Failure(BackupProblem.NOT_A_BACKUP, "not a valid backup file: ${e.message}")
}
return document.toContent()
envelope.checkEnvelope(file.format, file.version)?.let { return it }
return readBackup { file.toContent() }
}
// --- encode ---
private fun BackupContent.toDocument(): BackupDocument = BackupDocument(
private fun BackupContent.toFile(): BackupFile = BackupFile(
format = BACKUP_FORMAT,
version = BACKUP_VERSION,
exportedAtMillis = exportedAt.toEpochMilliseconds(),
@@ -195,38 +195,25 @@ object BackupCodec {
// --- decode + validate ---
private fun BackupDocument.toContent(): BackupResult {
if (format != BACKUP_FORMAT) {
return BackupResult.Failure(BackupProblem.NOT_A_BACKUP, "unknown format: '$format'")
}
if (version !in BACKUP_MIN_VERSION..BACKUP_VERSION) {
val problem = if (version > BACKUP_VERSION) BackupProblem.NEWER_VERSION else BackupProblem.INVALID_DATA
return BackupResult.Failure(problem, "unsupported backup version: $version")
}
private fun tooLarge(reason: String): Nothing = invalidBackup(reason, BackupProblem.TOO_LARGE)
/** Strict about known fields: [invalidBackup] rejects the whole file. */
private fun BackupFile.toContent(): BackupContent {
if (alarms.size > MAX_ALARMS || timers.size > MAX_TIMERS || worldClocks.size > MAX_WORLD_CLOCKS) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "backup contains too many records")
tooLarge("backup contains too many records")
}
val alarms = mutableListOf<BackupAlarm>()
for ((index, dto) in this.alarms.withIndex()) {
if (dto.hour !in 0..23 || dto.minute !in 0..59) {
return BackupResult.Failure(
BackupProblem.INVALID_DATA,
"alarms[$index]: hour/minute out of range (${dto.hour}:${dto.minute})",
)
invalidBackup("alarms[$index]: hour/minute out of range (${dto.hour}:${dto.minute})")
}
if (dto.label.length > MAX_LABEL_CHARS || (dto.ringtoneUri?.length ?: 0) > MAX_URI_CHARS) {
return BackupResult.Failure(
BackupProblem.TOO_LARGE,
"alarms[$index]: label or ringtone URI is too long",
)
tooLarge("alarms[$index]: label or ringtone URI is too long")
}
val repeatDays = RepeatDays.fromMask(dto.repeatDays)
val dates = dto.dates(repeatDays.isRepeating)
?: return BackupResult.Failure(
BackupProblem.INVALID_DATA,
"alarms[$index]: scheduled_date or pause is not a valid date range",
)
?: invalidBackup("alarms[$index]: scheduled_date or pause is not a valid date range")
alarms += BackupAlarm(
time = TimeOfDay(dto.hour, dto.minute),
label = dto.label,
@@ -250,13 +237,10 @@ object BackupCodec {
val timers = mutableListOf<BackupTimer>()
for ((index, dto) in this.timers.withIndex()) {
if (dto.durationMillis < 0) {
return BackupResult.Failure(BackupProblem.INVALID_DATA, "timers[$index]: negative duration")
invalidBackup("timers[$index]: negative duration")
}
if (dto.label.length > MAX_LABEL_CHARS || (dto.ringtoneUri?.length ?: 0) > MAX_URI_CHARS) {
return BackupResult.Failure(
BackupProblem.TOO_LARGE,
"timers[$index]: label or ringtone URI is too long",
)
tooLarge("timers[$index]: label or ringtone URI is too long")
}
timers += BackupTimer(
label = dto.label,
@@ -270,13 +254,10 @@ object BackupCodec {
val worldClocks = mutableListOf<BackupWorldClock>()
for ((index, dto) in this.worldClocks.withIndex()) {
if (!Zones.isValid(dto.zoneId)) {
return BackupResult.Failure(
BackupProblem.INVALID_DATA,
"worldClocks[$index]: not an IANA zone id: '${dto.zoneId}'",
)
invalidBackup("worldClocks[$index]: not an IANA zone id: '${dto.zoneId}'")
}
if ((dto.label?.length ?: 0) > MAX_LABEL_CHARS) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "worldClocks[$index]: label is too long")
tooLarge("worldClocks[$index]: label is too long")
}
worldClocks += BackupWorldClock(
zoneId = dto.zoneId,
@@ -290,7 +271,7 @@ object BackupCodec {
(settingsDto.timerRingtoneUri?.length ?: 0) > MAX_URI_CHARS ||
(settingsDto.timerPresets?.size ?: 0) > 1_000
) {
return BackupResult.Failure(BackupProblem.TOO_LARGE, "settings contain oversized values")
tooLarge("settings contain oversized values")
}
val settingsContent = BackupSettings(
themeMode = settingsDto.themeMode.toEnum(ThemeMode.SYSTEM),
@@ -324,14 +305,12 @@ object BackupCodec {
bedtime = settingsDto.bedtime?.toBedtime(),
)
return BackupResult.Success(
BackupContent(
exportedAt = Instant.fromEpochMilliseconds(exportedAtMillis),
alarms = alarms,
timers = timers,
worldClocks = worldClocks,
settings = settingsContent,
),
return BackupContent(
exportedAt = Instant.fromEpochMilliseconds(exportedAtMillis),
alarms = alarms,
timers = timers,
worldClocks = worldClocks,
settings = settingsContent,
)
}
@@ -12,9 +12,16 @@ const val BACKUP_VERSION: Int = 2
/** The oldest version this build still reads. v1 is v2 without the alarm dates. */
const val BACKUP_MIN_VERSION: Int = 1
/** The wire shape of `clockula-backup-v1.json`. See `docs/BACKUP.md`. */
/** The largest backup Clockula reads or writes, in bytes (and, decoded, in characters). */
const val BACKUP_MAX_BYTES: Int = 8 * 1024 * 1024
/**
* The wire shape of `clockula-backup-v1.json`. `format`, `version` and
* `exportedAt` are floret core-backup's envelope keys; `format` and
* `version` are checked by its rules. See `docs/BACKUP.md`.
*/
@Serializable
data class BackupDocument(
data class BackupFile(
val format: String,
val version: Int,
@SerialName("exportedAt") val exportedAtMillis: Long,
@@ -7,7 +7,7 @@ import kotlin.time.Duration.Companion.minutes
* The alarm ring cycle's constants. They are values rather than settings
* (docs/PLAN.md §4). How long an alarm rings before it is silenced as missed
* became a setting in #17: `ClockDefaults.alarmSilenceAfter`. The audio
* chain's own constants live in floret-kit's `VolumeRamp`, shared with the
* chain's own constants live in `domain/ring/RingAudio`, shared with the
* timer's ring.
*/
object AlarmRing {
@@ -45,3 +45,13 @@ object RingFallbackPolicy {
fun vibrationRequired(audioAvailable: Boolean, vibrateSetting: Boolean): Boolean =
vibrateSetting || !audioAvailable
}
/** Long buzz, short gap, long buzz, longer gap — loudly rhythmic, not a doorbell. */
object VibrationPattern {
val TIMINGS: LongArray = longArrayOf(500L, 250L, 500L, 1_000L)
val AMPLITUDES: IntArray = intArrayOf(255, 0, 255, 0)
/** The index the pattern loops from: 0, so the whole pattern repeats. */
const val REPEAT_INDEX: Int = 0
}
@@ -85,7 +85,7 @@ object MediaRingPolicy {
return ceil(fraction * musicMax).toInt().coerceIn(1, musicMax)
}
/** The index for a ramp [level] (`VolumeRamp.MIN_LEVEL`..1) on the way to [target]. */
/** The index for a ramp [level] (`RingAudio.MIN_VOLUME`..1) on the way to [target]. */
fun mediaVolumeIndex(level: Float, target: Int): Int {
if (target <= 0) return 0
return (level.coerceIn(0f, 1f) * target).roundToInt().coerceIn(1, target)
@@ -0,0 +1,17 @@
package de.jeanlucmakiola.clockula.domain.ring
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
/**
* The audio chain's constants, shared by both ring paths. They moved out of
* `AlarmRing` when the timer's ring started using the same player: a constant
* named for one caller reads as that caller's private business (slice plan D8).
*/
object RingAudio {
/** How often a ringing service steps the volume ramp. */
val RAMP_TICK: Duration = 200.milliseconds
/** The ramp's floor — a ramping ring never starts at true silence. */
const val MIN_VOLUME: Float = 0.05f
}
@@ -0,0 +1,19 @@
package de.jeanlucmakiola.clockula.domain.ring
import kotlin.time.Duration
/**
* Quadratic in amplitude is roughly linear in perceived loudness, so the ramp
* sounds like a steady climb rather than a jump at the end.
*/
object VolumeRamp {
/** `RingAudio.MIN_VOLUME`..1f. Never throws. */
fun levelAt(elapsed: Duration, ramp: Duration): Float {
if (ramp <= Duration.ZERO || elapsed >= ramp) return 1f
if (elapsed <= Duration.ZERO) return RingAudio.MIN_VOLUME
val progress = (elapsed / ramp).toFloat()
val level = RingAudio.MIN_VOLUME + (1f - RingAudio.MIN_VOLUME) * progress * progress
return level.coerceIn(RingAudio.MIN_VOLUME, 1f)
}
}
@@ -5,12 +5,12 @@ import android.app.Application
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import de.jeanlucmakiola.clockula.domain.alarm.DirectLaunchFacts
import de.jeanlucmakiola.clockula.domain.alarm.DirectLaunchPolicy
import de.jeanlucmakiola.floret.ring.isInCall
/**
* Opens a ring screen directly where a full-screen intent would only show a
@@ -66,7 +66,7 @@ object ForegroundRingScreen {
screenShowing = screenShowing,
overOtherApps = overOtherApps,
canDrawOverlays = Settings.canDrawOverlays(context),
inCall = context.isInCall(),
inCall = inCall(context),
)
if (!DirectLaunchPolicy.opensDirectly(facts)) return
// A refused start costs nothing: the notification is up either way.
@@ -80,4 +80,11 @@ object ForegroundRingScreen {
private fun phoneInUse(context: Context): Boolean =
context.getSystemService(PowerManager::class.java).isInteractive &&
!context.getSystemService(KeyguardManager::class.java).isKeyguardLocked
/** The audio mode, which needs no phone permission, unlike the telecom APIs. */
private fun inCall(context: Context): Boolean =
when (context.getSystemService(AudioManager::class.java).mode) {
AudioManager.MODE_IN_CALL, AudioManager.MODE_IN_COMMUNICATION, AudioManager.MODE_RINGTONE -> true
else -> false
}
}
@@ -0,0 +1,28 @@
package de.jeanlucmakiola.clockula.ring
import android.content.Context
import android.os.PowerManager
/**
* Keeps the CPU awake across the gap between an AlarmManager broadcast and the
* service it starts. The platform's own wake lock ends with the receiver, and
* the service takes its own only after a database read, so without this a
* dozing device can suspend in between and ring minutes late.
*
* Timed rather than released: the service holds its own lock well before the
* timeout, and a lock that outlives a crashed hand-off cannot leak.
*/
object HandoffWakeLock {
private const val TIMEOUT_MILLIS = 30_000L
fun acquire(context: Context, tag: String) {
val power = context.getSystemService(PowerManager::class.java) ?: return
runCatching {
power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag).apply {
setReferenceCounted(false)
acquire(TIMEOUT_MILLIS)
}
}
}
}
@@ -1,28 +1,35 @@
package de.jeanlucmakiola.clockula.ring
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.net.Uri
import de.jeanlucmakiola.clockula.data.ringtones.BundledTones
import de.jeanlucmakiola.clockula.domain.MediaSources
import de.jeanlucmakiola.clockula.domain.ring.AudioSourcePolicy
import de.jeanlucmakiola.clockula.domain.ring.MediaRingPolicy
import de.jeanlucmakiola.clockula.domain.ring.RingAudio
import de.jeanlucmakiola.clockula.domain.ring.RingtoneSourceKind
import de.jeanlucmakiola.floret.ring.TonePlayer
import de.jeanlucmakiola.floret.ring.VolumeRamp
import de.jeanlucmakiola.clockula.domain.ring.VolumeRamp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/**
* floret-kit's [TonePlayer] over the ringing thing's sources, plus a ring
* another app plays ([MediaAppRing]) in front of it. The ramp never edits the
* user's own alarm volume; a ring another app plays is the one exception.
* `MediaPlayer` over `USAGE_ALARM`, plus the ramp loop. The ramp is stepped into
* [MediaPlayer.setVolume] and **never** into `AudioManager.setStreamVolume`,
* which would edit the user's own alarm volume and leave it edited. (A ring
* another app plays is the one exception — see [MediaAppRing].)
*
* [start] does not wait for the sound: opening one can take seconds when
* another app plays it, and the caller has a notification to post and a
@@ -32,10 +39,18 @@ import kotlin.time.Duration.Companion.seconds
*/
class RingAudioPlayer(private val context: Context) {
private val tones = TonePlayer(context)
private val audioManager: AudioManager = context.getSystemService(AudioManager::class.java)
private val routes by lazy { MediaRouteCheck(context) }
private val attributes: AudioAttributes = AudioAttributes.Builder()
// USAGE_ALARM is what makes Do Not Disturb's alarm exemption apply.
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
private var player: MediaPlayer? = null
private var focusRequest: AudioFocusRequest? = null
private var ramp: Job? = null
/** Set while another app plays the ring ([MediaAppRing]). */
@@ -44,10 +59,8 @@ class RingAudioPlayer(private val context: Context) {
/**
* Which ring is live. [start] and [stop] both move it on, so work a ring
* left in flight — a music app that answers late — sees it is no longer
* wanted and releases what it opened rather than starting it. A `prepare`
* in flight is [TonePlayer]'s, guarded by its own counter, which [stop]
* moves on too.
* left in flight — a `prepare`, a music app that answers late — sees it is
* no longer wanted and releases what it opened rather than starting it.
*/
private var generation: Int = 0
@@ -91,7 +104,9 @@ class RingAudioPlayer(private val context: Context) {
ramp = null
mediaRing?.stop()
mediaRing = null
tones.stop()
player?.let(::release)
player = null
abandonFocus()
}
/** False when there is no media source, or it would not be heard, or the app would not play. */
@@ -128,8 +143,12 @@ class RingAudioPlayer(private val context: Context) {
}
/**
* The ordinary chain, through [TonePlayer]: a player that errors once it is
* playing hands the ring to the sources after its own, unramped, and to
* Prepares on IO, because [MediaPlayer.prepare] is blocking I/O and the
* moment the alarm rings is the worst possible moment to block the main
* thread with it.
*
* A player that errors once it is playing (the media server died, the file
* went away) hands the ring to the sources after its own, unramped, and to
* [onSilenced] when none is left — a ring never goes quiet mid-alarm.
*/
private suspend fun startPlayer(
@@ -139,9 +158,47 @@ class RingAudioPlayer(private val context: Context) {
rampFor: Duration,
rampStart: Duration,
onSilenced: () -> Unit,
from: Int = 0,
): Boolean {
if (ring != generation) return false
return tones.play(scope, sources(ringtoneUri), rampFor, rampStart, onSilenced)
for ((index, uri) in sources(ringtoneUri).withIndex()) {
if (index < from) continue
val prepared = withContext(Dispatchers.IO) { prepare(uri) } ?: continue
// Stopped while preparing: never start an obsolete ring.
if (ring != generation) {
release(prepared)
return false
}
requestFocus()
val initial = VolumeRamp.levelAt(rampStart, rampFor)
val started = runCatching {
prepared.setVolume(initial, initial)
prepared.start()
}.isSuccess
if (!started) {
release(prepared)
abandonFocus()
continue
}
player = prepared
prepared.setOnErrorListener { failed, _, _ ->
if (player === failed && ring == generation) {
ramp?.cancel()
ramp = null
player = null
release(failed)
abandonFocus()
scope.launch {
val next = startPlayer(ring, scope, ringtoneUri, Duration.ZERO, Duration.ZERO, onSilenced, index + 1)
if (!next && ring == generation) onSilenced()
}
}
true
}
ramp = launchRamp(scope, rampFor, rampStart) { level -> runCatching { player?.setVolume(level, level) } }
return true
}
return false
}
/**
@@ -161,7 +218,7 @@ class RingAudioPlayer(private val context: Context) {
onSilenced: () -> Unit,
) {
media.setLevel(VolumeRamp.levelAt(rampStart, rampFor))
ramp = VolumeRamp.launch(scope, rampFor, rampStart, media::setLevel)
ramp = launchRamp(scope, rampFor, rampStart, media::setLevel)
watchdog = scope.launch {
var stall = MediaRingPolicy.Stall()
while (isActive && ring == generation) {
@@ -178,6 +235,22 @@ class RingAudioPlayer(private val context: Context) {
}
}
/** Steps [setLevel] along [VolumeRamp] every [RingAudio.RAMP_TICK] from [from] until [rampFor] has passed. */
private fun launchRamp(
scope: CoroutineScope,
rampFor: Duration,
from: Duration,
setLevel: (Float) -> Unit,
): Job =
scope.launch {
var elapsed = from
while (isActive && elapsed < rampFor) {
delay(RingAudio.RAMP_TICK)
elapsed += RingAudio.RAMP_TICK
setLevel(VolumeRamp.levelAt(elapsed, rampFor))
}
}
/**
* The order is [AudioSourcePolicy]'s, so the decision — including the silent
* sentinel's empty list, which is what forces vibration (M5 D18) — lives in
@@ -195,4 +268,42 @@ class RingAudioPlayer(private val context: Context) {
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
}
}
/**
* A prepared, not-yet-started player, or null. A source that throws has its
* player released here: one leaked [MediaPlayer] per unusable fallback is
* still a leak, and there are three fallbacks.
*/
private fun prepare(uri: Uri): MediaPlayer? {
val candidate = MediaPlayer()
return runCatching {
candidate.setAudioAttributes(attributes)
candidate.setDataSource(context, uri)
candidate.isLooping = true
candidate.prepare()
candidate
}.getOrElse {
release(candidate)
null
}
}
private fun release(player: MediaPlayer) {
runCatching { player.stop() }
runCatching { player.release() }
}
/** GAIN_TRANSIENT: an alarm interrupts what is playing; it does not duck it. */
private fun requestFocus() {
val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(attributes)
.build()
focusRequest = request
runCatching { audioManager.requestAudioFocus(request) }
}
private fun abandonFocus() {
focusRequest?.let { runCatching { audioManager.abandonAudioFocusRequest(it) } }
focusRequest = null
}
}
@@ -0,0 +1,46 @@
package de.jeanlucmakiola.clockula.ring
import android.content.Context
import android.media.AudioAttributes
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import de.jeanlucmakiola.clockula.domain.ring.VibrationPattern
/**
* The waveform, looped, with `USAGE_ALARM` attributes so Do Not Disturb treats
* it the way it treats the sound. Shared by the alarm's ring and the timer's. `minSdk` is 29, so `VibratorManager` (API 31+)
* is guarded and the older accessor stands in below it.
*/
class RingVibrator(private val context: Context) {
private val attributes: AudioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
private val vibrator: Vibrator? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
context.getSystemService(VibratorManager::class.java)?.defaultVibrator
} else {
@Suppress("DEPRECATION")
context.getSystemService(Vibrator::class.java)
}
fun start() {
val device = vibrator?.takeIf { it.hasVibrator() } ?: return
val effect = VibrationEffect.createWaveform(
VibrationPattern.TIMINGS,
VibrationPattern.AMPLITUDES,
VibrationPattern.REPEAT_INDEX,
)
runCatching {
@Suppress("DEPRECATION")
device.vibrate(effect, attributes)
}
}
fun stop() {
runCatching { vibrator?.cancel() }
}
}
@@ -4,9 +4,9 @@ import android.content.Context
import android.content.Intent
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.clockula.alarm.receiver.HiltBroadcastReceiver
import de.jeanlucmakiola.clockula.ring.HandoffWakeLock
import de.jeanlucmakiola.clockula.timer.TimerEngine
import de.jeanlucmakiola.floret.di.ApplicationScope
import de.jeanlucmakiola.floret.ring.RingWakeLock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -29,7 +29,7 @@ class TimerExpiryReceiver : HiltBroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
RingWakeLock.handOff(context, "clockula:timer-expiry")
HandoffWakeLock.acquire(context, "clockula:timer-expiry")
val pendingResult = goAsync()
scope.launch {
try {
@@ -4,7 +4,10 @@ import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.NotificationManagerCompat
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.clockula.alarm.AlarmCapabilities
@@ -19,14 +22,12 @@ import de.jeanlucmakiola.clockula.domain.timer.TimerRingDecision
import de.jeanlucmakiola.clockula.domain.timer.TimerSettings
import de.jeanlucmakiola.clockula.ring.ForegroundRingScreen
import de.jeanlucmakiola.clockula.ring.RingAudioPlayer
import de.jeanlucmakiola.clockula.ring.RingVibrator
import de.jeanlucmakiola.clockula.timer.AlarmRingStatus
import de.jeanlucmakiola.clockula.timer.TimerEngine
import de.jeanlucmakiola.clockula.timer.TimerIntents
import de.jeanlucmakiola.clockula.timer.TimerServiceState
import de.jeanlucmakiola.clockula.ui.ring.TimerRingActivity
import de.jeanlucmakiola.floret.ring.RingVibrator
import de.jeanlucmakiola.floret.ring.RingWakeLock
import de.jeanlucmakiola.floret.ring.startRingForeground
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -86,7 +87,7 @@ class TimerService : Service() {
private val audio by lazy { RingAudioPlayer(this) }
private val vibrator by lazy { RingVibrator(this) }
private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, WAKE_LOCK_TIMEOUT_MILLIS) }
private var wakeLock: PowerManager.WakeLock? = null
private var collector: Job? = null
/** The two independent delays the engine hands down (D20). */
@@ -244,7 +245,7 @@ class TimerService : Service() {
releaseRing()
sounding = decision.subjectId
soundingSettings = decision.settings
wakeLock.acquire()
acquireWakeLock()
// Vibration first, and the sound without waiting for it: a sound
// another app plays can take seconds to open, and this runs
// inside the collector that posts the notification and its Stop.
@@ -330,19 +331,38 @@ class TimerService : Service() {
}
private fun startForeground(notification: Notification) {
// systemExempted, the same type and justification as the alarm's
// ringing service (D6).
startRingForeground(notificationId, notification)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
// systemExempted, the same type and justification as the alarm's
// ringing service: an app holding an exact-alarm permission,
// continuing an alarm-shaped event in the background (D6).
startForeground(
notificationId,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED,
)
} else {
startForeground(notificationId, notification)
}
wentForeground = true
}
private fun acquireWakeLock() {
if (wakeLock != null) return
val power = getSystemService(PowerManager::class.java)
wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG).apply {
setReferenceCounted(false)
runCatching { acquire(WAKE_LOCK_TIMEOUT_MILLIS) }
}
}
/** The whole ring released, not just the audio: an orphaned looping player cannot be stopped. */
private fun releaseRing() {
sounding = null
soundingSettings = null
audio.stop()
vibrator.stop()
wakeLock.release()
wakeLock?.let { if (it.isHeld) runCatching { it.release() } }
wakeLock = null
}
private fun stop() {
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.clockula.ui.ring
import android.os.Bundle
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
@@ -16,7 +17,6 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.clockula.domain.alarm.VolumeKeyEffect
import de.jeanlucmakiola.clockula.ui.theme.ClockulaTheme
import de.jeanlucmakiola.floret.ring.showOverLockScreen
/**
* The window a firing alarm gets: over the lock screen, with the display turned
@@ -39,8 +39,6 @@ class AlarmRingActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// An alarm the user has to unlock to silence is not an alarm. Keeping
// the screen on is scoped to this window, so it cannot outlive the ring.
showOverLockScreen()
setContent {
@@ -108,6 +106,21 @@ class AlarmRingActivity : ComponentActivity() {
return true
}
/**
* Shown over the lock screen with the display turned on: an alarm the user
* has to unlock to silence is not an alarm. `minSdk` is 29, so the
* pre-API-27 window flags are not needed.
*
* `FLAG_KEEP_SCREEN_ON` is the "wake lock for the ring duration only" that
* docs/PLAN.md §4 asks for — scoped to this window's life, so unlike a
* `PowerManager.WakeLock` it cannot be leaked past the alarm.
*/
private fun showOverLockScreen() {
setShowWhenLocked(true)
setTurnScreenOn(true)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
private companion object {
val VOLUME_KEYS = setOf(
KeyEvent.KEYCODE_VOLUME_UP,
@@ -1,23 +1,35 @@
package de.jeanlucmakiola.clockula.ui.ring
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Alarm
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
@@ -25,7 +37,7 @@ import de.jeanlucmakiola.clockula.R
import de.jeanlucmakiola.clockula.ui.common.rememberAlarmTimeFormatter
import de.jeanlucmakiola.floret.identity.collapseExit
import de.jeanlucmakiola.floret.identity.expandEnter
import de.jeanlucmakiola.floret.ring.RingBadge
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
/**
* The ring screen itself: the time, the label, snooze, and the dismiss
@@ -56,7 +68,7 @@ internal fun RingScreen(
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
RingBadge(icon = Icons.Rounded.Alarm)
RingingBadge()
Text(
text = formatTime(state.time),
style = MaterialTheme.typography.displayLarge,
@@ -128,6 +140,35 @@ internal fun RingScreen(
}
}
/** One pulsing circular badge — the screen's only motion flourish. */
@Composable
private fun RingingBadge() {
val reduceMotion = rememberReduceMotion()
val pulse = rememberInfiniteTransition(label = "ring-pulse")
val scale by pulse.animateFloat(
initialValue = 1f,
targetValue = if (reduceMotion) 1f else 1.08f,
animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
label = "ring-pulse-scale",
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(96.dp)
.scale(scale)
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape),
) {
Icon(
imageVector = Icons.Rounded.Alarm,
// The time and the label below say what this is; the badge is the
// same sentence in a circle.
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(48.dp),
)
}
}
private fun ChallengeUiState.escapeAvailable(): Boolean = when (this) {
ChallengeUiState.Direct -> false
is ChallengeUiState.Math -> escapeAvailable
@@ -1,6 +1,7 @@
package de.jeanlucmakiola.clockula.ui.ring
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
@@ -14,7 +15,6 @@ import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.clockula.ui.theme.ClockulaTheme
import de.jeanlucmakiola.floret.ring.showOverLockScreen
/**
* The window an expired timer gets, opened by the timer notification's
@@ -34,7 +34,9 @@ class TimerRingActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
// As AlarmRingActivity: shown over the lock screen, display on, and
// kept on for this window's life only.
showOverLockScreen()
setShowWhenLocked(true)
setTurnScreenOn(true)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContent {
ClockulaTheme {
@@ -1,27 +1,39 @@
package de.jeanlucmakiola.clockula.ui.ring
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Timer
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.clockula.R
import de.jeanlucmakiola.floret.ring.RingBadge
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
/**
* The timer ring screen: the label, "Finished", and the notification's two
@@ -41,7 +53,7 @@ internal fun TimerRingScreen(
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
RingBadge(icon = Icons.Rounded.Timer)
TimerBadge()
Text(
text = stringResource(R.string.timer_finished),
style = MaterialTheme.typography.displayMedium,
@@ -71,3 +83,30 @@ internal fun TimerRingScreen(
}
}
}
/** The alarm screen's pulsing badge, with the timer's icon. */
@Composable
private fun TimerBadge() {
val reduceMotion = rememberReduceMotion()
val pulse = rememberInfiniteTransition(label = "timer-ring-pulse")
val scale by pulse.animateFloat(
initialValue = 1f,
targetValue = if (reduceMotion) 1f else 1.08f,
animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
label = "timer-ring-pulse-scale",
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(96.dp)
.scale(scale)
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape),
) {
Icon(
imageVector = Icons.Rounded.Timer,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(48.dp),
)
}
}
@@ -32,7 +32,7 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.clockula.R
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow
@@ -1,6 +1,6 @@
package de.jeanlucmakiola.clockula.ui.settings
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupProblem
/**
* A one-off result the screen shows as a snackbar and then forgets. A failure
@@ -5,9 +5,10 @@ import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.clockula.backup.BackupEngine
import de.jeanlucmakiola.clockula.backup.BackupFiles
import de.jeanlucmakiola.clockula.backup.BackupTooLargeException
import de.jeanlucmakiola.clockula.data.backup.BackupCodec
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.clockula.data.backup.BackupResult
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow
@@ -74,7 +75,8 @@ class BackupViewModel @Inject internal constructor(
} else {
val failure = result.exceptionOrNull()
if (failure is CancellationException) throw failure
BackupEvent.ImportFailed(BackupProblem.UNREADABLE)
val problem = if (failure is BackupTooLargeException) BackupProblem.TOO_LARGE else BackupProblem.UNREADABLE
BackupEvent.ImportFailed(problem)
}
_events.trySend(event)
} catch (cancelled: CancellationException) {
@@ -89,7 +91,7 @@ class BackupViewModel @Inject internal constructor(
private suspend fun applyImport(text: String): BackupEvent = when (val decoded = BackupCodec.decode(text)) {
is BackupResult.Success -> {
engine.import(decoded.content)
engine.import(decoded.value)
BackupEvent.ImportSucceeded
}
is BackupResult.Failure -> BackupEvent.ImportFailed(decoded.problem)
@@ -33,7 +33,6 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings
/**
* The "why might my alarm not ring?" screen (`docs/PLAN.md` §4): one row per
@@ -146,10 +145,8 @@ private fun launchFix(context: Context, fix: SelfCheckFix) {
Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
.putExtra(Settings.EXTRA_CHANNEL_ID, RingNotifications.RING_CHANNEL_ID)
SelfCheckFix.OpenFullScreenIntentSettings -> {
context.openFullScreenIntentSettings()
return
}
SelfCheckFix.OpenFullScreenIntentSettings ->
Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, Uri.parse("package:${context.packageName}"))
SelfCheckFix.OpenBatteryOptimizationSettings ->
Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
SelfCheckFix.OpenAppDetailsSettings ->
@@ -214,8 +214,7 @@ class ArchitectureRulesTest {
/**
* M6 D31: "reuses M3's audio path" made mechanical. One `MediaPlayer`
* wrapper for both ring paths (floret-kit's `TonePlayer`, behind
* `ring/RingAudioPlayer`) and one for the picker's preview; a third
* wrapper for both ring paths and one for the picker's preview; a third
* audio path cannot be added without the build failing. The `/ring/` match
* covers the wrapper both before and after D8's package move.
*/
@@ -228,16 +227,6 @@ class ArchitectureRulesTest {
assertThat(offenders).isEmpty()
}
/** floret-kit's `TonePlayer` is that wrapper now, so only `RingAudioPlayer` may hold one. */
@Test
fun `TonePlayer lives only behind RingAudioPlayer`() {
val offenders = kotlinSources.containing("TonePlayer").filterNot {
it.endsWith("de/jeanlucmakiola/clockula/ring/RingAudioPlayer.kt")
}
assertThat(offenders).isEmpty()
}
/**
* M7 D19: the stopwatch is silent. It never opens audio, never vibrates and
* never takes a wake lock — which is the one thing a future "make the lap
@@ -252,7 +241,6 @@ class ArchitectureRulesTest {
"MediaPlayer",
"RingAudioPlayer",
"RingVibrator",
"TonePlayer",
"Vibrator",
"AudioManager",
// D3's "no wake lock, ever" is half of the promise this rule makes,
@@ -21,6 +21,8 @@ import de.jeanlucmakiola.clockula.domain.screensaver.ScreenSaverStyle
import de.jeanlucmakiola.clockula.domain.timer.TimerPresets
import de.jeanlucmakiola.clockula.domain.widget.QuickTimerWidgetSettings
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import org.junit.jupiter.api.Test
import java.time.DayOfWeek
import java.time.LocalDate
@@ -168,7 +170,7 @@ class BackupCodecTest {
val decoded = BackupCodec.decode(json)
assertThat(decoded).isInstanceOf(BackupResult.Success::class.java)
val defaults = (decoded as BackupResult.Success).content.settings.defaults
val defaults = (decoded as BackupResult.Success).value.settings.defaults
// Timers vibrated by the alarm default then, which defaults to on.
assertThat(defaults).isEqualTo(ClockDefaults(snoozeMinutes = 7, timerVibrate = true))
}
@@ -202,27 +204,27 @@ class BackupCodecTest {
fun `a file from before the week start setting follows the locale`() {
val decoded = BackupCodec.decode(settingsOnly(""""default_vibrate": true"""))
assertThat((decoded as BackupResult.Success).content.settings.weekStart).isEqualTo(WeekStartPref.Auto)
assertThat((decoded as BackupResult.Success).value.settings.weekStart).isEqualTo(WeekStartPref.Auto)
}
@Test
fun `an unknown week start follows the locale rather than rejecting the file`() {
val decoded = BackupCodec.decode(settingsOnly(""""week_start": "FUNDAY""""))
assertThat((decoded as BackupResult.Success).content.settings.weekStart).isEqualTo(WeekStartPref.Auto)
assertThat((decoded as BackupResult.Success).value.settings.weekStart).isEqualTo(WeekStartPref.Auto)
}
@Test
fun `a null week start follows the locale rather than rejecting the file`() {
val decoded = BackupCodec.decode(settingsOnly(""""week_start": null"""))
assertThat((decoded as BackupResult.Success).content.settings.weekStart).isEqualTo(WeekStartPref.Auto)
assertThat((decoded as BackupResult.Success).value.settings.weekStart).isEqualTo(WeekStartPref.Auto)
}
private fun settingsOnly(settings: String): String =
"""{ "format": "clockula-backup", "version": 1, "exportedAt": 0, "settings": { $settings } }"""
private fun BackupResult.defaults(): ClockDefaults = (this as BackupResult.Success).content.settings.defaults
private fun BackupResult<BackupContent>.defaults(): ClockDefaults = (this as BackupResult.Success).value.settings.defaults
@Test
fun `the retired default timer duration is no longer written`() {
@@ -232,7 +234,19 @@ class BackupCodecTest {
@Test
fun `wrong format rejects the whole file`() {
val decoded = BackupCodec.decode(minimalDocument(format = "something-else"))
assertThat(decoded).isInstanceOf(BackupResult.Failure::class.java)
assertThat((decoded as BackupResult.Failure).problem).isEqualTo(BackupProblem.NOT_A_BACKUP)
}
@Test
fun `a quoted version and a foreign appVersion still import, as before the floret envelope`() {
val json = minimalDocument(extraTopLevel = "\"appVersion\": 3,").replace("\"version\": 1", "\"version\": \"1\"")
assertThat(BackupCodec.decode(json)).isInstanceOf(BackupResult.Success::class.java)
}
@Test
fun `a file without an export time is not a backup`() {
val json = minimalDocument().replace("\"exportedAt\": 0,", "")
assertThat((BackupCodec.decode(json) as BackupResult.Failure).problem).isEqualTo(BackupProblem.NOT_A_BACKUP)
}
@Test
@@ -256,7 +270,7 @@ class BackupCodecTest {
"\"alarms\": [{\"hour\":7,\"minute\":0,\"repeat_days\":31}]",
)
val decoded = BackupCodec.decode(json) as BackupResult.Success
val alarm = decoded.content.alarms.single()
val alarm = decoded.value.alarms.single()
assertThat(alarm.scheduledDate).isNull()
assertThat(alarm.pause).isNull()
}
@@ -314,8 +328,8 @@ class BackupCodecTest {
alarmDocument("\"pause_start\":\"2026-10-26\",\"pause_end\":\"2026-10-28\""),
) as BackupResult.Success
assertThat(datedRepeating.content.alarms.single().scheduledDate).isNull()
assertThat(pausedOneShot.content.alarms.single().pause).isNull()
assertThat(datedRepeating.value.alarms.single().scheduledDate).isNull()
assertThat(pausedOneShot.value.alarms.single().pause).isNull()
}
@Test
@@ -345,7 +359,7 @@ class BackupCodecTest {
"settings": {}
}
""".trimIndent()
assertThat(BackupCodec.decode(json)).isInstanceOf(BackupResult.Failure::class.java)
assertThat((BackupCodec.decode(json) as BackupResult.Failure).problem).isEqualTo(BackupProblem.INVALID_DATA)
}
@Test
@@ -411,14 +425,14 @@ class BackupCodecTest {
""".trimIndent()
val result = BackupCodec.decode(json)
assertThat(result).isInstanceOf(BackupResult.Success::class.java)
val content = (result as BackupResult.Success).content
val content = (result as BackupResult.Success).value
assertThat(content.alarms.single().dismissChallenge).isEqualTo(DismissChallenge.NONE)
}
@Test
fun `a file without the volume-button setting keeps the volume keys as they were`() {
val result = BackupCodec.decode(minimalDocument())
val defaults = (result as BackupResult.Success).content.settings.defaults
val defaults = (result as BackupResult.Success).value.settings.defaults
assertThat(defaults.volumeButtons).isEqualTo(VolumeButtonAction.CONTROL_VOLUME)
}
@@ -429,7 +443,7 @@ class BackupCodecTest {
"\"settings\": {\"volume_buttons_while_ringing\": \"SOME_FUTURE_ACTION\"}",
)
val result = BackupCodec.decode(json)
val defaults = (result as BackupResult.Success).content.settings.defaults
val defaults = (result as BackupResult.Success).value.settings.defaults
assertThat(defaults.volumeButtons).isEqualTo(VolumeButtonAction.CONTROL_VOLUME)
}
@@ -440,7 +454,7 @@ class BackupCodecTest {
"\"alarms\": [{\"hour\":7,\"minute\":0,\"snooze_minutes\":0," +
"\"snooze_limit\":-5,\"volume_ramp_seconds\":100000}]",
)
val alarm = (BackupCodec.decode(json) as BackupResult.Success).content.alarms.single()
val alarm = (BackupCodec.decode(json) as BackupResult.Success).value.alarms.single()
assertThat(alarm.snoozeMinutes).isEqualTo(1)
assertThat(alarm.snoozeLimit).isEqualTo(0)
assertThat(alarm.volumeRampSeconds).isEqualTo(60)
@@ -452,19 +466,19 @@ class BackupCodecTest {
"\"timers\": []",
"\"timers\": [{\"duration_millis\":0},{\"duration_millis\":${Long.MAX_VALUE}}]",
)
val timers = (BackupCodec.decode(json) as BackupResult.Success).content.timers
val timers = (BackupCodec.decode(json) as BackupResult.Success).value.timers
assertThat(timers.map { it.duration }).containsExactly(TimerPresets.MIN, TimerPresets.MAX).inOrder()
}
@Test
fun `a file without timer presets keeps the built-in ones`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.timerPresets).isEqualTo(TimerPresets.BUILT_IN)
}
@Test
fun `a file from before bedtime existed carries no bedtime, so restoring it keeps the current one`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.bedtime).isNull()
}
@@ -475,7 +489,7 @@ class BackupCodecTest {
"\"settings\": {\"bedtime\": {\"enabled\": true, \"bedtime_minutes\": 99999, " +
"\"wake_minutes\": -5, \"days\": 255, \"reminder_minutes\": 999}}",
)
val bedtime = (BackupCodec.decode(json) as BackupResult.Success).content.settings.bedtime!!
val bedtime = (BackupCodec.decode(json) as BackupResult.Success).value.settings.bedtime!!
assertThat(bedtime.enabled).isTrue()
assertThat(bedtime.bedtime).isEqualTo(TimeOfDay(23, 59))
assertThat(bedtime.wakeTime).isEqualTo(TimeOfDay(0, 0))
@@ -485,7 +499,7 @@ class BackupCodecTest {
@Test
fun `a file from before silence after keeps the ten minutes it was made with`() {
val defaults = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings.defaults
val defaults = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings.defaults
assertThat(defaults.alarmSilenceAfterMinutes).isEqualTo(10)
assertThat(defaults.timerSilenceAfterMinutes).isEqualTo(10)
}
@@ -499,7 +513,7 @@ class BackupCodecTest {
@Test
fun `a file from before show-seconds existed keeps it off`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.worldClockSeconds).isFalse()
}
@@ -510,7 +524,7 @@ class BackupCodecTest {
@Test
fun `a file from before the compact home clock keeps it off`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.compactHomeClock).isFalse()
}
@@ -521,7 +535,7 @@ class BackupCodecTest {
@Test
fun `a file from before the automatic local clock keeps it on`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.defaults.automaticLocalClock).isTrue()
}
@@ -532,7 +546,7 @@ class BackupCodecTest {
@Test
fun `a file from before the screen saver restores its defaults`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.screenSaver).isEqualTo(ScreenSaverSettings())
}
@@ -542,27 +556,27 @@ class BackupCodecTest {
"\"settings\": {}",
"\"settings\": {\"screen_saver_style\": \"HOLOGRAM\", \"screen_saver_night_mode\": true}",
)
val settings = (BackupCodec.decode(json) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(json) as BackupResult.Success).value.settings
assertThat(settings.screenSaver).isEqualTo(ScreenSaverSettings(ScreenSaverStyle.DIGITAL, nightMode = true))
}
@Test
fun `a file without the quick tile's duration keeps its default`() {
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(minimalDocument()) as BackupResult.Success).value.settings
assertThat(settings.quickTileDuration).isEqualTo(QuickTimerWidgetSettings.DEFAULT)
}
@Test
fun `a quick tile duration the tile cannot start falls back to its default`() {
val json = minimalDocument().replace("\"settings\": {}", "\"settings\": {\"quick_tile_duration_millis\": 7200000}")
val settings = (BackupCodec.decode(json) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(json) as BackupResult.Success).value.settings
assertThat(settings.quickTileDuration).isEqualTo(QuickTimerWidgetSettings.DEFAULT)
}
@Test
fun `an empty preset list is honoured as all removed`() {
val json = minimalDocument().replace("\"settings\": {}", "\"settings\": {\"timer_presets\": []}")
val settings = (BackupCodec.decode(json) as BackupResult.Success).content.settings
val settings = (BackupCodec.decode(json) as BackupResult.Success).value.settings
assertThat(settings.timerPresets).isEmpty()
}
@@ -574,7 +588,7 @@ class BackupCodecTest {
@Test
fun `oversized document is rejected before parsing`() {
val result = BackupCodec.decode(" ".repeat(8 * 1024 * 1024 + 1))
assertThat(result).isInstanceOf(BackupResult.Failure::class.java)
assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.TOO_LARGE)
}
@Test
@@ -583,7 +597,7 @@ class BackupCodecTest {
"\"alarms\": []",
"\"alarms\": [{\"hour\":7,\"minute\":0,\"label\":\"${"x".repeat(64 * 1024 + 1)}\"}]",
)
assertThat(BackupCodec.decode(json)).isInstanceOf(BackupResult.Failure::class.java)
assertThat((BackupCodec.decode(json) as BackupResult.Failure).problem).isEqualTo(BackupProblem.TOO_LARGE)
}
private fun minimalDocument(
@@ -0,0 +1,78 @@
package de.jeanlucmakiola.clockula.data.backup
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.domain.DismissChallenge
import de.jeanlucmakiola.clockula.domain.TimeOfDay
import de.jeanlucmakiola.clockula.domain.backup.BackupContent
import de.jeanlucmakiola.clockula.domain.timer.TimerPresets
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.prefs.ThemeMode
import org.junit.jupiter.api.Test
import java.time.LocalDate
import kotlin.time.Duration.Companion.minutes
/**
* Backups written by earlier builds still restore (#38). The v2 file is what
* the codec wrote before it moved onto floret's envelope; the v1 file has the
* shape of the first release's backups, with the since-retired timer length.
*/
class BackupFixtureTest {
private fun fixture(name: String): String =
requireNotNull(javaClass.classLoader.getResource("backup/$name")) { name }.readText()
private fun decode(name: String): BackupContent =
(BackupCodec.decode(fixture(name)) as BackupResult.Success).value
@Test
fun `a version 2 backup still restores`() {
val content = decode("clockula-backup-v2.json")
assertThat(content.alarms).hasSize(3)
assertThat(content.alarms[1].scheduledDate).isEqualTo(LocalDate.of(2026, 12, 24))
assertThat(content.alarms[2].pause?.end).isEqualTo(LocalDate.of(2027, 1, 6))
assertThat(content.timers.single().duration).isEqualTo(5.minutes)
assertThat(content.worldClocks.single().zoneId).isEqualTo("Europe/Berlin")
assertThat(content.settings.themeMode).isEqualTo(ThemeMode.DARK)
assertThat(content.settings.bedtime?.reminderMinutes).isEqualTo(30)
}
@Test
fun `the written format is unchanged`() {
val text = fixture("clockula-backup-v2.json")
assertThat(BackupCodec.encode(decode("clockula-backup-v2.json"))).isEqualTo(text)
}
@Test
fun `a version 1 backup still restores with the defaults it predates`() {
val content = decode("clockula-backup-v1.json")
assertThat(content.alarms.map { it.time }).containsExactly(TimeOfDay(6, 45), TimeOfDay(9, 0)).inOrder()
assertThat(content.alarms.all { it.scheduledDate == null && it.pause == null }).isTrue()
assertThat(content.timers.single().label).isEqualTo("Tea")
assertThat(content.settings.themeMode).isEqualTo(ThemeMode.BLACK)
assertThat(content.settings.defaults.dismissChallenge).isEqualTo(DismissChallenge.MATH)
// No timer vibration of its own yet: the alarms' default carries over.
assertThat(content.settings.defaults.timerVibrate).isFalse()
assertThat(content.settings.timerPresets).isEqualTo(TimerPresets.BUILT_IN)
assertThat(content.settings.bedtime).isNull()
}
@Test
fun `the file still has floret's envelope`() {
val format = de.jeanlucmakiola.floret.backup.BackupFormat(BACKUP_FORMAT, BACKUP_VERSION, BACKUP_MIN_VERSION)
val document = format.decode(fixture("clockula-backup-v2.json")) as BackupResult.Success
assertThat(document.value.exportedAtMillis).isEqualTo(1_700_000_000_000L)
assertThat(document.value.body.keys).containsExactly("alarms", "timers", "worldClocks", "settings")
}
@Test
fun `a backup re-saved with a byte-order mark still restores`() {
val decoded = BackupCodec.decode("\uFEFF" + fixture("clockula-backup-v1.json"))
assertThat(decoded).isInstanceOf(BackupResult.Success::class.java)
}
}
@@ -0,0 +1,25 @@
package de.jeanlucmakiola.clockula.domain.ring
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
/**
* The looped waveform, now shared by both ring paths (slice plan D8). Moved
* here with its assertion unchanged: the pattern did not change, only where it
* lives.
*/
class VibrationPatternTest {
@Test
fun `the vibration pattern is a loopable, non-empty pair of timings and amplitudes`() {
val timings = VibrationPattern.TIMINGS
val amplitudes = VibrationPattern.AMPLITUDES
assertThat(timings.size).isEqualTo(amplitudes.size)
assertThat(timings.size).isGreaterThan(0)
assertThat(VibrationPattern.REPEAT_INDEX).isIn(timings.indices.toList())
assertThat(timings.filter { it <= 0L }).isEmpty()
assertThat(amplitudes.filterNot { it in 0..255 }).isEmpty()
assertThat(amplitudes.filter { it > 0 }).isNotEmpty()
}
}
@@ -0,0 +1,65 @@
package de.jeanlucmakiola.clockula.domain.ring
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/**
* The ramp is a pure function of elapsed time, so "it never starts at silence
* and never overshoots" is an assertion rather than a listening test.
*/
class VolumeRampTest {
private val ramp = 15.seconds
@Test
fun `the ramp starts at the floor rather than at silence`() {
val level = VolumeRamp.levelAt(Duration.ZERO, ramp)
assertThat(level).isEqualTo(RingAudio.MIN_VOLUME)
}
@Test
fun `the ramp reaches full volume exactly at its end`() {
val level = VolumeRamp.levelAt(ramp, ramp)
assertThat(level).isEqualTo(1f)
}
@Test
fun `past the end the ramp stays at full volume`() {
val level = VolumeRamp.levelAt(30.seconds, ramp)
assertThat(level).isEqualTo(1f)
}
@Test
fun `a zero ramp is full volume immediately`() {
assertThat(VolumeRamp.levelAt(5.seconds, Duration.ZERO)).isEqualTo(1f)
assertThat(VolumeRamp.levelAt(Duration.ZERO, Duration.ZERO)).isEqualTo(1f)
}
@Test
fun `a negative elapsed reading never falls below the floor`() {
val level = VolumeRamp.levelAt((-5).seconds, ramp)
assertThat(level).isEqualTo(RingAudio.MIN_VOLUME)
}
@Test
fun `the ramp never gets quieter as it runs`() {
val samples = (0..100).map { step -> VolumeRamp.levelAt((ramp / 100) * step, ramp) }
assertThat(samples.zipWithNext().filter { (a, b) -> b < a }).isEmpty()
}
@Test
fun `every sample across and beyond the ramp stays inside the floor and the ceiling`() {
val samples = (0..100).map { step ->
VolumeRamp.levelAt((-5).seconds + (35.seconds / 100) * step, ramp)
}
assertThat(samples.filterNot { it >= RingAudio.MIN_VOLUME && it <= 1f }).isEmpty()
}
}
@@ -2,8 +2,9 @@ package de.jeanlucmakiola.clockula.ui.settings
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.clockula.backup.BackupFiles
import de.jeanlucmakiola.clockula.backup.BackupTooLargeException
import de.jeanlucmakiola.clockula.data.backup.BackupCodec
import de.jeanlucmakiola.clockula.data.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.clockula.testing.MainDispatcherExtension
import de.jeanlucmakiola.clockula.testing.backupHarness
import kotlinx.coroutines.flow.first
@@ -53,4 +54,19 @@ class BackupViewModelTest {
assertThat(viewModel.events.first()).isEqualTo(BackupEvent.ImportFailed(BackupProblem.NOT_APPLIED))
assertThat(viewModel.busy.value).isFalse()
}
@Test
fun `an oversized file is reported as too large`(@TempDir tempDir: Path) = runTest(main.dispatcher) {
val harness = backupHarness(tempDir)
val files = object : BackupFiles {
override suspend fun write(treeUri: String, content: String): Result<Unit> = error("unused")
override suspend fun read(documentUri: String): Result<String> = Result.failure(BackupTooLargeException())
}
val viewModel = BackupViewModel(harness.backupEngine, files)
viewModel.onImportFilePicked("content://backup")
assertThat(viewModel.events.first()).isEqualTo(BackupEvent.ImportFailed(BackupProblem.TOO_LARGE))
}
}
@@ -0,0 +1,41 @@
{
"format": "clockula-backup",
"version": 1,
"exportedAt": 1690000000000,
"alarms": [
{
"hour": 6,
"minute": 45,
"label": "Work",
"repeat_days": 31,
"vibrate": true,
"snooze_minutes": 5
},
{
"hour": 9,
"minute": 0,
"enabled": false
}
],
"timers": [
{
"label": "Tea",
"duration_millis": 180000
}
],
"worldClocks": [
{
"zone_id": "Asia/Tokyo"
}
],
"settings": {
"theme_mode": "BLACK",
"dynamic_color": false,
"default_snooze_minutes": 8,
"default_snooze_limit": 2,
"default_vibrate": false,
"default_volume_ramp_seconds": 30,
"default_dismiss_challenge": "MATH",
"default_timer_duration_millis": 600000
}
}
@@ -0,0 +1,96 @@
{
"format": "clockula-backup",
"version": 2,
"exportedAt": 1700000000000,
"alarms": [
{
"hour": 7,
"minute": 30,
"label": "Gym",
"repeat_days": 31,
"skip_next_occurrence": true,
"ringtone_uri": "content://media/42",
"vibrate": false,
"snooze_minutes": 7,
"snooze_limit": 2,
"volume_ramp_seconds": 30,
"dismiss_challenge": "MATH"
},
{
"hour": 6,
"minute": 0,
"label": "Flight",
"scheduled_date": "2026-12-24"
},
{
"hour": 8,
"minute": 15,
"label": "Weekend",
"enabled": false,
"repeat_days": 31,
"skip_next_occurrence": true,
"ringtone_uri": "content://media/42",
"vibrate": false,
"snooze_minutes": 7,
"snooze_limit": 2,
"volume_ramp_seconds": 30,
"dismiss_challenge": "MATH",
"pause_start": "2026-12-20",
"pause_end": "2027-01-06"
}
],
"timers": [
{
"label": "Pasta",
"duration_millis": 300000,
"ringtone_uri": "content://media/7",
"sort_order": 3
}
],
"worldClocks": [
{
"zone_id": "Europe/Berlin",
"label": "Home",
"sort_order": 2
}
],
"settings": {
"theme_mode": "DARK",
"dynamic_color": false,
"default_snooze_minutes": 9,
"default_snooze_limit": 4,
"default_vibrate": false,
"default_volume_ramp_seconds": 20,
"default_alarm_ringtone_uri": "content://media/1",
"default_timer_ringtone_uri": "content://media/2",
"default_timer_vibrate": true,
"default_timer_volume_ramp_seconds": 10,
"default_dismiss_challenge": "HOLD",
"home_zone_id": "America/New_York",
"volume_buttons_while_ringing": "SNOOZE",
"default_alarm_silence_after_minutes": 25,
"default_timer_silence_after_minutes": 0,
"automatic_local_clock": false,
"world_clock_show_seconds": true,
"world_clock_compact_home": true,
"timer_presets": [
60000,
120000,
600000
],
"bedtime": {
"enabled": true,
"bedtime_minutes": 1395,
"wake_minutes": 405,
"days": 31,
"reminder_minutes": 30,
"grayscale": false,
"dark_theme": false,
"hide_always_on_display": true
},
"screen_saver_style": "ANALOG",
"screen_saver_night_mode": true,
"quick_tile_duration_millis": 180000,
"week_start": "SATURDAY"
}
}
+4 -4
View File
@@ -87,7 +87,7 @@ kit module: the kit's roadmap keeps schedulers app-local.
|---|---|
| `domain/` | `Alarm.kt`, `Timer.kt`, `WorldClock.kt`, `Stopwatch.kt`, `ClockDefaults.kt`, `Ringtone.kt` (the silent and bundled-tone sentinels), `RepeatSummary.kt`, `AlarmDefaults.kt`. Plain Kotlin, no Android |
| `domain/alarm/` | the alarm engine's pure half: occurrences, the resolver, the ring state, the presentation and scheduling policies, the challenge gate, `VolumeButtonPolicy` (#18), and `AlarmSetCountdown`, what the "Alarm in …" chip says (#19). The *shared* ring vocabulary moved out to `domain/ring/` in M6 |
| `domain/ring/` | what both ring paths share: `AudioSourcePolicy`/`RingtoneSourceKind`, `RingFallbackPolicy`, `MediaRingPolicy`, `SilenceAfter`. The ramp (`VolumeRamp`) and the vibration waveform (`VibrationPattern`) live in floret-kit's `ring` module |
| `domain/ring/` | what both ring paths share: `RingAudio` (the ramp tick, the volume floor), `VolumeRamp`, `AudioSourcePolicy`/`RingtoneSourceKind`, `RingFallbackPolicy`, `VibrationPattern` |
| `domain/stopwatch/` | the stopwatch path's pure half: `StopwatchReadings` (the one reading the pill, the shade and the tab share), `LapStats` (best and worst), `StopwatchLaps` (the lap cap), `StopwatchNotificationPolicy` |
| `domain/timer/` | the timer path's pure half: `TimerReadings` (the app's one timer precedence), `TimerExpiry` (the sweep and the slot's value), `TimerRingPolicy`, `TimerNotificationPolicy`, `TimerPresets`, `TimerDurationEntry`, `TimerSettings`, `TimerRing` |
| `domain/time/` | `WallClock`, `ElapsedRealtimeClock`, `ZoneProvider` (`current()` and, since M8, `available()`, the device's tzdata), `BootId`, `Ticker`, and for the screen saver `ClockChanges` (a time, zone or 12/24-hour change while collected), `HourFormat` and `MinuteBoundary` |
@@ -112,13 +112,13 @@ kit module: the kit's roadmap keeps schedulers app-local.
| `data/ringtones/` | the two ringtone seams, `RingtoneCatalog` (the bundled and device alarm sounds, titles, playability, a SAF grant) and `RingtonePreviewer`, plus their `System*` implementations, and `MediaLibrary`/`SystemMediaLibrary`, the picker's view of other apps' `MediaBrowserService` libraries |
| `data/time/` | `SystemWallClock`, `SystemElapsedRealtimeClock`, `SystemZoneProvider`, `AndroidBootIdProvider`, `RealTicker`, `AndroidClockChanges` (a receiver for `TIME_SET`/`TIMEZONE_CHANGED` registered only while collected), `AndroidHourFormat` |
| `data/di/` | `DataModule`, `DatabaseModule`, `RepositoryModule`, `TimeModule`, `RingtoneModule`, `ZoneModule` (M8; one `@Binds`, `ZoneNames → IcuZoneNames`), `BackupModule` (M10) |
| `data/backup/` | the backup's data-layer half (M10): `BackupDto`/`BackupCodec` (the pure JSON wire format, `ignoreUnknownKeys`, strict on known fields), `BackupDao` (one `@Transaction` replace-all over alarms/timers/world clocks; no schema or version change), `BackupRepository(+Impl)`, mapping through the existing `AlarmMapper`/`TimerMapper`/`WorldClockMapper`, never a second copy |
| `data/backup/` | the backup's data-layer half (M10): `BackupDto`/`BackupCodec` (the pure JSON wire format, checked by floret `core-backup`'s `BackupFormat` envelope rules, `ignoreUnknownKeys`, strict on known fields), `BackupDao` (one `@Transaction` replace-all over alarms/timers/world clocks; no schema or version change), `BackupRepository(+Impl)`, mapping through the existing `AlarmMapper`/`TimerMapper`/`WorldClockMapper`, never a second copy |
| `alarm/` | `AlarmEngine` and the four seams it talks to (`AlarmScheduler`, `AlarmCapabilities`, `RingCoordinator`, `AlarmNotifier`), plus `AlarmIntents` |
| `alarm/android/` | the seams' Android implementations: AlarmManager, the capability reads, the service handle, the snoozed and upcoming notifications |
| `alarm/receiver/` | `AlarmFireReceiver`, `AlarmActionReceiver`, `SystemEventReceiver` |
| `alarm/ring/` | the alarm's ringing foreground service and its notifications. Its audio player moved to `ring/` in M6, shared with the timer's ring; the vibrator now comes from floret-kit's `ring` module |
| `alarm/ring/` | the alarm's ringing foreground service and its notifications. Its audio player and vibrator moved to `ring/` in M6, shared with the timer's ring |
| `alarm/di/` | `AlarmModule`: `@Binds` for the four seams |
| `ring/` | `RingAudioPlayer` (the ringing thing's sources and the media-app ring in front of floret-kit's `TonePlayer`), `ForegroundRingScreen`, the media-app ring. The `MediaPlayer` wrapper, `RingVibrator`, `RingWakeLock` and `startRingForeground` come from floret-kit's `ring` module, shared with Calendula's full-screen reminders. A build rule fails on a second `MediaPlayer` path |
| `ring/` | `RingAudioPlayer` and `RingVibrator`: one `MediaPlayer` wrapper and one vibrator for both ring paths. A build rule fails on a second one |
| `timer/` | `TimerEngine` and the three seams it talks to (`TimerScheduler`, `TimerServiceHandle`, `AlarmRingStatus` + `AlarmStateRingStatus`), plus `TimerIntents`, and `QuickTileTimer` (#26), the quick-timer tile's model and tap, through the engine and with no Android type |
| `timer/android/` | the seams' Android implementations: the one elapsed-realtime AlarmManager slot, the service handle |
| `timer/receiver/` | `TimerExpiryReceiver` (the slot arriving), `TimerActionReceiver` (the notification's buttons) |
+6 -1
View File
@@ -4,7 +4,11 @@
own data, written to (and read from) a user-chosen folder via SAF
(`docs/PLAN.md` §7). This file is the schema's source of truth; the codec
(`data/backup/BackupDto.kt`, `BackupCodec.kt`) implements exactly what is
written here.
written here. The envelope keys (`format`, `version`, `exportedAt`) and the
format-name, version-range, size and byte-order-mark rules are floret-kit `core-backup`'s `BackupFormat`,
shared with Calendula's settings backup. The file is still decoded in one
streaming pass into Clockula's own classes, which also accept a number
written as a string where floret's tree reader would not.
## Top level
@@ -30,6 +34,7 @@ written here.
tomorrow's, or a paused one back on. The file name stays
`clockula-backup-v1.json` so an existing backup folder keeps working.
- `exportedAt`: epoch milliseconds, informational only (not re-imported).
- A leading byte-order mark (an editor re-saving the file) is ignored.
## Parsing rules
+1 -1
View File
@@ -35,7 +35,7 @@ room = "2.8.3"
# package directly, so it is declared at the version that already resolves.
graphicsShapes = "1.0.1"
# M10 backup: a pure-Kotlin JSON codec so BackupCodecTest runs on the JVM.
kotlinxSerialization = "1.11.0"
kotlinxSerialization = "1.13.0"
# M10 widgets.
glance = "1.2.0"