package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.ProfileId import java.awt.Frame import java.io.File import kotlinx.coroutines.flow.MutableStateFlow actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = DesktopBackgroundScheduler(database) /** * Desktop has no OS job runner for JVM code; [ForegroundScheduler] ticks while the process lives, so * "background" work means keeping the process alive: close-to-tray plus an optional login item. * [schedule] runs on every settings save, which makes it the one place that reconciles both with * [eu.friedcutlet.yokan.database.DbSettings]. */ private class DesktopBackgroundScheduler(private val database: YokanDatabase) : BackgroundScheduler { override fun schedule( metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int, autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean, libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints, ) { val settings = database.settings() DesktopSession.closeToTray.value = settings.desktopCloseToTray runCatching { DesktopAutostart.apply(settings.desktopLaunchAtLogin) } .onFailure { AppLogger.warn("Login item: ${it.message.orEmpty()}") } } override fun cancelAll() = Unit } /** Process-wide desktop window state read by `Main.kt`. */ object DesktopSession { val closeToTray = MutableStateFlow(false) /** The main window, for fullscreen and as the parent of native file dialogs. */ @Volatile var frame: Frame? = null } /** OS login item that starts the packaged app hidden in the tray. */ object DesktopAutostart { const val TRAY_FLAG = "--tray" private const val LABEL = "eu.friedcutlet.yokan" private val os = System.getProperty("os.name").lowercase() private val home = System.getProperty("user.home") /** jpackage launcher, or null under Gradle/IDE where a login item would start bare `java`. */ private fun launcher(): String? = ProcessHandle.current().info().command().orElse(null) ?.takeUnless { File(it).nameWithoutExtension.equals("java", ignoreCase = true) } fun apply(enabled: Boolean) { val launcher = launcher() if (enabled && launcher == null) { AppLogger.warn("Login item skipped: not running from a packaged install.") return } when { os.contains("mac") -> reconcile( File(home, "Library/LaunchAgents/$LABEL.plist"), enabled, ) { """ Label$LABEL ProgramArguments$launcher$TRAY_FLAG RunAtLoad """.trimIndent() } os.contains("win") -> { val key = """HKCU\Software\Microsoft\Windows\CurrentVersion\Run""" val args = if (enabled) { listOf("reg", "add", key, "/v", "Yokan", "/t", "REG_SZ", "/d", "\"$launcher\" $TRAY_FLAG", "/f") } else { listOf("reg", "delete", key, "/v", "Yokan", "/f") } // reg delete exits non-zero when the value is already absent; that is the desired state. ProcessBuilder(args).redirectErrorStream(true).start().waitFor() } else -> reconcile( File(home, ".config/autostart/yokan.desktop"), enabled, ) { """ [Desktop Entry] Type=Application Name=Yokan Exec=$launcher $TRAY_FLAG X-GNOME-Autostart-enabled=true """.trimIndent() } } } private fun reconcile(file: File, enabled: Boolean, content: () -> String) { if (!enabled) { file.delete() return } val text = content() if (file.exists() && file.readText() == text) return file.parentFile.mkdirs() file.writeText(text) } }