Yokan / rebuild
Course 1 8624561

BackgroundScheduler.desktop.kt

composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.desktop.kt

implementation113 lines
1package eu.friedcutlet.yokan.services.scheduling23import eu.friedcutlet.yokan.services.logging.AppLogger4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.domain.ProfileId6import java.awt.Frame7import java.io.File8import kotlinx.coroutines.flow.MutableStateFlow910actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler =11    DesktopBackgroundScheduler(database)1213/**14 * Desktop has no OS job runner for JVM code; [ForegroundScheduler] ticks while the process lives, so15 * "background" work means keeping the process alive: close-to-tray plus an optional login item.16 * [schedule] runs on every settings save, which makes it the one place that reconciles both with17 * [eu.friedcutlet.yokan.database.DbSettings].18 */19private class DesktopBackgroundScheduler(private val database: YokanDatabase) : BackgroundScheduler {20    override fun schedule(21        metadataRefreshMinutes: Long,22        libraryUpdateMinutes: Long,23        libraryUpdateDailyAtMinutes: Int,24        autoSyncMinutes: Long,25        autoBackupHours: Long,26        requireUnmetered: Boolean,27        libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,28    ) {29        val settings = database.settings()30        DesktopSession.closeToTray.value = settings.desktopCloseToTray31        runCatching { DesktopAutostart.apply(settings.desktopLaunchAtLogin) }32            .onFailure { AppLogger.warn("Login item: ${it.message.orEmpty()}") }33    }3435    override fun cancelAll() = Unit36}3738/** Process-wide desktop window state read by `Main.kt`. */39object DesktopSession {40    val closeToTray = MutableStateFlow(false)4142    /** The main window, for fullscreen and as the parent of native file dialogs. */43    @Volatile var frame: Frame? = null44}4546/** OS login item that starts the packaged app hidden in the tray. */47object DesktopAutostart {48    const val TRAY_FLAG = "--tray"49    private const val LABEL = "eu.friedcutlet.yokan"50    private val os = System.getProperty("os.name").lowercase()51    private val home = System.getProperty("user.home")5253    /** jpackage launcher, or null under Gradle/IDE where a login item would start bare `java`. */54    private fun launcher(): String? = ProcessHandle.current().info().command().orElse(null)55        ?.takeUnless { File(it).nameWithoutExtension.equals("java", ignoreCase = true) }5657    fun apply(enabled: Boolean) {58        val launcher = launcher()59        if (enabled && launcher == null) {60            AppLogger.warn("Login item skipped: not running from a packaged install.")61            return62        }63        when {64            os.contains("mac") -> reconcile(65                File(home, "Library/LaunchAgents/$LABEL.plist"),66                enabled,67            ) {68                """69                <?xml version="1.0" encoding="UTF-8"?>70                <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">71                <plist version="1.0"><dict>72                <key>Label</key><string>$LABEL</string>73                <key>ProgramArguments</key><array><string>$launcher</string><string>$TRAY_FLAG</string></array>74                <key>RunAtLoad</key><true/>75                </dict></plist>76                """.trimIndent()77            }78            os.contains("win") -> {79                val key = """HKCU\Software\Microsoft\Windows\CurrentVersion\Run"""80                val args = if (enabled) {81                    listOf("reg", "add", key, "/v", "Yokan", "/t", "REG_SZ", "/d", "\"$launcher\" $TRAY_FLAG", "/f")82                } else {83                    listOf("reg", "delete", key, "/v", "Yokan", "/f")84                }85                // reg delete exits non-zero when the value is already absent; that is the desired state.86                ProcessBuilder(args).redirectErrorStream(true).start().waitFor()87            }88            else -> reconcile(89                File(home, ".config/autostart/yokan.desktop"),90                enabled,91            ) {92                """93                [Desktop Entry]94                Type=Application95                Name=Yokan96                Exec=$launcher $TRAY_FLAG97                X-GNOME-Autostart-enabled=true98                """.trimIndent()99            }100        }101    }102103    private fun reconcile(file: File, enabled: Boolean, content: () -> String) {104        if (!enabled) {105            file.delete()106            return107        }108        val text = content()109        if (file.exists() && file.readText() == text) return110        file.parentFile.mkdirs()111        file.writeText(text)112    }113}114

Search chapters, reference and source filenames.