25 changed files with 73 additions and 527 deletions

No files matched your search

+1
View File
@@ -217,6 +217,7 @@ dependencies {
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,6 +7,7 @@ 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
@@ -23,7 +24,7 @@ class AndroidAlarmCapabilities @Inject constructor(
override fun snapshot(): CapabilitySnapshot = CapabilitySnapshot(
canScheduleExactAlarms = canScheduleExactAlarms(),
canUseFullScreenIntent = canUseFullScreenIntent(),
canUseFullScreenIntent = context.canUseFullScreenIntent(),
notificationsEnabled = notifications().areNotificationsEnabled(),
)
@@ -34,13 +35,6 @@ 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) HandoffWakeLock.acquire(context, "clockula:alarm-fire")
if (action == AlarmIntents.ACTION_FIRE) RingWakeLock.handOff(context, "clockula:alarm-fire")
val pendingResult = goAsync()
scope.launch {
try {
@@ -6,10 +6,7 @@ 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
@@ -21,8 +18,10 @@ 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
@@ -58,7 +57,7 @@ class AlarmRingService : Service() {
private val audio by lazy { RingAudioPlayer(this) }
private val vibrator by lazy { RingVibrator(this) }
private var wakeLock: PowerManager.WakeLock? = null
private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, WAKE_LOCK_TIMEOUT_MILLIS) }
private var ringing: Job? = null
/** The alarm this service last asked a ring screen for. */
@@ -94,7 +93,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.
acquireWakeLock()
wakeLock.acquire()
ringing = scope.launch {
val session = engine.ringSession()
if (session == null) {
@@ -184,26 +183,7 @@ class AlarmRingService : Service() {
private fun startForeground(notification: Notification) {
posted = 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) }
}
startRingForeground(RingNotifications.RING_NOTIFICATION_ID, notification)
}
private fun releaseRing() {
@@ -211,8 +191,7 @@ class AlarmRingService : Service() {
ringing = null
audio.stop()
vibrator.stop()
wakeLock?.let { if (it.isHeld) runCatching { it.release() } }
wakeLock = null
wakeLock.release()
}
private fun stop() {
@@ -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 `domain/ring/RingAudio`, shared with the
* chain's own constants live in floret-kit's `VolumeRamp`, shared with the
* timer's ring.
*/
object AlarmRing {
@@ -45,13 +45,3 @@ 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] (`RingAudio.MIN_VOLUME`..1) on the way to [target]. */
/** The index for a ramp [level] (`VolumeRamp.MIN_LEVEL`..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)
@@ -1,17 +0,0 @@
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
}
@@ -1,19 +0,0 @@
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 = inCall(context),
inCall = context.isInCall(),
)
if (!DirectLaunchPolicy.opensDirectly(facts)) return
// A refused start costs nothing: the notification is up either way.
@@ -80,11 +80,4 @@ 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
}
}
@@ -1,28 +0,0 @@
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,35 +1,28 @@
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.clockula.domain.ring.VolumeRamp
import de.jeanlucmakiola.floret.ring.TonePlayer
import de.jeanlucmakiola.floret.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
/**
* `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].)
* 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.
*
* [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
@@ -39,18 +32,10 @@ import kotlin.time.Duration.Companion.seconds
*/
class RingAudioPlayer(private val context: Context) {
private val audioManager: AudioManager = context.getSystemService(AudioManager::class.java)
private val tones = TonePlayer(context)
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]). */
@@ -59,8 +44,10 @@ 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 `prepare`, a music app that answers late — sees it is
* no longer wanted and releases what it opened rather than starting it.
* 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.
*/
private var generation: Int = 0
@@ -104,9 +91,7 @@ class RingAudioPlayer(private val context: Context) {
ramp = null
mediaRing?.stop()
mediaRing = null
player?.let(::release)
player = null
abandonFocus()
tones.stop()
}
/** False when there is no media source, or it would not be heard, or the app would not play. */
@@ -143,12 +128,8 @@ class RingAudioPlayer(private val context: Context) {
}
/**
* 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
* 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
* [onSilenced] when none is left — a ring never goes quiet mid-alarm.
*/
private suspend fun startPlayer(
@@ -158,47 +139,9 @@ class RingAudioPlayer(private val context: Context) {
rampFor: Duration,
rampStart: Duration,
onSilenced: () -> Unit,
from: Int = 0,
): Boolean {
if (ring != generation) return false
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
return tones.play(scope, sources(ringtoneUri), rampFor, rampStart, onSilenced)
}
/**
@@ -218,7 +161,7 @@ class RingAudioPlayer(private val context: Context) {
onSilenced: () -> Unit,
) {
media.setLevel(VolumeRamp.levelAt(rampStart, rampFor))
ramp = launchRamp(scope, rampFor, rampStart, media::setLevel)
ramp = VolumeRamp.launch(scope, rampFor, rampStart, media::setLevel)
watchdog = scope.launch {
var stall = MediaRingPolicy.Stall()
while (isActive && ring == generation) {
@@ -235,22 +178,6 @@ 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
@@ -268,42 +195,4 @@ 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
}
}
@@ -1,46 +0,0 @@
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)
HandoffWakeLock.acquire(context, "clockula:timer-expiry")
RingWakeLock.handOff(context, "clockula:timer-expiry")
val pendingResult = goAsync()
scope.launch {
try {
@@ -4,10 +4,7 @@ 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
@@ -22,12 +19,14 @@ 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
@@ -87,7 +86,7 @@ class TimerService : Service() {
private val audio by lazy { RingAudioPlayer(this) }
private val vibrator by lazy { RingVibrator(this) }
private var wakeLock: PowerManager.WakeLock? = null
private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, WAKE_LOCK_TIMEOUT_MILLIS) }
private var collector: Job? = null
/** The two independent delays the engine hands down (D20). */
@@ -245,7 +244,7 @@ class TimerService : Service() {
releaseRing()
sounding = decision.subjectId
soundingSettings = decision.settings
acquireWakeLock()
wakeLock.acquire()
// 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.
@@ -331,38 +330,19 @@ class TimerService : Service() {
}
private fun startForeground(notification: 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)
}
// systemExempted, the same type and justification as the alarm's
// ringing service (D6).
startRingForeground(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?.let { if (it.isHeld) runCatching { it.release() } }
wakeLock = null
wakeLock.release()
}
private fun stop() {
@@ -2,7 +2,6 @@ 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
@@ -17,6 +16,7 @@ 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,6 +39,8 @@ 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 {
@@ -106,21 +108,6 @@ 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,35 +1,23 @@
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
@@ -37,7 +25,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.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.ring.RingBadge
/**
* The ring screen itself: the time, the label, snooze, and the dismiss
@@ -68,7 +56,7 @@ internal fun RingScreen(
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
RingingBadge()
RingBadge(icon = Icons.Rounded.Alarm)
Text(
text = formatTime(state.time),
style = MaterialTheme.typography.displayLarge,
@@ -140,35 +128,6 @@ 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,7 +1,6 @@
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
@@ -15,6 +14,7 @@ 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,9 +34,7 @@ class TimerRingActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
// As AlarmRingActivity: shown over the lock screen, display on, and
// kept on for this window's life only.
setShowWhenLocked(true)
setTurnScreenOn(true)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
showOverLockScreen()
setContent {
ClockulaTheme {
@@ -1,39 +1,27 @@
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.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.ring.RingBadge
/**
* The timer ring screen: the label, "Finished", and the notification's two
@@ -53,7 +41,7 @@ internal fun TimerRingScreen(
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
TimerBadge()
RingBadge(icon = Icons.Rounded.Timer)
Text(
text = stringResource(R.string.timer_finished),
style = MaterialTheme.typography.displayMedium,
@@ -83,30 +71,3 @@ 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),
)
}
}
@@ -33,6 +33,7 @@ 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
@@ -145,8 +146,10 @@ 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 ->
Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, Uri.parse("package:${context.packageName}"))
SelfCheckFix.OpenFullScreenIntentSettings -> {
context.openFullScreenIntentSettings()
return
}
SelfCheckFix.OpenBatteryOptimizationSettings ->
Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
SelfCheckFix.OpenAppDetailsSettings ->
@@ -214,7 +214,8 @@ class ArchitectureRulesTest {
/**
* M6 D31: "reuses M3's audio path" made mechanical. One `MediaPlayer`
* wrapper for both ring paths and one for the picker's preview; a third
* wrapper for both ring paths (floret-kit's `TonePlayer`, behind
* `ring/RingAudioPlayer`) 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.
*/
@@ -227,6 +228,16 @@ 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
@@ -241,6 +252,7 @@ class ArchitectureRulesTest {
"MediaPlayer",
"RingAudioPlayer",
"RingVibrator",
"TonePlayer",
"Vibrator",
"AudioManager",
// D3's "no wake lock, ever" is half of the promise this rule makes,
@@ -1,25 +0,0 @@
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()
}
}
@@ -1,65 +0,0 @@
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()
}
}
+3 -3
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: `RingAudio` (the ramp tick, the volume floor), `VolumeRamp`, `AudioSourcePolicy`/`RingtoneSourceKind`, `RingFallbackPolicy`, `VibrationPattern` |
| `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/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` |
@@ -116,9 +116,9 @@ kit module: the kit's roadmap keeps schedulers app-local.
| `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 and vibrator moved to `ring/` in M6, shared with the timer's ring |
| `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/di/` | `AlarmModule`: `@Binds` for the four seams |
| `ring/` | `RingAudioPlayer` and `RingVibrator`: one `MediaPlayer` wrapper and one vibrator for both ring paths. A build rule fails on a second one |
| `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 |
| `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) |