UwU 2 minggu lalu
induk
melakukan
127c6ef573
43 mengubah file dengan 1919 tambahan dan 254 penghapusan
  1. 15 12
      src/main/index.ts
  2. 11 3
      src/main/ipc/lwe.handlers.ts
  3. 12 9
      src/main/ipc/wallpaper.handlers.ts
  4. 1 2
      src/main/services/config.service.ts
  5. 1 1
      src/main/services/dependency.service.ts
  6. 6 5
      src/main/services/diagnostics.service.ts
  7. 397 0
      src/main/services/display.restore.test.ts
  8. 267 63
      src/main/services/display.service.ts
  9. 14 0
      src/main/services/lwe.service.test.ts
  10. 17 6
      src/main/services/lwe.service.ts
  11. 578 0
      src/main/services/playlist-player.service.test.ts
  12. 171 52
      src/main/services/playlist-player.service.ts
  13. 94 9
      src/main/services/restore-plan.test.ts
  14. 46 9
      src/main/services/restore-plan.ts
  15. 22 18
      src/main/services/schedule.service.ts
  16. 79 0
      src/main/services/wallpaper-state.service.test.ts
  17. 34 4
      src/main/services/wallpaper-state.service.ts
  18. 5 1
      src/main/services/wallpaper.service.ts
  19. 16 5
      src/renderer/src/components/common/DetailSidebar.tsx
  20. 44 5
      src/renderer/src/components/common/PlayScreenPrompt.tsx
  21. 6 7
      src/renderer/src/components/common/RangeInput.tsx
  22. 4 7
      src/renderer/src/components/common/sidebar/ImageAdjustmentsSection.tsx
  23. 17 12
      src/renderer/src/components/common/sidebar/VideoTrimSection.tsx
  24. 1 2
      src/renderer/src/components/library/WallpaperCard.tsx
  25. 13 8
      src/renderer/src/hooks/useWallpaperActions.ts
  26. 1 2
      src/renderer/src/utils/rangeCommit.ts
  27. 2 0
      src/shared/constants.ts
  28. 3 0
      src/shared/i18n/locales/de.ts
  29. 1 1
      src/shared/i18n/locales/en.ts
  30. 3 0
      src/shared/i18n/locales/es.ts
  31. 3 0
      src/shared/i18n/locales/fr.ts
  32. 3 0
      src/shared/i18n/locales/it.ts
  33. 3 0
      src/shared/i18n/locales/ja.ts
  34. 3 0
      src/shared/i18n/locales/ko.ts
  35. 3 0
      src/shared/i18n/locales/pl.ts
  36. 3 0
      src/shared/i18n/locales/pt.ts
  37. 3 0
      src/shared/i18n/locales/ru.ts
  38. 3 0
      src/shared/i18n/locales/tr.ts
  39. 3 0
      src/shared/i18n/locales/zh-CN.ts
  40. 3 0
      src/shared/i18n/locales/zh-TW.ts
  41. 5 6
      src/shared/playScreen.test.ts
  42. 2 5
      src/shared/playScreen.ts
  43. 1 0
      src/shared/types.ts

+ 15 - 12
src/main/index.ts

@@ -11,10 +11,11 @@ import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.
 import { getTrayEnabled, getAutostartEnabled, getAutostartMinimized, getAutostartPlaylistId, getKillLweOnQuit, getConfiguredBackupPath } from './services/config.service'
 import { getTrayEnabled, getAutostartEnabled, getAutostartMinimized, getAutostartPlaylistId, getKillLweOnQuit, getConfiguredBackupPath } from './services/config.service'
 import { refreshAutostartExec } from './services/autostart.service'
 import { refreshAutostartExec } from './services/autostart.service'
 import { createTray } from './services/tray.service'
 import { createTray } from './services/tray.service'
-import { initPlaylistPlayer, playlistRestoreSkipScreens, startPlaylist } from './services/playlist-player.service'
-import { checkEarlierRunEngines, killAllLweProcesses, getLweStatus } from './services/lwe.service'
-import { expandScreen, initDisplay, restoreAssignedWallpapers } from './services/display.service'
-import { catchUpScreens, initSchedule } from './services/schedule.service'
+import { initPlaylistPlayer, playlistRestoreSkipScreens, restoreVolume, startPlaylist } from './services/playlist-player.service'
+import { checkEarlierRunEngines, blockLaunches, killAllLweProcesses, getLweStatus } from './services/lwe.service'
+import { cancelRestore, expandScreen, getDisplayTargets, initDisplay, restoreAssignedWallpapers } from './services/display.service'
+import { mergeSkipScreens } from './services/restore-plan'
+import { initSchedule, takeCatchUp } from './services/schedule.service'
 import { initUpdates } from './services/update.service'
 import { initUpdates } from './services/update.service'
 import { detectDesktopEnv, hasStatusNotifierHost } from './utils/platform'
 import { detectDesktopEnv, hasStatusNotifierHost } from './utils/platform'
 import { needsSoftwareCompositing, readGpuVendors } from './utils/gpuWorkaround'
 import { needsSoftwareCompositing, readGpuVendors } from './utils/gpuWorkaround'
@@ -244,6 +245,7 @@ app.whenReady().then(async () => {
   await checkEarlierRunEngines()
   await checkEarlierRunEngines()
   initDisplay(win)
   initDisplay(win)
   const resumed = initPlaylistPlayer(win)
   const resumed = initPlaylistPlayer(win)
+  const targets = getDisplayTargets()
 
 
   if (getTrayEnabled()) createTray(win)
   if (getTrayEnabled()) createTray(win)
 
 
@@ -254,24 +256,25 @@ app.whenReady().then(async () => {
   if (!resumed && autostartPlaylistId && getLweStatus().installed) {
   if (!resumed && autostartPlaylistId && getLweStatus().installed) {
     try {
     try {
       startPlaylist(autostartPlaylistId)
       startPlaylist(autostartPlaylistId)
-      autostartScreens = expandScreen(undefined)
+      autostartScreens = targets
     } catch (err) {
     } catch (err) {
       console.error('[App] Failed to autostart playlist:', err)
       console.error('[App] Failed to autostart playlist:', err)
     }
     }
   }
   }
-  const scheduleScreens = catchUpScreens().flatMap((screen) => expandScreen(screen))
-  initSchedule(win)
+  const catchUp = takeCatchUp()
+  const scheduleScreens = catchUp.flatMap((rule) => expandScreen(rule.screen, targets))
+  initSchedule(win, catchUp)
   initUpdates(win)
   initUpdates(win)
 
 
-  // not awaited: a restore is at least 2s per screen, and its dependency dialog must not hold the tray.
-  // '*' is every current screen, same as a schedule rule for all of them
-  const playlistScreens = playlistRestoreSkipScreens().flatMap((screen) => expandScreen(screen))
-  const skip = new Set([...playlistScreens, ...autostartScreens, ...scheduleScreens])
-  void restoreAssignedWallpapers(skip).catch((err: unknown) => { console.error('[Display] Restore failed:', err) })
+  const playlistScreens = playlistRestoreSkipScreens().flatMap((screen) => expandScreen(screen, targets))
+  const skip = mergeSkipScreens(playlistScreens, autostartScreens, scheduleScreens)
+  void restoreAssignedWallpapers(skip, restoreVolume).catch((err: unknown) => { console.error('[Display] Restore failed:', err) })
 }).catch((err: unknown) => { console.error('[Main] startup failed:', err) })
 }).catch((err: unknown) => { console.error('[Main] startup failed:', err) })
 
 
 app.on('before-quit', (event) => {
 app.on('before-quit', (event) => {
   isQuitting = true
   isQuitting = true
+  cancelRestore()
+  blockLaunches()
 
 
   if (getKillLweOnQuit() && !hasKilledLweOnQuit) {
   if (getKillLweOnQuit() && !hasKilledLweOnQuit) {
     event.preventDefault()
     event.preventDefault()

+ 11 - 3
src/main/ipc/lwe.handlers.ts

@@ -4,8 +4,8 @@ import { getLweStatus, detectDistro, installLweDeps, installLwe, uninstallLwe, l
 import { getPrebuiltTarget, installLwePrebuilt } from '../services/lwe-prebuilt.service'
 import { getPrebuiltTarget, installLwePrebuilt } from '../services/lwe-prebuilt.service'
 import { installLibnode, libnodeNeeded } from '../services/lwe-libnode.service'
 import { installLibnode, libnodeNeeded } from '../services/lwe-libnode.service'
 import { addUserFonts, listUserFonts, removeUserFont } from '../services/fonts.service'
 import { addUserFonts, listUserFonts, removeUserFont } from '../services/fonts.service'
-import { stopDisplay } from '../services/display.service'
-import { stopPlaylist } from '../services/playlist-player.service'
+import { forgetAssignments, stopDisplay } from '../services/display.service'
+import { getPlaybackStates, stopPlaylist, suspendPlaylist } from '../services/playlist-player.service'
 import type { ScreenTarget } from '@shared/types'
 import type { ScreenTarget } from '@shared/types'
 import { invalidateEnvCache } from '../services/wallpaper.service'
 import { invalidateEnvCache } from '../services/wallpaper.service'
 import { refreshEngineUpdate } from '../services/update.service'
 import { refreshEngineUpdate } from '../services/update.service'
@@ -95,7 +95,15 @@ export function registerLweHandlers(win: BrowserWindow): void {
   })
   })
 
 
   ipcMain.handle(IpcChannels.LWE_KILL_ALL, async () => {
   ipcMain.handle(IpcChannels.LWE_KILL_ALL, async () => {
-    return await killAllLweProcesses()
+    const resumes = getPlaybackStates().filter((state) => state.isPlaying).map((state) => suspendPlaylist(state.screen))
+    const result = await killAllLweProcesses()
+    if (result.ok) {
+      stopPlaylist()
+      forgetAssignments()
+    } else {
+      for (const resume of resumes) resume()
+    }
+    return result
   })
   })
 
 
   ipcMain.handle(IpcChannels.LWE_LIST_OBJECTS, async (_e, wallpaperPath: string) => {
   ipcMain.handle(IpcChannels.LWE_LIST_OBJECTS, async (_e, wallpaperPath: string) => {

+ 12 - 9
src/main/ipc/wallpaper.handlers.ts

@@ -3,11 +3,12 @@ import { IpcChannels } from '@shared/ipc-channels'
 import { detectEnvironment } from '../services/wallpaper.service'
 import { detectEnvironment } from '../services/wallpaper.service'
 import { getWallpaper, updateWallpaper } from '../services/library.service'
 import { getWallpaper, updateWallpaper } from '../services/library.service'
 import { getActiveWallpaperId } from '../services/wallpaper-state.service'
 import { getActiveWallpaperId } from '../services/wallpaper-state.service'
-import { pausePlaylist } from '../services/playlist-player.service'
+import { releasePlaylistScreen } from '../services/playlist-player.service'
 import {
 import {
   expandScreen,
   expandScreen,
   getDisplayTargets,
   getDisplayTargets,
   getScreenAssignments,
   getScreenAssignments,
+  isShownOn,
   showSplitScreen,
   showSplitScreen,
   showWallpaper,
   showWallpaper,
   stopDisplay,
   stopDisplay,
@@ -37,20 +38,22 @@ export function registerWallpaperHandlers(): void {
     if (!wallpaper) throw new Error(`Wallpaper ${options.wallpaperId} not found in library`)
     if (!wallpaper) throw new Error(`Wallpaper ${options.wallpaperId} not found in library`)
 
 
     // a playlist would replace it again on its next switch
     // a playlist would replace it again on its next switch
-    for (const target of expandScreen(options.screen)) pausePlaylist(target)
+    for (const target of expandScreen(options.screen)) releasePlaylistScreen(target)
 
 
     const appliedPath = await showWallpaper(wallpaper, options.screen, { backend: options.backend })
     const appliedPath = await showWallpaper(wallpaper, options.screen, { backend: options.backend })
 
 
-    updateWallpaper(options.wallpaperId, {
-      appliedCount: (wallpaper.appliedCount ?? 0) + 1,
-      lastAppliedAt: Date.now()
-    })
+    if (isShownOn(options.wallpaperId, options.screen)) {
+      updateWallpaper(options.wallpaperId, {
+        appliedCount: (wallpaper.appliedCount ?? 0) + 1,
+        lastAppliedAt: Date.now()
+      })
+    }
 
 
     return { ok: true, appliedPath }
     return { ok: true, appliedPath }
   })
   })
 
 
   ipcMain.handle(IpcChannels.WALLPAPER_STOP, async (_e, screen?: ScreenTarget) => {
   ipcMain.handle(IpcChannels.WALLPAPER_STOP, async (_e, screen?: ScreenTarget) => {
-    for (const s of expandScreen(screen)) pausePlaylist(s)
+    for (const s of expandScreen(screen)) releasePlaylistScreen(s)
     await stopDisplay(screen)
     await stopDisplay(screen)
     return { ok: true }
     return { ok: true }
   })
   })
@@ -61,12 +64,12 @@ export function registerWallpaperHandlers(): void {
   })
   })
 
 
   ipcMain.handle(IpcChannels.WALLPAPER_SHOW_SPLIT, async (_e, screen: ScreenTarget) => {
   ipcMain.handle(IpcChannels.WALLPAPER_SHOW_SPLIT, async (_e, screen: ScreenTarget) => {
-    await showSplitScreen(screen, () => pausePlaylist(screen))
+    await showSplitScreen(screen, () => releasePlaylistScreen(screen))
     return { ok: true }
     return { ok: true }
   })
   })
 
 
   ipcMain.handle(IpcChannels.WALLPAPER_TEST_LAUNCH, async (_e, wallpaperId: string, screen?: ScreenTarget) => {
   ipcMain.handle(IpcChannels.WALLPAPER_TEST_LAUNCH, async (_e, wallpaperId: string, screen?: ScreenTarget) => {
-    for (const s of expandScreen(screen).slice(0, 1)) pausePlaylist(s)
+    for (const s of expandScreen(screen).slice(0, 1)) releasePlaylistScreen(s)
     await testFreshLaunch(wallpaperId, screen)
     await testFreshLaunch(wallpaperId, screen)
     return { ok: true }
     return { ok: true }
   })
   })

+ 1 - 2
src/main/services/config.service.ts

@@ -38,7 +38,6 @@ interface AppConfig {
   autostartPlaylistId: string | null
   autostartPlaylistId: string | null
   killLweOnQuit: boolean
   killLweOnQuit: boolean
   skipPlaylistResume: boolean
   skipPlaylistResume: boolean
-  /** A path change starts a new engine instead of hotswapping. Off keeps transitions. */
   freshProcessOnPathChange: boolean
   freshProcessOnPathChange: boolean
   /** Legacy, only read to migrate into cardBorders */
   /** Legacy, only read to migrate into cardBorders */
   voteBorders: boolean
   voteBorders: boolean
@@ -402,7 +401,7 @@ const RESETS_WITH_ENGINE_SETTINGS: Record<keyof AppConfig, boolean> = {
   autostartPlaylistId: false,
   autostartPlaylistId: false,
   killLweOnQuit: false,
   killLweOnQuit: false,
   skipPlaylistResume: false,
   skipPlaylistResume: false,
-  freshProcessOnPathChange: false,
+  freshProcessOnPathChange: true,
   voteBorders: false,
   voteBorders: false,
   cardBorders: false,
   cardBorders: false,
   cardBadges: false,
   cardBadges: false,

+ 1 - 1
src/main/services/dependency.service.ts

@@ -40,7 +40,7 @@ export async function ensureDependencyInstalled(
 
 
   const title = wallpaper.title || wallpaper.id
   const title = wallpaper.title || wallpaper.id
 
 
-  // startup restore must not open a dialog, least of all over a minimized tray start
+  // 'never' is the startup restore, which must not open a dialog
   if (mode === 'never') throw new Error(t('dependency.skipped', { title, id: dependencyId }))
   if (mode === 'never') throw new Error(t('dependency.skipped', { title, id: dependencyId }))
 
 
   if (mode === 'once' && alreadyAsked.has(dependencyId)) {
   if (mode === 'once' && alreadyAsked.has(dependencyId)) {

+ 6 - 5
src/main/services/diagnostics.service.ts

@@ -15,7 +15,7 @@ import {
   type EngineHistory
   type EngineHistory
 } from './lwe.service'
 } from './lwe.service'
 import { stopDisplay } from './display.service'
 import { stopDisplay } from './display.service'
-import { getPlaybackStates, pausePlaylist, resumePlaylist } from './playlist-player.service'
+import { getPlaybackStates, restoreVolume, suspendPlaylist } from './playlist-player.service'
 import { detectDesktopEnv, detectDisplayServer, getConnectedScreens, runningAppImage } from '../utils/platform'
 import { detectDesktopEnv, detectDisplayServer, getConnectedScreens, runningAppImage } from '../utils/platform'
 import { hostCommand, hostAppPath, isFlatpak } from '../utils/flatpak'
 import { hostCommand, hostAppPath, isFlatpak } from '../utils/flatpak'
 
 
@@ -120,7 +120,7 @@ async function restartPlaying(): Promise<string[]> {
       notes.push(`${inst.screen}: not restarted (${inst.split ? 'split screen' : 'not in the library'})`)
       notes.push(`${inst.screen}: not restarted (${inst.split ? 'split screen' : 'not in the library'})`)
       continue
       continue
     }
     }
-    await applyWallpaperMeta(wallpaper, { screen: inst.screen, forceFresh: true })
+    await applyWallpaperMeta(wallpaper, { screen: inst.screen, forceFresh: true, volume: restoreVolume(inst.screen, wallpaper.id) })
   }
   }
   return notes
   return notes
 }
 }
@@ -213,7 +213,8 @@ async function runTarget(target: DiagnosticsTarget, seconds: number, notes: stri
   const pausedPlaylists = getPlaybackStates().filter(
   const pausedPlaylists = getPlaybackStates().filter(
     (s) => s.isPlaying && (s.screen === target.screen || s.screen === '*' || target.screen === '*')
     (s) => s.isPlaying && (s.screen === target.screen || s.screen === '*' || target.screen === '*')
   )
   )
-  for (const state of pausedPlaylists) pausePlaylist(state.screen)
+  const volume = previous ? restoreVolume(target.screen, previous.id) : undefined
+  const resumes = pausedPlaylists.map((state) => suspendPlaylist(state.screen))
 
 
   const exits: EngineHistory[] = []
   const exits: EngineHistory[] = []
   const exit = { at: 0 }
   const exit = { at: 0 }
@@ -244,12 +245,12 @@ async function runTarget(target: DiagnosticsTarget, seconds: number, notes: stri
     setDiagnosticStats(false)
     setDiagnosticStats(false)
     stopListening()
     stopListening()
     try {
     try {
-      if (previous) await applyWallpaperMeta(previous, { screen: target.screen, forceFresh: true })
+      if (previous) await applyWallpaperMeta(previous, { screen: target.screen, forceFresh: true, volume })
       else await stopDisplay(target.screen)
       else await stopDisplay(target.screen)
     } catch (err) {
     } catch (err) {
       notes.push(`could not restore the previous wallpaper: ${(err as Error).message}`)
       notes.push(`could not restore the previous wallpaper: ${(err as Error).message}`)
     }
     }
-    for (const state of pausedPlaylists) resumePlaylist(state.screen)
+    for (const resume of resumes) resume()
   }
   }
   return { histories: histories.length > 0 ? histories : exits, snapshot }
   return { histories: histories.length > 0 ? histories : exits, snapshot }
 }
 }

+ 397 - 0
src/main/services/display.restore.test.ts

@@ -0,0 +1,397 @@
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const h = vi.hoisted(() => ({
+  dir: '',
+  launches: [] as ('ok' | 'fail')[],
+  launched: 0,
+  screens: ['DP-1'],
+  unused: [] as string[],
+  live: null as string[] | null,
+  engine: true,
+  clearOnFail: () => {}
+}))
+
+vi.mock('electron', () => ({ app: { on: () => {}, getPath: () => '/tmp' } }))
+vi.mock('electron-store', () => ({
+  default: class {
+    private data: Record<string, unknown> = {}
+    get(key: string): unknown {
+      return this.data[key]
+    }
+    set(key: string, value: unknown): void {
+      this.data[key] = value
+    }
+  }
+}))
+vi.mock('../i18n', () => ({ t: (key: string) => key }))
+vi.mock('./dependency.service', () => ({ ensureDependencyInstalled: async () => {} }))
+vi.mock('./library.service', () => ({
+  getWallpaper: (id: string) => ({ id, title: id, type: 'scene', localPath: path.join(h.dir, id) }),
+  getAllWallpapers: () => [],
+  updateWallpaper: () => {}
+}))
+vi.mock('./config.service', () => ({
+  getDefaultFps: () => null,
+  getDisplayMode: () => 'per-screen',
+  getGlobalEngineFlags: () => ({}),
+  getSplitScreens: () => ({ 'DP-1': { layout: 'aspect', slots: [{ wallpaperId: 'w1' }, { wallpaperId: 'w2' }] } })
+}))
+const applyWallpaperMeta = vi.fn<(wallpaper: { id: string }, options: unknown) => Promise<string>>(async () => '')
+vi.mock('./wallpaper.service', () => ({ applyWallpaperMeta, isAnimatedWallpaper: () => true, usesEngine: () => h.engine }))
+vi.mock('./lwe.service', () => ({
+  ALL_SCREENS: '*',
+  getActiveScreens: () => h.screens,
+  getLweStatus: () => ({ installed: true }),
+  getRunningInstances: () => [],
+  isLweRunning: (screen: string) => (h.live ?? h.screens).includes(screen),
+  getUnusedScreens: () => h.unused,
+  hotswapLweSettings: async () => true,
+  launchLweAsync: async () => {
+    h.launched++
+    if (h.launches.shift() === 'fail') {
+      h.clearOnFail()
+      throw new Error('linux-wallpaperengine failed')
+    }
+  },
+  liveEngineFlagOptions: () => ({}),
+  onLweExit: () => {},
+  stopLwe: async () => {},
+  supportsSplitScreens: () => true
+}))
+
+const display = await import('./display.service')
+const state = await import('./wallpaper-state.service')
+
+beforeAll(() => {
+  h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lwe-restore-'))
+  for (const id of ['w1', 'w2', 'w3']) {
+    fs.mkdirSync(path.join(h.dir, id))
+    fs.writeFileSync(path.join(h.dir, id, 'project.json'), '{}')
+  }
+  h.clearOnFail = () => state.clearAssignment('DP-1')
+})
+
+afterAll(() => {
+  fs.rmSync(h.dir, { recursive: true, force: true })
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+beforeEach(() => {
+  vi.useFakeTimers()
+  h.launches = []
+  h.launched = 0
+  h.screens = ['DP-1']
+  h.unused = []
+  h.live = null
+  h.engine = true
+  applyWallpaperMeta.mockClear()
+  state.clearAssignment()
+  state.setAssignment('DP-1', 'w1')
+  state.markSplitActive('DP-1')
+})
+
+describe('restoring a split', () => {
+  it('shows it again when the first try dies at launch and the second works', async () => {
+    h.launches = ['fail', 'ok']
+
+    await display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(3500)
+
+    expect(h.launched).toBe(2)
+    expect(applyWallpaperMeta).not.toHaveBeenCalled()
+    expect(state.getAssignments()['DP-1']).toBe('w1')
+    expect(state.isSplitActive('DP-1')).toBe(true)
+  })
+
+  it('does not wait for the retry before it goes on to the other screens', async () => {
+    h.launches = ['fail', 'ok']
+
+    await display.restoreAssignedWallpapers()
+
+    expect(h.launched).toBe(1)
+  })
+
+  it('falls back to the first slot when the split keeps dying', async () => {
+    h.launches = ['fail', 'fail']
+
+    await display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(3500)
+
+    expect(h.launched).toBe(2)
+    expect(applyWallpaperMeta.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['w1'])
+    expect(state.isSplitActive('DP-1')).toBe(false)
+  })
+
+  it('leaves the screen to whoever took it while the retry waited', async () => {
+    h.launches = ['fail', 'ok']
+
+    await display.restoreAssignedWallpapers()
+    await display.showWallpaper({ id: 'w3', title: 'w3', localPath: path.join(h.dir, 'w3') } as never, 'DP-1')
+    applyWallpaperMeta.mockClear()
+    await vi.advanceTimersByTimeAsync(3500)
+
+    expect(h.launched).toBe(1)
+    expect(applyWallpaperMeta).not.toHaveBeenCalled()
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+  })
+})
+
+function wallpaperW(n: number): never {
+  return { id: `w${n}`, title: `w${n}`, localPath: path.join(h.dir, `w${n}`) } as never
+}
+
+describe('a launch that a newer one overtook', () => {
+  it('does not write its assignment over the newer one', async () => {
+    const slow = display.showSplitScreen('DP-1')
+    await display.showWallpaper({ id: 'w3', title: 'w3', localPath: path.join(h.dir, 'w3') } as never, 'DP-1')
+    await slow
+
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+    expect(state.isSplitActive('DP-1')).toBe(false)
+  })
+
+  it('still assigns when the newer caller was a stop', async () => {
+    let finish: (value: string) => void = () => {}
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finish = resolve }))
+    const slow = display.showWallpaper(wallpaperW(3), 'DP-1')
+    await display.stopDisplay('DP-1')
+    finish('')
+    await slow
+
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+  })
+
+  it('still assigns when the newer launch failed', async () => {
+    let finish: (value: string) => void = () => {}
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finish = resolve }))
+    applyWallpaperMeta.mockImplementationOnce(async () => { throw new Error('declined') })
+    const slow = display.showWallpaper(wallpaperW(3), 'DP-1')
+    await expect(display.showWallpaper({ id: 'w2', title: 'w2', localPath: path.join(h.dir, 'w2') } as never, 'DP-1')).rejects.toThrow('declined')
+    finish('')
+    await slow
+
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+  })
+
+  it('does not launch onto a screen a newer launch already took', async () => {
+    const first = display.showWallpaper(wallpaperW(3), '*')
+    await first
+    applyWallpaperMeta.mockClear()
+    const older = display.showWallpaper(wallpaperW(2), 'DP-1')
+    await older
+
+    expect(applyWallpaperMeta).toHaveBeenCalledTimes(1)
+  })
+})
+
+describe('a launch whose engine was killed meanwhile', () => {
+  it('is not recorded', async () => {
+    let finish: (value: string) => void = () => {}
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finish = resolve }))
+    const slow = display.showWallpaper(wallpaperW(3), 'DP-1')
+    display.forgetAssignments()
+    h.live = []
+    finish('')
+    await slow
+
+    expect(state.getAssignments()['DP-1']).toBeUndefined()
+  })
+})
+
+describe('a static wallpaper', () => {
+  it('is recorded although no engine runs', async () => {
+    h.engine = false
+    h.live = []
+
+    await display.showWallpaper(wallpaperW(3), 'DP-1')
+
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+  })
+})
+
+describe('a split somebody asked for, overtaken during its prompts', () => {
+  it('still launches and releases the screen', async () => {
+    const before = vi.fn<() => void>()
+    const split = display.showSplitScreen('DP-1', before)
+    await display.showWallpaper(wallpaperW(3), 'DP-1')
+    await split
+
+    expect(before).toHaveBeenCalledOnce()
+    expect(h.launched).toBe(1)
+  })
+})
+
+describe('isShownOn', () => {
+  it('is true only for the screens of the call', async () => {
+    h.screens = ['DP-1', 'DP-2']
+    state.setAssignment('DP-1', 'w3')
+
+    expect(display.isShownOn('w3', 'DP-1')).toBe(true)
+    expect(display.isShownOn('w3', 'DP-2')).toBe(false)
+  })
+})
+
+describe('a split that something newer overtook during its dependency prompts', () => {
+  it('does not launch', async () => {
+    const split = display.showSplitScreen('DP-1')
+    await display.showWallpaper(wallpaperW(3), 'DP-1')
+    await split
+
+    expect(h.launched).toBe(0)
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+  })
+})
+
+describe('a launch on its way', () => {
+  it('keeps an older call from launching onto a screen a newer one is working on', async () => {
+    h.screens = ['DP-1', 'DP-2']
+    let finishOlder: (value: string) => void = () => {}
+    let finishNewer: (value: string) => void = () => {}
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finishOlder = resolve }))
+    const older = display.showWallpaper(wallpaperW(2), '*')
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finishNewer = resolve }))
+    const newer = display.showWallpaper(wallpaperW(3), 'DP-2')
+
+    finishOlder('')
+    await older
+    finishNewer('')
+    await newer
+
+    expect(applyWallpaperMeta.mock.calls.map(([wallpaper, options]) => [wallpaper.id, (options as { screen: string }).screen])).toEqual([
+      ['w2', 'DP-1'],
+      ['w3', 'DP-2']
+    ])
+    expect(state.getAssignments()['DP-2']).toBe('w3')
+  })
+
+  it('lets an older call reach a later screen when the newer call aborted on an earlier one', async () => {
+    h.screens = ['DP-1', 'DP-2']
+    let finishNewer: (value: string) => void = () => {}
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finishNewer = resolve }))
+    const older = display.showWallpaper(wallpaperW(2), 'DP-2')
+    applyWallpaperMeta.mockClear()
+    applyWallpaperMeta.mockImplementationOnce(async () => { throw new Error('declined') })
+    const newer = display.showWallpaper(wallpaperW(3), '*')
+    await expect(newer).rejects.toThrow('declined')
+    finishNewer('')
+    await older
+
+    expect(state.getAssignments()['DP-2']).toBe('w2')
+  })
+
+  it('lets an older call go on when the newer one failed', async () => {
+    applyWallpaperMeta.mockImplementationOnce(async () => { throw new Error('declined') })
+    await expect(display.showWallpaper(wallpaperW(3), 'DP-1')).rejects.toThrow('declined')
+
+    await display.showWallpaper(wallpaperW(2), 'DP-1')
+
+    expect(state.getAssignments()['DP-1']).toBe('w2')
+  })
+})
+
+describe('restoring a screen that is not up yet', () => {
+  it('leaves a screen to a launch that began between two passes', async () => {
+    state.clearAssignment()
+    state.setAssignment('DP-1', 'w8')
+    const restore = display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(0)
+
+    fs.mkdirSync(path.join(h.dir, 'w8'))
+    fs.writeFileSync(path.join(h.dir, 'w8', 'project.json'), '{}')
+    let finish: (value: string) => void = () => {}
+    applyWallpaperMeta.mockImplementationOnce(() => new Promise<string>((resolve) => { finish = resolve }))
+    const user = display.showWallpaper(wallpaperW(3), 'DP-1')
+    applyWallpaperMeta.mockClear()
+    await vi.advanceTimersByTimeAsync(3500)
+    finish('')
+    await user
+    await restore
+
+    expect(applyWallpaperMeta).not.toHaveBeenCalled()
+    expect(state.getAssignments()['DP-1']).toBe('w3')
+  })
+
+  it('waits for a wallpaper folder that is mounted a moment later', async () => {
+    state.clearAssignment()
+    state.setAssignment('DP-1', 'w9')
+    const restore = display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(0)
+    expect(applyWallpaperMeta).not.toHaveBeenCalled()
+
+    fs.mkdirSync(path.join(h.dir, 'w9'))
+    fs.writeFileSync(path.join(h.dir, 'w9', 'project.json'), '{}')
+    await vi.advanceTimersByTimeAsync(3500)
+    await restore
+
+    expect(applyWallpaperMeta.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['w9'])
+  })
+
+  it('does not retry an old shared assignment in per-screen mode', async () => {
+    state.clearAssignment()
+    state.setAssignment('*', 'w1')
+    const restore = display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(0)
+    await restore
+
+    expect(h.launched).toBe(0)
+  })
+
+  it('restores it when the output shows up a moment later', async () => {
+    h.screens = ['DP-2']
+    const restore = display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(0)
+    expect(h.launched).toBe(0)
+
+    h.screens = ['DP-1', 'DP-2']
+    await vi.advanceTimersByTimeAsync(3500)
+    await restore
+
+    expect(h.launched).toBe(1)
+  })
+
+  it('does not wait for a screen the user turned off', async () => {
+    h.screens = ['DP-2']
+    h.unused = ['DP-1']
+    const restore = display.restoreAssignedWallpapers()
+    await restore
+
+    expect(h.launched).toBe(0)
+  })
+
+  it('gives up after a few tries', async () => {
+    h.screens = ['DP-2']
+    const restore = display.restoreAssignedWallpapers()
+    await vi.advanceTimersByTimeAsync(30_000)
+    await restore
+
+    expect(h.launched).toBe(0)
+  })
+})
+
+describe('quitting', () => {
+  it('starts nothing after the app began to quit', async () => {
+    h.launches = ['fail', 'ok']
+
+    await display.restoreAssignedWallpapers()
+    display.cancelRestore()
+    await vi.advanceTimersByTimeAsync(3500)
+
+    expect(h.launched).toBe(1)
+    expect(applyWallpaperMeta).not.toHaveBeenCalled()
+  })
+
+  it('also starts nothing when the quit came before the restore began', async () => {
+    display.cancelRestore()
+
+    await display.restoreAssignedWallpapers()
+
+    expect(h.launched).toBe(0)
+    expect(applyWallpaperMeta).not.toHaveBeenCalled()
+  })
+})

+ 267 - 63
src/main/services/display.service.ts

@@ -8,18 +8,21 @@ import type {
   EngineFlags,
   EngineFlags,
   ScreenAssignment,
   ScreenAssignment,
   ScreenTarget,
   ScreenTarget,
+  SplitScreen,
   WallpaperBackend,
   WallpaperBackend,
   WallpaperCompat,
   WallpaperCompat,
   WallpaperMeta
   WallpaperMeta
 } from '@shared/types'
 } from '@shared/types'
 import { getAllWallpapers, getWallpaper, updateWallpaper } from './library.service'
 import { getAllWallpapers, getWallpaper, updateWallpaper } from './library.service'
-import { applyWallpaperMeta, isAnimatedWallpaper } from './wallpaper.service'
+import { applyWallpaperMeta, isAnimatedWallpaper, usesEngine } from './wallpaper.service'
 import {
 import {
   ALL_SCREENS,
   ALL_SCREENS,
   getActiveScreens,
   getActiveScreens,
   getLweStatus,
   getLweStatus,
   getRunningInstances,
   getRunningInstances,
+  getUnusedScreens,
   hotswapLweSettings,
   hotswapLweSettings,
+  isLweRunning,
   launchLweAsync,
   launchLweAsync,
   liveEngineFlagOptions,
   liveEngineFlagOptions,
   onLweExit,
   onLweExit,
@@ -29,23 +32,73 @@ import {
   type LweSplitSlot
   type LweSplitSlot
 } from './lwe.service'
 } from './lwe.service'
 import { resolveEngineFlags } from '@shared/engineFlags'
 import { resolveEngineFlags } from '@shared/engineFlags'
-import { clearAssignment, getAssignments, setAssignment } from './wallpaper-state.service'
-import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens, setSplitScreen } from './config.service'
-import { planRestore, restoreSuperseded } from './restore-plan'
+import {
+  clearAssignment,
+  getAssignments,
+  isSplitActive,
+  markSplitActive,
+  setAssignment,
+  splitActiveScreens
+} from './wallpaper-state.service'
+import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens } from './config.service'
+import { planRestore, restoreSuperseded, trySplit, type RestoreInput } from './restore-plan'
 import { ensureDependencyInstalled } from './dependency.service'
 import { ensureDependencyInstalled } from './dependency.service'
 import { t } from '../i18n'
 import { t } from '../i18n'
 
 
 const LAUNCH_CHECK_MS = 20_000
 const LAUNCH_CHECK_MS = 20_000
-// bumped when a screen is launched or stopped, so a later restore does not replace that
+// bumped by every launch and stop of a screen, so a restore can tell it was overtaken
 const screenUse = new Map<string, number>()
 const screenUse = new Map<string, number>()
 
 
-function markScreenUsed(screen: ScreenTarget): void {
-  screenUse.set(screen, (screenUse.get(screen) ?? 0) + 1)
+function markScreenUsed(screen: ScreenTarget): number {
+  const count = (screenUse.get(screen) ?? 0) + 1
+  screenUse.set(screen, count)
+
+  return count
 }
 }
 
 
 function screenUseCount(screen: ScreenTarget): number {
 function screenUseCount(screen: ScreenTarget): number {
   return screenUse.get(screen) ?? 0
   return screenUse.get(screen) ?? 0
 }
 }
+
+const screenCommitted = new Map<string, number>()
+
+function newerLaunchLanded(screen: ScreenTarget, stamp: number): boolean {
+  return (screenCommitted.get(screen) ?? 0) > stamp
+}
+
+// a stop never claims a screen
+const screenClaims = new Map<string, number>()
+
+function claimStamp(screen: ScreenTarget, stamp: number): void {
+  if ((screenClaims.get(screen) ?? 0) < stamp) screenClaims.set(screen, stamp)
+}
+
+function claimScreen(screen: ScreenTarget): number {
+  const stamp = markScreenUsed(screen)
+  claimStamp(screen, stamp)
+
+  return stamp
+}
+
+function releaseScreen(screen: ScreenTarget, stamp: number): void {
+  if (screenClaims.get(screen) === stamp) screenClaims.delete(screen)
+}
+
+function newerLaunchTakes(screen: ScreenTarget, stamp: number): boolean {
+  return newerLaunchLanded(screen, stamp) || (screenClaims.get(screen) ?? 0) > stamp
+}
+
+// a killed engine still resolves its launch
+function launchStood(engine: boolean, screen: ScreenTarget): boolean {
+  return !engine || isLweRunning(screen)
+}
+
+function commitLaunch(screen: ScreenTarget, stamp: number): boolean {
+  if (newerLaunchLanded(screen, stamp)) return false
+  screenCommitted.set(screen, stamp)
+
+  return true
+}
 // automatic relaunches after a runtime crash, at most one per screen in this window
 // automatic relaunches after a runtime crash, at most one per screen in this window
 const RELAUNCH_COOLDOWN_MS = 60_000
 const RELAUNCH_COOLDOWN_MS = 60_000
 
 
@@ -53,6 +106,7 @@ let win: BrowserWindow | null = null
 const lastAutoRelaunch = new Map<ScreenTarget, number>()
 const lastAutoRelaunch = new Map<ScreenTarget, number>()
 const launchChecks = new Map<ScreenTarget, ReturnType<typeof setTimeout>>()
 const launchChecks = new Map<ScreenTarget, ReturnType<typeof setTimeout>>()
 let playlistRecovery: ((screen: ScreenTarget, wallpaperId: string) => boolean) | null = null
 let playlistRecovery: ((screen: ScreenTarget, wallpaperId: string) => boolean) | null = null
+let volumeSource: VolumeSource | null = null
 
 
 function send(channel: string, payload?: unknown): void {
 function send(channel: string, payload?: unknown): void {
   if (win && !win.isDestroyed()) win.webContents.send(channel, payload)
   if (win && !win.isDestroyed()) win.webContents.send(channel, payload)
@@ -65,14 +119,25 @@ export function getDisplayTargets(): ScreenTarget[] {
 }
 }
 
 
 /** '*' (or nothing) means every screen: one engine in shared mode, one per screen otherwise */
 /** '*' (or nothing) means every screen: one engine in shared mode, one per screen otherwise */
-export function expandScreen(screen?: ScreenTarget): ScreenTarget[] {
-  const targets = getDisplayTargets()
+export function expandScreen(screen?: ScreenTarget, targets: ScreenTarget[] = getDisplayTargets()): ScreenTarget[] {
   if (screen === undefined || screen === ALL_SCREENS) return targets
   if (screen === undefined || screen === ALL_SCREENS) return targets
   return targets.includes(screen) ? [screen] : []
   return targets.includes(screen) ? [screen] : []
 }
 }
 
 
+export function isShownOn(wallpaperId: string, screen?: ScreenTarget): boolean {
+  const assigned = getAssignments()
+
+  return expandScreen(screen).some((target) => (assigned[target] ?? assigned[ALL_SCREENS]) === wallpaperId)
+}
+
 export function getScreenAssignments(): ScreenAssignment[] {
 export function getScreenAssignments(): ScreenAssignment[] {
-  return Object.entries(getAssignments()).map(([screen, wallpaperId]) => ({ screen, wallpaperId }))
+  const splits = new Set(splitActiveScreens())
+
+  return Object.entries(getAssignments()).map(([screen, wallpaperId]) => ({
+    screen,
+    wallpaperId,
+    split: splits.has(screen)
+  }))
 }
 }
 
 
 const busySources = new Map<string, () => string[]>()
 const busySources = new Map<string, () => string[]>()
@@ -108,6 +173,10 @@ export function setPlaylistRecovery(handler: (screen: ScreenTarget, wallpaperId:
   playlistRecovery = handler
   playlistRecovery = handler
 }
 }
 
 
+export function setVolumeSource(source: VolumeSource): void {
+  volumeSource = source
+}
+
 function patchCompat(wallpaper: WallpaperMeta, patch: Partial<WallpaperCompat>): void {
 function patchCompat(wallpaper: WallpaperMeta, patch: Partial<WallpaperCompat>): void {
   updateWallpaper(wallpaper.id, { compat: { ...wallpaper.compat, ...patch } })
   updateWallpaper(wallpaper.id, { compat: { ...wallpaper.compat, ...patch } })
   send(IpcChannels.EVENT_LIBRARY_CHANGED)
   send(IpcChannels.EVENT_LIBRARY_CHANGED)
@@ -142,15 +211,21 @@ export async function showWallpaper(
   if (targets.length === 0) throw new Error(`Screen ${screen} is not connected`)
   if (targets.length === 0) throw new Error(`Screen ${screen} is not connected`)
 
 
   let appliedPath = ''
   let appliedPath = ''
-  for (const target of targets) {
-    markScreenUsed(target)
-    appliedPath = await applyWallpaperMeta(wallpaper, { ...options, screen: target })
-    setAssignment(target, wallpaper.id)
-    // a single wallpaper replaces a split, or the next start would bring the split back
-    // whenever this wallpaper is also the split's first slot
-    setSplitScreen(target, null)
-    // only a wallpaper that crashed on launch before needs its fresh launches watched
-    if (wallpaper.compat?.freshLaunch === 'crash') watchLaunch(wallpaper.id, target)
+  const engine = usesEngine(wallpaper)
+  const stamps = new Map(targets.map((target) => [target, markScreenUsed(target)]))
+  try {
+    for (const target of targets) {
+      const stamp = stamps.get(target) ?? 0
+      if (newerLaunchTakes(target, stamp)) continue
+      claimStamp(target, stamp)
+      appliedPath = await applyWallpaperMeta(wallpaper, { ...options, screen: target })
+      if (!launchStood(engine, target) || !commitLaunch(target, stamp)) continue
+      setAssignment(target, wallpaper.id)
+      // only a wallpaper that crashed on launch before needs its fresh launches watched
+      if (wallpaper.compat?.freshLaunch === 'crash') watchLaunch(wallpaper.id, target)
+    }
+  } finally {
+    for (const [target, stamp] of stamps) releaseScreen(target, stamp)
   }
   }
   send(IpcChannels.EVENT_DISPLAY_CHANGED)
   send(IpcChannels.EVENT_DISPLAY_CHANGED)
   return appliedPath
   return appliedPath
@@ -160,21 +235,40 @@ export async function showWallpaper(
 export async function showSplitScreen(
 export async function showSplitScreen(
   screen: ScreenTarget,
   screen: ScreenTarget,
   beforeLaunch?: () => void,
   beforeLaunch?: () => void,
-  dependencyPrompt: 'always' | 'once' | 'never' = 'always'
+  dependencyPrompt: 'always' | 'once' | 'never' = 'always',
+  skipMissing = false
 ): Promise<void> {
 ): Promise<void> {
   if (getDisplayMode() !== 'per-screen' || screen === ALL_SCREENS) throw new Error(t('split.needsPerScreen'))
   if (getDisplayMode() !== 'per-screen' || screen === ALL_SCREENS) throw new Error(t('split.needsPerScreen'))
   if (!getDisplayTargets().includes(screen)) throw new Error(`Screen ${screen} is not connected`)
   if (!getDisplayTargets().includes(screen)) throw new Error(`Screen ${screen} is not connected`)
   if (!supportsSplitScreens()) throw new Error(t('split.engineTooOld'))
   if (!supportsSplitScreens()) throw new Error(t('split.engineTooOld'))
+  const claim = { stamp: claimScreen(screen) }
+  try {
+    await launchSplit(screen, claim, beforeLaunch, dependencyPrompt, skipMissing)
+  } finally {
+    releaseScreen(screen, claim.stamp)
+  }
+}
+
+async function launchSplit(
+  screen: ScreenTarget,
+  claim: { stamp: number },
+  beforeLaunch: (() => void) | undefined,
+  dependencyPrompt: 'always' | 'once' | 'never',
+  skipMissing: boolean
+): Promise<void> {
 
 
   const split = getSplitScreens()[screen]
   const split = getSplitScreens()[screen]
   const slots: LweSplitSlot[] = []
   const slots: LweSplitSlot[] = []
   const shown: WallpaperMeta[] = []
   const shown: WallpaperMeta[] = []
-  for (const slot of split?.slots ?? []) {
-    const wallpaper = getWallpaper(slot.wallpaperId)
-    if (!wallpaper?.localPath || !isAnimatedWallpaper(wallpaper) || !wallpaperIsOnDisk(wallpaper.localPath)) continue
-    await ensureDependencyInstalled(wallpaper, dependencyPrompt)
+  for (const { slot, wallpaper, path: slotPath } of showableSplitSlots(screen, skipMissing)) {
+    try {
+      await ensureDependencyInstalled(wallpaper, dependencyPrompt)
+    } catch (err) {
+      if (dependencyPrompt === 'never') continue
+      throw err
+    }
     slots.push({
     slots.push({
-      path: wallpaper.localPath,
+      path: slotPath,
       scalingMode: slot.scalingMode ?? wallpaper.scalingMode,
       scalingMode: slot.scalingMode ?? wallpaper.scalingMode,
       zoom: wallpaper.zoom,
       zoom: wallpaper.zoom,
       offsetX: wallpaper.offsetX,
       offsetX: wallpaper.offsetX,
@@ -185,7 +279,12 @@ export async function showSplitScreen(
     shown.push(wallpaper)
     shown.push(wallpaper)
   }
   }
   if (slots.length === 0 || !split) throw new Error(t('split.empty'))
   if (slots.length === 0 || !split) throw new Error(t('split.empty'))
-  markScreenUsed(screen)
+  if (newerLaunchTakes(screen, claim.stamp)) {
+    // restore leaves the screen to whoever took it, a split somebody asked for goes on
+    if (!beforeLaunch) return
+    releaseScreen(screen, claim.stamp)
+    claim.stamp = claimScreen(screen)
+  }
   beforeLaunch?.()
   beforeLaunch?.()
 
 
   // overrides would hit every slot by id, so slots play as published
   // overrides would hit every slot by id, so slots play as published
@@ -196,12 +295,16 @@ export async function showSplitScreen(
     fps: getDefaultFps() ?? undefined,
     fps: getDefaultFps() ?? undefined,
     forceFresh: true
     forceFresh: true
   })
   })
+  if (!isLweRunning(screen) || !commitLaunch(screen, claim.stamp)) return
   setAssignment(screen, shown[0].id)
   setAssignment(screen, shown[0].id)
+  markSplitActive(screen)
   send(IpcChannels.EVENT_DISPLAY_CHANGED)
   send(IpcChannels.EVENT_DISPLAY_CHANGED)
 }
 }
 
 
 export async function stopDisplay(screen?: ScreenTarget): Promise<void> {
 export async function stopDisplay(screen?: ScreenTarget): Promise<void> {
-  for (const target of expandScreen(screen)) markScreenUsed(target)
+  // no expandScreen here, it shells out
+  const marked = screen === undefined || screen === ALL_SCREENS ? [...screenUse.keys()] : [screen]
+  for (const target of marked) markScreenUsed(target)
   if (screen === undefined || screen === ALL_SCREENS) {
   if (screen === undefined || screen === ALL_SCREENS) {
     await stopLwe()
     await stopLwe()
     clearAssignment()
     clearAssignment()
@@ -224,7 +327,12 @@ function notifyCrash(wallpaper: WallpaperMeta, screen: ScreenTarget, phase: Cras
 
 
 async function relaunchFresh(wallpaper: WallpaperMeta, screen: ScreenTarget): Promise<boolean> {
 async function relaunchFresh(wallpaper: WallpaperMeta, screen: ScreenTarget): Promise<boolean> {
   try {
   try {
-    await applyWallpaperMeta(getWallpaper(wallpaper.id) ?? wallpaper, { screen, forceFresh: true, dependencyPrompt: 'once' })
+    await applyWallpaperMeta(getWallpaper(wallpaper.id) ?? wallpaper, {
+      screen,
+      forceFresh: true,
+      dependencyPrompt: 'once',
+      volume: volumeSource?.(screen, wallpaper.id)
+    })
     return true
     return true
   } catch (err) {
   } catch (err) {
     console.error('[Display] Fresh relaunch failed:', (err as Error).message)
     console.error('[Display] Fresh relaunch failed:', (err as Error).message)
@@ -312,13 +420,24 @@ export async function testFreshLaunch(wallpaperId: string, screen?: ScreenTarget
   if (!wallpaper) throw new Error(`Wallpaper ${wallpaperId} not found in library`)
   if (!wallpaper) throw new Error(`Wallpaper ${wallpaperId} not found in library`)
   const target = expandScreen(screen)[0]
   const target = expandScreen(screen)[0]
   if (!target) throw new Error('No screen to test on')
   if (!target) throw new Error('No screen to test on')
-  await applyWallpaperMeta(wallpaper, { screen: target, forceFresh: true })
-  setAssignment(target, wallpaper.id)
+  const stamp = claimScreen(target)
+  try {
+    await applyWallpaperMeta(wallpaper, { screen: target, forceFresh: true })
+  } finally {
+    releaseScreen(target, stamp)
+  }
+  if (launchStood(usesEngine(wallpaper), target) && commitLaunch(target, stamp)) setAssignment(target, wallpaper.id)
   send(IpcChannels.EVENT_DISPLAY_CHANGED)
   send(IpcChannels.EVENT_DISPLAY_CHANGED)
   watchLaunch(wallpaper.id, target, () => { notifyCrash(getWallpaper(wallpaper.id) ?? wallpaper, target, 'launch', t('crash.testPassed')) }
   watchLaunch(wallpaper.id, target, () => { notifyCrash(getWallpaper(wallpaper.id) ?? wallpaper, target, 'launch', t('crash.testPassed')) }
   )
   )
 }
 }
 
 
+export function forgetAssignments(): void {
+  for (const target of screenUse.keys()) markScreenUsed(target)
+  clearAssignment()
+  send(IpcChannels.EVENT_DISPLAY_CHANGED)
+}
+
 /** Stops everything and forgets assignments, the screens mean something else after a mode switch */
 /** Stops everything and forgets assignments, the screens mean something else after a mode switch */
 export async function resetDisplays(): Promise<void> {
 export async function resetDisplays(): Promise<void> {
   for (const timer of launchChecks.values()) clearTimeout(timer)
   for (const timer of launchChecks.values()) clearTimeout(timer)
@@ -333,7 +452,7 @@ export function initDisplay(window: BrowserWindow): void {
   })
   })
 }
 }
 
 
-/** A missing drive still has a library entry. Launching that path marks a healthy wallpaper as a launch crash. */
+// a missing drive keeps its library entry, and launching it would mark a healthy wallpaper as crashed
 function wallpaperIsOnDisk(localPath: string): boolean {
 function wallpaperIsOnDisk(localPath: string): boolean {
   if (!fs.existsSync(localPath)) return false
   if (!fs.existsSync(localPath)) return false
   try {
   try {
@@ -343,45 +462,109 @@ function wallpaperIsOnDisk(localPath: string): boolean {
   }
   }
 }
 }
 
 
-/** The slot showSplitScreen would store as the assignment, when that folder is actually there */
-function splitSlotId(screen: ScreenTarget): string | null {
-  const split = getSplitScreens()[screen]
-  if (!split) return null
-  for (const slot of split.slots) {
+// a manual show lets the engine report a missing folder
+function showableSplitSlots(screen: ScreenTarget, onDiskOnly = true): { slot: SplitScreen['slots'][number]; wallpaper: WallpaperMeta; path: string }[] {
+  return (getSplitScreens()[screen]?.slots ?? []).flatMap((slot) => {
     const wallpaper = getWallpaper(slot.wallpaperId)
     const wallpaper = getWallpaper(slot.wallpaperId)
-    if (!wallpaper?.localPath || !isAnimatedWallpaper(wallpaper) || !wallpaperIsOnDisk(wallpaper.localPath)) continue
-    return wallpaper.id
-  }
-  return null
-}
-
-/**
- * Puts the last animated wallpaper back on each screen after a restart. A live engine already showing
- * it is left alone. A split comes back through showSplitScreen. Screens a playlist or schedule just
- * claimed are skipped so the two launches do not run over each other.
- */
-export async function restoreAssignedWallpapers(skipScreens: ReadonlySet<ScreenTarget> = new Set()): Promise<void> {
-  if (!getLweStatus().installed) return
-  const saved = getAssignments()
-  const useAtStart = new Map(Object.keys(saved).map((screen) => [screen, screenUseCount(screen)]))
-  const targets = new Set(getDisplayTargets())
+    const localPath = wallpaper?.localPath
+    return wallpaper && localPath && isAnimatedWallpaper(wallpaper) && (!onDiskOnly || wallpaperIsOnDisk(localPath)) ? [{ slot, wallpaper, path: localPath }] : []
+  })
+}
+
+const SPLIT_RETRY_MS = 3000
+
+export type VolumeSource = (screen: ScreenTarget, wallpaperId: string) => number | undefined
+
+type Running = ReturnType<typeof getRunningInstances>[number]
+
+function engineOf(inst?: Running): RestoreInput['running'] {
+  return inst ? { split: !!inst.split, wallpaperPath: inst.wallpaperPath } : undefined
+}
+
+// a restore waiting for a retry must not start an engine after the shutdown kill
+let restoreRun = 0
+let restoreCancelled = false
+
+export function cancelRestore(): void {
+  restoreCancelled = true
+  restoreRun++
+}
+
+function splitTry(screen: ScreenTarget) {
+  return trySplit({
+    show: () => showSplitScreen(screen, undefined, 'never', true),
+    uses: () => screenUseCount(screen),
+    onError: (err) => { console.error(`[Display] Could not restore the split on ${screen}:`, (err as Error).message) }
+  })
+}
+
+async function retrySplit(
+  run: number,
+  screen: ScreenTarget,
+  wallpaper: WallpaperMeta | null | undefined,
+  input: RestoreInput,
+  volumeFor?: VolumeSource
+): Promise<void> {
+  const settled = screenUseCount(screen)
+  await new Promise((resolve) => setTimeout(resolve, SPLIT_RETRY_MS))
+  if (run !== restoreRun || screenUseCount(screen) !== settled) return
+  if ((await splitTry(screen)) !== 'failed' || !wallpaper || run !== restoreRun) return
+
+  // the failed tries changed what is running
+  const live = getRunningInstances().find((inst) => inst.screen === screen)
+  if (planRestore({ ...input, splitActive: false, running: engineOf(live) }) !== 'wallpaper') return
+
+  console.log(`[Display] Restoring ${wallpaper.title} on ${screen} instead of its split`)
+  await showWallpaper(wallpaper, screen, { dependencyPrompt: 'never', volume: volumeFor?.(screen, wallpaper.id) })
+}
+
+export async function restoreAssignedWallpapers(
+  skipScreens: ReadonlySet<ScreenTarget> = new Set(),
+  volumeFor?: VolumeSource
+): Promise<void> {
+  if (restoreCancelled || !getLweStatus().installed) return
+  await restoreScreens(++restoreRun, skipScreens, volumeFor, undefined, 0)
+}
+
+const RESTORE_RETRIES = 5
+
+async function restoreScreens(
+  run: number,
+  skipScreens: ReadonlySet<ScreenTarget>,
+  volumeFor: VolumeSource | undefined,
+  only: readonly ScreenTarget[] | undefined,
+  attempt: number,
+  carried?: { useAtStart: Map<string, number>; targets?: Set<string> }
+): Promise<void> {
+  const saved = Object.fromEntries(Object.entries(getAssignments()).filter(([screen]) => !only || only.includes(screen)))
+  // judged against the first pass, a launch started since has taken the screen
+  const useAtStart = new Map(Object.keys(saved).map((screen) => [screen, carried?.useAtStart.get(screen) ?? screenUseCount(screen)]))
+  const targets = carried?.targets ?? new Set(getDisplayTargets())
   const running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
   const running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
+  // '*' is an old single-wallpaper assignment, restorable in shared mode only
+  const missing = Object.keys(saved).filter((screen) => screen !== ALL_SCREENS && !targets.has(screen) && !skipScreens.has(screen))
+  const unused = missing.length > 0 ? new Set(getUnusedScreens()) : new Set<string>()
+  const waiting = new Set(missing.filter((screen) => !unused.has(screen)))
   for (const [screen, wallpaperId] of Object.entries(saved)) {
   for (const [screen, wallpaperId] of Object.entries(saved)) {
+    if (run !== restoreRun) return
     const wallpaper = getWallpaper(wallpaperId)
     const wallpaper = getWallpaper(wallpaperId)
     const localPath = wallpaper?.localPath ?? ''
     const localPath = wallpaper?.localPath ?? ''
     const inst = running.get(screen)
     const inst = running.get(screen)
-    const plan = planRestore({
+    const splitActive = isSplitActive(screen)
+    const input: RestoreInput = {
       skipped: skipScreens.has(screen),
       skipped: skipScreens.has(screen),
       connected: targets.has(screen),
       connected: targets.has(screen),
       animated: !!wallpaper && isAnimatedWallpaper(wallpaper),
       animated: !!wallpaper && isAnimatedWallpaper(wallpaper),
       onDisk: !!localPath && wallpaperIsOnDisk(localPath),
       onDisk: !!localPath && wallpaperIsOnDisk(localPath),
       localPath,
       localPath,
-      running: inst ? { split: !!inst.split, wallpaperPath: inst.wallpaperPath } : undefined,
-      splitSlotId: splitSlotId(screen),
-      wallpaperId
-    })
-    if (plan === 'skip' || !wallpaper) continue
-    // an earlier screen takes at least 2s. Play, the tray or a playlist may have taken this one since.
+      running: engineOf(inst),
+      splitActive,
+      splitShowable: splitActive && showableSplitSlots(screen).length > 0
+    }
+    const plan = planRestore(input)
+    if (plan === 'wait') waiting.add(screen)
+    if (plan === 'skip' || plan === 'wait') continue
+    // an earlier screen takes 2s or more, Play, the tray or a playlist may have taken this one since
     if (restoreSuperseded(wallpaperId, getAssignments()[screen], useAtStart.get(screen) ?? 0, screenUseCount(screen))) {
     if (restoreSuperseded(wallpaperId, getAssignments()[screen], useAtStart.get(screen) ?? 0, screenUseCount(screen))) {
       console.log(`[Display] Leaving ${screen}, it changed while restoring`)
       console.log(`[Display] Leaving ${screen}, it changed while restoring`)
       continue
       continue
@@ -389,13 +572,34 @@ export async function restoreAssignedWallpapers(skipScreens: ReadonlySet<ScreenT
     try {
     try {
       if (plan === 'split') {
       if (plan === 'split') {
         console.log(`[Display] Restoring split on ${screen}`)
         console.log(`[Display] Restoring split on ${screen}`)
-        await showSplitScreen(screen, undefined, 'never')
-      } else {
-        console.log(`[Display] Restoring ${wallpaper.title} on ${screen}`)
-        await showWallpaper(wallpaper, screen, { dependencyPrompt: 'never' })
+
+        if ((await splitTry(screen)) === 'failed') {
+          void retrySplit(run, screen, wallpaper, input, volumeFor).catch((err: unknown) => {
+            console.error(`[Display] Could not restore ${screen}:`, (err as Error).message)
+          })
+        }
+        continue
       }
       }
+
+      if (!wallpaper) continue
+
+      console.log(`[Display] Restoring ${wallpaper.title} on ${screen}`)
+      await showWallpaper(wallpaper, screen, { dependencyPrompt: 'never', volume: volumeFor?.(screen, wallpaperId) })
     } catch (err) {
     } catch (err) {
       console.error(`[Display] Could not restore ${wallpaper?.title ?? wallpaperId} on ${screen}:`, (err as Error).message)
       console.error(`[Display] Could not restore ${wallpaper?.title ?? wallpaperId} on ${screen}:`, (err as Error).message)
     }
     }
   }
   }
+
+  if (waiting.size === 0) return
+  if (attempt >= RESTORE_RETRIES) {
+    console.log(`[Display] Gave up restoring ${[...waiting].join(', ')}, still waiting after ${RESTORE_RETRIES} tries`)
+    return
+  }
+  await new Promise((resolve) => setTimeout(resolve, SPLIT_RETRY_MS))
+  if (run !== restoreRun) return
+  const onlyFolders = [...waiting].every((screen) => targets.has(screen))
+  await restoreScreens(run, skipScreens, volumeFor, [...waiting], attempt + 1, {
+    useAtStart,
+    targets: onlyFolders ? targets : undefined
+  })
 }
 }

+ 14 - 0
src/main/services/lwe.service.test.ts

@@ -174,6 +174,10 @@ describe('buildHotswapLines', () => {
     ])
     ])
   })
   })
 
 
+  it('resets to the engine default volume when the swapped wallpaper has none', () => {
+    expect(buildHotswapLines(hotswapOptionsFor('/w/loud', {}))).toContain('volume=15')
+  })
+
   it('keeps a muted wallpaper muted when the swap is built', () => {
   it('keeps a muted wallpaper muted when the swap is built', () => {
     expect(buildHotswapLines(hotswapOptionsFor('/w/quiet', { volume: 0, soundVolume: { '7': 0 } }))).toContain('volume=0')
     expect(buildHotswapLines(hotswapOptionsFor('/w/quiet', { volume: 0, soundVolume: { '7': 0 } }))).toContain('volume=0')
   })
   })
@@ -305,3 +309,13 @@ describe('parsePacmanRepos', () => {
     expect(parsePacmanRepos(conf)).toEqual(['core', 'extra', 'garuda'])
     expect(parsePacmanRepos(conf)).toEqual(['core', 'extra', 'garuda'])
   })
   })
 })
 })
+
+describe('launches while the app quits', () => {
+  it('start no engine', async () => {
+    vi.resetModules()
+    const fresh = await import('./lwe.service')
+    fresh.blockLaunches()
+
+    await expect(fresh.launchLweAsync('/w/a', { screen: 'DP-1' })).rejects.toThrow('quitting')
+  })
+})

+ 17 - 6
src/main/services/lwe.service.ts

@@ -66,7 +66,7 @@ import {
   getDisabledScreens,
   getDisabledScreens,
   getFreshProcessOnPathChange
   getFreshProcessOnPathChange
 } from './config.service'
 } from './config.service'
-import { DEFAULT_LWE_FPS, DEFAULT_LWE_REPO } from '@shared/constants'
+import { DEFAULT_ENGINE_VOLUME, DEFAULT_LWE_FPS, DEFAULT_LWE_REPO } from '@shared/constants'
 import { engineFlagArgs, filterSupportedArgs } from '@shared/engineFlags'
 import { engineFlagArgs, filterSupportedArgs } from '@shared/engineFlags'
 import { imageAdjustmentArgs, imageAdjustmentLines, type ImageAdjustments } from '@shared/imageAdjustments'
 import { imageAdjustmentArgs, imageAdjustmentLines, type ImageAdjustments } from '@shared/imageAdjustments'
 import { formatVideoSegments, type VideoSegment } from '@shared/videoTrim'
 import { formatVideoSegments, type VideoSegment } from '@shared/videoTrim'
@@ -1042,9 +1042,13 @@ function windowedGeometry(screen?: ScreenTarget): string {
   return getScreenGeometry(screen && screen !== ALL_SCREENS ? screen : undefined) ?? FALLBACK_WINDOW
   return getScreenGeometry(screen && screen !== ALL_SCREENS ? screen : undefined) ?? FALLBACK_WINDOW
 }
 }
 
 
+export function getUnusedScreens(): string[] {
+  return [...getDisabledScreens(), ...getMirroredScreens()]
+}
+
 export function getActiveScreens(): string[] {
 export function getActiveScreens(): string[] {
   const all = getConnectedScreens()
   const all = getConnectedScreens()
-  const off = new Set([...getDisabledScreens(), ...getMirroredScreens()])
+  const off = new Set(getUnusedScreens())
   const active = all.filter((s) => !off.has(s))
   const active = all.filter((s) => !off.has(s))
   return active.length > 0 ? active : all
   return active.length > 0 ? active : all
 }
 }
@@ -1754,9 +1758,8 @@ export function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptio
       ...options.audioSensitivity
       ...options.audioSensitivity
     },
     },
     soundVolume: options.soundVolume ?? {},
     soundVolume: options.soundVolume ?? {},
-    // 0 must be sent. Leaving volume out keeps the previous wallpaper's level, so a muted wallpaper
-    // comes back audible when it is applied to another screen.
-    ...(options.volume !== undefined ? { volume: options.volume } : {}),
+    // a swap that sends no volume keeps the previous wallpaper's level, muted included
+    volume: options.volume ?? DEFAULT_ENGINE_VOLUME,
     ...(supportsEffectHotswap()
     ...(supportsEffectHotswap()
       ? { disabledEffects: options.disabledEffects ?? [], enabledEffects: options.enabledEffects ?? [] }
       ? { disabledEffects: options.disabledEffects ?? [], enabledEffects: options.enabledEffects ?? [] }
       : {}),
       : {}),
@@ -1765,7 +1768,6 @@ export function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptio
   }
   }
 }
 }
 
 
-/** Same-path changes hotswap. A different path hotswaps too, unless the setting starts a new process. */
 export function canHotswapExisting(
 export function canHotswapExisting(
   existing: { wallpaperPath: string; launchKey: string; controlFile: string | null } | undefined,
   existing: { wallpaperPath: string; launchKey: string; controlFile: string | null } | undefined,
   options: { forceFresh?: boolean; customArgs?: string },
   options: { forceFresh?: boolean; customArgs?: string },
@@ -1781,8 +1783,16 @@ export function canHotswapExisting(
   return true
   return true
 }
 }
 
 
+let launchesBlocked = false
+
+/** The app is quitting: an engine that starts now would outlive the shutdown kill */
+export function blockLaunches(): void {
+  launchesBlocked = true
+}
+
 /** Hotswaps the engine on the screen when possible, else restarts it. Resolves once it survived 2s */
 /** Hotswaps the engine on the screen when possible, else restarts it. Resolves once it survived 2s */
 export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOptions = {}): Promise<void> {
 export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOptions = {}): Promise<void> {
+  if (launchesBlocked) throw new Error('WE Manager is quitting')
   const screen = options.screen ?? ALL_SCREENS
   const screen = options.screen ?? ALL_SCREENS
   const key = launchKey(options)
   const key = launchKey(options)
 
 
@@ -1806,6 +1816,7 @@ export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOp
   }
   }
 
 
   await stopLwe(screen)
   await stopLwe(screen)
+  if (launchesBlocked) throw new Error('WE Manager is quitting')
 
 
   const binaryPath = getLweBinaryPath()
   const binaryPath = getLweBinaryPath()
   const controlFile = supportsFlag('--control-file') ? controlFileFor(screen) : null
   const controlFile = supportsFlag('--control-file') ? controlFileFor(screen) : null

+ 578 - 0
src/main/services/playlist-player.service.test.ts

@@ -0,0 +1,578 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const h = vi.hoisted(() => ({
+  disk: {} as Record<string, unknown>,
+  skipResume: false,
+  targets: ['DP-1', 'DP-2'],
+  assignments: {} as Record<string, string>,
+  gate: null as Promise<string> | null,
+  overtaken: false,
+  release: (_value: string) => {},
+  playlist: {
+    id: 'p',
+    title: 'p',
+    items: [{ wallpaperId: 'a' }, { wallpaperId: 'b', volume: 30 }, { wallpaperId: 'c' }],
+    settings: { randomize: false, sortBy: 'manual', defaultDurationSec: 60, defaultVolume: 80 },
+    createdAt: 0,
+    updatedAt: 0
+  }
+}))
+
+vi.mock('electron', () => ({ app: { on: () => {} } }))
+// the saved players outlive a "restart", which is a fresh import of the service
+vi.mock('electron-store', () => ({
+  default: class {
+    constructor(opts: { defaults: Record<string, unknown> }) {
+      h.disk.data ??= structuredClone(opts.defaults)
+    }
+    get(key: string): unknown {
+      return (h.disk.data as Record<string, unknown>)[key]
+    }
+    set(key: string, value: unknown): void {
+      ;(h.disk.data as Record<string, unknown>)[key] = value
+    }
+  }
+}))
+vi.mock('./playlist.service', () => ({
+  getPlaylist: (id: string) => (id === 'p' ? h.playlist : null),
+  getAllPlaylists: () => [h.playlist]
+}))
+vi.mock('./library.service', () => ({
+  getWallpaper: (id: string) => ({ id, title: id, type: 'scene', localPath: `/w/${id}` }),
+  updateWallpaper: () => {}
+}))
+vi.mock('./lwe.service', () => ({ getLweStatus: () => ({ installed: true }), ALL_SCREENS: '*' }))
+vi.mock('./config.service', () => ({ getAutostartPlaylistId: () => null, getSkipPlaylistResume: () => h.skipResume }))
+vi.mock('./steam.service', () => ({ getFavoriteItemIds: () => [] }))
+vi.mock('./wallpaper-state.service', () => ({ getAssignments: () => h.assignments }))
+vi.mock('../utils/video', () => ({ findWallpaperVideoFile: () => null, getVideoDurationSec: () => undefined }))
+
+const showWallpaper = vi.fn<(wallpaper: { id: string }, screen: string) => Promise<string>>(async (wallpaper, screen) => {
+  const path = h.gate ? await h.gate : ''
+  if (!h.overtaken) h.assignments[screen] = wallpaper.id
+
+  return path
+})
+vi.mock('./display.service', () => ({
+  expandScreen: (screen?: string) => (screen && screen !== '*' ? [screen] : h.targets),
+  getDisplayTargets: () => h.targets,
+  setBusyWallpaperSource: () => {},
+  setPlaylistRecovery: () => {},
+  setVolumeSource: () => {},
+  showWallpaper
+}))
+
+const win = { isDestroyed: () => false, webContents: { send: () => {} } } as never
+
+async function boot() {
+  vi.resetModules()
+  return await import('./playlist-player.service')
+}
+
+async function pausedOnB() {
+  const first = await boot()
+  first.startPlaylist('p', 'DP-1')
+  await vi.advanceTimersByTimeAsync(0)
+  await first.nextItem('DP-1')
+  first.pausePlaylist('DP-1')
+  showWallpaper.mockClear()
+}
+
+async function neverLaunched() {
+  h.gate = new Promise<string>(() => {})
+  const first = await boot()
+  first.startPlaylist('p', 'DP-1')
+  first.pausePlaylist('DP-1')
+  h.gate = null
+  showWallpaper.mockClear()
+  const second = await boot()
+  second.initPlaylistPlayer(win)
+  return second
+}
+
+async function savedOnDp1() {
+  const first = await boot()
+  first.startPlaylist('p', 'DP-1')
+  await vi.advanceTimersByTimeAsync(0)
+  h.skipResume = true
+  const second = await boot()
+  second.initPlaylistPlayer(win)
+  return second
+}
+
+beforeEach(() => {
+  vi.useFakeTimers()
+  h.disk = {}
+  h.skipResume = false
+  h.targets = ['DP-1', 'DP-2']
+  h.assignments = {}
+  h.gate = null
+  h.overtaken = false
+  h.playlist.items = [{ wallpaperId: 'a' }, { wallpaperId: 'b', volume: 30 }, { wallpaperId: 'c' }]
+  showWallpaper.mockClear()
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+describe('after a restart', () => {
+  it('a playing playlist resumes and keeps its screen away from wallpaper restore', async () => {
+    const first = await boot()
+    first.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).toHaveBeenCalledTimes(1)
+    expect(second.playlistRestoreSkipScreens()).toEqual(['DP-1'])
+  })
+
+  it('a paused playlist shows nothing itself and hands restore the volume of the item it left', async () => {
+    await pausedOnB()
+    h.assignments = { 'DP-1': 'b' }
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+    expect(second.getPlaybackStates()).toMatchObject([{ screen: 'DP-1', isPlaying: false, currentItemId: 'b', currentIndex: 1 }])
+    expect(second.playlistRestoreSkipScreens()).toEqual([])
+    expect(second.restoreVolume('DP-1', 'b')).toBe(30)
+    expect(second.restoreVolume('DP-1', 'a')).toBeUndefined()
+  })
+
+  it('a wallpaper put on the screen by hand keeps its own volume, even when it is a playlist item', async () => {
+    await pausedOnB()
+    h.assignments = { 'DP-1': 'c' }
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+
+    expect(second.getPlaybackStates()).toMatchObject([{ currentItemId: null, currentIndex: 1 }])
+    expect(second.restoreVolume('DP-1', 'c')).toBeUndefined()
+  })
+
+  it('keeps where the playlist was when Next moved it while it was paused', async () => {
+    await pausedOnB()
+    h.assignments = { 'DP-1': 'b' }
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    await second.nextItem('DP-1')
+    h.assignments = { 'DP-1': 'c' }
+
+    const third = await boot()
+    third.initPlaylistPlayer(win)
+
+    expect(third.getPlaybackStates()).toMatchObject([{ currentItemId: 'c', currentIndex: 2 }])
+    expect(third.restoreVolume('DP-1', 'c')).toBe(80)
+  })
+
+  it('keeps where the playlist was through a start where another wallpaper was on the screen', async () => {
+    await pausedOnB()
+    h.assignments = { 'DP-1': 'z' }
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    h.assignments = { 'DP-1': 'b' }
+
+    const third = await boot()
+    third.initPlaylistPlayer(win)
+
+    expect(third.getPlaybackStates()).toMatchObject([{ currentItemId: 'b', currentIndex: 1 }])
+    expect(third.restoreVolume('DP-1', 'b')).toBe(30)
+  })
+
+  it('Resume shows the playlist item again after a wallpaper by hand, as it does after a restart', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    service.releasePlaylistScreen('DP-1')
+    h.assignments['DP-1'] = 'z'
+    service.resumePlaylist('DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['a'])
+  })
+
+  it('Resume only starts the timer when the wallpaper by hand failed to launch', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    service.releasePlaylistScreen('DP-1')
+    service.resumePlaylist('DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('does not count a launch that something newer overtook as shown', async () => {
+    h.overtaken = true
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(service.getPlaybackStates()).toMatchObject([{ currentItemId: null }])
+    expect((h.disk.data as { players: Record<string, { shownId: unknown }> }).players['DP-1'].shownId).toBeNull()
+  })
+
+  it('a second Resume does not start a second apply', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    service.releasePlaylistScreen('DP-1')
+    h.assignments['DP-1'] = 'z'
+    showWallpaper.mockClear()
+    h.gate = new Promise<string>(() => {})
+
+    service.resumePlaylist('DP-1')
+    service.resumePlaylist('DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).toHaveBeenCalledTimes(1)
+  })
+
+  it('Resume only starts the timer while the playlist item is still on the screen', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    service.pausePlaylist('DP-1')
+    showWallpaper.mockClear()
+
+    service.resumePlaylist('DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('finds the assigned wallpaper of the shared screen', async () => {
+    h.targets = ['*']
+    const first = await boot()
+    first.startPlaylist('p')
+    await vi.advanceTimersByTimeAsync(0)
+    await first.nextItem()
+    first.pausePlaylist()
+    h.assignments = { '*': 'b' }
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+
+    expect(second.getPlaybackStates()).toMatchObject([{ screen: '*', currentItemId: 'b' }])
+    expect(second.restoreVolume('DP-1', 'b')).toBe(30)
+  })
+
+  describe('and nothing was shown by the playlist', () => {
+    it('Resume shows the first item before the timer moves on', async () => {
+      const second = await neverLaunched()
+
+      second.resumePlaylist('DP-1')
+      await vi.advanceTimersByTimeAsync(0)
+
+      expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['a'])
+      expect(second.getPlaybackStates()).toMatchObject([{ isPlaying: true, currentItemId: 'a' }])
+
+      await vi.advanceTimersByTimeAsync(61_000)
+      expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['a', 'b'])
+    })
+
+    it('Next shows the first item, not the second', async () => {
+      const second = await neverLaunched()
+
+      await second.nextItem('DP-1')
+
+      expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['a'])
+    })
+
+    it('Next goes on from the item it showed last, also when a wallpaper by hand is on the screen', async () => {
+      await pausedOnB()
+      h.assignments = { 'DP-1': 'z' }
+      const second = await boot()
+      second.initPlaylistPlayer(win)
+
+      await second.nextItem('DP-1')
+
+      expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['c'])
+    })
+
+    it('Previous shows the item the playlist is on', async () => {
+      const second = await neverLaunched()
+
+      await second.previousItem('DP-1')
+
+      expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['a'])
+    })
+  })
+})
+
+describe('playlists that are not resumed', () => {
+  it('make no player but keep the playing saved screen out of wallpaper restore', async () => {
+    const second = await savedOnDp1()
+
+    expect(second.getPlaybackStates()).toEqual([])
+    expect(second.playlistRestoreSkipScreens()).toEqual(['DP-1'])
+  })
+
+  it('also keep a paused one away from wallpaper restore', async () => {
+    const first = await boot()
+    first.startPlaylist('p', 'DP-1')
+    first.pausePlaylist('DP-1')
+    h.skipResume = true
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+
+    expect(second.playlistRestoreSkipScreens()).toEqual(['DP-1'])
+  })
+
+  it('keep the saved player for a later start with the setting off', async () => {
+    await savedOnDp1()
+    h.skipResume = false
+    showWallpaper.mockClear()
+
+    const third = await boot()
+    third.initPlaylistPlayer(win)
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).toHaveBeenCalledTimes(1)
+  })
+
+  it('keep it through a playlist started on another screen, also after the setting is turned off', async () => {
+    const second = await savedOnDp1()
+    h.skipResume = false
+
+    second.startPlaylist('p', 'DP-2')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    const third = await boot()
+    third.initPlaylistPlayer(win)
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper.mock.calls.map(([, screen]) => screen).sort()).toEqual(['DP-1', 'DP-2'])
+  })
+
+  it('are not forgotten by a pause of all of them', async () => {
+    const first = await boot()
+    first.startPlaylist('p')
+    await vi.advanceTimersByTimeAsync(0)
+    h.skipResume = true
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    second.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    second.pausePlaylist()
+
+    expect(second.playlistRestoreSkipScreens().sort()).toEqual(['DP-1', 'DP-2'])
+  })
+
+  it('give the screen back when a wallpaper is put on it by hand', async () => {
+    const second = await savedOnDp1()
+
+    second.releasePlaylistScreen('DP-1')
+
+    expect(second.playlistRestoreSkipScreens()).toEqual([])
+  })
+
+  it('give the screen back when a wallpaper is put on it by hand while its playlist plays', async () => {
+    const first = await boot()
+    first.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    h.skipResume = true
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    second.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    expect(second.playlistRestoreSkipScreens()).toEqual(['DP-1'])
+
+    second.releasePlaylistScreen('DP-1')
+    h.assignments['DP-1'] = 'z'
+
+    expect(second.playlistRestoreSkipScreens()).toEqual([])
+  })
+
+  it('give the screen back when its playlist is stopped', async () => {
+    const second = await savedOnDp1()
+
+    second.stopPlaylist('DP-1')
+
+    expect(second.playlistRestoreSkipScreens()).toEqual([])
+  })
+
+  it('ignore a shared screen entry in per-screen mode and a playlist without items', async () => {
+    const first = await boot()
+    first.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    ;(h.disk.data as { players: Record<string, unknown> }).players['*'] = { playlistId: 'p', isPlaying: true }
+    h.skipResume = true
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    expect(second.playlistRestoreSkipScreens()).toEqual(['DP-1'])
+
+    h.playlist.items = []
+    expect(second.playlistRestoreSkipScreens()).toEqual([])
+  })
+
+  it('ignore a saved screen whose playlist is gone', async () => {
+    const first = await boot()
+    first.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    ;(h.disk.data as { players: Record<string, { playlistId: string }> }).players['DP-1'].playlistId = 'gone'
+    h.skipResume = true
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+
+    expect(second.playlistRestoreSkipScreens()).toEqual([])
+  })
+})
+
+describe('a monitor that is not up yet', () => {
+  it('keeps its saved playlist for the start where it is', async () => {
+    const first = await boot()
+    first.startPlaylist('p')
+    await vi.advanceTimersByTimeAsync(0)
+    h.targets = ['DP-2']
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+    await vi.advanceTimersByTimeAsync(0)
+    h.targets = ['DP-1', 'DP-2']
+    showWallpaper.mockClear()
+
+    const third = await boot()
+    third.initPlaylistPlayer(win)
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper.mock.calls.map(([, screen]) => screen).sort()).toEqual(['DP-1', 'DP-2'])
+  })
+})
+
+describe('what is saved', () => {
+  it('drops the players of playlists that no longer exist', async () => {
+    const first = await boot()
+    first.startPlaylist('p', 'DP-1')
+    first.startPlaylist('p', 'DP-2')
+    await vi.advanceTimersByTimeAsync(0)
+    const players = (h.disk.data as { players: Record<string, { playlistId: string }> }).players
+    players['DP-1'].playlistId = 'gone'
+
+    const second = await boot()
+    second.initPlaylistPlayer(win)
+
+    expect(Object.keys((h.disk.data as { players: object }).players)).toEqual(['DP-2'])
+  })
+})
+
+describe('holding a playlist for a while', () => {
+  it('is not held any more after a play of one of its items', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    const resume = service.suspendPlaylist('DP-1')
+
+    await service.playItem('p', 'c', 'DP-1')
+    showWallpaper.mockClear()
+    resume()
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('saves a held playlist as playing when something else persists', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    service.startPlaylist('p', 'DP-2')
+    await vi.advanceTimersByTimeAsync(0)
+
+    service.suspendPlaylist('DP-1')
+    service.pausePlaylist('DP-2')
+
+    const saved = (h.disk.data as { players: Record<string, { isPlaying: boolean }> }).players
+    expect(saved['DP-1'].isPlaying).toBe(true)
+  })
+
+  it('lets it go on afterwards without having saved a pause', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    const resume = service.suspendPlaylist('DP-1')
+
+    expect(service.getPlaybackStates()[0].isPlaying).toBe(false)
+    expect((h.disk.data as { players: Record<string, { isPlaying: boolean }> }).players['DP-1'].isPlaying).toBe(true)
+
+    resume()
+    expect(service.getPlaybackStates()[0].isPlaying).toBe(true)
+  })
+
+  it('leaves it alone when somebody paused it meanwhile', async () => {
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    const resume = service.suspendPlaylist('DP-1')
+    service.pausePlaylist('DP-1')
+    resume()
+
+    expect(service.getPlaybackStates()[0].isPlaying).toBe(false)
+  })
+})
+
+describe('an apply that something took the player from', () => {
+  it('does not go on to the next items when its launch fails after a restart', async () => {
+    let fail: (reason: Error) => void = () => {}
+    showWallpaper.mockImplementationOnce(() => new Promise<string>((_resolve, reject) => { fail = reject }))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    fail(new Error('declined'))
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['a'])
+  })
+
+  it('does not go on after a stop either', async () => {
+    let fail: (reason: Error) => void = () => {}
+    showWallpaper.mockImplementationOnce(() => new Promise<string>((_resolve, reject) => { fail = reject }))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    service.stopPlaylist('DP-1')
+    fail(new Error('declined'))
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+})
+
+describe('stopping during an apply', () => {
+  it('does not arm the timer of the player that is gone', async () => {
+    h.gate = new Promise<string>((resolve) => {
+      h.release = resolve
+    })
+    const service = await boot()
+
+    service.startPlaylist('p', 'DP-1')
+    service.stopPlaylist('DP-1')
+    h.release('')
+    await vi.advanceTimersByTimeAsync(3_600_000)
+
+    expect(showWallpaper).toHaveBeenCalledTimes(1)
+  })
+})

+ 171 - 52
src/main/services/playlist-player.service.ts

@@ -4,17 +4,20 @@ import { IpcChannels } from '@shared/ipc-channels'
 import type { Playlist, PlaylistItem, PlaylistPlaybackState, ScreenTarget } from '@shared/types'
 import type { Playlist, PlaylistItem, PlaylistPlaybackState, ScreenTarget } from '@shared/types'
 import { compatStatus } from '@shared/compat'
 import { compatStatus } from '@shared/compat'
 import { trimmedVideoLength, videoSegmentsOf } from '@shared/videoTrim'
 import { trimmedVideoLength, videoSegmentsOf } from '@shared/videoTrim'
-import { getPlaylist } from './playlist.service'
+import { getAllPlaylists, getPlaylist } from './playlist.service'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getLweStatus, ALL_SCREENS } from './lwe.service'
 import { getLweStatus, ALL_SCREENS } from './lwe.service'
 import { getAutostartPlaylistId, getSkipPlaylistResume } from './config.service'
 import { getAutostartPlaylistId, getSkipPlaylistResume } from './config.service'
+import { mergePlayers, playlistSkipScreens, savedScreensFor } from './restore-plan'
+import { getAssignments } from './wallpaper-state.service'
 import { getFavoriteItemIds } from './steam.service'
 import { getFavoriteItemIds } from './steam.service'
-import { expandScreen, getDisplayTargets, setBusyWallpaperSource, setPlaylistRecovery, showWallpaper } from './display.service'
+import { expandScreen, getDisplayTargets, setBusyWallpaperSource, setPlaylistRecovery, setVolumeSource, showWallpaper } from './display.service'
 import { findWallpaperVideoFile, getVideoDurationSec } from '../utils/video'
 import { findWallpaperVideoFile, getVideoDurationSec } from '../utils/video'
 
 
 interface SavedPlayer {
 interface SavedPlayer {
   playlistId: string
   playlistId: string
   isPlaying: boolean
   isPlaying: boolean
+  shownId?: string | null
 }
 }
 
 
 interface PlaybackStore {
 interface PlaybackStore {
@@ -34,6 +37,10 @@ interface Player {
   timer: NodeJS.Timeout | null
   timer: NodeJS.Timeout | null
   scheduleToken: number
   scheduleToken: number
   applying: boolean
   applying: boolean
+  applyId: number
+  /** The item the playlist itself put on the screen last, the playlist goes on from there after a restart */
+  lastShown: string | null
+  suspended: boolean
 }
 }
 
 
 let win: BrowserWindow | null = null
 let win: BrowserWindow | null = null
@@ -84,12 +91,16 @@ function buildOrder(playlist: Playlist): string[] {
   return items.map((i) => i.wallpaperId)
   return items.map((i) => i.wallpaperId)
 }
 }
 
 
-function persist(): void {
-  const saved: Record<ScreenTarget, SavedPlayer> = {}
+function persist(stopped: readonly ScreenTarget[] = [], prune = true): void {
+  const live: Record<ScreenTarget, SavedPlayer> = {}
   for (const [screen, p] of players) {
   for (const [screen, p] of players) {
-    if (p.state.playlistId) saved[screen] = { playlistId: p.state.playlistId, isPlaying: p.state.isPlaying }
+    if (p.state.playlistId) {
+      live[screen] = { playlistId: p.state.playlistId, isPlaying: p.state.isPlaying || p.suspended, shownId: p.lastShown }
+    }
   }
   }
-  store.set('players', saved)
+  const existing = prune ? new Set(getAllPlaylists().map((playlist) => playlist.id)) : null
+  const saved = Object.fromEntries(Object.entries(savedPlayers()).filter(([, player]) => !existing || existing.has(player.playlistId)))
+  store.set('players', mergePlayers(saved, live, [...stopped, ...players.keys()]))
 }
 }
 
 
 function clearTimer(player: Player): void {
 function clearTimer(player: Player): void {
@@ -107,6 +118,10 @@ function emitState(): void {
   for (const cb of listeners) cb()
   for (const cb of listeners) cb()
 }
 }
 
 
+function itemVolume(playlist: Playlist, item?: PlaylistItem): number {
+  return item?.volume ?? playlist.settings.defaultVolume
+}
+
 function findItem(playlist: Playlist, wallpaperId: string): PlaylistItem | undefined {
 function findItem(playlist: Playlist, wallpaperId: string): PlaylistItem | undefined {
   return playlist.items.find((i) => i.wallpaperId === wallpaperId)
   return playlist.items.find((i) => i.wallpaperId === wallpaperId)
 }
 }
@@ -129,9 +144,13 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
   const inRotation = rotationFilter(playlist, state.order)
   const inRotation = rotationFilter(playlist, state.order)
   const anyPlayable = state.order.some((id) => inRotation(id) && known(id))
   const anyPlayable = state.order.some((id) => inRotation(id) && known(id))
 
 
+  const mine = ++player.applyId
+  const stale = (): boolean => player.state !== state || players.get(state.screen) !== player || player.applyId !== mine
+
   player.applying = true
   player.applying = true
   try {
   try {
     for (let tries = 0; tries < count; tries++, state.currentIndex = (state.currentIndex + 1) % count) {
     for (let tries = 0; tries < count; tries++, state.currentIndex = (state.currentIndex + 1) % count) {
+      if (stale()) return
       const wallpaper = getWallpaper(state.order[state.currentIndex])
       const wallpaper = getWallpaper(state.order[state.currentIndex])
       if (!wallpaper) continue
       if (!wallpaper) continue
       if (wallpaper.id !== picked && (!inRotation(wallpaper.id) || (anyPlayable && !known(wallpaper.id)))) continue
       if (wallpaper.id !== picked && (!inRotation(wallpaper.id) || (anyPlayable && !known(wallpaper.id)))) continue
@@ -139,23 +158,41 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
       const item = findItem(playlist, wallpaper.id)
       const item = findItem(playlist, wallpaper.id)
       try {
       try {
         await showWallpaper(wallpaper, state.screen, {
         await showWallpaper(wallpaper, state.screen, {
-          volume: item?.volume ?? playlist.settings.defaultVolume,
+          volume: itemVolume(playlist, item),
           dependencyPrompt: 'once'
           dependencyPrompt: 'once'
         })
         })
       } catch (err) {
       } catch (err) {
         console.error('[PlaylistPlayer] Failed to apply wallpaper:', err)
         console.error('[PlaylistPlayer] Failed to apply wallpaper:', err)
         continue
         continue
       }
       }
-      updateWallpaper(wallpaper.id, {
-        appliedCount: (wallpaper.appliedCount ?? 0) + 1,
-        lastAppliedAt: Date.now()
-      })
-      state.currentItemId = wallpaper.id
+      if (stale()) return
+      // a launch that something newer overtook is not what the screen shows
+      if (assignedId(state.screen) === wallpaper.id) {
+        updateWallpaper(wallpaper.id, {
+          appliedCount: (wallpaper.appliedCount ?? 0) + 1,
+          lastAppliedAt: Date.now()
+        })
+        state.currentItemId = wallpaper.id
+        player.lastShown = wallpaper.id
+      }
       return
       return
     }
     }
   } finally {
   } finally {
-    player.applying = false
+    if (player.applyId === mine) player.applying = false
+  }
+}
+
+async function showCurrent(player: Player, playlist: Playlist, picked?: string): Promise<void> {
+  const state = player.state
+  await applyCurrent(player, playlist, picked)
+  if (player.state !== state) return
+  scheduleNext(player, playlist)
+  try {
+    persist([], false)
+  } catch (err) {
+    console.error('[PlaylistPlayer] Could not save the playlist state:', err)
   }
   }
+  emitState()
 }
 }
 
 
 // covers engine startup/hotswap time
 // covers engine startup/hotswap time
@@ -200,7 +237,7 @@ function scheduleNext(player: Player, playlist: Playlist): void {
 }
 }
 
 
 async function advance(player: Player): Promise<void> {
 async function advance(player: Player): Promise<void> {
-  if (!player.state.playlistId) return
+  if (!player.state.playlistId || player.applying) return
   const playlist = getPlaylist(player.state.playlistId)
   const playlist = getPlaylist(player.state.playlistId)
   if (!playlist || playlist.items.length === 0) {
   if (!playlist || playlist.items.length === 0) {
     stopPlaylist(player.state.screen)
     stopPlaylist(player.state.screen)
@@ -213,15 +250,21 @@ async function advance(player: Player): Promise<void> {
     player.state.currentIndex = 0
     player.state.currentIndex = 0
   }
   }
 
 
-  await applyCurrent(player, playlist)
-  emitState()
-  scheduleNext(player, playlist)
+  await showCurrent(player, playlist)
 }
 }
 
 
 function playerFor(screen: ScreenTarget): Player {
 function playerFor(screen: ScreenTarget): Player {
   let player = players.get(screen)
   let player = players.get(screen)
   if (!player) {
   if (!player) {
-    player = { state: idleState(screen), timer: null, scheduleToken: 0, applying: false }
+    player = {
+      state: idleState(screen),
+      timer: null,
+      scheduleToken: 0,
+      applying: false,
+      applyId: 0,
+      lastShown: null,
+      suspended: false
+    }
     players.set(screen, player)
     players.set(screen, player)
   }
   }
   return player
   return player
@@ -234,22 +277,36 @@ function selectPlayers(screen?: ScreenTarget): Player[] {
   return player ? [player] : []
   return player ? [player] : []
 }
 }
 
 
-function startOn(screen: ScreenTarget, playlist: Playlist): PlaylistPlaybackState {
+function assignedId(screen: ScreenTarget): string | undefined {
+  const assigned = getAssignments()
+
+  return assigned[screen] ?? assigned[ALL_SCREENS]
+}
+
+function owns(player: Player): boolean {
+  return player.lastShown !== null && assignedId(player.state.screen) === player.lastShown
+}
+
+function startOn(screen: ScreenTarget, playlist: Playlist, paused = false, shownId?: string | null): PlaylistPlaybackState {
   const player = playerFor(screen)
   const player = playerFor(screen)
   clearTimer(player)
   clearTimer(player)
+  const order = buildOrder(playlist)
+  const at = paused && shownId ? order.indexOf(shownId) : -1
+  player.lastShown = at >= 0 ? order[at] : null
+  player.suspended = false
+  player.applying = false
+  player.applyId++
   player.state = {
   player.state = {
     screen,
     screen,
     playlistId: playlist.id,
     playlistId: playlist.id,
-    currentItemId: null,
-    currentIndex: 0,
-    isPlaying: true,
-    order: buildOrder(playlist)
+    currentItemId: owns(player) ? player.lastShown : null,
+    currentIndex: Math.max(at, 0),
+    isPlaying: !paused,
+    order
   }
   }
+  if (paused) return player.state
 
 
-  void applyCurrent(player, playlist).then(() => {
-    emitState()
-    scheduleNext(player, playlist)
-  })
+  void showCurrent(player, playlist)
   return player.state
   return player.state
 }
 }
 
 
@@ -286,6 +343,10 @@ export async function playItem(playlistId: string, wallpaperId: string, screen?:
     clearTimer(player)
     clearTimer(player)
     if (player.state.playlistId !== playlistId) {
     if (player.state.playlistId !== playlistId) {
       player.state = { ...idleState(target), playlistId: playlist.id, isPlaying: true, order: buildOrder(playlist) }
       player.state = { ...idleState(target), playlistId: playlist.id, isPlaying: true, order: buildOrder(playlist) }
+      player.lastShown = null
+      player.suspended = false
+      player.applying = false
+      player.applyId++
     }
     }
 
 
     let index = player.state.order.indexOf(wallpaperId)
     let index = player.state.order.indexOf(wallpaperId)
@@ -295,42 +356,81 @@ export async function playItem(playlistId: string, wallpaperId: string, screen?:
     }
     }
     player.state.currentIndex = index
     player.state.currentIndex = index
     player.state.isPlaying = true
     player.state.isPlaying = true
+    player.suspended = false
 
 
-    await applyCurrent(player, playlist, wallpaperId)
-    scheduleNext(player, playlist)
+    await showCurrent(player, playlist, wallpaperId)
   }
   }
-  persist()
-  emitState()
   return getPlaybackStates()
   return getPlaybackStates()
 }
 }
 
 
 export function stopPlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
 export function stopPlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
+  const stopped: ScreenTarget[] = []
+
   for (const player of selectPlayers(screen)) {
   for (const player of selectPlayers(screen)) {
     clearTimer(player)
     clearTimer(player)
+    // an apply still running must not arm the timer of a player that is gone
+    player.state.isPlaying = false
     players.delete(player.state.screen)
     players.delete(player.state.screen)
+    stopped.push(player.state.screen)
   }
   }
-  persist()
+  persist([...stopped, ...savedScreens(screen)])
   emitState()
   emitState()
   return getPlaybackStates()
   return getPlaybackStates()
 }
 }
 
 
-export function pausePlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
+function pause(screen: ScreenTarget | undefined, forget: readonly ScreenTarget[]): void {
   for (const player of selectPlayers(screen)) {
   for (const player of selectPlayers(screen)) {
     if (!player.state.playlistId) continue
     if (!player.state.playlistId) continue
     clearTimer(player)
     clearTimer(player)
     player.state.isPlaying = false
     player.state.isPlaying = false
+    player.suspended = false
   }
   }
-  persist()
+  persist(forget)
   emitState()
   emitState()
+}
+
+export function pausePlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
+  pause(screen, [])
   return getPlaybackStates()
   return getPlaybackStates()
 }
 }
 
 
+export function releasePlaylistScreen(screen: ScreenTarget): void {
+  pause(screen, savedScreens(screen))
+}
+
+export function suspendPlaylist(screen: ScreenTarget): () => void {
+  const player = players.get(screen)
+  if (!player?.state.isPlaying) return () => {}
+
+  clearTimer(player)
+  player.state.isPlaying = false
+  player.suspended = true
+  emitState()
+
+  return () => {
+    const playlist = player.state.playlistId ? getPlaylist(player.state.playlistId) : null
+    if (!player.suspended || players.get(screen) !== player || !playlist) return
+    resumePlayer(player, playlist)
+    emitState()
+  }
+}
+
+function resumePlayer(player: Player, playlist: Playlist): void {
+  player.suspended = false
+  player.state.isPlaying = true
+
+  if (!owns(player) && !player.applying) {
+    clearTimer(player)
+    void showCurrent(player, playlist)
+  } else {
+    scheduleNext(player, playlist)
+  }
+}
+
 export function resumePlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
 export function resumePlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
   for (const player of selectPlayers(screen)) {
   for (const player of selectPlayers(screen)) {
     const playlist = player.state.playlistId ? getPlaylist(player.state.playlistId) : null
     const playlist = player.state.playlistId ? getPlaylist(player.state.playlistId) : null
-    if (!playlist) continue
-    player.state.isPlaying = true
-    scheduleNext(player, playlist)
+    if (playlist) resumePlayer(player, playlist)
   }
   }
   persist()
   persist()
   emitState()
   emitState()
@@ -340,7 +440,10 @@ export function resumePlaylist(screen?: ScreenTarget): PlaylistPlaybackState[] {
 export async function nextItem(screen?: ScreenTarget): Promise<PlaylistPlaybackState[]> {
 export async function nextItem(screen?: ScreenTarget): Promise<PlaylistPlaybackState[]> {
   for (const player of selectPlayers(screen)) {
   for (const player of selectPlayers(screen)) {
     if (!player.state.playlistId || player.applying) continue
     if (!player.state.playlistId || player.applying) continue
-    await advance(player)
+
+    const playlist = getPlaylist(player.state.playlistId)
+    if (playlist && player.lastShown === null) await showCurrent(player, playlist)
+    else await advance(player)
   }
   }
   return getPlaybackStates()
   return getPlaybackStates()
 }
 }
@@ -353,15 +456,13 @@ export async function previousItem(screen?: ScreenTarget): Promise<PlaylistPlayb
 
 
     const { order } = player.state
     const { order } = player.state
     const inRotation = rotationFilter(playlist, order)
     const inRotation = rotationFilter(playlist, order)
-    for (let step = 0; step < order.length; step++) {
+    for (let step = 0; player.lastShown !== null && step < order.length; step++) {
       player.state.currentIndex = (player.state.currentIndex - 1 + order.length) % order.length
       player.state.currentIndex = (player.state.currentIndex - 1 + order.length) % order.length
       if (inRotation(order[player.state.currentIndex])) break
       if (inRotation(order[player.state.currentIndex])) break
     }
     }
 
 
-    await applyCurrent(player, playlist)
-    scheduleNext(player, playlist)
+    await showCurrent(player, playlist)
   }
   }
-  emitState()
   return getPlaybackStates()
   return getPlaybackStates()
 }
 }
 
 
@@ -382,15 +483,33 @@ function savedPlayers(): Record<ScreenTarget, SavedPlayer> {
   return legacyId ? { [ALL_SCREENS]: { playlistId: legacyId, isPlaying: store.get('isPlaying') } } : {}
   return legacyId ? { [ALL_SCREENS]: { playlistId: legacyId, isPlaying: store.get('isPlaying') } } : {}
 }
 }
 
 
-/** Screens a playlist owns after init, so wallpaper restore does not launch over them */
-export function activePlaylistScreens(): ScreenTarget[] {
-  return [...players.values()].filter((player) => player.state.playlistId).map((player) => player.state.screen)
+function activePlaylistScreens(): ScreenTarget[] {
+  return [...players.values()].filter((player) => player.state.playlistId && player.state.isPlaying).map((player) => player.state.screen)
+}
+
+export function restoreVolume(screen: ScreenTarget, wallpaperId: string): number | undefined {
+  const player = players.get(screen) ?? players.get(ALL_SCREENS)
+  const playlist = player?.state.playlistId ? getPlaylist(player.state.playlistId) : null
+  const item = playlist && player && owns(player) && player.lastShown === wallpaperId ? findItem(playlist, wallpaperId) : undefined
+
+  return playlist && item ? itemVolume(playlist, item) : undefined
 }
 }
 
 
-/** With "Don't resume playlists", the saved screens are skipped too, or restore puts the last item back without its volume */
+function savedScreens(screen?: ScreenTarget): ScreenTarget[] {
+  return savedScreensFor(Object.keys(savedPlayers()), screen)
+}
+
+// with "Don't resume playlists" restore would put the last item back without its volume
 export function playlistRestoreSkipScreens(): ScreenTarget[] {
 export function playlistRestoreSkipScreens(): ScreenTarget[] {
-  if (getSkipPlaylistResume()) return Object.keys(savedPlayers())
-  return activePlaylistScreens()
+  const targets = getDisplayTargets()
+  const playlists = new Map(getAllPlaylists().map((playlist) => [playlist.id, playlist]))
+  const saved = Object.entries(savedPlayers())
+    .filter(([screen, player]) => (playlists.get(player.playlistId)?.items.length ?? 0) > 0 && targets.includes(screen))
+    // a wallpaper put on the screen by hand since is not the playlist's to hold back
+    .filter(([screen, player]) => player.shownId === undefined || assignedId(screen) === player.shownId)
+    .map(([screen]) => screen)
+
+  return playlistSkipScreens(getSkipPlaylistResume(), saved, activePlaylistScreens())
 }
 }
 
 
 /** Resumes the playlists active at the last close, true if any (the autostart playlist is then skipped) */
 /** Resumes the playlists active at the last close, true if any (the autostart playlist is then skipped) */
@@ -400,6 +519,7 @@ export function initPlaylistPlayer(window: BrowserWindow): boolean {
   setBusyWallpaperSource('playlist', () =>
   setBusyWallpaperSource('playlist', () =>
     [...players.values()].flatMap((p) => [p.state.currentItemId, p.applying ? p.state.order[p.state.currentIndex] : null]).filter((id): id is string => !!id)
     [...players.values()].flatMap((p) => [p.state.currentItemId, p.applying ? p.state.order[p.state.currentIndex] : null]).filter((id): id is string => !!id)
   )
   )
+  setVolumeSource(restoreVolume)
   setPlaylistRecovery((screen) => {
   setPlaylistRecovery((screen) => {
     const player = players.get(screen)
     const player = players.get(screen)
     if (!player?.state.isPlaying || player.applying) return false
     if (!player?.state.isPlaying || player.applying) return false
@@ -415,13 +535,12 @@ export function initPlaylistPlayer(window: BrowserWindow): boolean {
     const playlist = getPlaylist(saved.playlistId)
     const playlist = getPlaylist(saved.playlistId)
     if (!playlist || playlist.items.length === 0 || !targets.includes(screen)) continue
     if (!playlist || playlist.items.length === 0 || !targets.includes(screen)) continue
 
 
-    startOn(screen, playlist)
-    resumed = true
     const isConfiguredAutostart = saved.playlistId === getAutostartPlaylistId()
     const isConfiguredAutostart = saved.playlistId === getAutostartPlaylistId()
-    if (!saved.isPlaying && !isConfiguredAutostart) pausePlaylist(screen)
+    startOn(screen, playlist, !saved.isPlaying && !isConfiguredAutostart, saved.shownId)
+    resumed = true
   }
   }
-  store.set('activePlaylistId', null)
   persist()
   persist()
+  store.set('activePlaylistId', null)
   emitState()
   emitState()
   return resumed
   return resumed
 }
 }

+ 94 - 9
src/main/services/restore-plan.test.ts

@@ -1,5 +1,5 @@
 import { describe, expect, it } from 'vitest'
 import { describe, expect, it } from 'vitest'
-import { mergeSkipScreens, planRestore, playlistSkipScreens, restoreSuperseded, type RestoreInput } from './restore-plan'
+import { mergePlayers, mergeSkipScreens, planRestore, savedScreensFor, trySplit, playlistSkipScreens, restoreSuperseded, type RestoreInput } from './restore-plan'
 
 
 function input(patch: Partial<RestoreInput> = {}): RestoreInput {
 function input(patch: Partial<RestoreInput> = {}): RestoreInput {
   return {
   return {
@@ -8,8 +8,8 @@ function input(patch: Partial<RestoreInput> = {}): RestoreInput {
     animated: true,
     animated: true,
     onDisk: true,
     onDisk: true,
     localPath: '/w/a',
     localPath: '/w/a',
-    splitSlotId: null,
-    wallpaperId: 'a',
+    splitActive: false,
+    splitShowable: false,
     ...patch
     ...patch
   }
   }
 }
 }
@@ -24,23 +24,31 @@ describe('planRestore', () => {
   })
   })
 
 
   it('leaves a running split alone', () => {
   it('leaves a running split alone', () => {
-    expect(planRestore(input({ running: { split: true, wallpaperPath: '/w/a' }, splitSlotId: 'a' }))).toBe('skip')
+    expect(planRestore(input({ running: { split: true, wallpaperPath: '/w/a' }, splitActive: true, splitShowable: true }))).toBe('skip')
   })
   })
 
 
   it('restores a split that is not running through the split, not as one wallpaper', () => {
   it('restores a split that is not running through the split, not as one wallpaper', () => {
-    expect(planRestore(input({ splitSlotId: 'a', wallpaperId: 'a' }))).toBe('split')
+    expect(planRestore(input({ splitActive: true, splitShowable: true }))).toBe('split')
   })
   })
 
 
-  it('restores the assigned wallpaper when it is not the split first slot', () => {
-    expect(planRestore(input({ splitSlotId: 'slot', wallpaperId: 'a' }))).toBe('wallpaper')
+  it('restores a single wallpaper when its screen has a split configured but not showing', () => {
+    expect(planRestore(input({ splitActive: false, splitShowable: true }))).toBe('wallpaper')
+  })
+
+  it('does not restart a healthy single engine because a split is configured', () => {
+    expect(planRestore(input({ running: { split: false, wallpaperPath: '/w/a' }, splitShowable: true }))).toBe('skip')
+  })
+
+  it('falls back to the wallpaper when the active split has nothing showable left', () => {
+    expect(planRestore(input({ splitActive: true, splitShowable: false }))).toBe('wallpaper')
   })
   })
 
 
   it('skips a screen a playlist or schedule already claimed', () => {
   it('skips a screen a playlist or schedule already claimed', () => {
     expect(planRestore(input({ skipped: true }))).toBe('skip')
     expect(planRestore(input({ skipped: true }))).toBe('skip')
   })
   })
 
 
-  it('skips a wallpaper whose folder is missing', () => {
-    expect(planRestore(input({ onDisk: false }))).toBe('skip')
+  it('waits for a wallpaper whose folder is missing', () => {
+    expect(planRestore(input({ onDisk: false }))).toBe('wait')
   })
   })
 
 
   it('skips a static image, which has no engine and would cover every screen', () => {
   it('skips a static image, which has no engine and would cover every screen', () => {
@@ -81,3 +89,80 @@ describe('mergeSkipScreens', () => {
     expect([...mergeSkipScreens(['HDMI-A-2'], ['*'], ['HDMI-A-3'])]).toEqual(['HDMI-A-2', '*', 'HDMI-A-3'])
     expect([...mergeSkipScreens(['HDMI-A-2'], ['*'], ['HDMI-A-3'])]).toEqual(['HDMI-A-2', '*', 'HDMI-A-3'])
   })
   })
 })
 })
+
+describe('mergePlayers', () => {
+  const saved = { 'DP-1': { playlistId: 'a' }, 'DP-2': { playlistId: 'b' } }
+
+  it('keeps the saved players nothing touched', () => {
+    expect(mergePlayers(saved, {}, [])).toEqual(saved)
+  })
+
+  it('lets a live player or a stopped screen replace its saved one', () => {
+    expect(mergePlayers(saved, { 'DP-1': { playlistId: 'c' } }, ['DP-1', 'DP-2'])).toEqual({
+      'DP-1': { playlistId: 'c' }
+    })
+  })
+
+  it('keeps an untouched screen next to a live one', () => {
+    expect(mergePlayers(saved, { 'DP-1': { playlistId: 'c' } }, ['DP-1'])).toEqual({
+      'DP-1': { playlistId: 'c' },
+      'DP-2': { playlistId: 'b' }
+    })
+  })
+})
+
+describe('savedScreensFor', () => {
+  it('names every saved screen for a stop of all of them', () => {
+    expect(savedScreensFor(['DP-1', 'DP-2'])).toEqual(['DP-1', 'DP-2'])
+    expect(savedScreensFor(['DP-1', 'DP-2'], '*')).toEqual(['DP-1', 'DP-2'])
+  })
+
+  it('names the screen itself and the shared entry for one screen', () => {
+    expect(savedScreensFor(['DP-1', 'DP-2', '*'], 'DP-1')).toEqual(['DP-1', '*'])
+    expect(savedScreensFor(['DP-2'], 'DP-1')).toEqual([])
+  })
+})
+
+function attempt(show: () => Promise<void>, marks: number[]) {
+  let uses = 0
+  const errors: unknown[] = []
+
+  return {
+    errors,
+    run: () =>
+      trySplit({
+        show: async () => {
+          uses += 1
+          for (const _ of marks) uses += 1
+          await show()
+        },
+        uses: () => uses,
+        onError: (error) => errors.push(error)
+      })
+  }
+}
+
+describe('trySplit', () => {
+  it('is done when the split shows', async () => {
+    expect(await attempt(async () => {}, []).run()).toBe('done')
+  })
+
+  it('has failed when only the try itself marked the screen, even if the assignment is gone', async () => {
+    const t = attempt(async () => { throw new Error('exited') }, [])
+
+    expect(await t.run()).toBe('failed')
+    expect(t.errors).toHaveLength(1)
+  })
+
+  it('has failed too when the try threw before it marked the screen', async () => {
+    let uses = 0
+
+    expect(await trySplit({ show: async () => { throw new Error('early') }, uses: () => uses, onError: () => {} })).toBe('failed')
+    expect(uses).toBe(0)
+  })
+
+  it('leaves the screen when somebody else marked it during the try', async () => {
+    expect(await attempt(async () => { throw new Error('replaced') }, [1]).run()).toBe('left')
+  })
+})
+

+ 46 - 9
src/main/services/restore-plan.ts

@@ -5,33 +5,50 @@ export interface RestoreInput {
   onDisk: boolean
   onDisk: boolean
   localPath: string
   localPath: string
   running?: { split: boolean; wallpaperPath: string }
   running?: { split: boolean; wallpaperPath: string }
-  /** First on-disk slot a split would show, or null when this screen has no showable split */
-  splitSlotId: string | null
-  wallpaperId: string
+  /** The saved assignment is the first slot of a split that was showing */
+  splitActive: boolean
+  splitShowable: boolean
 }
 }
 
 
-export type RestorePlan = 'skip' | 'split' | 'wallpaper'
+export type RestorePlan = 'skip' | 'split' | 'wait' | 'wallpaper'
 
 
-/** What startup should do with one saved screen. A static image and a missing folder are skipped. */
 export function planRestore(input: RestoreInput): RestorePlan {
 export function planRestore(input: RestoreInput): RestorePlan {
   if (input.skipped || !input.connected) return 'skip'
   if (input.skipped || !input.connected) return 'skip'
   if (input.running?.split) return 'skip'
   if (input.running?.split) return 'skip'
-  if (input.splitSlotId !== null && input.splitSlotId === input.wallpaperId) return 'split'
-  if (!input.animated || !input.onDisk) return 'skip'
+  if (input.splitActive && input.splitShowable) return 'split'
+  if (!input.animated) return 'skip'
   if (input.running && input.running.wallpaperPath === input.localPath) return 'skip'
   if (input.running && input.running.wallpaperPath === input.localPath) return 'skip'
+  if (!input.onDisk) return 'wait'
   return 'wallpaper'
   return 'wallpaper'
 }
 }
 
 
-/** Don't-resume skips the saved playlist screens. Otherwise only screens that actually resumed. */
 export function playlistSkipScreens(skipResume: boolean, saved: readonly string[], active: readonly string[]): string[] {
 export function playlistSkipScreens(skipResume: boolean, saved: readonly string[], active: readonly string[]): string[] {
   return skipResume ? [...saved] : [...active]
   return skipResume ? [...saved] : [...active]
 }
 }
 
 
+/** players nothing touched this session stay as saved */
+export function mergePlayers<T>(
+  saved: Readonly<Record<string, T>>,
+  live: Readonly<Record<string, T>>,
+  touched: readonly string[]
+): Record<string, T> {
+  const kept: Record<string, T> = {}
+
+  for (const [screen, player] of Object.entries(saved)) {
+    if (!touched.includes(screen)) kept[screen] = player
+  }
+
+  return { ...kept, ...live }
+}
+
+export function savedScreensFor(saved: readonly string[], screen?: string): string[] {
+  return screen === undefined || screen === '*' ? [...saved] : saved.filter((name) => name === screen || name === '*')
+}
+
 export function mergeSkipScreens(...groups: readonly (readonly string[])[]): Set<string> {
 export function mergeSkipScreens(...groups: readonly (readonly string[])[]): Set<string> {
   return new Set(groups.flat())
   return new Set(groups.flat())
 }
 }
 
 
-/** True when something else took the screen after restore read it. The newer launch stays. */
 export function restoreSuperseded(
 export function restoreSuperseded(
   assignedAtStart: string,
   assignedAtStart: string,
   assignedNow: string | undefined,
   assignedNow: string | undefined,
@@ -40,3 +57,23 @@ export function restoreSuperseded(
 ): boolean {
 ): boolean {
   return assignedNow !== assignedAtStart || useNow !== useAtStart
   return assignedNow !== assignedAtStart || useNow !== useAtStart
 }
 }
+
+export interface SplitTry {
+  show: () => Promise<void>
+  uses: () => number
+  onError: (error: unknown) => void
+}
+
+// the try marks the screen once itself, a second mark means somebody else took it
+export async function trySplit(attempt: SplitTry): Promise<'done' | 'left' | 'failed'> {
+  const before = attempt.uses()
+
+  try {
+    await attempt.show()
+    return 'done'
+  } catch (error) {
+    attempt.onError(error)
+  }
+
+  return attempt.uses() - before <= 1 ? 'failed' : 'left'
+}

+ 22 - 18
src/main/services/schedule.service.ts

@@ -2,11 +2,11 @@ import { openStore } from '../utils/safeStore'
 import { nativeTheme, type BrowserWindow } from 'electron'
 import { nativeTheme, type BrowserWindow } from 'electron'
 import { randomUUID } from 'crypto'
 import { randomUUID } from 'crypto'
 import { IpcChannels } from '@shared/ipc-channels'
 import { IpcChannels } from '@shared/ipc-channels'
-import type { ScheduleRule, ScreenTarget } from '@shared/types'
+import type { ScheduleRule } from '@shared/types'
 import { dueTimeRules } from '@shared/schedule'
 import { dueTimeRules } from '@shared/schedule'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getPlaylist } from './playlist.service'
 import { getPlaylist } from './playlist.service'
-import { expandScreen, setBusyWallpaperSource, showWallpaper, stopDisplay } from './display.service'
+import { expandScreen, isShownOn, setBusyWallpaperSource, showWallpaper, stopDisplay } from './display.service'
 import { startPlaylist, stopPlaylist } from './playlist-player.service'
 import { startPlaylist, stopPlaylist } from './playlist-player.service'
 
 
 interface ScheduleStore {
 interface ScheduleStore {
@@ -63,7 +63,9 @@ export async function runRule(rule: ScheduleRule): Promise<void> {
       if (left > 0) runningWallpapers.set(wallpaper.id, left)
       if (left > 0) runningWallpapers.set(wallpaper.id, left)
       else runningWallpapers.delete(wallpaper.id)
       else runningWallpapers.delete(wallpaper.id)
     }
     }
-    updateWallpaper(wallpaper.id, { appliedCount: (wallpaper.appliedCount ?? 0) + 1, lastAppliedAt: Date.now() })
+    if (isShownOn(wallpaper.id, screen)) {
+      updateWallpaper(wallpaper.id, { appliedCount: (wallpaper.appliedCount ?? 0) + 1, lastAppliedAt: Date.now() })
+    }
   } else if (action.type === 'playlist') {
   } else if (action.type === 'playlist') {
     if (!getPlaylist(action.playlistId)) throw new Error('The scheduled playlist no longer exists')
     if (!getPlaylist(action.playlistId)) throw new Error('The scheduled playlist no longer exists')
     startPlaylist(action.playlistId, screen)
     startPlaylist(action.playlistId, screen)
@@ -76,20 +78,24 @@ export async function runRule(rule: ScheduleRule): Promise<void> {
 }
 }
 
 
 // one after another, a later rule for a single screen has to land after an earlier one for all of them
 // one after another, a later rule for a single screen has to land after an earlier one for all of them
-async function runAll(rules: ScheduleRule[]): Promise<void> {
+async function runAll(rules: readonly ScheduleRule[]): Promise<void> {
   for (const rule of rules) {
   for (const rule of rules) {
     await runRule(rule).catch((err: unknown) => { console.error(`[Schedule] "${rule.name}" failed:`, err) })
     await runRule(rule).catch((err: unknown) => { console.error(`[Schedule] "${rule.name}" failed:`, err) })
   }
   }
 }
 }
 
 
+function dueRules(now: number): ScheduleRule[] {
+  const last = store.get('lastTick')
+  if (last === null || last >= now) return []
+  const from = new Date(Math.max(last, now - MAX_CATCH_UP_MS))
+  return dueTimeRules(store.get('rules'), from, new Date(now))
+}
+
 function tick(): void {
 function tick(): void {
   const now = Date.now()
   const now = Date.now()
-  const last = store.get('lastTick')
+  const due = dueRules(now)
   store.set('lastTick', now)
   store.set('lastTick', now)
-  if (last === null || last >= now) return
-
-  const from = new Date(Math.max(last, now - MAX_CATCH_UP_MS))
-  void runAll(dueTimeRules(store.get('rules'), from, new Date(now)))
+  void runAll(due)
 }
 }
 
 
 function onThemeChanged(): void {
 function onThemeChanged(): void {
@@ -100,20 +106,18 @@ function onThemeChanged(): void {
   void runAll(store.get('rules').filter((r) => r.enabled && r.trigger.type === 'theme' && r.trigger.theme === theme))
   void runAll(store.get('rules').filter((r) => r.enabled && r.trigger.type === 'theme' && r.trigger.theme === theme))
 }
 }
 
 
-/** Screens whose catch-up rule is about to launch, so restore does not launch there as well */
-export function catchUpScreens(now = Date.now()): ScreenTarget[] {
-  const last = store.get('lastTick')
-  if (last === null || last >= now) return []
-  const from = new Date(Math.max(last, now - MAX_CATCH_UP_MS))
-  return dueTimeRules(store.get('rules'), from, new Date(now)).map((rule) => rule.screen)
+export function takeCatchUp(now = Date.now()): ScheduleRule[] {
+  const due = dueRules(now)
+  store.set('lastTick', now)
+  return due
 }
 }
 
 
-/** Call after the playlist player resumed, so a rule that came due while closed wins over it */
-export function initSchedule(window: BrowserWindow): void {
+/** Call after the playlist player resumed, so a rule that came due while closed (takeCatchUp) wins over it */
+export function initSchedule(window: BrowserWindow, catchUp: readonly ScheduleRule[]): void {
   win = window
   win = window
   setBusyWallpaperSource('schedule', () => [...runningWallpapers.keys()])
   setBusyWallpaperSource('schedule', () => [...runningWallpapers.keys()])
   lastDark = nativeTheme.shouldUseDarkColors
   lastDark = nativeTheme.shouldUseDarkColors
   nativeTheme.on('updated', onThemeChanged)
   nativeTheme.on('updated', onThemeChanged)
-  tick()
+  void runAll(catchUp)
   timer ??= setInterval(tick, TICK_MS)
   timer ??= setInterval(tick, TICK_MS)
 }
 }

+ 79 - 0
src/main/services/wallpaper-state.service.test.ts

@@ -0,0 +1,79 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const writes: string[] = []
+
+vi.mock('electron', () => ({ app: { on: () => {} } }))
+vi.mock('electron-store', () => ({
+  default: class {
+    private data: Record<string, unknown> = {}
+    get(key: string): unknown {
+      return this.data[key]
+    }
+    set(key: string, value: unknown): void {
+      writes.push(key)
+      this.data[key] = value
+    }
+  }
+}))
+
+import { clearAssignment, getAssignments, isSplitActive, markSplitActive, setAssignment } from './wallpaper-state.service'
+
+beforeEach(() => {
+  clearAssignment()
+  writes.length = 0
+})
+
+describe('split flag', () => {
+  it('is dropped when a single wallpaper takes the screen, and only there', () => {
+    setAssignment('DP-1', 'a')
+    setAssignment('DP-2', 'b')
+    markSplitActive('DP-1')
+    markSplitActive('DP-2')
+
+    setAssignment('DP-1', 'c')
+
+    expect(isSplitActive('DP-1')).toBe(false)
+    expect(isSplitActive('DP-2')).toBe(true)
+  })
+
+  it('is dropped everywhere when the shared screen takes a wallpaper', () => {
+    setAssignment('DP-1', 'a')
+    markSplitActive('DP-1')
+
+    setAssignment('*', 'b')
+
+    expect(isSplitActive('DP-1')).toBe(false)
+    expect(getAssignments()).toEqual({ '*': 'b' })
+  })
+
+  it('goes with the assignment of one screen, or all of them', () => {
+    setAssignment('DP-1', 'a')
+    setAssignment('DP-2', 'b')
+    markSplitActive('DP-1')
+    markSplitActive('DP-2')
+
+    clearAssignment('DP-1')
+    expect(isSplitActive('DP-1')).toBe(false)
+    expect(isSplitActive('DP-2')).toBe(true)
+
+    clearAssignment()
+    expect(isSplitActive('DP-2')).toBe(false)
+  })
+
+  it('stays when only the shared assignment is cleared', () => {
+    setAssignment('DP-1', 'a')
+    markSplitActive('DP-1')
+
+    clearAssignment('*')
+
+    expect(isSplitActive('DP-1')).toBe(true)
+  })
+
+  it('costs no extra write while no split was ever active', () => {
+    setAssignment('DP-1', 'a')
+    clearAssignment('DP-1')
+    clearAssignment()
+
+    expect(writes).not.toContain('splitActive')
+  })
+})

+ 34 - 4
src/main/services/wallpaper-state.service.ts

@@ -5,6 +5,7 @@ interface StoreSchema {
   /** Written by older versions, read once as the '*' assignment */
   /** Written by older versions, read once as the '*' assignment */
   activeWallpaperId?: string
   activeWallpaperId?: string
   assignments?: Record<ScreenTarget, string>
   assignments?: Record<ScreenTarget, string>
+  splitActive?: Record<ScreenTarget, boolean>
 }
 }
 
 
 const store = openStore<StoreSchema>()
 const store = openStore<StoreSchema>()
@@ -16,21 +17,50 @@ export function getAssignments(): Record<ScreenTarget, string> {
   return legacy ? { '*': legacy } : {}
   return legacy ? { '*': legacy } : {}
 }
 }
 
 
+function dropSplit(screen?: ScreenTarget): void {
+  const current = store.get('splitActive') ?? {}
+
+  if (screen === undefined) {
+    if (Object.keys(current).length > 0) store.set('splitActive', {})
+    return
+  }
+
+  if (!(screen in current)) return
+
+  const next = { ...current }
+  delete next[screen]
+  store.set('splitActive', next)
+}
+
 export function setAssignment(screen: ScreenTarget, wallpaperId: string): void {
 export function setAssignment(screen: ScreenTarget, wallpaperId: string): void {
   const next = screen === '*' ? {} : { ...getAssignments() }
   const next = screen === '*' ? {} : { ...getAssignments() }
   if (screen !== '*') delete next['*']
   if (screen !== '*') delete next['*']
   next[screen] = wallpaperId
   next[screen] = wallpaperId
   store.set('assignments', next)
   store.set('assignments', next)
+  dropSplit(screen === '*' ? undefined : screen)
 }
 }
 
 
 export function clearAssignment(screen?: ScreenTarget): void {
 export function clearAssignment(screen?: ScreenTarget): void {
   if (screen === undefined) {
   if (screen === undefined) {
     store.set('assignments', {})
     store.set('assignments', {})
-    return
+  } else {
+    const next = { ...getAssignments() }
+    delete next[screen]
+    store.set('assignments', next)
   }
   }
-  const next = { ...getAssignments() }
-  delete next[screen]
-  store.set('assignments', next)
+  dropSplit(screen)
+}
+
+export function markSplitActive(screen: ScreenTarget): void {
+  store.set('splitActive', { ...store.get('splitActive'), [screen]: true })
+}
+
+export function splitActiveScreens(): ScreenTarget[] {
+  return Object.keys(store.get('splitActive') ?? {})
+}
+
+export function isSplitActive(screen: ScreenTarget): boolean {
+  return store.get('splitActive')?.[screen] === true
 }
 }
 
 
 /** The wallpaper on the first screen, for callers that only care about one */
 /** The wallpaper on the first screen, for callers that only care about one */

+ 5 - 1
src/main/services/wallpaper.service.ts

@@ -250,6 +250,10 @@ export function isAnimatedWallpaper(wallpaper: WallpaperMeta): boolean {
   return wallpaper.type === 'scene' || wallpaper.type === 'web' || wallpaper.type === 'video'
   return wallpaper.type === 'scene' || wallpaper.type === 'web' || wallpaper.type === 'video'
 }
 }
 
 
+export function usesEngine(wallpaper: WallpaperMeta): boolean {
+  return isAnimatedWallpaper(wallpaper) && os.platform() === 'linux' && getLweStatus().installed
+}
+
 /** linux-wallpaperengine when available, else a static image */
 /** linux-wallpaperengine when available, else a static image */
 export async function applyWallpaperMeta(
 export async function applyWallpaperMeta(
   wallpaper: WallpaperMeta,
   wallpaper: WallpaperMeta,
@@ -266,7 +270,7 @@ export async function applyWallpaperMeta(
 
 
   await ensureDependencyInstalled(wallpaper, options.dependencyPrompt)
   await ensureDependencyInstalled(wallpaper, options.dependencyPrompt)
 
 
-  if (isAnimatedWallpaper(wallpaper) && os.platform() === 'linux' && getLweStatus().installed) {
+  if (usesEngine(wallpaper)) {
     await launchLweAsync(wallpaper.localPath, {
     await launchLweAsync(wallpaper.localPath, {
       ...(await lweOptionsFor(wallpaper, options)),
       ...(await lweOptionsFor(wallpaper, options)),
       screen: options.screen,
       screen: options.screen,

+ 16 - 5
src/renderer/src/components/common/DetailSidebar.tsx

@@ -1,6 +1,7 @@
 import { useState, useRef, type ReactNode } from 'react'
 import { useState, useRef, type ReactNode } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import FontNotice from './FontNotice'
 import FontNotice from './FontNotice'
+import { useToast } from './Toast'
 import {
 import {
   X,
   X,
   Star,
   Star,
@@ -47,6 +48,7 @@ import {
 import clsx from 'clsx'
 import clsx from 'clsx'
 import { openWorkshopPage, openProfilePage, isWorkshopId } from '../../utils/steam'
 import { openWorkshopPage, openProfilePage, isWorkshopId } from '../../utils/steam'
 import { WE_TYPES, WE_AGE_RATINGS, canonicalResolutionTag, resolutionsFromTags } from '../../constants/weFilters'
 import { WE_TYPES, WE_AGE_RATINGS, canonicalResolutionTag, resolutionsFromTags } from '../../constants/weFilters'
+import { DEFAULT_ENGINE_VOLUME } from '@shared/constants'
 import { formatFileSize } from '../../utils/format'
 import { formatFileSize } from '../../utils/format'
 import RangeInput from './RangeInput'
 import RangeInput from './RangeInput'
 import { useDislikedIds, useVoteAction, useVotedIds } from '../../hooks/useVotes'
 import { useDislikedIds, useVoteAction, useVotedIds } from '../../hooks/useVotes'
@@ -412,6 +414,7 @@ export default function DetailSidebar({
 }: DetailSidebarProps) {
 }: DetailSidebarProps) {
   const workshopId = isWorkshopId(id)
   const workshopId = isWorkshopId(id)
   const queryClient = useQueryClient()
   const queryClient = useQueryClient()
+  const { showToast } = useToast()
   const lweInstalled = useLweInstalled()
   const lweInstalled = useLweInstalled()
   const cachedLiked = useVotedIds().has(id)
   const cachedLiked = useVotedIds().has(id)
   const isDisliked = useDislikedIds().has(id)
   const isDisliked = useDislikedIds().has(id)
@@ -478,9 +481,8 @@ export default function DetailSidebar({
 
 
   const { targets, perScreen } = useDisplayTargets()
   const { targets, perScreen } = useDisplayTargets()
   const [playScreen, setPlayScreen] = useState<ScreenTarget>('*')
   const [playScreen, setPlayScreen] = useState<ScreenTarget>('*')
-  const activeScreens = useScreenAssignments()
-    .filter((a) => a.wallpaperId === id)
-    .map((a) => a.screen)
+  const assignments = useScreenAssignments().filter((a) => a.wallpaperId === id)
+  const activeScreens = assignments.map((a) => a.screen)
   const isActive = activeScreens.length > 0
   const isActive = activeScreens.length > 0
 
 
   const { data: objects = [], isLoading: objectsLoading } = useQuery({
   const { data: objects = [], isLoading: objectsLoading } = useQuery({
@@ -584,7 +586,16 @@ export default function DetailSidebar({
             soundVolume: patch.soundVolume
             soundVolume: patch.soundVolume
           }, localPath)
           }, localPath)
       if (!ok) {
       if (!ok) {
-        for (const screen of activeScreens) await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen })
+        // a split takes the layout of its slots from the wallpaper and nothing else, and a single wallpaper would replace it
+        const reachesSplit = ['scalingMode', 'zoom', 'offsetX', 'offsetY', 'cornerColor', 'imageAdjustments'].some((key) => key in patch)
+        for (const { screen, split } of assignments) {
+          try {
+            if (!split) await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen })
+            else if (reachesSplit) await window.electronAPI.wallpaper.showSplit(screen)
+          } catch (err) {
+            showToast((err as Error).message, { warning: true, durationMs: 6000 })
+          }
+        }
       }
       }
       void queryClient.invalidateQueries({ queryKey: ['screen-assignments'] })
       void queryClient.invalidateQueries({ queryKey: ['screen-assignments'] })
     }
     }
@@ -696,7 +707,7 @@ export default function DetailSidebar({
 
 
   const [volumeDraft, setVolumeDraft] = useState<number | null>(null)
   const [volumeDraft, setVolumeDraft] = useState<number | null>(null)
   const [isCommittingVolume, setIsCommittingVolume] = useState(false)
   const [isCommittingVolume, setIsCommittingVolume] = useState(false)
-  const volume = volumeDraft ?? libraryMeta?.volumeOverride ?? 15
+  const volume = volumeDraft ?? libraryMeta?.volumeOverride ?? DEFAULT_ENGINE_VOLUME
 
 
   async function commitVolume(v: number) {
   async function commitVolume(v: number) {
     setIsCommittingVolume(true)
     setIsCommittingVolume(true)

+ 44 - 5
src/renderer/src/components/common/PlayScreenPrompt.tsx

@@ -11,7 +11,7 @@ type Pending = {
 
 
 let openPrompt: ((targets: ScreenTarget[]) => Promise<ScreenTarget | null>) | null = null
 let openPrompt: ((targets: ScreenTarget[]) => Promise<ScreenTarget | null>) | null = null
 
 
-/** null means cancel. The default is every screen, which is what card Play used to do. */
+// null means cancel
 export function askPlayScreen(targets: ScreenTarget[]): Promise<ScreenTarget | null> {
 export function askPlayScreen(targets: ScreenTarget[]): Promise<ScreenTarget | null> {
   if (!openPrompt) return Promise.resolve(CARD_PLAY_DEFAULT_SCREEN)
   if (!openPrompt) return Promise.resolve(CARD_PLAY_DEFAULT_SCREEN)
   return openPrompt(targets)
   return openPrompt(targets)
@@ -21,21 +21,55 @@ export default function PlayScreenPrompt() {
   const [pending, setPending] = useState<Pending | null>(null)
   const [pending, setPending] = useState<Pending | null>(null)
   const [value, setValue] = useState<ScreenTarget>(CARD_PLAY_DEFAULT_SCREEN)
   const [value, setValue] = useState<ScreenTarget>(CARD_PLAY_DEFAULT_SCREEN)
   const dialogRef = useRef<HTMLDivElement>(null)
   const dialogRef = useRef<HTMLDivElement>(null)
+  const pendingRef = useRef<Pending | null>(null)
+  const returnFocus = useRef<HTMLElement | null>(null)
 
 
   useEffect(() => {
   useEffect(() => {
     openPrompt = (targets) => new Promise((resolve) => {
     openPrompt = (targets) => new Promise((resolve) => {
+      if (!pendingRef.current && document.activeElement instanceof HTMLElement) returnFocus.current = document.activeElement
+      pendingRef.current?.resolve(null)
+      const next = { targets, resolve }
+      pendingRef.current = next
       setValue(CARD_PLAY_DEFAULT_SCREEN)
       setValue(CARD_PLAY_DEFAULT_SCREEN)
-      setPending({ targets, resolve })
+      setPending(next)
     })
     })
-    return () => { openPrompt = null }
+    return () => {
+      openPrompt = null
+      pendingRef.current?.resolve(null)
+      pendingRef.current = null
+    }
   }, [])
   }, [])
 
 
+  useEffect(() => {
+    if (!pending) return
+    const onKey = (e: KeyboardEvent) => {
+      const root = dialogRef.current
+      if (!root || (e.target instanceof Node && root.contains(e.target))) return
+      e.stopImmediatePropagation()
+      if (e.key === 'Escape') {
+        e.preventDefault()
+        finish(null)
+      } else if (e.key === 'Tab') {
+        e.preventDefault()
+        root.querySelector<HTMLElement>('button, select, input')?.focus()
+      }
+    }
+    window.addEventListener('keydown', onKey, true)
+    return () => { window.removeEventListener('keydown', onKey, true) }
+  }, [pending])
+
   function finish(screen: ScreenTarget | null) {
   function finish(screen: ScreenTarget | null) {
-    pending?.resolve(screen)
+    const current = pendingRef.current
+    pendingRef.current = null
+    current?.resolve(screen)
     setPending(null)
     setPending(null)
+    returnFocus.current?.focus()
+    returnFocus.current = null
   }
   }
 
 
   function onKeyDown(e: ReactKeyboardEvent<HTMLDivElement>) {
   function onKeyDown(e: ReactKeyboardEvent<HTMLDivElement>) {
+    // the grid behind the modal has shortcuts of its own
+    e.stopPropagation()
     if (e.key === 'Escape') {
     if (e.key === 'Escape') {
       e.preventDefault()
       e.preventDefault()
       finish(null)
       finish(null)
@@ -61,7 +95,12 @@ export default function PlayScreenPrompt() {
   if (!pending) return null
   if (!pending) return null
 
 
   return (
   return (
-    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-8">
+    <div
+      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-8"
+      onMouseDown={(e) => {
+        if (e.button === 0 && e.target === e.currentTarget) finish(null)
+      }}
+    >
       <div
       <div
         ref={dialogRef}
         ref={dialogRef}
         role="dialog"
         role="dialog"

+ 6 - 7
src/renderer/src/components/common/RangeInput.tsx

@@ -1,5 +1,5 @@
 import type { ChangeEvent, KeyboardEvent, PointerEvent } from 'react'
 import type { ChangeEvent, KeyboardEvent, PointerEvent } from 'react'
-import { useRef } from 'react'
+import { useState } from 'react'
 import { isRangeKey } from '../../utils/dom'
 import { isRangeKey } from '../../utils/dom'
 import { createRangeCommit } from '../../utils/rangeCommit'
 import { createRangeCommit } from '../../utils/rangeCommit'
 
 
@@ -15,17 +15,16 @@ interface Props {
   onCommit: (value: number) => void
   onCommit: (value: number) => void
 }
 }
 
 
-/** One commit path for every detail-panel slider. The value comes from the drag, not a later read of the input. */
 export default function RangeInput({ min, max, step, value, disabled, title, className, onLive, onCommit }: Props) {
 export default function RangeInput({ min, max, step, value, disabled, title, className, onLive, onCommit }: Props) {
-  const machine = useRef(createRangeCommit())
+  const [machine] = useState(createRangeCommit)
 
 
   function end() {
   function end() {
-    const next = machine.current.end()
+    const next = machine.end()
     if (next !== null) onCommit(next)
     if (next !== null) onCommit(next)
   }
   }
 
 
   function pointerDown(e: PointerEvent<HTMLInputElement>) {
   function pointerDown(e: PointerEvent<HTMLInputElement>) {
-    machine.current.pointerDown()
+    machine.pointerDown()
     try {
     try {
       e.currentTarget.setPointerCapture(e.pointerId)
       e.currentTarget.setPointerCapture(e.pointerId)
     } catch {
     } catch {
@@ -44,9 +43,9 @@ export default function RangeInput({ min, max, step, value, disabled, title, cla
       title={title}
       title={title}
       className={`w-full touch-none accent-accent-500 disabled:opacity-50 ${className ?? ''}`}
       className={`w-full touch-none accent-accent-500 disabled:opacity-50 ${className ?? ''}`}
       onPointerDown={pointerDown}
       onPointerDown={pointerDown}
-      onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => { machine.current.keyDown(e.key) }}
+      onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => { machine.keyDown(e.key) }}
       onChange={(e: ChangeEvent<HTMLInputElement>) => {
       onChange={(e: ChangeEvent<HTMLInputElement>) => {
-        const next = machine.current.change(e.target.value)
+        const next = machine.change(e.target.value)
         if (next !== null) onLive?.(next)
         if (next !== null) onLive?.(next)
       }}
       }}
       onPointerUp={end}
       onPointerUp={end}

+ 4 - 7
src/renderer/src/components/common/sidebar/ImageAdjustmentsSection.tsx

@@ -3,6 +3,7 @@ import { Loader2, RotateCcw, SlidersHorizontal } from 'lucide-react'
 import type { ImageAdjustments } from '@shared/types'
 import type { ImageAdjustments } from '@shared/types'
 import { IMAGE_FILTERS, NEUTRAL_COLOR_VALUE, hasImageAdjustments } from '@shared/imageAdjustments'
 import { IMAGE_FILTERS, NEUTRAL_COLOR_VALUE, hasImageAdjustments } from '@shared/imageAdjustments'
 import { t, translatedOr } from '../../../i18n'
 import { t, translatedOr } from '../../../i18n'
+import RangeInput from '../RangeInput'
 import type { MessageKey } from '@shared/i18n'
 import type { MessageKey } from '@shared/i18n'
 
 
 interface Props {
 interface Props {
@@ -52,17 +53,13 @@ export default function ImageAdjustmentsSection({ adjustments = {}, live, onComm
           <span className="flex-1">{label}</span>
           <span className="flex-1">{label}</span>
           <span>{value}</span>
           <span>{value}</span>
         </div>
         </div>
-        <input
-          type="range"
+        <RangeInput
           min={0}
           min={0}
           max={100}
           max={100}
           value={value}
           value={value}
           disabled={busy}
           disabled={busy}
-          onChange={(e) => { slide(key, Number(e.target.value)) }}
-          onMouseUp={() => void (draft && commit(draft))}
-          onTouchEnd={() => void (draft && commit(draft))}
-          onKeyUp={() => void (draft && commit(draft))}
-          className="w-full accent-accent-500 disabled:opacity-50"
+          onLive={(next) => { slide(key, next) }}
+          onCommit={(next) => void commit({ ...current, [key]: next })}
         />
         />
       </div>
       </div>
     )
     )

+ 17 - 12
src/renderer/src/components/common/sidebar/VideoTrimSection.tsx

@@ -9,6 +9,7 @@ import {
   type VideoSegment
   type VideoSegment
 } from '@shared/videoTrim'
 } from '@shared/videoTrim'
 import { t } from '../../../i18n'
 import { t } from '../../../i18n'
+import RangeInput from '../RangeInput'
 
 
 interface Props {
 interface Props {
   segments: VideoSegment[]
   segments: VideoSegment[]
@@ -71,16 +72,21 @@ export default function VideoTrimSection({ segments, duration, live, onCommit, o
     }
     }
   }
   }
 
 
-  function slide(side: 'start' | 'end', value: number) {
-    if (!part) return
+  function slid(side: 'start' | 'end', value: number) {
+    if (!part) return null
     const end = endOf(part)
     const end = endOf(part)
     const changed =
     const changed =
       side === 'start'
       side === 'start'
         ? { ...part, start: end === null ? value : Math.min(value, end - MIN_LENGTH) }
         ? { ...part, start: end === null ? value : Math.min(value, end - MIN_LENGTH) }
         : { ...part, end: Math.max(value, part.start + MIN_LENGTH) }
         : { ...part, end: Math.max(value, part.start + MIN_LENGTH) }
-    const next = withPart(index, changed)
-    setDraft(next)
-    onPreview(normalizeVideoSegments(next, duration), side === 'end' ? seamSeek(changed) : undefined)
+    return { changed, next: withPart(index, changed) }
+  }
+
+  function slide(side: 'start' | 'end', value: number) {
+    const moved = slid(side, value)
+    if (!moved) return
+    setDraft(moved.next)
+    onPreview(normalizeVideoSegments(moved.next, duration), side === 'end' ? seamSeek(moved.changed) : undefined)
   }
   }
 
 
   function commitText(i: number, side: 'start' | 'end', text: string) {
   function commitText(i: number, side: 'start' | 'end', text: string) {
@@ -147,19 +153,18 @@ export default function VideoTrimSection({ segments, duration, live, onCommit, o
     return (
     return (
       <div className="flex items-center gap-1.5">
       <div className="flex items-center gap-1.5">
         <span className="w-7 text-gray-500">{side === 'start' ? t('trim.start') : t('trim.end')}</span>
         <span className="w-7 text-gray-500">{side === 'start' ? t('trim.start') : t('trim.end')}</span>
-        <input
-          type="range"
+        <RangeInput
           min={0}
           min={0}
           max={duration}
           max={duration}
           step={0.1}
           step={0.1}
           value={side === 'start' ? part.start : (part.end ?? duration)}
           value={side === 'start' ? part.start : (part.end ?? duration)}
           disabled={busy}
           disabled={busy}
-          onChange={(e) => { slide(side, Number(e.target.value)) }}
-          onMouseUp={() => void (draft && commit(draft))}
-          onTouchEnd={() => void (draft && commit(draft))}
-          onKeyUp={() => void (draft && commit(draft))}
+          onLive={(next) => { slide(side, next) }}
+          onCommit={(value) => {
+            const moved = slid(side, value)
+            if (moved) void commit(moved.next)
+          }}
           title={side === 'start' ? t('trim.startHint') : t('trim.endHint')}
           title={side === 'start' ? t('trim.startHint') : t('trim.endHint')}
-          className="w-full accent-accent-500 disabled:opacity-50"
         />
         />
       </div>
       </div>
     )
     )

+ 1 - 2
src/renderer/src/components/library/WallpaperCard.tsx

@@ -108,8 +108,7 @@ export default function WallpaperCard({
     setIsApplying(true)
     setIsApplying(true)
     setError(null)
     setError(null)
     try {
     try {
-      // no screen yet: the hook asks which monitor when per-screen mode has two or more
-      await applyWallpaper(wallpaper.id)
+      await applyWallpaper(wallpaper.id, undefined, setError)
     } finally {
     } finally {
       setIsApplying(false)
       setIsApplying(false)
     }
     }

+ 13 - 8
src/renderer/src/hooks/useWallpaperActions.ts

@@ -6,19 +6,24 @@ import { askPlayScreen } from '../components/common/PlayScreenPrompt'
 import { forEachIgnoringErrors } from '../utils/async'
 import { forEachIgnoringErrors } from '../utils/async'
 import { t } from '../i18n'
 import { t } from '../i18n'
 
 
-export function useApplyWallpaper(): (id: string, screen?: ScreenTarget) => Promise<void> {
+export function useApplyWallpaper(): (
+  id: string,
+  screen?: ScreenTarget,
+  onError?: (message: string) => void
+) => Promise<void> {
   const queryClient = useQueryClient()
   const queryClient = useQueryClient()
   const { showToast } = useToast()
   const { showToast } = useToast()
 
 
-  return async (id, screen) => {
+  return async (id, screen, onError = showToast) => {
     try {
     try {
       let chosen = screen
       let chosen = screen
       if (chosen === undefined) {
       if (chosen === undefined) {
-        const [cfg, targets] = await Promise.all([
-          window.electronAPI.config.get(),
-          window.electronAPI.wallpaper.getTargets()
-        ])
-        if (cardPlayNeedsScreenChoice(cfg.displayMode, targets)) {
+        const targets = await queryClient.fetchQuery({
+          queryKey: ['display-targets'],
+          queryFn: () => window.electronAPI.wallpaper.getTargets(),
+          staleTime: 30_000
+        })
+        if (cardPlayNeedsScreenChoice(targets)) {
           const picked = await askPlayScreen(targets.filter((name) => name !== '*'))
           const picked = await askPlayScreen(targets.filter((name) => name !== '*'))
           if (picked === null) return
           if (picked === null) return
           chosen = picked
           chosen = picked
@@ -27,7 +32,7 @@ export function useApplyWallpaper(): (id: string, screen?: ScreenTarget) => Prom
       await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen: chosen })
       await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen: chosen })
       void queryClient.invalidateQueries({ queryKey: ['library'] })
       void queryClient.invalidateQueries({ queryKey: ['library'] })
     } catch (err) {
     } catch (err) {
-      showToast((err as Error).message)
+      onError((err as Error).message)
     }
     }
   }
   }
 }
 }

+ 1 - 2
src/renderer/src/utils/rangeCommit.ts

@@ -21,10 +21,9 @@ export function createRangeCommit() {
     },
     },
     end(): number | null {
     end(): number | null {
       const value = live
       const value = live
-      const active = dragging || value !== null
       live = null
       live = null
       dragging = false
       dragging = false
-      return active && value !== null ? value : null
+      return value
     }
     }
   }
   }
 }
 }

+ 2 - 0
src/shared/constants.ts

@@ -10,3 +10,5 @@ export const APP_RELEASE_REPO = 'WallpaperEngineLover/we_manager'
 export const RECOMMENDED_WEB_FPS = 60
 export const RECOMMENDED_WEB_FPS = 60
 
 
 export const DEFAULT_LWE_FPS = 60
 export const DEFAULT_LWE_FPS = 60
+
+export const DEFAULT_ENGINE_VOLUME = 15

+ 3 - 0
src/shared/i18n/locales/de.ts

@@ -816,6 +816,9 @@ export const de: Messages = {
   'settings.killAllHint': 'Beendet jede laufende Instanz zwangsweise, auch solche, die nicht von WE Manager gestartet wurden.',
   'settings.killAllHint': 'Beendet jede laufende Instanz zwangsweise, auch solche, die nicht von WE Manager gestartet wurden.',
   'settings.killOnQuit': 'Alle linux-wallpaperengine-Prozesse beenden, wenn WE Manager beendet wird',
   'settings.killOnQuit': 'Alle linux-wallpaperengine-Prozesse beenden, wenn WE Manager beendet wird',
   'settings.skipPlaylistResume': 'Playlists beim Start von WE Manager nicht fortsetzen',
   'settings.skipPlaylistResume': 'Playlists beim Start von WE Manager nicht fortsetzen',
+  'settings.skipPlaylistResumeHint': 'Bildschirme mit einer Playlist bleiben nach einem Neustart leer. Das letzte Playlist-Element wird nicht wiederhergestellt.',
+  'settings.freshProcessOnPathChange': 'Neuen Engine-Prozess starten, wenn sich das Hintergrundbild ändert',
+  'settings.freshProcessOnPathChangeHint': 'Standardmäßig aus, damit ein Wechsel die laufende Engine und ihren Übergang behält. Aktiviere es, wenn ein getauschtes Hintergrundbild leer bleibt oder der vorherige Ton weiterläuft. Playlists, Zeitpläne und das Tray starten die Engine dann ebenfalls neu.',
   'settings.lweHint': 'Nötig für animierte/Szenen-Hintergründe unter Linux. Rendert Wallpaper-Engine-Szenen direkt auf deinem Desktop.',
   'settings.lweHint': 'Nötig für animierte/Szenen-Hintergründe unter Linux. Rendert Wallpaper-Engine-Szenen direkt auf deinem Desktop.',
   'settings.none': 'Keine',
   'settings.none': 'Keine',
   'settings.notConfigured': 'Nicht eingerichtet',
   'settings.notConfigured': 'Nicht eingerichtet',

+ 1 - 1
src/shared/i18n/locales/en.ts

@@ -814,7 +814,7 @@ export const en = {
   'settings.killAllHint': 'Force-kills every running instance, including ones not launched by WE Manager.',
   'settings.killAllHint': 'Force-kills every running instance, including ones not launched by WE Manager.',
   'settings.killOnQuit': 'Kill all linux-wallpaperengine processes when WE Manager quits',
   'settings.killOnQuit': 'Kill all linux-wallpaperengine processes when WE Manager quits',
   'settings.skipPlaylistResume': 'Don\'t resume playlists when WE Manager starts',
   'settings.skipPlaylistResume': 'Don\'t resume playlists when WE Manager starts',
-  'settings.skipPlaylistResumeHint': 'Those screens stay blank after a restart. The last playlist item is not put back.',
+  'settings.skipPlaylistResumeHint': 'Screens that had a playlist stay blank after a restart. The last playlist item is not put back.',
   'settings.freshProcessOnPathChange': 'Start a new engine process when the wallpaper changes',
   'settings.freshProcessOnPathChange': 'Start a new engine process when the wallpaper changes',
   'settings.freshProcessOnPathChangeHint': 'Off by default, so a change keeps the running engine and its transition. Turn it on when a swapped wallpaper stays blank or the previous audio keeps playing. Playlists, schedules and the tray then restart the engine too.',
   'settings.freshProcessOnPathChangeHint': 'Off by default, so a change keeps the running engine and its transition. Turn it on when a swapped wallpaper stays blank or the previous audio keeps playing. Playlists, schedules and the tray then restart the engine too.',
   'settings.lweHint': 'Required for animated/scene wallpapers on Linux. Renders Wallpaper Engine scenes directly on your desktop.',
   'settings.lweHint': 'Required for animated/scene wallpapers on Linux. Renders Wallpaper Engine scenes directly on your desktop.',

+ 3 - 0
src/shared/i18n/locales/es.ts

@@ -816,6 +816,9 @@ export const es: Messages = {
   'settings.killAllHint': 'Fuerza el cierre de todas las instancias en ejecución, incluidas las que no lanzó WE Manager.',
   'settings.killAllHint': 'Fuerza el cierre de todas las instancias en ejecución, incluidas las que no lanzó WE Manager.',
   'settings.killOnQuit': 'Terminar todos los procesos de linux-wallpaperengine al salir de WE Manager',
   'settings.killOnQuit': 'Terminar todos los procesos de linux-wallpaperengine al salir de WE Manager',
   'settings.skipPlaylistResume': 'No reanudar las listas de reproducción al iniciar WE Manager',
   'settings.skipPlaylistResume': 'No reanudar las listas de reproducción al iniciar WE Manager',
+  'settings.skipPlaylistResumeHint': 'Las pantallas que tenían una lista quedan en blanco tras reiniciar. El último elemento de la lista no se restaura.',
+  'settings.freshProcessOnPathChange': 'Iniciar un proceso nuevo del motor cuando cambie el fondo',
+  'settings.freshProcessOnPathChangeHint': 'Desactivado por defecto, así un cambio conserva el motor en ejecución y su transición. Actívalo cuando un fondo cambiado quede en blanco o siga sonando el audio anterior. Las listas, las programaciones y la bandeja también reiniciarán el motor.',
   'settings.lweHint': 'Necesario para fondos animados/de escena en Linux. Renderiza las escenas de Wallpaper Engine directamente en tu escritorio.',
   'settings.lweHint': 'Necesario para fondos animados/de escena en Linux. Renderiza las escenas de Wallpaper Engine directamente en tu escritorio.',
   'settings.none': 'Ninguna',
   'settings.none': 'Ninguna',
   'settings.notConfigured': 'Sin configurar',
   'settings.notConfigured': 'Sin configurar',

+ 3 - 0
src/shared/i18n/locales/fr.ts

@@ -816,6 +816,9 @@ export const fr: Messages = {
   'settings.killAllHint': 'Force l\'arrêt de toutes les instances en cours, y compris celles non lancées par WE Manager.',
   'settings.killAllHint': 'Force l\'arrêt de toutes les instances en cours, y compris celles non lancées par WE Manager.',
   'settings.killOnQuit': 'Arrêter tous les processus linux-wallpaperengine en quittant WE Manager',
   'settings.killOnQuit': 'Arrêter tous les processus linux-wallpaperengine en quittant WE Manager',
   'settings.skipPlaylistResume': 'Ne pas reprendre les playlists au démarrage de WE Manager',
   'settings.skipPlaylistResume': 'Ne pas reprendre les playlists au démarrage de WE Manager',
+  'settings.skipPlaylistResumeHint': 'Les écrans qui avaient une playlist restent vides après un redémarrage. Le dernier élément de la playlist n\'est pas remis en place.',
+  'settings.freshProcessOnPathChange': 'Démarrer un nouveau processus du moteur quand le fond d\'écran change',
+  'settings.freshProcessOnPathChangeHint': 'Désactivé par défaut : un changement garde le moteur en cours et sa transition. Activez-le si un fond remplacé reste vide ou si l\'audio précédent continue. Les playlists, les planifications et la zone de notification redémarrent alors aussi le moteur.',
   'settings.lweHint': 'Nécessaire pour les fonds d\'écran animés/scènes sous Linux. Affiche les scènes Wallpaper Engine directement sur votre bureau.',
   'settings.lweHint': 'Nécessaire pour les fonds d\'écran animés/scènes sous Linux. Affiche les scènes Wallpaper Engine directement sur votre bureau.',
   'settings.none': 'Aucune',
   'settings.none': 'Aucune',
   'settings.notConfigured': 'Non configuré',
   'settings.notConfigured': 'Non configuré',

+ 3 - 0
src/shared/i18n/locales/it.ts

@@ -816,6 +816,9 @@ export const it: Messages = {
   'settings.killAllHint': 'Termina forzatamente ogni istanza in esecuzione, comprese quelle non avviate da WE Manager.',
   'settings.killAllHint': 'Termina forzatamente ogni istanza in esecuzione, comprese quelle non avviate da WE Manager.',
   'settings.killOnQuit': 'Termina tutti i processi di linux-wallpaperengine alla chiusura di WE Manager',
   'settings.killOnQuit': 'Termina tutti i processi di linux-wallpaperengine alla chiusura di WE Manager',
   'settings.skipPlaylistResume': 'Non riprendere le playlist all\'avvio di WE Manager',
   'settings.skipPlaylistResume': 'Non riprendere le playlist all\'avvio di WE Manager',
+  'settings.skipPlaylistResumeHint': 'Gli schermi che avevano una playlist restano vuoti dopo un riavvio. L\'ultimo elemento della playlist non viene ripristinato.',
+  'settings.freshProcessOnPathChange': 'Avvia un nuovo processo del motore quando cambia lo sfondo',
+  'settings.freshProcessOnPathChangeHint': 'Disattivato per impostazione predefinita, così un cambio mantiene il motore in esecuzione e la sua transizione. Attivalo se uno sfondo sostituito resta vuoto o l\'audio precedente continua. Anche playlist, pianificazioni e area di notifica riavviano il motore.',
   'settings.lweHint': 'Necessario per gli sfondi animati/scene su Linux. Renderizza le scene di Wallpaper Engine direttamente sul tuo desktop.',
   'settings.lweHint': 'Necessario per gli sfondi animati/scene su Linux. Renderizza le scene di Wallpaper Engine direttamente sul tuo desktop.',
   'settings.none': 'Nessuna',
   'settings.none': 'Nessuna',
   'settings.notConfigured': 'Non configurato',
   'settings.notConfigured': 'Non configurato',

+ 3 - 0
src/shared/i18n/locales/ja.ts

@@ -782,6 +782,9 @@ export const ja: Messages = {
   'settings.killAllHint': 'WE Manager が起動したもの以外も含め、実行中のすべてのインスタンスを強制終了します。',
   'settings.killAllHint': 'WE Manager が起動したもの以外も含め、実行中のすべてのインスタンスを強制終了します。',
   'settings.killOnQuit': 'WE Manager の終了時に linux-wallpaperengine のプロセスをすべて終了',
   'settings.killOnQuit': 'WE Manager の終了時に linux-wallpaperengine のプロセスをすべて終了',
   'settings.skipPlaylistResume': 'WE Manager の起動時にプレイリストを再開しない',
   'settings.skipPlaylistResume': 'WE Manager の起動時にプレイリストを再開しない',
+  'settings.skipPlaylistResumeHint': '再起動後、プレイリストがあった画面は空白のままになります。プレイリストの最後の項目は復元されません。',
+  'settings.freshProcessOnPathChange': '壁紙が変わるときに新しいエンジンプロセスを開始する',
+  'settings.freshProcessOnPathChangeHint': '既定ではオフで、切り替えても実行中のエンジンとトランジションが維持されます。入れ替えた壁紙が空白のままの場合や、前の音声が鳴り続ける場合にオンにしてください。プレイリスト、スケジュール、トレイでもエンジンが再起動します。',
   'settings.lweHint': 'Linux でアニメーション/シーン壁紙を使うのに必要です。Wallpaper Engine のシーンをデスクトップに直接描画します。',
   'settings.lweHint': 'Linux でアニメーション/シーン壁紙を使うのに必要です。Wallpaper Engine のシーンをデスクトップに直接描画します。',
   'settings.none': 'なし',
   'settings.none': 'なし',
   'settings.notConfigured': '未設定',
   'settings.notConfigured': '未設定',

+ 3 - 0
src/shared/i18n/locales/ko.ts

@@ -782,6 +782,9 @@ export const ko: Messages = {
   'settings.killAllHint': 'WE Manager가 실행하지 않은 것을 포함해 실행 중인 모든 인스턴스를 강제로 종료합니다.',
   'settings.killAllHint': 'WE Manager가 실행하지 않은 것을 포함해 실행 중인 모든 인스턴스를 강제로 종료합니다.',
   'settings.killOnQuit': 'WE Manager를 종료할 때 모든 linux-wallpaperengine 프로세스 종료',
   'settings.killOnQuit': 'WE Manager를 종료할 때 모든 linux-wallpaperengine 프로세스 종료',
   'settings.skipPlaylistResume': 'WE Manager를 시작할 때 재생목록을 이어서 재생하지 않기',
   'settings.skipPlaylistResume': 'WE Manager를 시작할 때 재생목록을 이어서 재생하지 않기',
+  'settings.skipPlaylistResumeHint': '다시 시작한 뒤 재생 목록이 있던 화면은 비어 있습니다. 재생 목록의 마지막 항목은 복원되지 않습니다.',
+  'settings.freshProcessOnPathChange': '배경화면이 바뀔 때 새 엔진 프로세스 시작',
+  'settings.freshProcessOnPathChangeHint': '기본값은 꺼짐이며, 변경해도 실행 중인 엔진과 전환 효과가 유지됩니다. 바꾼 배경화면이 비어 있거나 이전 소리가 계속 나올 때 켜세요. 재생 목록, 일정, 트레이에서도 엔진이 다시 시작됩니다.',
   'settings.lweHint': 'Linux에서 애니메이션/장면 배경화면에 필요합니다. Wallpaper Engine 장면을 바탕 화면에 직접 렌더링합니다.',
   'settings.lweHint': 'Linux에서 애니메이션/장면 배경화면에 필요합니다. Wallpaper Engine 장면을 바탕 화면에 직접 렌더링합니다.',
   'settings.none': '없음',
   'settings.none': '없음',
   'settings.notConfigured': '설정 안 됨',
   'settings.notConfigured': '설정 안 됨',

+ 3 - 0
src/shared/i18n/locales/pl.ts

@@ -884,6 +884,9 @@ export const pl: Messages = {
   'settings.killAllHint': 'Wymusza zakończenie wszystkich uruchomionych instancji, także tych nie uruchomionych przez WE Manager.',
   'settings.killAllHint': 'Wymusza zakończenie wszystkich uruchomionych instancji, także tych nie uruchomionych przez WE Manager.',
   'settings.killOnQuit': 'Kończ wszystkie procesy linux-wallpaperengine przy zamykaniu WE Manager',
   'settings.killOnQuit': 'Kończ wszystkie procesy linux-wallpaperengine przy zamykaniu WE Manager',
   'settings.skipPlaylistResume': 'Nie wznawiaj playlist po uruchomieniu WE Manager',
   'settings.skipPlaylistResume': 'Nie wznawiaj playlist po uruchomieniu WE Manager',
+  'settings.skipPlaylistResumeHint': 'Ekrany, na których była playlista, pozostają puste po ponownym uruchomieniu. Ostatni element playlisty nie jest przywracany.',
+  'settings.freshProcessOnPathChange': 'Uruchom nowy proces silnika przy zmianie tapety',
+  'settings.freshProcessOnPathChangeHint': 'Domyślnie wyłączone, więc zmiana zachowuje działający silnik i jego przejście. Włącz, gdy podmieniona tapeta pozostaje pusta albo gra dźwięk poprzedniej. Playlisty, harmonogramy i zasobnik również uruchomią wtedy silnik od nowa.',
   'settings.lweHint': 'Wymagany dla animowanych tapet/scen w Linuksie. Renderuje sceny Wallpaper Engine bezpośrednio na pulpicie.',
   'settings.lweHint': 'Wymagany dla animowanych tapet/scen w Linuksie. Renderuje sceny Wallpaper Engine bezpośrednio na pulpicie.',
   'settings.none': 'Brak',
   'settings.none': 'Brak',
   'settings.notConfigured': 'Nieskonfigurowany',
   'settings.notConfigured': 'Nieskonfigurowany',

+ 3 - 0
src/shared/i18n/locales/pt.ts

@@ -816,6 +816,9 @@ export const pt: Messages = {
   'settings.killAllHint': 'Força o encerramento de todas as instâncias em execução, incluindo as que não foram iniciadas pelo WE Manager.',
   'settings.killAllHint': 'Força o encerramento de todas as instâncias em execução, incluindo as que não foram iniciadas pelo WE Manager.',
   'settings.killOnQuit': 'Encerrar todos os processos do linux-wallpaperengine ao sair do WE Manager',
   'settings.killOnQuit': 'Encerrar todos os processos do linux-wallpaperengine ao sair do WE Manager',
   'settings.skipPlaylistResume': 'Não retomar as playlists ao iniciar o WE Manager',
   'settings.skipPlaylistResume': 'Não retomar as playlists ao iniciar o WE Manager',
+  'settings.skipPlaylistResumeHint': 'As telas que tinham uma playlist ficam em branco após reiniciar. O último item da playlist não é restaurado.',
+  'settings.freshProcessOnPathChange': 'Iniciar um novo processo do motor quando o papel de parede mudar',
+  'settings.freshProcessOnPathChangeHint': 'Desativado por padrão, assim uma troca mantém o motor em execução e sua transição. Ative quando um papel de parede trocado ficar em branco ou o áudio anterior continuar. Playlists, agendamentos e a bandeja também reiniciam o motor.',
   'settings.lweHint': 'Necessário para papéis de parede animados/de cena no Linux. Renderiza as cenas do Wallpaper Engine direto na sua área de trabalho.',
   'settings.lweHint': 'Necessário para papéis de parede animados/de cena no Linux. Renderiza as cenas do Wallpaper Engine direto na sua área de trabalho.',
   'settings.none': 'Nenhuma',
   'settings.none': 'Nenhuma',
   'settings.notConfigured': 'Não configurado',
   'settings.notConfigured': 'Não configurado',

+ 3 - 0
src/shared/i18n/locales/ru.ts

@@ -884,6 +884,9 @@ export const ru: Messages = {
   'settings.killAllHint': 'Принудительно завершает все запущенные экземпляры, включая не запущенные WE Manager.',
   'settings.killAllHint': 'Принудительно завершает все запущенные экземпляры, включая не запущенные WE Manager.',
   'settings.killOnQuit': 'Завершать все процессы linux-wallpaperengine при выходе из WE Manager',
   'settings.killOnQuit': 'Завершать все процессы linux-wallpaperengine при выходе из WE Manager',
   'settings.skipPlaylistResume': 'Не возобновлять плейлисты при запуске WE Manager',
   'settings.skipPlaylistResume': 'Не возобновлять плейлисты при запуске WE Manager',
+  'settings.skipPlaylistResumeHint': 'Экраны, на которых был плейлист, остаются пустыми после перезапуска. Последний элемент плейлиста не возвращается.',
+  'settings.freshProcessOnPathChange': 'Запускать новый процесс движка при смене обоев',
+  'settings.freshProcessOnPathChangeHint': 'По умолчанию выключено, поэтому смена сохраняет работающий движок и его переход. Включите, если сменённые обои остаются пустыми или продолжает звучать прежний звук. Плейлисты, расписания и трей тогда тоже перезапускают движок.',
   'settings.lweHint': 'Нужен для анимированных обоев и сцен в Linux. Рендерит сцены Wallpaper Engine прямо на рабочем столе.',
   'settings.lweHint': 'Нужен для анимированных обоев и сцен в Linux. Рендерит сцены Wallpaper Engine прямо на рабочем столе.',
   'settings.none': 'Нет',
   'settings.none': 'Нет',
   'settings.notConfigured': 'Не настроено',
   'settings.notConfigured': 'Не настроено',

+ 3 - 0
src/shared/i18n/locales/tr.ts

@@ -816,6 +816,9 @@ export const tr: Messages = {
   'settings.killAllHint': 'WE Manager tarafından başlatılmayanlar dahil çalışan her örneği zorla sonlandırır.',
   'settings.killAllHint': 'WE Manager tarafından başlatılmayanlar dahil çalışan her örneği zorla sonlandırır.',
   'settings.killOnQuit': 'WE Manager kapanınca tüm linux-wallpaperengine süreçlerini sonlandır',
   'settings.killOnQuit': 'WE Manager kapanınca tüm linux-wallpaperengine süreçlerini sonlandır',
   'settings.skipPlaylistResume': 'WE Manager açıldığında oynatma listelerini sürdürme',
   'settings.skipPlaylistResume': 'WE Manager açıldığında oynatma listelerini sürdürme',
+  'settings.skipPlaylistResumeHint': 'Oynatma listesi olan ekranlar yeniden başlatmadan sonra boş kalır. Son oynatma listesi öğesi geri konmaz.',
+  'settings.freshProcessOnPathChange': 'Duvar kağıdı değiştiğinde yeni bir motor işlemi başlat',
+  'settings.freshProcessOnPathChangeHint': 'Varsayılan olarak kapalıdır; bir değişiklik çalışan motoru ve geçişini korur. Değiştirilen duvar kağıdı boş kalıyorsa veya önceki ses çalmaya devam ediyorsa açın. Oynatma listeleri, zamanlamalar ve tepsi de motoru yeniden başlatır.',
   'settings.lweHint': 'Linux\'ta hareketli/sahne duvar kağıtları için gereklidir. Wallpaper Engine sahnelerini doğrudan masaüstünüzde işler.',
   'settings.lweHint': 'Linux\'ta hareketli/sahne duvar kağıtları için gereklidir. Wallpaper Engine sahnelerini doğrudan masaüstünüzde işler.',
   'settings.none': 'Yok',
   'settings.none': 'Yok',
   'settings.notConfigured': 'Yapılandırılmadı',
   'settings.notConfigured': 'Yapılandırılmadı',

+ 3 - 0
src/shared/i18n/locales/zh-CN.ts

@@ -782,6 +782,9 @@ export const zhCN: Messages = {
   'settings.killAllHint': '强制结束所有正在运行的实例,包括不是由 WE Manager 启动的。',
   'settings.killAllHint': '强制结束所有正在运行的实例,包括不是由 WE Manager 启动的。',
   'settings.killOnQuit': '退出 WE Manager 时结束所有 linux-wallpaperengine 进程',
   'settings.killOnQuit': '退出 WE Manager 时结束所有 linux-wallpaperengine 进程',
   'settings.skipPlaylistResume': 'WE Manager 启动时不恢复播放列表',
   'settings.skipPlaylistResume': 'WE Manager 启动时不恢复播放列表',
+  'settings.skipPlaylistResumeHint': '重启后,之前播放列表所在的屏幕保持空白,不会恢复播放列表的最后一项。',
+  'settings.freshProcessOnPathChange': '更换壁纸时启动新的引擎进程',
+  'settings.freshProcessOnPathChangeHint': '默认关闭,更换时保留正在运行的引擎及其过渡效果。当换上的壁纸一直空白或上一个壁纸的声音仍在播放时再开启。播放列表、计划和托盘也会因此重启引擎。',
   'settings.lweHint': '在 Linux 上使用动态/场景壁纸所必需。直接在桌面上渲染 Wallpaper Engine 场景。',
   'settings.lweHint': '在 Linux 上使用动态/场景壁纸所必需。直接在桌面上渲染 Wallpaper Engine 场景。',
   'settings.none': '无',
   'settings.none': '无',
   'settings.notConfigured': '未配置',
   'settings.notConfigured': '未配置',

+ 3 - 0
src/shared/i18n/locales/zh-TW.ts

@@ -782,6 +782,9 @@ export const zhTW: Messages = {
   'settings.killAllHint': '強制結束所有執行中的執行個體,包括不是由 WE Manager 啟動的。',
   'settings.killAllHint': '強制結束所有執行中的執行個體,包括不是由 WE Manager 啟動的。',
   'settings.killOnQuit': '結束 WE Manager 時結束所有 linux-wallpaperengine 處理程序',
   'settings.killOnQuit': '結束 WE Manager 時結束所有 linux-wallpaperengine 處理程序',
   'settings.skipPlaylistResume': 'WE Manager 啟動時不恢復播放清單',
   'settings.skipPlaylistResume': 'WE Manager 啟動時不恢復播放清單',
+  'settings.skipPlaylistResumeHint': '重新啟動後,原本有播放清單的螢幕保持空白,不會還原播放清單的最後一項。',
+  'settings.freshProcessOnPathChange': '更換桌布時啟動新的引擎處理程序',
+  'settings.freshProcessOnPathChangeHint': '預設關閉,更換時保留執行中的引擎及其轉場效果。當換上的桌布一直空白或上一個桌布的聲音仍在播放時再開啟。播放清單、排程和系統匣也會因此重新啟動引擎。',
   'settings.lweHint': '在 Linux 上使用動態/場景桌布所必需。直接在桌面上算繪 Wallpaper Engine 場景。',
   'settings.lweHint': '在 Linux 上使用動態/場景桌布所必需。直接在桌面上算繪 Wallpaper Engine 場景。',
   'settings.none': '無',
   'settings.none': '無',
   'settings.notConfigured': '未設定',
   'settings.notConfigured': '未設定',

+ 5 - 6
src/shared/playScreen.test.ts

@@ -2,14 +2,13 @@ import { describe, expect, it } from 'vitest'
 import { CARD_PLAY_DEFAULT_SCREEN, cardPlayNeedsScreenChoice } from './playScreen'
 import { CARD_PLAY_DEFAULT_SCREEN, cardPlayNeedsScreenChoice } from './playScreen'
 
 
 describe('card play screen question', () => {
 describe('card play screen question', () => {
-  it('asks in per-screen mode when two monitors are connected', () => {
-    expect(cardPlayNeedsScreenChoice('per-screen', ['HDMI-A-3', 'HDMI-A-2'])).toBe(true)
+  it('asks when two monitors are connected', () => {
+    expect(cardPlayNeedsScreenChoice(['HDMI-A-3', 'HDMI-A-2'])).toBe(true)
   })
   })
 
 
-  it('does not ask for one monitor, shared mode, or when a screen was already chosen by the caller', () => {
-    expect(cardPlayNeedsScreenChoice('per-screen', ['HDMI-A-3'])).toBe(false)
-    expect(cardPlayNeedsScreenChoice('shared', ['HDMI-A-3', 'HDMI-A-2'])).toBe(false)
-    expect(cardPlayNeedsScreenChoice('per-screen', ['*'])).toBe(false)
+  it('does not ask for one monitor or for the single target of shared mode', () => {
+    expect(cardPlayNeedsScreenChoice(['HDMI-A-3'])).toBe(false)
+    expect(cardPlayNeedsScreenChoice(['*'])).toBe(false)
   })
   })
 
 
   it('defaults to every screen, which is what Enter used to do', () => {
   it('defaults to every screen, which is what Enter used to do', () => {

+ 2 - 5
src/shared/playScreen.ts

@@ -1,8 +1,5 @@
-import type { DisplayMode } from './types'
-
-/** Card Play asks only in per-screen mode with two or more real monitors. All screens is the default. */
-export function cardPlayNeedsScreenChoice(mode: DisplayMode, targets: readonly string[]): boolean {
-  return mode === 'per-screen' && targets.filter((name) => name !== '*').length > 1
+export function cardPlayNeedsScreenChoice(targets: readonly string[]): boolean {
+  return targets.filter((name) => name !== '*').length > 1
 }
 }
 
 
 export const CARD_PLAY_DEFAULT_SCREEN = '*'
 export const CARD_PLAY_DEFAULT_SCREEN = '*'

+ 1 - 0
src/shared/types.ts

@@ -292,6 +292,7 @@ export type DisplayMode = 'shared' | 'per-screen'
 export interface ScreenAssignment {
 export interface ScreenAssignment {
   screen: ScreenTarget
   screen: ScreenTarget
   wallpaperId: string
   wallpaperId: string
+  split: boolean
 }
 }
 
 
 /** How the slots of a split screen share it, see the engine's --split-layout */
 /** How the slots of a split screen share it, see the engine's --split-layout */