index.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { app, BrowserWindow, net, protocol, shell } from 'electron'
  2. import path from 'path'
  3. import { pathToFileURL } from 'url'
  4. import { IpcChannels } from '@shared/ipc-channels'
  5. import { isSteamRunning, startVotedItemsSync, onFailedVotesChange, bindSteamToWindow } from './services/steam.service'
  6. import { initLibrary, checkUnavailableWallpapers, backfillResolutions, onHdrDetected, queueHdrCheck } from './services/library.service'
  7. import { startWatcher } from './services/watcher.service'
  8. import { checkOutdatedBackups } from './services/backup.service'
  9. import { registerAllHandlers } from './ipc'
  10. import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.service'
  11. import { getTrayEnabled, getAutostartPlaylistId, getKillLweOnQuit } from './services/config.service'
  12. import { createTray } from './services/tray.service'
  13. import { initPlaylistPlayer, startPlaylist } from './services/playlist-player.service'
  14. import { killAllLweProcesses, getLweStatus } from './services/lwe.service'
  15. import { initDisplay } from './services/display.service'
  16. import { initSchedule } from './services/schedule.service'
  17. import { hasStatusNotifierHost } from './utils/platform'
  18. const startMinimized = process.argv.includes('--minimized')
  19. let isQuitting = false
  20. let hasKilledLweOnQuit = false
  21. const BACKGROUND_SYNC_INTERVAL_MS = 3 * 60 * 1000
  22. const TRAY_HOST_WAIT_MS = 10_000
  23. // Keeps "liked" state and library availability fresh without the user having to restart the
  24. // app or click "Check unavailable" - votes cast on Steam directly (client, community website)
  25. // and items taken down from the Workshop both eventually show up on their own.
  26. function startBackgroundSync(win: BrowserWindow): void {
  27. startVotedItemsSync((ids) => {
  28. if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_VOTED_IDS_CHANGED, ids)
  29. })
  30. onFailedVotesChange((failed) => {
  31. if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_FAILED_VOTES_CHANGED, failed)
  32. })
  33. const syncResolutions = async (): Promise<void> => {
  34. if (await backfillResolutions() && !win.isDestroyed()) {
  35. win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
  36. }
  37. }
  38. onHdrDetected(() => {
  39. if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
  40. })
  41. const syncOutdatedBackups = async (): Promise<void> => {
  42. try {
  43. if (await checkOutdatedBackups() && !win.isDestroyed()) {
  44. win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
  45. }
  46. } catch (err) {
  47. console.warn('[Backup] Outdated check failed:', err)
  48. }
  49. }
  50. win.webContents.once('did-finish-load', () => {
  51. void syncResolutions()
  52. void syncOutdatedBackups()
  53. queueHdrCheck()
  54. })
  55. const pushSteamStatus = (): void => {
  56. if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_STEAM_STATUS, isSteamRunning())
  57. }
  58. win.on('show', pushSteamStatus)
  59. win.on('restore', pushSteamStatus)
  60. setInterval(async () => {
  61. if (win.isDestroyed()) return
  62. const running = isSteamRunning()
  63. win.webContents.send(IpcChannels.EVENT_STEAM_STATUS, running)
  64. await syncOutdatedBackups()
  65. if (!running) return
  66. try {
  67. const { changed } = await checkUnavailableWallpapers()
  68. if (changed && !win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
  69. await syncResolutions()
  70. } catch {
  71. // transient Steam hiccup - try again next tick
  72. }
  73. }, BACKGROUND_SYNC_INTERVAL_MS)
  74. }
  75. // gives a panel that starts after us until the deadline, then shows the window
  76. function showWindowUnlessTrayAppears(win: BrowserWindow): void {
  77. const deadline = Date.now() + TRAY_HOST_WAIT_MS
  78. const timer = setInterval(() => {
  79. if (win.isDestroyed() || win.isVisible() || hasStatusNotifierHost(0)) {
  80. clearInterval(timer)
  81. } else if (Date.now() >= deadline) {
  82. clearInterval(timer)
  83. win.show()
  84. }
  85. }, 1000)
  86. }
  87. function createWindow(): BrowserWindow {
  88. const startHidden = startMinimized && getTrayEnabled()
  89. const win = new BrowserWindow({
  90. width: 1280,
  91. height: 800,
  92. minWidth: 900,
  93. minHeight: 600,
  94. backgroundColor: '#0f0f0f',
  95. titleBarStyle: 'hiddenInset',
  96. show: !startHidden,
  97. webPreferences: {
  98. preload: path.join(__dirname, '../preload/index.cjs'),
  99. contextIsolation: true,
  100. nodeIntegration: false,
  101. sandbox: false
  102. }
  103. })
  104. win.webContents.setWindowOpenHandler(({ url }) => {
  105. shell.openExternal(url)
  106. return { action: 'deny' }
  107. })
  108. // When the tray is enabled, closing the window hides it instead of quitting so the
  109. // tray icon remains the only way back in (and the app keeps running for playlists).
  110. // Without a StatusNotifier host there is no icon to come back through, so it quits.
  111. win.on('close', (event) => {
  112. if (getTrayEnabled() && !isQuitting && hasStatusNotifierHost()) {
  113. event.preventDefault()
  114. win.hide()
  115. }
  116. })
  117. if (process.env.NODE_ENV === 'development' && process.env['ELECTRON_RENDERER_URL']) {
  118. win.loadURL(process.env['ELECTRON_RENDERER_URL'])
  119. } else {
  120. win.loadFile(path.join(__dirname, '../renderer/index.html'))
  121. }
  122. if (startHidden && !hasStatusNotifierHost()) showWindowUnlessTrayAppears(win)
  123. return win
  124. }
  125. app.whenReady().then(() => {
  126. protocol.handle('wallpaper', async (request) => {
  127. const filePath = decodeURIComponent(request.url.replace('wallpaper://', ''))
  128. try {
  129. return await net.fetch(pathToFileURL(filePath).toString())
  130. } catch {
  131. // File not on disk yet (e.g. still downloading) - a rejected fetch here
  132. // would otherwise surface as an uncaught net::ERR_FILE_NOT_FOUND
  133. return new Response(null, { status: 404 })
  134. }
  135. })
  136. initLibrary()
  137. const win = createWindow()
  138. bindSteamToWindow(win)
  139. registerAllHandlers(win)
  140. startWatcher(win)
  141. startBackgroundSync(win)
  142. initDesktopIcons()
  143. initDisplay(win)
  144. const resumed = initPlaylistPlayer(win)
  145. if (getTrayEnabled()) createTray(win)
  146. const autostartPlaylistId = getAutostartPlaylistId()
  147. if (!resumed && autostartPlaylistId && getLweStatus().installed) {
  148. try {
  149. startPlaylist(autostartPlaylistId)
  150. } catch (err) {
  151. console.error('[App] Failed to autostart playlist:', err)
  152. }
  153. }
  154. initSchedule(win)
  155. })
  156. app.on('before-quit', (event) => {
  157. isQuitting = true
  158. if (getKillLweOnQuit() && !hasKilledLweOnQuit) {
  159. event.preventDefault()
  160. hasKilledLweOnQuit = true
  161. killAllLweProcesses().finally(() => app.quit())
  162. }
  163. })
  164. app.on('window-all-closed', () => {
  165. cleanupDesktopIcons()
  166. if (process.platform !== 'darwin') app.quit()
  167. })
  168. app.on('activate', () => {
  169. if (BrowserWindow.getAllWindows().length === 0) {
  170. createWindow()
  171. } else {
  172. BrowserWindow.getAllWindows()[0].show()
  173. }
  174. })