import { app, BrowserWindow, net, protocol, shell } from 'electron' import path from 'path' import { pathToFileURL } from 'url' import { IpcChannels } from '@shared/ipc-channels' import { isSteamRunning, startVotedItemsSync, onFailedVotesChange, bindSteamToWindow } from './services/steam.service' import { initLibrary, checkUnavailableWallpapers, backfillResolutions, onHdrDetected, queueHdrCheck } from './services/library.service' import { startWatcher } from './services/watcher.service' import { checkOutdatedBackups } from './services/backup.service' import { registerAllHandlers } from './ipc' import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.service' import { getTrayEnabled, getAutostartPlaylistId, getKillLweOnQuit } from './services/config.service' import { createTray } from './services/tray.service' import { initPlaylistPlayer, startPlaylist } from './services/playlist-player.service' import { killAllLweProcesses, getLweStatus } from './services/lwe.service' import { initDisplay } from './services/display.service' import { initSchedule } from './services/schedule.service' import { hasStatusNotifierHost } from './utils/platform' const startMinimized = process.argv.includes('--minimized') let isQuitting = false let hasKilledLweOnQuit = false const BACKGROUND_SYNC_INTERVAL_MS = 3 * 60 * 1000 const TRAY_HOST_WAIT_MS = 10_000 // Keeps "liked" state and library availability fresh without the user having to restart the // app or click "Check unavailable" - votes cast on Steam directly (client, community website) // and items taken down from the Workshop both eventually show up on their own. function startBackgroundSync(win: BrowserWindow): void { startVotedItemsSync((ids) => { if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_VOTED_IDS_CHANGED, ids) }) onFailedVotesChange((failed) => { if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_FAILED_VOTES_CHANGED, failed) }) const syncResolutions = async (): Promise => { if (await backfillResolutions() && !win.isDestroyed()) { win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED) } } onHdrDetected(() => { if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED) }) const syncOutdatedBackups = async (): Promise => { try { if (await checkOutdatedBackups() && !win.isDestroyed()) { win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED) } } catch (err) { console.warn('[Backup] Outdated check failed:', err) } } win.webContents.once('did-finish-load', () => { void syncResolutions() void syncOutdatedBackups() queueHdrCheck() }) const pushSteamStatus = (): void => { if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_STEAM_STATUS, isSteamRunning()) } win.on('show', pushSteamStatus) win.on('restore', pushSteamStatus) setInterval(async () => { if (win.isDestroyed()) return const running = isSteamRunning() win.webContents.send(IpcChannels.EVENT_STEAM_STATUS, running) await syncOutdatedBackups() if (!running) return try { const { changed } = await checkUnavailableWallpapers() if (changed && !win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED) await syncResolutions() } catch { // transient Steam hiccup - try again next tick } }, BACKGROUND_SYNC_INTERVAL_MS) } // gives a panel that starts after us until the deadline, then shows the window function showWindowUnlessTrayAppears(win: BrowserWindow): void { const deadline = Date.now() + TRAY_HOST_WAIT_MS const timer = setInterval(() => { if (win.isDestroyed() || win.isVisible() || hasStatusNotifierHost(0)) { clearInterval(timer) } else if (Date.now() >= deadline) { clearInterval(timer) win.show() } }, 1000) } function createWindow(): BrowserWindow { const startHidden = startMinimized && getTrayEnabled() const win = new BrowserWindow({ width: 1280, height: 800, minWidth: 900, minHeight: 600, backgroundColor: '#0f0f0f', titleBarStyle: 'hiddenInset', show: !startHidden, webPreferences: { preload: path.join(__dirname, '../preload/index.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: false } }) win.webContents.setWindowOpenHandler(({ url }) => { shell.openExternal(url) return { action: 'deny' } }) // When the tray is enabled, closing the window hides it instead of quitting so the // tray icon remains the only way back in (and the app keeps running for playlists). // Without a StatusNotifier host there is no icon to come back through, so it quits. win.on('close', (event) => { if (getTrayEnabled() && !isQuitting && hasStatusNotifierHost()) { event.preventDefault() win.hide() } }) if (process.env.NODE_ENV === 'development' && process.env['ELECTRON_RENDERER_URL']) { win.loadURL(process.env['ELECTRON_RENDERER_URL']) } else { win.loadFile(path.join(__dirname, '../renderer/index.html')) } if (startHidden && !hasStatusNotifierHost()) showWindowUnlessTrayAppears(win) return win } app.whenReady().then(() => { protocol.handle('wallpaper', async (request) => { const filePath = decodeURIComponent(request.url.replace('wallpaper://', '')) try { return await net.fetch(pathToFileURL(filePath).toString()) } catch { // File not on disk yet (e.g. still downloading) - a rejected fetch here // would otherwise surface as an uncaught net::ERR_FILE_NOT_FOUND return new Response(null, { status: 404 }) } }) initLibrary() const win = createWindow() bindSteamToWindow(win) registerAllHandlers(win) startWatcher(win) startBackgroundSync(win) initDesktopIcons() initDisplay(win) const resumed = initPlaylistPlayer(win) if (getTrayEnabled()) createTray(win) const autostartPlaylistId = getAutostartPlaylistId() if (!resumed && autostartPlaylistId && getLweStatus().installed) { try { startPlaylist(autostartPlaylistId) } catch (err) { console.error('[App] Failed to autostart playlist:', err) } } initSchedule(win) }) app.on('before-quit', (event) => { isQuitting = true if (getKillLweOnQuit() && !hasKilledLweOnQuit) { event.preventDefault() hasKilledLweOnQuit = true killAllLweProcesses().finally(() => app.quit()) } }) app.on('window-all-closed', () => { cleanupDesktopIcons() if (process.platform !== 'darwin') app.quit() }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } else { BrowserWindow.getAllWindows()[0].show() } })