display.service.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import type { BrowserWindow } from 'electron'
  2. import fs from 'fs'
  3. import path from 'path'
  4. import { IpcChannels } from '@shared/ipc-channels'
  5. import type {
  6. CrashEvent,
  7. CrashPhase,
  8. EngineFlags,
  9. ScreenAssignment,
  10. ScreenTarget,
  11. SplitScreen,
  12. WallpaperBackend,
  13. WallpaperCompat,
  14. WallpaperMeta
  15. } from '@shared/types'
  16. import { getAllWallpapers, getWallpaper, updateWallpaper } from './library.service'
  17. import { applyWallpaperMeta, isAnimatedWallpaper, usesEngine } from './wallpaper.service'
  18. import {
  19. ALL_SCREENS,
  20. getActiveScreens,
  21. getLweStatus,
  22. getRunningInstances,
  23. getUnusedScreens,
  24. hotswapLweSettings,
  25. isLweRunning,
  26. launchLweAsync,
  27. liveEngineFlagOptions,
  28. onLweExit,
  29. stopLwe,
  30. supportsSplitScreens,
  31. type LweExitInfo,
  32. type LweSplitSlot
  33. } from './lwe.service'
  34. import { resolveEngineFlags } from '@shared/engineFlags'
  35. import {
  36. clearAssignment,
  37. getAssignments,
  38. isSplitActive,
  39. markSplitActive,
  40. setAssignment,
  41. splitActiveScreens
  42. } from './wallpaper-state.service'
  43. import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens } from './config.service'
  44. import { planRestore, restoreSuperseded, trySplit, type RestoreInput } from './restore-plan'
  45. import { ensureDependencyInstalled } from './dependency.service'
  46. import { t } from '../i18n'
  47. const LAUNCH_CHECK_MS = 20_000
  48. // bumped by every launch and stop of a screen, so a restore can tell it was overtaken
  49. const screenUse = new Map<string, number>()
  50. function markScreenUsed(screen: ScreenTarget): number {
  51. const count = (screenUse.get(screen) ?? 0) + 1
  52. screenUse.set(screen, count)
  53. return count
  54. }
  55. function screenUseCount(screen: ScreenTarget): number {
  56. return screenUse.get(screen) ?? 0
  57. }
  58. const screenCommitted = new Map<string, number>()
  59. function newerLaunchLanded(screen: ScreenTarget, stamp: number): boolean {
  60. return (screenCommitted.get(screen) ?? 0) > stamp
  61. }
  62. // a stop never claims a screen
  63. const screenClaims = new Map<string, number>()
  64. function claimStamp(screen: ScreenTarget, stamp: number): void {
  65. if ((screenClaims.get(screen) ?? 0) < stamp) screenClaims.set(screen, stamp)
  66. }
  67. function claimScreen(screen: ScreenTarget): number {
  68. const stamp = markScreenUsed(screen)
  69. claimStamp(screen, stamp)
  70. return stamp
  71. }
  72. function releaseScreen(screen: ScreenTarget, stamp: number): void {
  73. if (screenClaims.get(screen) === stamp) screenClaims.delete(screen)
  74. }
  75. function newerLaunchTakes(screen: ScreenTarget, stamp: number): boolean {
  76. return newerLaunchLanded(screen, stamp) || (screenClaims.get(screen) ?? 0) > stamp
  77. }
  78. // a killed engine still resolves its launch
  79. function launchStood(engine: boolean, screen: ScreenTarget): boolean {
  80. return !engine || isLweRunning(screen)
  81. }
  82. function commitLaunch(screen: ScreenTarget, stamp: number): boolean {
  83. if (newerLaunchLanded(screen, stamp)) return false
  84. screenCommitted.set(screen, stamp)
  85. return true
  86. }
  87. // automatic relaunches after a runtime crash, at most one per screen in this window
  88. const RELAUNCH_COOLDOWN_MS = 60_000
  89. let win: BrowserWindow | null = null
  90. const lastAutoRelaunch = new Map<ScreenTarget, number>()
  91. const launchChecks = new Map<ScreenTarget, ReturnType<typeof setTimeout>>()
  92. let playlistRecovery: ((screen: ScreenTarget, wallpaperId: string) => boolean) | null = null
  93. let volumeSource: VolumeSource | null = null
  94. function send(channel: string, payload?: unknown): void {
  95. if (win && !win.isDestroyed()) win.webContents.send(channel, payload)
  96. }
  97. export function getDisplayTargets(): ScreenTarget[] {
  98. if (getDisplayMode() === 'shared') return [ALL_SCREENS]
  99. const screens = getActiveScreens()
  100. return screens.length > 0 ? screens : [ALL_SCREENS]
  101. }
  102. /** '*' (or nothing) means every screen: one engine in shared mode, one per screen otherwise */
  103. export function expandScreen(screen?: ScreenTarget, targets: ScreenTarget[] = getDisplayTargets()): ScreenTarget[] {
  104. if (screen === undefined || screen === ALL_SCREENS) return targets
  105. return targets.includes(screen) ? [screen] : []
  106. }
  107. export function isShownOn(wallpaperId: string, screen?: ScreenTarget): boolean {
  108. const assigned = getAssignments()
  109. return expandScreen(screen).some((target) => (assigned[target] ?? assigned[ALL_SCREENS]) === wallpaperId)
  110. }
  111. export function getScreenAssignments(): ScreenAssignment[] {
  112. const splits = new Set(splitActiveScreens())
  113. return Object.entries(getAssignments()).map(([screen, wallpaperId]) => ({
  114. screen,
  115. wallpaperId,
  116. split: splits.has(screen)
  117. }))
  118. }
  119. const busySources = new Map<string, () => string[]>()
  120. export function setBusyWallpaperSource(name: string, source: () => string[]): void {
  121. busySources.set(name, source)
  122. }
  123. export function getWallpapersInUse(): Set<string> {
  124. const ids = new Set(getScreenAssignments().map((a) => a.wallpaperId))
  125. for (const source of busySources.values()) for (const id of source()) ids.add(id)
  126. return ids
  127. }
  128. /** Live global flags reach running wallpapers without their own */
  129. export async function pushGlobalEngineFlags(before: EngineFlags, after: EngineFlags): Promise<void> {
  130. const splitScreens = new Set(getRunningInstances().filter((i) => i.split).map((i) => i.screen))
  131. for (const { screen, wallpaperId } of getScreenAssignments()) {
  132. // split engines run with the global flags only
  133. const own = splitScreens.has(screen) ? undefined : getWallpaper(wallpaperId)?.engineFlags
  134. const previous = liveEngineFlagOptions(resolveEngineFlags(before, own))
  135. const next = liveEngineFlagOptions(resolveEngineFlags(after, own))
  136. // a resent hwdec would reopen the video decoder for nothing
  137. const changed = Object.fromEntries(
  138. Object.entries(next).filter(([key, value]) => previous[key as keyof typeof previous] !== value)
  139. )
  140. if (Object.keys(changed).length > 0) await hotswapLweSettings(changed, { screens: [screen] })
  141. }
  142. }
  143. /** On a playing screen the playlist player handles crashes */
  144. export function setPlaylistRecovery(handler: (screen: ScreenTarget, wallpaperId: string) => boolean): void {
  145. playlistRecovery = handler
  146. }
  147. export function setVolumeSource(source: VolumeSource): void {
  148. volumeSource = source
  149. }
  150. function patchCompat(wallpaper: WallpaperMeta, patch: Partial<WallpaperCompat>): void {
  151. updateWallpaper(wallpaper.id, { compat: { ...wallpaper.compat, ...patch } })
  152. send(IpcChannels.EVENT_LIBRARY_CHANGED)
  153. }
  154. function watchLaunch(wallpaperId: string, screen: ScreenTarget, onSurvived?: () => void): void {
  155. clearTimeout(launchChecks.get(screen))
  156. launchChecks.set(
  157. screen,
  158. setTimeout(() => {
  159. launchChecks.delete(screen)
  160. const wallpaper = getWallpaper(wallpaperId)
  161. const inst = getRunningInstances().find((i) => i.screen === screen)
  162. if (!wallpaper || !inst || inst.wallpaperPath !== wallpaper.localPath || inst.swappedAt !== null) return
  163. if (wallpaper.compat?.freshLaunch !== 'ok') patchCompat(wallpaper, { freshLaunch: 'ok' })
  164. onSurvived?.()
  165. }, LAUNCH_CHECK_MS)
  166. )
  167. }
  168. export async function showWallpaper(
  169. wallpaper: WallpaperMeta,
  170. screen: ScreenTarget | undefined,
  171. options: {
  172. volume?: number
  173. backend?: WallpaperBackend
  174. dependencyPrompt?: 'always' | 'once' | 'never'
  175. forceFresh?: boolean
  176. } = {}
  177. ): Promise<string> {
  178. const targets = expandScreen(screen)
  179. if (targets.length === 0) throw new Error(`Screen ${screen} is not connected`)
  180. let appliedPath = ''
  181. const engine = usesEngine(wallpaper)
  182. const stamps = new Map(targets.map((target) => [target, markScreenUsed(target)]))
  183. try {
  184. for (const target of targets) {
  185. const stamp = stamps.get(target) ?? 0
  186. if (newerLaunchTakes(target, stamp)) continue
  187. claimStamp(target, stamp)
  188. appliedPath = await applyWallpaperMeta(wallpaper, { ...options, screen: target })
  189. if (!launchStood(engine, target) || !commitLaunch(target, stamp)) continue
  190. setAssignment(target, wallpaper.id)
  191. // only a wallpaper that crashed on launch before needs its fresh launches watched
  192. if (wallpaper.compat?.freshLaunch === 'crash') watchLaunch(wallpaper.id, target)
  193. }
  194. } finally {
  195. for (const [target, stamp] of stamps) releaseScreen(target, stamp)
  196. }
  197. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  198. return appliedPath
  199. }
  200. export class SplitUnavailableError extends Error {}
  201. /** One fresh engine for all slots of the screen, beforeLaunch runs once the split is known to be showable */
  202. export async function showSplitScreen(
  203. screen: ScreenTarget,
  204. beforeLaunch?: () => void,
  205. dependencyPrompt: 'always' | 'once' | 'never' = 'always',
  206. skipMissing = false
  207. ): Promise<void> {
  208. if (getDisplayMode() !== 'per-screen' || screen === ALL_SCREENS) throw new SplitUnavailableError(t('split.needsPerScreen'))
  209. if (!getDisplayTargets().includes(screen)) throw new SplitUnavailableError(`Screen ${screen} is not connected`)
  210. if (!supportsSplitScreens()) throw new SplitUnavailableError(t('split.engineTooOld'))
  211. const claim = { stamp: claimScreen(screen) }
  212. try {
  213. await launchSplit(screen, claim, beforeLaunch, dependencyPrompt, skipMissing)
  214. } finally {
  215. releaseScreen(screen, claim.stamp)
  216. }
  217. }
  218. async function launchSplit(
  219. screen: ScreenTarget,
  220. claim: { stamp: number },
  221. beforeLaunch: (() => void) | undefined,
  222. dependencyPrompt: 'always' | 'once' | 'never',
  223. skipMissing: boolean
  224. ): Promise<void> {
  225. const split = getSplitScreens()[screen]
  226. const slots: LweSplitSlot[] = []
  227. const shown: WallpaperMeta[] = []
  228. for (const { slot, wallpaper, path: slotPath } of showableSplitSlots(screen, skipMissing)) {
  229. try {
  230. await ensureDependencyInstalled(wallpaper, dependencyPrompt)
  231. } catch (err) {
  232. if (dependencyPrompt === 'never') continue
  233. throw err
  234. }
  235. slots.push({
  236. path: slotPath,
  237. scalingMode: slot.scalingMode ?? wallpaper.scalingMode,
  238. zoom: wallpaper.zoom,
  239. offsetX: wallpaper.offsetX,
  240. offsetY: wallpaper.offsetY,
  241. cornerColor: wallpaper.cornerColor,
  242. imageAdjustments: wallpaper.imageAdjustments
  243. })
  244. shown.push(wallpaper)
  245. }
  246. if (slots.length === 0 || !split) throw new SplitUnavailableError(t('split.empty'))
  247. if (newerLaunchTakes(screen, claim.stamp)) {
  248. // restore leaves the screen to whoever took it, a split somebody asked for goes on
  249. if (!beforeLaunch) return
  250. releaseScreen(screen, claim.stamp)
  251. claim.stamp = claimScreen(screen)
  252. }
  253. beforeLaunch?.()
  254. // overrides would hit every slot by id, so slots play as published
  255. await launchLweAsync(slots[0].path, {
  256. screen,
  257. split: { layout: split.layout, slots },
  258. engineFlags: resolveEngineFlags(getGlobalEngineFlags()),
  259. fps: getDefaultFps() ?? undefined,
  260. forceFresh: true
  261. })
  262. if (!isLweRunning(screen) || !commitLaunch(screen, claim.stamp)) return
  263. setAssignment(screen, shown[0].id)
  264. markSplitActive(screen)
  265. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  266. }
  267. export async function stopDisplay(screen?: ScreenTarget): Promise<void> {
  268. // no expandScreen here, it shells out
  269. const marked = screen === undefined || screen === ALL_SCREENS ? [...screenUse.keys()] : [screen]
  270. for (const target of marked) markScreenUsed(target)
  271. if (screen === undefined || screen === ALL_SCREENS) {
  272. await stopLwe()
  273. clearAssignment()
  274. } else {
  275. await stopLwe(screen)
  276. clearAssignment(screen)
  277. }
  278. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  279. }
  280. function wallpaperForPath(wallpaperPath: string): WallpaperMeta | undefined {
  281. if (!wallpaperPath) return undefined
  282. return getAllWallpapers().find((w) => w.localPath === wallpaperPath)
  283. }
  284. function notifyCrash(wallpaper: WallpaperMeta, screen: ScreenTarget, phase: CrashPhase, outcome: string): void {
  285. const event: CrashEvent = { wallpaperId: wallpaper.id, title: wallpaper.title, screen, phase, outcome }
  286. send(IpcChannels.EVENT_WALLPAPER_CRASHED, event)
  287. }
  288. async function relaunchFresh(wallpaper: WallpaperMeta, screen: ScreenTarget): Promise<boolean> {
  289. try {
  290. await applyWallpaperMeta(getWallpaper(wallpaper.id) ?? wallpaper, {
  291. screen,
  292. forceFresh: true,
  293. dependencyPrompt: 'once',
  294. volume: volumeSource?.(screen, wallpaper.id)
  295. })
  296. return true
  297. } catch (err) {
  298. console.error('[Display] Fresh relaunch failed:', (err as Error).message)
  299. return false
  300. }
  301. }
  302. // any slot can be the one that crashed, so nothing is recorded on a wallpaper
  303. async function handleSplitCrash(info: LweExitInfo): Promise<void> {
  304. console.warn(`[Display] Split screen crashed on ${info.screen} (${info.phase}, ${info.description})`)
  305. const notify = (outcome: string): void => {
  306. const event: CrashEvent = { wallpaperId: '', title: t('split.title'), screen: info.screen, phase: info.phase, outcome }
  307. send(IpcChannels.EVENT_WALLPAPER_CRASHED, event)
  308. }
  309. const last = lastAutoRelaunch.get(info.screen) ?? 0
  310. if (info.phase !== 'launch' && Date.now() - last > RELAUNCH_COOLDOWN_MS) {
  311. lastAutoRelaunch.set(info.screen, Date.now())
  312. try {
  313. await showSplitScreen(info.screen)
  314. notify(t('crash.runtimeRestarted'))
  315. return
  316. } catch (err) {
  317. console.error('[Display] Split screen relaunch failed:', (err as Error).message)
  318. }
  319. }
  320. clearAssignment(info.screen)
  321. notify(info.phase === 'launch' ? t('compat.crashes') : t('compat.unstable'))
  322. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  323. }
  324. async function handleExit(info: LweExitInfo): Promise<void> {
  325. if (info.crashed && info.split) return handleSplitCrash(info)
  326. const wallpaper = wallpaperForPath(info.wallpaperPath)
  327. if (!info.crashed || !wallpaper) {
  328. if (!info.crashed) clearAssignment(info.screen === ALL_SCREENS ? undefined : info.screen)
  329. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  330. return
  331. }
  332. console.warn(`[Display] ${wallpaper.title} crashed on ${info.screen} (${info.phase}, ${info.description})`)
  333. const crash = { at: Date.now(), phase: info.phase, screen: info.screen, log: info.log.slice(-30) }
  334. clearTimeout(launchChecks.get(info.screen))
  335. launchChecks.delete(info.screen)
  336. if (info.phase === 'hotswap') {
  337. patchCompat(wallpaper, { hotswapCrash: true, lastCrash: crash })
  338. // a fresh launch tells whether only the hotswap is the problem
  339. if (!(await relaunchFresh(wallpaper, info.screen))) return
  340. notifyCrash(wallpaper, info.screen, 'hotswap', t('crash.hotswapTesting'))
  341. watchLaunch(wallpaper.id, info.screen, () => { notifyCrash(wallpaper, info.screen, 'hotswap', t('crash.hotswapFreshWorks')) }
  342. )
  343. return
  344. }
  345. if (info.phase === 'launch') {
  346. patchCompat(wallpaper, { freshLaunch: 'crash', lastCrash: crash })
  347. clearAssignment(info.screen === ALL_SCREENS ? undefined : info.screen)
  348. const skipped = playlistRecovery?.(info.screen, wallpaper.id) ?? false
  349. notifyCrash(wallpaper, info.screen, 'launch', skipped ? t('crash.launchSkipped') : t('compat.crashes'))
  350. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  351. return
  352. }
  353. patchCompat(wallpaper, { runtimeCrashes: (wallpaper.compat?.runtimeCrashes ?? 0) + 1, lastCrash: crash })
  354. if (playlistRecovery?.(info.screen, wallpaper.id)) {
  355. notifyCrash(wallpaper, info.screen, 'runtime', t('crash.runtimeSkipped'))
  356. return
  357. }
  358. const last = lastAutoRelaunch.get(info.screen) ?? 0
  359. if (Date.now() - last > RELAUNCH_COOLDOWN_MS) {
  360. lastAutoRelaunch.set(info.screen, Date.now())
  361. if (await relaunchFresh(wallpaper, info.screen)) {
  362. notifyCrash(wallpaper, info.screen, 'runtime', t('crash.runtimeRestarted'))
  363. return
  364. }
  365. }
  366. clearAssignment(info.screen === ALL_SCREENS ? undefined : info.screen)
  367. notifyCrash(wallpaper, info.screen, 'runtime', t('compat.unstable'))
  368. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  369. }
  370. export async function testFreshLaunch(wallpaperId: string, screen?: ScreenTarget): Promise<void> {
  371. const wallpaper = getWallpaper(wallpaperId)
  372. if (!wallpaper) throw new Error(`Wallpaper ${wallpaperId} not found in library`)
  373. const target = expandScreen(screen)[0]
  374. if (!target) throw new Error('No screen to test on')
  375. const stamp = claimScreen(target)
  376. try {
  377. await applyWallpaperMeta(wallpaper, { screen: target, forceFresh: true })
  378. } finally {
  379. releaseScreen(target, stamp)
  380. }
  381. if (launchStood(usesEngine(wallpaper), target) && commitLaunch(target, stamp)) setAssignment(target, wallpaper.id)
  382. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  383. watchLaunch(wallpaper.id, target, () => { notifyCrash(getWallpaper(wallpaper.id) ?? wallpaper, target, 'launch', t('crash.testPassed')) }
  384. )
  385. }
  386. export function forgetAssignments(): void {
  387. for (const target of screenUse.keys()) markScreenUsed(target)
  388. clearAssignment()
  389. send(IpcChannels.EVENT_DISPLAY_CHANGED)
  390. }
  391. /** Stops everything and forgets assignments, the screens mean something else after a mode switch */
  392. export async function resetDisplays(): Promise<void> {
  393. for (const timer of launchChecks.values()) clearTimeout(timer)
  394. launchChecks.clear()
  395. await stopDisplay()
  396. }
  397. export function initDisplay(window: BrowserWindow): void {
  398. win = window
  399. onLweExit((info) => {
  400. void handleExit(info).catch((err: unknown) => { console.error('[Display] Crash handling failed:', err) })
  401. })
  402. }
  403. // a missing drive keeps its library entry, and launching it would mark a healthy wallpaper as crashed
  404. function wallpaperIsOnDisk(localPath: string): boolean {
  405. if (!fs.existsSync(localPath)) return false
  406. try {
  407. return fs.statSync(localPath).isFile() || fs.existsSync(path.join(localPath, 'project.json'))
  408. } catch {
  409. return false
  410. }
  411. }
  412. // a manual show lets the engine report a missing folder
  413. function showableSplitSlots(screen: ScreenTarget, onDiskOnly = true): { slot: SplitScreen['slots'][number]; wallpaper: WallpaperMeta; path: string }[] {
  414. return (getSplitScreens()[screen]?.slots ?? []).flatMap((slot) => {
  415. const wallpaper = getWallpaper(slot.wallpaperId)
  416. const localPath = wallpaper?.localPath
  417. return wallpaper && localPath && isAnimatedWallpaper(wallpaper) && (!onDiskOnly || wallpaperIsOnDisk(localPath)) ? [{ slot, wallpaper, path: localPath }] : []
  418. })
  419. }
  420. const SPLIT_RETRY_MS = 3000
  421. export type VolumeSource = (screen: ScreenTarget, wallpaperId: string) => number | undefined
  422. type Running = ReturnType<typeof getRunningInstances>[number]
  423. function engineOf(inst?: Running): RestoreInput['running'] {
  424. return inst ? { split: !!inst.split, wallpaperPath: inst.wallpaperPath } : undefined
  425. }
  426. // a restore waiting for a retry must not start an engine after the shutdown kill
  427. let restoreRun = 0
  428. let restoreCancelled = false
  429. export function cancelRestore(): void {
  430. restoreCancelled = true
  431. restoreRun++
  432. }
  433. function splitTry(screen: ScreenTarget) {
  434. return trySplit({
  435. show: () => showSplitScreen(screen, undefined, 'never', true),
  436. uses: () => screenUseCount(screen),
  437. onError: (err) => { console.error(`[Display] Could not restore the split on ${screen}:`, (err as Error).message) }
  438. })
  439. }
  440. async function retrySplit(
  441. run: number,
  442. screen: ScreenTarget,
  443. wallpaper: WallpaperMeta | null | undefined,
  444. input: RestoreInput,
  445. volumeFor?: VolumeSource
  446. ): Promise<void> {
  447. const settled = screenUseCount(screen)
  448. await new Promise((resolve) => setTimeout(resolve, SPLIT_RETRY_MS))
  449. if (run !== restoreRun || screenUseCount(screen) !== settled) return
  450. if ((await splitTry(screen)) !== 'failed' || !wallpaper || run !== restoreRun) return
  451. // the failed tries changed what is running
  452. const live = getRunningInstances().find((inst) => inst.screen === screen)
  453. if (planRestore({ ...input, splitActive: false, running: engineOf(live) }) !== 'wallpaper') return
  454. console.log(`[Display] Restoring ${wallpaper.title} on ${screen} instead of its split`)
  455. await showWallpaper(wallpaper, screen, { dependencyPrompt: 'never', volume: volumeFor?.(screen, wallpaper.id) })
  456. }
  457. export async function restoreAssignedWallpapers(
  458. skipScreens: ReadonlySet<ScreenTarget> = new Set(),
  459. volumeFor?: VolumeSource
  460. ): Promise<void> {
  461. if (restoreCancelled || !getLweStatus().installed) return
  462. await restoreScreens(++restoreRun, skipScreens, volumeFor, undefined, 0)
  463. }
  464. const RESTORE_RETRIES = 5
  465. async function restoreScreens(
  466. run: number,
  467. skipScreens: ReadonlySet<ScreenTarget>,
  468. volumeFor: VolumeSource | undefined,
  469. only: readonly ScreenTarget[] | undefined,
  470. attempt: number,
  471. carried?: { useAtStart: Map<string, number>; targets?: Set<string> }
  472. ): Promise<void> {
  473. const saved = Object.fromEntries(Object.entries(getAssignments()).filter(([screen]) => !only || only.includes(screen)))
  474. // judged against the first pass, a launch started since has taken the screen
  475. const useAtStart = new Map(Object.keys(saved).map((screen) => [screen, carried?.useAtStart.get(screen) ?? screenUseCount(screen)]))
  476. const targets = carried?.targets ?? new Set(getDisplayTargets())
  477. const running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
  478. // '*' is an old single-wallpaper assignment, restorable in shared mode only
  479. const missing = Object.keys(saved).filter((screen) => screen !== ALL_SCREENS && !targets.has(screen) && !skipScreens.has(screen))
  480. const unused = missing.length > 0 ? new Set(getUnusedScreens()) : new Set<string>()
  481. const waiting = new Set(missing.filter((screen) => !unused.has(screen)))
  482. for (const [screen, wallpaperId] of Object.entries(saved)) {
  483. if (run !== restoreRun) return
  484. const wallpaper = getWallpaper(wallpaperId)
  485. const localPath = wallpaper?.localPath ?? ''
  486. const inst = running.get(screen)
  487. const splitActive = isSplitActive(screen)
  488. const input: RestoreInput = {
  489. skipped: skipScreens.has(screen),
  490. connected: targets.has(screen),
  491. animated: !!wallpaper && isAnimatedWallpaper(wallpaper),
  492. onDisk: !!localPath && wallpaperIsOnDisk(localPath),
  493. localPath,
  494. running: engineOf(inst),
  495. splitActive,
  496. splitShowable: splitActive && showableSplitSlots(screen).length > 0
  497. }
  498. const plan = planRestore(input)
  499. if (plan === 'wait') waiting.add(screen)
  500. if (plan === 'skip' || plan === 'wait') continue
  501. // an earlier screen takes 2s or more, Play, the tray or a playlist may have taken this one since
  502. if (restoreSuperseded(wallpaperId, getAssignments()[screen], useAtStart.get(screen) ?? 0, screenUseCount(screen))) {
  503. console.log(`[Display] Leaving ${screen}, it changed while restoring`)
  504. continue
  505. }
  506. try {
  507. if (plan === 'split') {
  508. console.log(`[Display] Restoring split on ${screen}`)
  509. if ((await splitTry(screen)) === 'failed') {
  510. void retrySplit(run, screen, wallpaper, input, volumeFor).catch((err: unknown) => {
  511. console.error(`[Display] Could not restore ${screen}:`, (err as Error).message)
  512. })
  513. }
  514. continue
  515. }
  516. if (!wallpaper) continue
  517. console.log(`[Display] Restoring ${wallpaper.title} on ${screen}`)
  518. await showWallpaper(wallpaper, screen, { dependencyPrompt: 'never', volume: volumeFor?.(screen, wallpaperId) })
  519. } catch (err) {
  520. console.error(`[Display] Could not restore ${wallpaper?.title ?? wallpaperId} on ${screen}:`, (err as Error).message)
  521. }
  522. }
  523. if (waiting.size === 0) return
  524. if (attempt >= RESTORE_RETRIES) {
  525. console.log(`[Display] Gave up restoring ${[...waiting].join(', ')}, still waiting after ${RESTORE_RETRIES} tries`)
  526. return
  527. }
  528. await new Promise((resolve) => setTimeout(resolve, SPLIT_RETRY_MS))
  529. if (run !== restoreRun) return
  530. const onlyFolders = [...waiting].every((screen) => targets.has(screen))
  531. await restoreScreens(run, skipScreens, volumeFor, [...waiting], attempt + 1, {
  532. useAtStart,
  533. targets: onlyFolders ? targets : undefined
  534. })
  535. }