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 ec9675b3..3ef3f2a4 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 @@ -54,7 +54,7 @@ class ReminderChannels @Inject constructor( val manager = manager val existing = manager.notificationChannels val existingIds = existing.mapTo(HashSet()) { it.id } - val versions = currentVersions(existingIds) + val versions = currentVersions(existingIds).also { knownVersions = it } if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return val groups = manager.notificationChannelGroups val plan = plan(calendars, existing, groups.map { it.id }, versions, showingChannelIds()) @@ -83,6 +83,14 @@ class ReminderChannels @Inject constructor( versions, ) + /** + * The current versions last resolved under the lock ([sync], [channelFor]). + * Only [recreate], under the same lock, moves a calendar higher and updates + * it, so a hit whose channel still exists is current. + */ + @Volatile + private var knownVersions: Map = emptyMap() + private fun currentVersions(existingChannelIds: Collection): Map = currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) @@ -104,8 +112,12 @@ class ReminderChannels @Inject constructor( @Synchronized fun channelFor(calendarId: Long): String? { val manager = manager + knownVersions[calendarId]?.let { version -> + val known = reminderChannelId(calendarId, version) + if (manager.getNotificationChannel(known) != null) return known + } val existing = manager.notificationChannels - val versions = currentVersions(existing.map { it.id }) + val versions = currentVersions(existing.map { it.id }).also { knownVersions = it } val id = reminderChannelId(calendarId, versions[calendarId] ?: 0) if (existing.any { it.id == id }) return id val calendars = try { @@ -163,40 +175,49 @@ class ReminderChannels @Inject constructor( * Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is * fixed once created, so each moves to a new channel version carrying over * everything else, and the old one retires (#518). Calendars without a - * channel are skipped unless [createMissing]. + * channel are skipped unless [createMissing]. Returns whether every move + * went through. */ - suspend fun setSound(calendarIds: Collection, sound: Uri?, createMissing: Boolean) { + suspend fun setSound(calendarIds: Collection, sound: Uri?, createMissing: Boolean): Boolean { if (createMissing) calendarIds.forEach(::channelFor) val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id } val current = currentVersions(existingIds) val floors = calendarIds .filter { reminderChannelId(it, current[it] ?: 0) in existingIds } .associateWith { (current[it] ?: 0) + 1 } - if (floors.isEmpty()) return - recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) + if (floors.isEmpty()) return true + return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } /** Create each calendar's [versions] from its current channel, then retire the old one. */ @Synchronized - private fun recreate(versions: Map, sound: Uri?) { + private fun recreate(versions: Map, sound: Uri?): Boolean { val manager = manager val byId = manager.notificationChannels.associateBy { it.id } val current = currentReminderChannelVersions(byId.keys, emptyMap()) val showing = showingChannelIds() + var allApplied = true versions.forEach { (calendarId, version) -> val from = current[calendarId]?.takeIf { it < version } ?: return@forEach val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach - manager.createNotificationChannel( - NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply { - description = old.description - old.group?.let { group = it } - inheritFrom(old) - setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) - }, - ) - if (old.id !in showing) manager.deleteNotificationChannel(old.id) + try { + manager.createNotificationChannel( + NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply { + description = old.description + old.group?.let { group = it } + inheritFrom(old) + setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + }, + ) + knownVersions = knownVersions + (calendarId to version) + if (old.id !in showing) manager.deleteNotificationChannel(old.id) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not move calendar $calendarId to a new sound", e) + allApplied = false + } } lastSync = null + return allApplied } private fun plan( @@ -246,9 +267,10 @@ class ReminderChannels @Inject constructor( } /** - * Carry a channel's sound, vibration, lights, badge and lock-screen choice - * over to a new one: the legacy channel to a per-calendar one on upgrade, or - * a calendar's channel to its next version (#518). + * Carry a channel's sound, vibration, lights and badge over to a new one: the + * legacy channel to a per-calendar one on upgrade, or a calendar's channel to + * its next version (#518). Lock-screen visibility and a DND override can't + * follow: the system resets both on channels an app creates. */ private fun NotificationChannel.inheritFrom(template: NotificationChannel) { setSound(template.sound, template.audioAttributes) @@ -258,8 +280,6 @@ class ReminderChannels @Inject constructor( enableLights(template.shouldShowLights()) lightColor = template.lightColor setShowBadge(template.canShowBadge()) - // The system only keeps a private or secret choice; "public" resets to its default. - lockscreenVisibility = template.lockscreenVisibility // Only honoured with Do Not Disturb access, so usually left to the user. setBypassDnd(template.canBypassDnd()) } @@ -272,12 +292,7 @@ class ReminderChannels @Inject constructor( private fun retireLegacyChannel(): Boolean { val manager = manager if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true - val showing = runCatching { - manager.activeNotifications.any { it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID } - }.getOrElse { e -> - Log.w(TAG, "Could not read active notifications", e) - true - } + val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds() if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) return !showing } @@ -293,7 +308,7 @@ class ReminderChannels @Inject constructor( const val TAG = "ReminderChannels" val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT) + .setUsage(AudioAttributes.USAGE_NOTIFICATION) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build() } 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 f7a4fd46..47bd2cd7 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 @@ -65,15 +65,6 @@ class ReminderNotifier @Inject constructor( /** Post [alert], unless its calendar is silenced or gone. */ suspend fun post(alert: ReminderAlert) { if (isSilenced(alert.calendarId)) return - val channelId = try { - channels.channelFor(alert.calendarId) ?: run { - Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") - return - } - } catch (e: Exception) { - Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) - return - } val title = displayTitle(alert) val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) @@ -96,6 +87,16 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" ยท ") + // Resolved last, so a sound picked meanwhile (#518) can't retire it before notify. + val channelId = try { + channels.channelFor(alert.calendarId) ?: run { + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + return + } + } catch (e: Exception) { + Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + return + } val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) 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 26254258..be5b6fcf 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 @@ -8,6 +8,7 @@ import android.os.Build import android.os.PowerManager import android.provider.Settings import android.provider.Settings.System.DEFAULT_NOTIFICATION_URI +import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility @@ -27,6 +28,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -122,7 +124,14 @@ internal fun NotificationsScreen( context.openNotificationSettings() } } - val sounds by viewModel.channelSounds.collectAsStateWithLifecycle() + val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle() + val sounds = loadedSounds.orEmpty() + val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed) + LaunchedEffect(Unit) { + viewModel.soundFailed.collect { + Toast.makeText(context, soundFailedMessage, Toast.LENGTH_LONG).show() + } + } // ALL_CALENDARS, a calendar id, or null when no pick is pending. var soundTarget by rememberSaveable { mutableStateOf(null) } val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> @@ -136,7 +145,8 @@ internal fun NotificationsScreen( } } val pickSoundTitle = stringResource(R.string.settings_notification_sound) - val pickSound: (Long) -> Unit = { target -> + val pickSound: (Long) -> Unit = pick@{ target -> + if (soundTarget != null) return@pick val current = if (target == ALL_CALENDARS) { (sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound } else { @@ -179,7 +189,7 @@ internal fun NotificationsScreen( if (calendarIds.isNotEmpty()) { GroupedRow( title = stringResource(R.string.settings_notification_sound), - summary = globalSoundLabel(sounds, calendarIds), + summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) }, position = Position.Middle, onClick = { pickSound(ALL_CALENDARS) }, ) @@ -293,7 +303,7 @@ internal fun NotificationsScreen( state = state, notifying = notifying, blocked = blocked, - soundLabel = soundLabel(sounds[calendar.id]), + soundLabel = loadedSounds?.let { soundLabel(it[calendar.id]) }, onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, onPickSound = { pickSound(calendar.id) }, onOpenSettings = { openCalendarSettings(calendar.id) }, @@ -397,7 +407,7 @@ private fun CalendarNotificationRows( state: SettingsUiState, notifying: Boolean, blocked: Boolean, - soundLabel: String, + soundLabel: String?, onSetNotifying: (Boolean) -> Unit, onPickSound: () -> Unit, onOpenSettings: () -> Unit, 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 7f341726..f4bf87b6 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 @@ -53,6 +53,7 @@ import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -390,10 +391,15 @@ class SettingsViewModel @Inject constructor( private var channelStatusJob: Job? = null - private val _channelSounds = MutableStateFlow>(emptyMap()) + private val _channelSounds = MutableStateFlow?>(null) - /** Each calendar's reminder sound (#518); a calendar without a channel yet is absent. */ - val channelSounds: StateFlow> = _channelSounds.asStateFlow() + /** 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 = MutableSharedFlow(extraBufferCapacity = 1) + + /** Emits when a picked sound couldn't be applied to every calendar. */ + val soundFailed: SharedFlow = _soundFailed fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() @@ -416,21 +422,26 @@ class SettingsViewModel @Inject constructor( * that only get a channel when something posts are left alone. */ fun setReminderSoundForAll(sound: Uri?) = applySound { - sync() + try { + sync() + } catch (e: Exception) { + Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e) + } setSound(visibleCalendars.first().map { it.id }, sound, createMissing = false) } - private fun applySound(block: suspend ReminderChannels.() -> Unit) { + /** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */ + private fun applySound(block: suspend ReminderChannels.() -> Boolean) { viewModelScope.launch { - withContext(io) { + val applied = withContext(io + NonCancellable) { try { reminderChannels.block() - } catch (e: CancellationException) { - throw e } catch (e: Exception) { Log.w("SettingsViewModel", "Could not set the reminder sound", e) + false } } + if (!applied) _soundFailed.tryEmit(Unit) 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 cc0a428f..8943542d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -741,6 +741,7 @@ Default (%1$s) Custom sound + Couldn\'t change the sound for every calendar Differs per calendar More notification settings Vibration, pop-ups and more for each calendar, in system settings diff --git a/floret-kit b/floret-kit index 8dc244fc..40ef6992 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 8dc244fc331935ca0f7f9f04715fec928ebc91af +Subproject commit 40ef6992ae205a880272c47e396269d336762d83