package eu.friedcutlet.yokan.services.appicons import android.content.ComponentName import android.content.pm.PackageManager import android.os.Build import eu.friedcutlet.yokan.AndroidAppContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext actual fun createPlatformAppIconService(): AppIconService = AndroidAppIconService() private class AndroidAppIconService : AppIconService { override val capabilities = AppIconCapabilities(AppIconPlatform.Android, ExplicitAppIcons) private val mutex = Mutex() private val context get() = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" } private val manager get() = context.packageManager // Stable names must be retained across upgrades; never disable the deep-link target activity. private fun component(selection: AppIconSelection) = ComponentName(context, when (selection) { AppIconSelection.Default -> "eu.friedcutlet.yokan.LauncherDefault" ExplicitAppIcons[1] -> "eu.friedcutlet.yokan.LauncherToriiLight" ExplicitAppIcons[2] -> "eu.friedcutlet.yokan.LauncherToriiDark" else -> error("Unsupported icon") }) private fun enabled(selection: AppIconSelection): Boolean = when (manager.getComponentEnabledSetting(component(selection))) { PackageManager.COMPONENT_ENABLED_STATE_DEFAULT -> selection == AppIconSelection.Default PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> true else -> false } override suspend fun current(): AppIconSelection? = withContext(Dispatchers.IO) { mutex.withLock { ExplicitAppIcons.filter(::enabled).singleOrNull() } } override suspend fun apply(selection: AppIconSelection) = withContext(Dispatchers.IO) { require(selection in capabilities.choices) mutex.withLock { if (Build.VERSION.SDK_INT >= 33) { manager.setComponentEnabledSettings(ExplicitAppIcons.map { icon -> PackageManager.ComponentEnabledSetting(component(icon), if (icon == selection) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP) }) } else { // Older OS versions have no atomic batch. Enable the destination first so a // failure can leave duplicate icons, but never an installation without a launcher. manager.setComponentEnabledSetting(component(selection), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP) ExplicitAppIcons.filter { it != selection }.forEach { icon -> manager.setComponentEnabledSetting(component(icon), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP) } } check(ExplicitAppIcons.filter(::enabled).singleOrNull() == selection) } } }