diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 4cd51d44..daee1254 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -157,10 +157,20 @@ class ReminderChannels @Inject constructor( /** * Run [block] with [calendarId]'s channel held: no sound pick or sync can - * move or retire it until [block] returns. Null when the calendar is gone. + * move or retire it until [block] returns. Null, without running [block], + * when the calendar is gone or its channel can't be made; [block]'s own + * failures propagate. */ @Synchronized - fun withChannel(calendarId: Long, block: (String) -> T): T? = channelFor(calendarId)?.let(block) + fun withChannel(calendarId: Long, block: (String) -> T): T? { + val channelId = try { + channelFor(calendarId) + } catch (e: Exception) { + Log.w(TAG, "No channel for calendar $calendarId", e) + null + } + return channelId?.let(block) + } /** What the system currently lets through for [calendarIds]' reminders (#145). */ fun status(calendarIds: Collection): ReminderChannelStatus { @@ -174,6 +184,10 @@ class ReminderChannels @Inject constructor( return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys)) } + /** A "Silent" (low) channel keeps its sound but never plays it. */ + private fun NotificationChannel.audibleSound(): Uri? = + sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW } + /** * The sound each of [calendarIds]' channels plays; null is silent. A * calendar whose channel doesn't exist yet is left out. @@ -182,7 +196,7 @@ class ReminderChannels @Inject constructor( val byId = manager.notificationChannels.associateBy { it.id } val versions = currentVersions(byId.keys) return calendarIds.mapNotNull { id -> - byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.sound } + byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() } }.toMap() } @@ -200,7 +214,7 @@ class ReminderChannels @Inject constructor( val floors = calendarIds .filter { reminderChannelId(it, current[it] ?: 0) in existingIds } .associateWith { (current[it] ?: 0) + 1 } - if (floors.isEmpty()) return true + if (floors.isEmpty()) return false return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } @@ -215,8 +229,12 @@ class ReminderChannels @Inject constructor( val current = currentReminderChannelVersions(byId.keys, emptyMap()) var allApplied = true versions.forEach { (calendarId, version) -> - val from = current[calendarId]?.takeIf { it < version } ?: return@forEach - val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach + val from = current[calendarId]?.takeIf { it < version } + val old = from?.let { byId[reminderChannelId(calendarId, it)] } + if (old == null) { + allApplied = false + return@forEach + } try { // Picking a sound asks for one, which a "Silent" (low) channel would never play. val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index d9b196ae..81d9a791 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -87,15 +87,10 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" ยท ") - val posted = try { - // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. - channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) } - } catch (e: Exception) { - Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) - return - } + // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. + val posted = channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) } if (posted == null) { - Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}") } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index be5b6fcf..d926912e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -1,7 +1,6 @@ package de.jeanlucmakiola.calendula.ui.settings import android.Manifest -import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.os.Build @@ -127,9 +126,11 @@ internal fun NotificationsScreen( val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle() val sounds = loadedSounds.orEmpty() val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed) + val soundUnreadableMessage = stringResource(R.string.settings_notification_sound_unreadable) LaunchedEffect(Unit) { - viewModel.soundFailed.collect { - Toast.makeText(context, soundFailedMessage, Toast.LENGTH_LONG).show() + viewModel.soundFailed.collect { failure -> + val message = if (failure == SoundFailure.Unreadable) soundUnreadableMessage else soundFailedMessage + Toast.makeText(context, message, Toast.LENGTH_LONG).show() } } // ALL_CALENDARS, a calendar id, or null when no pick is pending. @@ -157,7 +158,8 @@ internal fun NotificationsScreen( // A missing or mixed sound preselects Default; a silent one, Silent. val preselect = if (current == null) DEFAULT_NOTIFICATION_URI else current.uri soundPicker.launch(notificationSoundPickerIntent(preselect, pickSoundTitle)) - } catch (e: ActivityNotFoundException) { + } catch (e: RuntimeException) { + // No picker, or one that refuses to start: the system screen still has the sound. soundTarget = null if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index 261c1c60..c4902c6b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -140,3 +140,6 @@ data class SpecialDatesUiState( /** A reminder channel's sound: null [uri] is silent; [title] is null when it can't be resolved. */ data class ReminderSound(val uri: Uri?, val title: String?) + +/** Why a picked reminder sound wasn't applied. */ +enum class SoundFailure { NotApplied, Unreadable } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 56cb4ed5..def50ab1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -399,10 +399,10 @@ class SettingsViewModel @Inject constructor( /** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */ val channelSounds: StateFlow?> = _channelSounds.asStateFlow() - private val _soundFailed = Channel(Channel.CONFLATED) + private val _soundFailed = Channel(Channel.CONFLATED) - /** Emits when a picked sound couldn't be applied to every calendar; kept until the screen collects it. */ - val soundFailed: Flow = _soundFailed.receiveAsFlow() + /** Emits when a picked sound couldn't be applied; kept until the screen collects it. */ + val soundFailed: Flow = _soundFailed.receiveAsFlow() private val soundTitles = mutableMapOf() @@ -413,12 +413,18 @@ class SettingsViewModel @Inject constructor( val sounds = onChannels { sounds(calendarIds) } ?: return@launch _channelSounds.value = withContext(io) { sounds.mapValues { (_, uri) -> - ReminderSound(uri, uri?.let { synchronized(soundTitles) { soundTitles.getOrPut(it) { appContext.ringtoneTitle(it) } } }) + ReminderSound(uri, uri?.let(::soundTitle)) } } } } + /** A sound's title, cached unless it is a "default" alias whose target can change. */ + private fun soundTitle(uri: Uri): String? { + if (uri.authority == Settings.AUTHORITY) return appContext.ringtoneTitle(uri) + return synchronized(soundTitles) { soundTitles.getOrPut(uri) { appContext.ringtoneTitle(uri) } } + } + /** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */ fun setReminderSound(calendarId: Long, sound: Uri?) = applySound(sound) { setSound(listOf(calendarId), sound, createMissing = true) @@ -445,17 +451,20 @@ class SettingsViewModel @Inject constructor( /** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */ private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) { viewModelScope.launch { - val applied = withContext(io + NonCancellable) { + val failure = withContext(io + NonCancellable) { try { // The system plays the sound but checks that Calendula could read it. - if (sound != null && !canRead(sound)) return@withContext false - reminderChannels.block() + when { + sound != null && !canRead(sound) -> SoundFailure.Unreadable + reminderChannels.block() -> null + else -> SoundFailure.NotApplied + } } catch (e: Exception) { Log.w("SettingsViewModel", "Could not set the reminder sound", e) - false + SoundFailure.NotApplied } } - if (!applied) _soundFailed.trySend(Unit) + failure?.let(_soundFailed::trySend) refreshChannelStatus(visibleCalendars.first().map { it.id }) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8943542d..5cb0d084 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -741,7 +741,8 @@ Default (%1$s) Custom sound - Couldn\'t change the sound for every calendar + Couldn\'t change the notification sound + Calendula can\'t play this sound. Pick another one. Differs per calendar More notification settings Vibration, pop-ups and more for each calendar, in system settings