浏览代码

Merge pull request #12 from LennonAmos (restore wallpapers on startup, keep volume 0)

UwU 3 周之前
父节点
当前提交
0fb94c8d70

+ 12 - 3
src/main/index.ts

@@ -11,10 +11,10 @@ import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.
 import { getTrayEnabled, getAutostartEnabled, getAutostartMinimized, getAutostartPlaylistId, getKillLweOnQuit, getConfiguredBackupPath } from './services/config.service'
 import { refreshAutostartExec } from './services/autostart.service'
 import { createTray } from './services/tray.service'
-import { initPlaylistPlayer, startPlaylist } from './services/playlist-player.service'
+import { initPlaylistPlayer, playlistRestoreSkipScreens, startPlaylist } from './services/playlist-player.service'
 import { checkEarlierRunEngines, killAllLweProcesses, getLweStatus } from './services/lwe.service'
-import { initDisplay } from './services/display.service'
-import { initSchedule } from './services/schedule.service'
+import { expandScreen, initDisplay, restoreAssignedWallpapers } from './services/display.service'
+import { catchUpScreens, initSchedule } from './services/schedule.service'
 import { initUpdates } from './services/update.service'
 import { detectDesktopEnv, hasStatusNotifierHost } from './utils/platform'
 import { needsSoftwareCompositing, readGpuVendors } from './utils/gpuWorkaround'
@@ -250,15 +250,24 @@ app.whenReady().then(async () => {
   if (getAutostartEnabled()) refreshAutostartExec(getAutostartMinimized())
 
   const autostartPlaylistId = getAutostartPlaylistId()
+  let autostartScreens: string[] = []
   if (!resumed && autostartPlaylistId && getLweStatus().installed) {
     try {
       startPlaylist(autostartPlaylistId)
+      autostartScreens = expandScreen(undefined)
     } catch (err) {
       console.error('[App] Failed to autostart playlist:', err)
     }
   }
+  const scheduleScreens = catchUpScreens().flatMap((screen) => expandScreen(screen))
   initSchedule(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) })
 }).catch((err: unknown) => { console.error('[Main] startup failed:', err) })
 
 app.on('before-quit', (event) => {

+ 8 - 0
src/main/ipc/config.handlers.ts

@@ -42,6 +42,8 @@ import {
   setKillLweOnQuit,
   getSkipPlaylistResume,
   setSkipPlaylistResume,
+  getFreshProcessOnPathChange,
+  setFreshProcessOnPathChange,
   getCardBorders,
   getCardBadges,
   getAppearance,
@@ -126,6 +128,7 @@ export function registerConfigHandlers(): void {
     autostartPlaylistId: getAutostartPlaylistId(),
     killLweOnQuit: getKillLweOnQuit(),
     skipPlaylistResume: getSkipPlaylistResume(),
+    freshProcessOnPathChange: getFreshProcessOnPathChange(),
     cardBorders: getCardBorders(),
     cardBadges: getCardBadges(),
     audioScreen: getAudioScreen(),
@@ -184,6 +187,11 @@ export function registerConfigHandlers(): void {
     return { ok: true }
   })
 
+  ipcMain.handle(IpcChannels.CONFIG_SET_FRESH_PROCESS_ON_PATH_CHANGE, (_e, enabled: boolean) => {
+    setFreshProcessOnPathChange(enabled)
+    return { ok: true }
+  })
+
   ipcMain.handle(IpcChannels.CONFIG_SET_CARD_BORDERS, (_e, borders: CardBorders) => {
     return setCardBorders(borders)
   })

+ 1 - 1
src/main/ipc/wallpaper.handlers.ts

@@ -37,7 +37,7 @@ export function registerWallpaperHandlers(): void {
     if (!wallpaper) throw new Error(`Wallpaper ${options.wallpaperId} not found in library`)
 
     // a playlist would replace it again on its next switch
-    for (const screen of expandScreen(options.screen)) pausePlaylist(screen)
+    for (const target of expandScreen(options.screen)) pausePlaylist(target)
 
     const appliedPath = await showWallpaper(wallpaper, options.screen, { backend: options.backend })
 

+ 12 - 0
src/main/services/config.service.ts

@@ -38,6 +38,8 @@ interface AppConfig {
   autostartPlaylistId: string | null
   killLweOnQuit: boolean
   skipPlaylistResume: boolean
+  /** A path change starts a new engine instead of hotswapping. Off keeps transitions. */
+  freshProcessOnPathChange: boolean
   /** Legacy, only read to migrate into cardBorders */
   voteBorders: boolean
   cardBorders: CardBorders | null
@@ -91,6 +93,7 @@ const store = openStore<AppConfig>({
     autostartPlaylistId: null,
     killLweOnQuit: false,
     skipPlaylistResume: false,
+    freshProcessOnPathChange: false,
     voteBorders: true,
     cardBorders: null,
     cardBadges: null,
@@ -199,6 +202,14 @@ export function getSkipPlaylistResume(): boolean {
   return store.get('skipPlaylistResume')
 }
 
+export function getFreshProcessOnPathChange(): boolean {
+  return store.get('freshProcessOnPathChange')
+}
+
+export function setFreshProcessOnPathChange(enabled: boolean): void {
+  store.set('freshProcessOnPathChange', enabled)
+}
+
 export function setSkipPlaylistResume(enabled: boolean): void {
   store.set('skipPlaylistResume', enabled)
 }
@@ -391,6 +402,7 @@ const RESETS_WITH_ENGINE_SETTINGS: Record<keyof AppConfig, boolean> = {
   autostartPlaylistId: false,
   killLweOnQuit: false,
   skipPlaylistResume: false,
+  freshProcessOnPathChange: false,
   voteBorders: false,
   cardBorders: false,
   cardBadges: false,

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

@@ -33,13 +33,16 @@ function getMissingDependency(wallpaper: WallpaperMeta): string | null {
 // throws unless the wallpaper can go ahead, since after "Install now" the download has only just started
 export async function ensureDependencyInstalled(
   wallpaper: WallpaperMeta,
-  mode: 'always' | 'once' = 'always'
+  mode: 'always' | 'once' | 'never' = 'always'
 ): Promise<void> {
   const dependencyId = getMissingDependency(wallpaper)
   if (!dependencyId) return
 
   const title = wallpaper.title || wallpaper.id
 
+  // startup restore must not open a dialog, least of all over a minimized tray start
+  if (mode === 'never') throw new Error(t('dependency.skipped', { title, id: dependencyId }))
+
   if (mode === 'once' && alreadyAsked.has(dependencyId)) {
     throw new Error(t('dependency.skipped', { title, id: dependencyId }))
   }

+ 96 - 5
src/main/services/display.service.ts

@@ -1,4 +1,6 @@
 import type { BrowserWindow } from 'electron'
+import fs from 'fs'
+import path from 'path'
 import { IpcChannels } from '@shared/ipc-channels'
 import type {
   CrashEvent,
@@ -15,6 +17,7 @@ import { applyWallpaperMeta, isAnimatedWallpaper } from './wallpaper.service'
 import {
   ALL_SCREENS,
   getActiveScreens,
+  getLweStatus,
   getRunningInstances,
   hotswapLweSettings,
   launchLweAsync,
@@ -27,11 +30,22 @@ import {
 } from './lwe.service'
 import { resolveEngineFlags } from '@shared/engineFlags'
 import { clearAssignment, getAssignments, setAssignment } from './wallpaper-state.service'
-import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens } from './config.service'
+import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens, setSplitScreen } from './config.service'
+import { planRestore, restoreSuperseded } from './restore-plan'
 import { ensureDependencyInstalled } from './dependency.service'
 import { t } from '../i18n'
 
 const LAUNCH_CHECK_MS = 20_000
+// bumped when a screen is launched or stopped, so a later restore does not replace that
+const screenUse = new Map<string, number>()
+
+function markScreenUsed(screen: ScreenTarget): void {
+  screenUse.set(screen, (screenUse.get(screen) ?? 0) + 1)
+}
+
+function screenUseCount(screen: ScreenTarget): number {
+  return screenUse.get(screen) ?? 0
+}
 // automatic relaunches after a runtime crash, at most one per screen in this window
 const RELAUNCH_COOLDOWN_MS = 60_000
 
@@ -120,7 +134,7 @@ export async function showWallpaper(
   options: {
     volume?: number
     backend?: WallpaperBackend
-    dependencyPrompt?: 'always' | 'once'
+    dependencyPrompt?: 'always' | 'once' | 'never'
     forceFresh?: boolean
   } = {}
 ): Promise<string> {
@@ -129,8 +143,12 @@ export async function showWallpaper(
 
   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)
   }
@@ -139,7 +157,11 @@ export async function showWallpaper(
 }
 
 /** One fresh engine for all slots of the screen, beforeLaunch runs once the split is known to be showable */
-export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () => void): Promise<void> {
+export async function showSplitScreen(
+  screen: ScreenTarget,
+  beforeLaunch?: () => void,
+  dependencyPrompt: 'always' | 'once' | 'never' = 'always'
+): Promise<void> {
   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 (!supportsSplitScreens()) throw new Error(t('split.engineTooOld'))
@@ -149,8 +171,8 @@ export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () =>
   const shown: WallpaperMeta[] = []
   for (const slot of split?.slots ?? []) {
     const wallpaper = getWallpaper(slot.wallpaperId)
-    if (!wallpaper?.localPath || !isAnimatedWallpaper(wallpaper)) continue
-    await ensureDependencyInstalled(wallpaper)
+    if (!wallpaper?.localPath || !isAnimatedWallpaper(wallpaper) || !wallpaperIsOnDisk(wallpaper.localPath)) continue
+    await ensureDependencyInstalled(wallpaper, dependencyPrompt)
     slots.push({
       path: wallpaper.localPath,
       scalingMode: slot.scalingMode ?? wallpaper.scalingMode,
@@ -163,6 +185,7 @@ export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () =>
     shown.push(wallpaper)
   }
   if (slots.length === 0 || !split) throw new Error(t('split.empty'))
+  markScreenUsed(screen)
   beforeLaunch?.()
 
   // overrides would hit every slot by id, so slots play as published
@@ -178,6 +201,7 @@ export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () =>
 }
 
 export async function stopDisplay(screen?: ScreenTarget): Promise<void> {
+  for (const target of expandScreen(screen)) markScreenUsed(target)
   if (screen === undefined || screen === ALL_SCREENS) {
     await stopLwe()
     clearAssignment()
@@ -308,3 +332,70 @@ export function initDisplay(window: BrowserWindow): void {
     void handleExit(info).catch((err: unknown) => { console.error('[Display] Crash handling failed:', err) })
   })
 }
+
+/** A missing drive still has a library entry. Launching that path marks a healthy wallpaper as a launch crash. */
+function wallpaperIsOnDisk(localPath: string): boolean {
+  if (!fs.existsSync(localPath)) return false
+  try {
+    return fs.statSync(localPath).isFile() || fs.existsSync(path.join(localPath, 'project.json'))
+  } catch {
+    return false
+  }
+}
+
+/** 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) {
+    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 running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
+  for (const [screen, wallpaperId] of Object.entries(saved)) {
+    const wallpaper = getWallpaper(wallpaperId)
+    const localPath = wallpaper?.localPath ?? ''
+    const inst = running.get(screen)
+    const plan = planRestore({
+      skipped: skipScreens.has(screen),
+      connected: targets.has(screen),
+      animated: !!wallpaper && isAnimatedWallpaper(wallpaper),
+      onDisk: !!localPath && wallpaperIsOnDisk(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.
+    if (restoreSuperseded(wallpaperId, getAssignments()[screen], useAtStart.get(screen) ?? 0, screenUseCount(screen))) {
+      console.log(`[Display] Leaving ${screen}, it changed while restoring`)
+      continue
+    }
+    try {
+      if (plan === 'split') {
+        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' })
+      }
+    } catch (err) {
+      console.error(`[Display] Could not restore ${wallpaper?.title ?? wallpaperId} on ${screen}:`, (err as Error).message)
+    }
+  }
+}

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

@@ -19,6 +19,7 @@ vi.mock('./config.service', () => ({
   getDefaultAudioSensitivity: () => 1,
   getDisablePuppetAnimation: () => false,
   getScriptLimits: () => false,
+  getFreshProcessOnPathChange: () => false,
   getLoader: () => loaderSettings
 }))
 
@@ -27,6 +28,8 @@ const {
   buildLweEnvVars,
   buildHotswapLines,
   buildLweArgs,
+  canHotswapExisting,
+  hotswapOptionsFor,
   lwePackageOwner,
   nodeDevelPackage,
   parsePacmanRepos,
@@ -171,6 +174,10 @@ describe('buildHotswapLines', () => {
     ])
   })
 
+  it('keeps a muted wallpaper muted when the swap is built', () => {
+    expect(buildHotswapLines(hotswapOptionsFor('/w/quiet', { volume: 0, soundVolume: { '7': 0 } }))).toContain('volume=0')
+  })
+
   it('writes a full wallpaper swap in the order the engine expects', () => {
     expect(
       buildHotswapLines({
@@ -192,6 +199,34 @@ describe('buildHotswapLines', () => {
   })
 })
 
+describe('canHotswapExisting', () => {
+  const existing = { wallpaperPath: '/w/a', launchKey: 'k', controlFile: '/run/c' }
+
+  it('hotswaps a different wallpaper by default', () => {
+    expect(canHotswapExisting(existing, {}, 'k', '/w/b', 1, false)).toBe(true)
+  })
+
+  it('starts a new process for a different path when that setting is on', () => {
+    expect(canHotswapExisting(existing, {}, 'k', '/w/b', 1, true)).toBe(false)
+  })
+
+  it('keeps the same wallpaper on a hotswap even with the setting on', () => {
+    expect(canHotswapExisting(existing, {}, 'k', '/w/a', 1, true)).toBe(true)
+  })
+
+  it('does not hotswap a forced fresh launch, a different key, or a missing engine', () => {
+    expect(canHotswapExisting(existing, { forceFresh: true }, 'k', '/w/a', 1, false)).toBe(false)
+    expect(canHotswapExisting(existing, {}, 'other', '/w/a', 1, false)).toBe(false)
+    expect(canHotswapExisting(undefined, {}, 'k', '/w/a', 0, false)).toBe(false)
+  })
+
+  it('hotswaps a missing control file only when that engine is the only one', () => {
+    const bare = { wallpaperPath: '/w/a', launchKey: 'k', controlFile: null }
+    expect(canHotswapExisting(bare, {}, 'k', '/w/b', 1, false)).toBe(true)
+    expect(canHotswapExisting(bare, {}, 'k', '/w/b', 2, false)).toBe(false)
+  })
+})
+
 describe('buildCleanBuildEnv', () => {
   it('drops AppImage mount entries from path lists and the AppImage variables', () => {
     const saved = { ...process.env }

+ 30 - 8
src/main/services/lwe.service.ts

@@ -63,7 +63,8 @@ import {
   getDefaultAudioSensitivity,
   getDisablePuppetAnimation,
   getScriptLimits,
-  getDisabledScreens
+  getDisabledScreens,
+  getFreshProcessOnPathChange
 } from './config.service'
 import { DEFAULT_LWE_FPS, DEFAULT_LWE_REPO } from '@shared/constants'
 import { engineFlagArgs, filterSupportedArgs } from '@shared/engineFlags'
@@ -1726,7 +1727,7 @@ export function liveEngineFlagOptions(
   }
 }
 
-function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): HotswapOptions {
+export function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): HotswapOptions {
   const defaultSensitivity = getDefaultAudioSensitivity()
   return {
     path: wallpaperPath,
@@ -1753,6 +1754,9 @@ function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): Ho
       ...options.audioSensitivity
     },
     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 } : {}),
     ...(supportsEffectHotswap()
       ? { disabledEffects: options.disabledEffects ?? [], enabledEffects: options.enabledEffects ?? [] }
       : {}),
@@ -1761,6 +1765,22 @@ function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): Ho
   }
 }
 
+/** Same-path changes hotswap. A different path hotswaps too, unless the setting starts a new process. */
+export function canHotswapExisting(
+  existing: { wallpaperPath: string; launchKey: string; controlFile: string | null } | undefined,
+  options: { forceFresh?: boolean; customArgs?: string },
+  key: string,
+  wallpaperPath: string,
+  liveCount: number,
+  freshProcessOnPathChange: boolean
+): boolean {
+  if (options.forceFresh || !!options.customArgs?.trim()) return false
+  if (!existing || existing.launchKey !== key) return false
+  if (existing.controlFile === null && liveCount !== 1) return false
+  if (freshProcessOnPathChange && existing.wallpaperPath !== wallpaperPath) return false
+  return true
+}
+
 /** 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> {
   const screen = options.screen ?? ALL_SCREENS
@@ -1772,12 +1792,14 @@ export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOp
   }
 
   const existing = liveInstance(screen)
-  const canHotswap =
-    existing &&
-    !options.forceFresh &&
-    !options.customArgs?.trim() &&
-    existing.launchKey === key &&
-    (existing.controlFile !== null || liveInstances().length === 1)
+  const canHotswap = canHotswapExisting(
+    existing,
+    options,
+    key,
+    wallpaperPath,
+    liveInstances().length,
+    getFreshProcessOnPathChange()
+  )
 
   if (canHotswap && (await hotswapLweSettings(hotswapOptionsFor(wallpaperPath, options), { screens: [screen] }))) {
     return

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

@@ -382,6 +382,17 @@ function savedPlayers(): Record<ScreenTarget, SavedPlayer> {
   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)
+}
+
+/** With "Don't resume playlists", the saved screens are skipped too, or restore puts the last item back without its volume */
+export function playlistRestoreSkipScreens(): ScreenTarget[] {
+  if (getSkipPlaylistResume()) return Object.keys(savedPlayers())
+  return activePlaylistScreens()
+}
+
 /** Resumes the playlists active at the last close, true if any (the autostart playlist is then skipped) */
 
 export function initPlaylistPlayer(window: BrowserWindow): boolean {

+ 83 - 0
src/main/services/restore-plan.test.ts

@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest'
+import { mergeSkipScreens, planRestore, playlistSkipScreens, restoreSuperseded, type RestoreInput } from './restore-plan'
+
+function input(patch: Partial<RestoreInput> = {}): RestoreInput {
+  return {
+    skipped: false,
+    connected: true,
+    animated: true,
+    onDisk: true,
+    localPath: '/w/a',
+    splitSlotId: null,
+    wallpaperId: 'a',
+    ...patch
+  }
+}
+
+describe('planRestore', () => {
+  it('leaves a running engine that already shows the wallpaper', () => {
+    expect(planRestore(input({ running: { split: false, wallpaperPath: '/w/a' } }))).toBe('skip')
+  })
+
+  it('hotswaps when a different wallpaper is running', () => {
+    expect(planRestore(input({ running: { split: false, wallpaperPath: '/w/old' } }))).toBe('wallpaper')
+  })
+
+  it('leaves a running split alone', () => {
+    expect(planRestore(input({ running: { split: true, wallpaperPath: '/w/a' }, splitSlotId: 'a' }))).toBe('skip')
+  })
+
+  it('restores a split that is not running through the split, not as one wallpaper', () => {
+    expect(planRestore(input({ splitSlotId: 'a', wallpaperId: 'a' }))).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('skips a screen a playlist or schedule already claimed', () => {
+    expect(planRestore(input({ skipped: true }))).toBe('skip')
+  })
+
+  it('skips a wallpaper whose folder is missing', () => {
+    expect(planRestore(input({ onDisk: false }))).toBe('skip')
+  })
+
+  it('skips a static image, which has no engine and would cover every screen', () => {
+    expect(planRestore(input({ animated: false }))).toBe('skip')
+  })
+})
+
+describe('playlistSkipScreens', () => {
+  it('skips the saved playlist screens when playlists are not resumed', () => {
+    expect(playlistSkipScreens(true, ['HDMI-A-2'], [])).toEqual(['HDMI-A-2'])
+  })
+
+  it('skips only the screens that actually resumed', () => {
+    expect(playlistSkipScreens(false, ['HDMI-A-2'], ['HDMI-A-3'])).toEqual(['HDMI-A-3'])
+  })
+})
+
+describe('restoreSuperseded', () => {
+  it('keeps going when the screen is still the one restore read', () => {
+    expect(restoreSuperseded('a', 'a', 0, 0)).toBe(false)
+  })
+
+  it('stops when the assignment changed while an earlier screen was launching', () => {
+    expect(restoreSuperseded('a', 'b', 0, 1)).toBe(true)
+  })
+
+  it('stops when the same wallpaper was launched again', () => {
+    expect(restoreSuperseded('a', 'a', 0, 1)).toBe(true)
+  })
+
+  it('stops when the assignment was cleared', () => {
+    expect(restoreSuperseded('a', undefined, 0, 1)).toBe(true)
+  })
+})
+
+describe('mergeSkipScreens', () => {
+  it('keeps playlist, autostart and schedule screens together', () => {
+    expect([...mergeSkipScreens(['HDMI-A-2'], ['*'], ['HDMI-A-3'])]).toEqual(['HDMI-A-2', '*', 'HDMI-A-3'])
+  })
+})

+ 42 - 0
src/main/services/restore-plan.ts

@@ -0,0 +1,42 @@
+export interface RestoreInput {
+  skipped: boolean
+  connected: boolean
+  animated: boolean
+  onDisk: boolean
+  localPath: 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
+}
+
+export type RestorePlan = 'skip' | 'split' | 'wallpaper'
+
+/** What startup should do with one saved screen. A static image and a missing folder are skipped. */
+export function planRestore(input: RestoreInput): RestorePlan {
+  if (input.skipped || !input.connected) 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.running && input.running.wallpaperPath === input.localPath) return 'skip'
+  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[] {
+  return skipResume ? [...saved] : [...active]
+}
+
+export function mergeSkipScreens(...groups: readonly (readonly string[])[]): Set<string> {
+  return new Set(groups.flat())
+}
+
+/** True when something else took the screen after restore read it. The newer launch stays. */
+export function restoreSuperseded(
+  assignedAtStart: string,
+  assignedNow: string | undefined,
+  useAtStart: number,
+  useNow: number
+): boolean {
+  return assignedNow !== assignedAtStart || useNow !== useAtStart
+}

+ 9 - 1
src/main/services/schedule.service.ts

@@ -2,7 +2,7 @@ import { openStore } from '../utils/safeStore'
 import { nativeTheme, type BrowserWindow } from 'electron'
 import { randomUUID } from 'crypto'
 import { IpcChannels } from '@shared/ipc-channels'
-import type { ScheduleRule } from '@shared/types'
+import type { ScheduleRule, ScreenTarget } from '@shared/types'
 import { dueTimeRules } from '@shared/schedule'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getPlaylist } from './playlist.service'
@@ -100,6 +100,14 @@ function onThemeChanged(): void {
   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)
+}
+
 /** Call after the playlist player resumed, so a rule that came due while closed wins over it */
 export function initSchedule(window: BrowserWindow): void {
   win = window

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

@@ -257,7 +257,7 @@ export async function applyWallpaperMeta(
     fps?: number
     volume?: number
     backend?: WallpaperBackend
-    dependencyPrompt?: 'always' | 'once'
+    dependencyPrompt?: 'always' | 'once' | 'never'
     screen?: ScreenTarget
     forceFresh?: boolean
   } = {}

+ 2 - 0
src/preload/index.ts

@@ -185,6 +185,8 @@ const api = {
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_KILL_LWE_ON_QUIT, enabled),
     setSkipPlaylistResume: (enabled: boolean): Promise<{ ok: boolean }> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_SKIP_PLAYLIST_RESUME, enabled),
+    setFreshProcessOnPathChange: (enabled: boolean): Promise<{ ok: boolean }> =>
+      ipcRenderer.invoke(IpcChannels.CONFIG_SET_FRESH_PROCESS_ON_PATH_CHANGE, enabled),
     setCardBorders: (borders: CardBorders): Promise<CardBorders> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_CARD_BORDERS, borders),
     setCardBadges: (badges: CardBadges): Promise<CardBadges> =>

+ 2 - 0
src/renderer/src/App.tsx

@@ -12,6 +12,7 @@ import GnomeExtensionNotice from './components/layout/GnomeExtensionNotice'
 import UpdateNotice from './components/updates/UpdateNotice'
 import GraphicsNotice from './components/layout/GraphicsNotice'
 import UpdatePrompt from './components/updates/UpdatePrompt'
+import PlayScreenPrompt from './components/common/PlayScreenPrompt'
 import { useToast } from './components/common/Toast'
 import { screenLabel } from './utils/screens'
 import { UPDATE_STATUS_KEY, useConfig } from './hooks/queries'
@@ -188,6 +189,7 @@ export default function App() {
         </div>
         <StatusBar />
         <UpdatePrompt />
+        <PlayScreenPrompt />
       </div>
     </ErrorBoundary>
   )

+ 25 - 77
src/renderer/src/components/common/DetailSidebar.tsx

@@ -48,7 +48,7 @@ import clsx from 'clsx'
 import { openWorkshopPage, openProfilePage, isWorkshopId } from '../../utils/steam'
 import { WE_TYPES, WE_AGE_RATINGS, canonicalResolutionTag, resolutionsFromTags } from '../../constants/weFilters'
 import { formatFileSize } from '../../utils/format'
-import { isRangeKey } from '../../utils/dom'
+import RangeInput from './RangeInput'
 import { useDislikedIds, useVoteAction, useVotedIds } from '../../hooks/useVotes'
 import { useFavoriteAction, useFavoriteIds, useItemFavoriteStatus } from '../../hooks/useFavorites'
 import { useConfig, useLweInstalled } from '../../hooks/queries'
@@ -264,17 +264,13 @@ function PropertyRow({
           </span>
           <span className="text-gray-500">{num}</span>
         </div>
-        <input
-          type="range"
+        <RangeInput
           min={property.min ?? 0}
           max={property.max ?? 100}
           step={property.step || 1}
           value={num}
-          onChange={(e) => { setDraft(Number(e.target.value)) }}
-          onMouseUp={(e) => { onCommit(e.currentTarget.value); setDraft(null) }}
-          onTouchEnd={(e) => { onCommit(e.currentTarget.value); setDraft(null) }}
-          onKeyUp={(e) => { if (!isRangeKey(e.key)) return; onCommit(e.currentTarget.value); setDraft(null) }}
-          className="w-full accent-accent-500"
+          onLive={setDraft}
+          onCommit={(v) => { onCommit(String(v)); setDraft(null) }}
         />
       </div>
     )
@@ -327,17 +323,13 @@ function AudioObjectRow({
         </span>
         <span className="text-gray-500">{percent === 0 ? 'locked' : `${percent}%`}</span>
       </div>
-      <input
-        type="range"
+      <RangeInput
         min={0}
         max={200}
         step={5}
         value={percent}
-        onChange={(e) => { setDraft(Number(e.target.value)) }}
-        onMouseUp={(e) => { onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
-        onTouchEnd={(e) => { onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
-        onKeyUp={(e) => { if (!isRangeKey(e.key)) return; onCommit(Number(e.currentTarget.value) / 100); setDraft(null) }}
-        className="w-full accent-accent-500"
+        onLive={setDraft}
+        onCommit={(v) => { onCommit(v / 100); setDraft(null) }}
       />
     </div>
   )
@@ -363,17 +355,13 @@ function SoundTrackRow({
         </span>
         <span className="text-gray-500">{value === 0 ? 'muted' : `${Math.round(value * 100)}%`}</span>
       </div>
-      <input
-        type="range"
+      <RangeInput
         min={0}
         max={1}
         step={0.1}
         value={value}
-        onChange={(e) => { setDraft(Number(e.target.value)) }}
-        onMouseUp={(e) => { onCommit(Number(e.currentTarget.value)); setDraft(null) }}
-        onTouchEnd={(e) => { onCommit(Number(e.currentTarget.value)); setDraft(null) }}
-        onKeyUp={(e) => { if (!isRangeKey(e.key)) return; onCommit(Number(e.currentTarget.value)); setDraft(null) }}
-        className="w-full accent-accent-500"
+        onLive={setDraft}
+        onCommit={(v) => { onCommit(v); setDraft(null) }}
       />
     </div>
   )
@@ -1106,22 +1094,14 @@ export default function DetailSidebar({
               {isCommittingZoom && <Loader2 size={11} className="animate-spin" />}
               <span className="normal-case text-gray-400">{zoomPercent}%</span>
             </div>
-            <input
-              type="range"
+            <RangeInput
               min={25}
               max={300}
               step={1}
               value={zoomPercent}
               disabled={isCommittingZoom}
-              onChange={(e) => {
-                const v = Number(e.target.value)
-                setZoomDraft(v)
-                previewLive({ zoom: v / 100 })
-              }}
-              onMouseUp={(e) => void commitZoom(Number(e.currentTarget.value))}
-              onTouchEnd={(e) => void commitZoom(Number(e.currentTarget.value))}
-              onKeyUp={(e) => void (isRangeKey(e.key) && commitZoom(Number(e.currentTarget.value)))}
-              className="w-full accent-accent-500 disabled:opacity-50"
+              onLive={(v) => { setZoomDraft(v); previewLive({ zoom: v / 100 }) }}
+              onCommit={(v) => { void commitZoom(v) }}
             />
           </div>
         )}
@@ -1140,22 +1120,14 @@ export default function DetailSidebar({
             </div>
             <div className="flex items-center gap-1.5">
               <span className="w-12 shrink-0 text-[10px] normal-case text-gray-500">{t('detail.leftRight')}</span>
-              <input
-                type="range"
+              <RangeInput
                 min={-100}
                 max={100}
                 step={1}
                 value={Math.round(offsetX * 100)}
                 disabled={isCommittingOffset}
-                onChange={(e) => {
-                  const v = Number(e.target.value) / 100
-                  setOffsetXDraft(v)
-                  previewLive({ offsetX: v, offsetY })
-                }}
-                onMouseUp={(e) => void commitOffset(Number(e.currentTarget.value) / 100, offsetY)}
-                onTouchEnd={(e) => void commitOffset(Number(e.currentTarget.value) / 100, offsetY)}
-                onKeyUp={(e) => void (isRangeKey(e.key) && commitOffset(Number(e.currentTarget.value) / 100, offsetY))}
-                className="w-full accent-accent-500 disabled:opacity-50"
+                onLive={(v) => { const next = v / 100; setOffsetXDraft(next); previewLive({ offsetX: next, offsetY }) }}
+                onCommit={(v) => { void commitOffset(v / 100, offsetY) }}
               />
               <span className="w-8 shrink-0 text-right text-[10px] text-gray-400">
                 {Math.round(offsetX * 100)}
@@ -1163,22 +1135,14 @@ export default function DetailSidebar({
             </div>
             <div className="mt-1.5 flex items-center gap-1.5">
               <span className="w-12 shrink-0 text-[10px] normal-case text-gray-500">{t('detail.upDown')}</span>
-              <input
-                type="range"
+              <RangeInput
                 min={-100}
                 max={100}
                 step={1}
                 value={Math.round(offsetY * 100)}
                 disabled={isCommittingOffset}
-                onChange={(e) => {
-                  const v = Number(e.target.value) / 100
-                  setOffsetYDraft(v)
-                  previewLive({ offsetX, offsetY: v })
-                }}
-                onMouseUp={(e) => void commitOffset(offsetX, Number(e.currentTarget.value) / 100)}
-                onTouchEnd={(e) => void commitOffset(offsetX, Number(e.currentTarget.value) / 100)}
-                onKeyUp={(e) => void (isRangeKey(e.key) && commitOffset(offsetX, Number(e.currentTarget.value) / 100))}
-                className="w-full accent-accent-500 disabled:opacity-50"
+                onLive={(v) => { const next = v / 100; setOffsetYDraft(next); previewLive({ offsetX, offsetY: next }) }}
+                onCommit={(v) => { void commitOffset(offsetX, v / 100) }}
               />
               <span className="w-8 shrink-0 text-right text-[10px] text-gray-400">
                 {Math.round(offsetY * 100)}
@@ -1253,23 +1217,15 @@ export default function DetailSidebar({
               />
               <span className="normal-case text-gray-400">%</span>
             </div>
-            <input
-              type="range"
+            <RangeInput
               min={10}
               max={200}
               step={5}
               value={speedPercent}
               disabled={isCommittingSpeed}
-              onChange={(e) => {
-                const v = Number(e.target.value)
-                setSpeedDraft(v)
-                previewLive({ speed: v / 100 })
-              }}
-              onMouseUp={(e) => void commitSpeed(Number(e.currentTarget.value))}
-              onTouchEnd={(e) => void commitSpeed(Number(e.currentTarget.value))}
-              onKeyUp={(e) => void (isRangeKey(e.key) && commitSpeed(Number(e.currentTarget.value)))}
               title={t('detail.speedHint')}
-              className="w-full accent-accent-500 disabled:opacity-50"
+              onLive={(v) => { setSpeedDraft(v); previewLive({ speed: v / 100 }) }}
+              onCommit={(v) => { void commitSpeed(v) }}
             />
           </div>
         )}
@@ -1349,21 +1305,13 @@ export default function DetailSidebar({
                 {t('detail.volumeHint')}
               </p>
             )}
-            <input
-              type="range"
+            <RangeInput
               min={0}
               max={128}
               value={volume}
               disabled={isCommittingVolume}
-              onChange={(e) => {
-                const v = Number(e.target.value)
-                setVolumeDraft(v)
-                previewLive({ volume: v })
-              }}
-              onMouseUp={(e) => void commitVolume(Number(e.currentTarget.value))}
-              onTouchEnd={(e) => void commitVolume(Number(e.currentTarget.value))}
-              onKeyUp={(e) => void (isRangeKey(e.key) && commitVolume(Number(e.currentTarget.value)))}
-              className="w-full accent-accent-500 disabled:opacity-50"
+              onLive={(v) => { setVolumeDraft(v); previewLive({ volume: v }) }}
+              onCommit={(v) => { void commitVolume(v) }}
             />
           </div>
         )}

+ 98 - 0
src/renderer/src/components/common/PlayScreenPrompt.tsx

@@ -0,0 +1,98 @@
+import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'
+import type { ScreenTarget } from '@shared/types'
+import { CARD_PLAY_DEFAULT_SCREEN } from '@shared/playScreen'
+import { t } from '../../i18n'
+import ScreenSelect from './ScreenSelect'
+
+type Pending = {
+  targets: ScreenTarget[]
+  resolve: (screen: ScreenTarget | null) => void
+}
+
+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. */
+export function askPlayScreen(targets: ScreenTarget[]): Promise<ScreenTarget | null> {
+  if (!openPrompt) return Promise.resolve(CARD_PLAY_DEFAULT_SCREEN)
+  return openPrompt(targets)
+}
+
+export default function PlayScreenPrompt() {
+  const [pending, setPending] = useState<Pending | null>(null)
+  const [value, setValue] = useState<ScreenTarget>(CARD_PLAY_DEFAULT_SCREEN)
+  const dialogRef = useRef<HTMLDivElement>(null)
+
+  useEffect(() => {
+    openPrompt = (targets) => new Promise((resolve) => {
+      setValue(CARD_PLAY_DEFAULT_SCREEN)
+      setPending({ targets, resolve })
+    })
+    return () => { openPrompt = null }
+  }, [])
+
+  function finish(screen: ScreenTarget | null) {
+    pending?.resolve(screen)
+    setPending(null)
+  }
+
+  function onKeyDown(e: ReactKeyboardEvent<HTMLDivElement>) {
+    if (e.key === 'Escape') {
+      e.preventDefault()
+      finish(null)
+      return
+    }
+    if (e.key !== 'Tab') return
+    const root = dialogRef.current
+    if (!root) return
+    const items = [...root.querySelectorAll<HTMLElement>('button, select, input, a, [tabindex]:not([tabindex="-1"])')]
+      .filter((el) => !el.hasAttribute('disabled'))
+    if (items.length === 0) return
+    const first = items[0]
+    const last = items[items.length - 1]
+    if (e.shiftKey && document.activeElement === first) {
+      e.preventDefault()
+      last.focus()
+    } else if (!e.shiftKey && document.activeElement === last) {
+      e.preventDefault()
+      first.focus()
+    }
+  }
+
+  if (!pending) return null
+
+  return (
+    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-8">
+      <div
+        ref={dialogRef}
+        role="dialog"
+        aria-modal="true"
+        aria-labelledby="play-screen-title"
+        tabIndex={-1}
+        onKeyDown={onKeyDown}
+        className="w-full max-w-sm rounded-xl border border-fg/10 bg-popup p-4 shadow-2xl"
+      >
+        <h3 id="play-screen-title" className="text-sm font-semibold text-gray-100">{t('playlist.whichScreen')}</h3>
+        <div className="mt-3">
+          <ScreenSelect targets={pending.targets} value={value} onChange={setValue} title={t('playlist.whichScreen')} />
+        </div>
+        <div className="mt-4 flex justify-end gap-2">
+          <button
+            type="button"
+            onClick={() => { finish(null) }}
+            className="rounded-lg px-3 py-1.5 text-sm text-gray-300 hover:bg-fg/5"
+          >
+            {t('common.cancel')}
+          </button>
+          <button
+            type="button"
+            autoFocus
+            onClick={() => { finish(value) }}
+            className="rounded-lg bg-accent-600 px-3 py-1.5 text-sm text-white hover:bg-accent-500"
+          >
+            {t('play.wallpaper')}
+          </button>
+        </div>
+      </div>
+    </div>
+  )
+}

+ 59 - 0
src/renderer/src/components/common/RangeInput.tsx

@@ -0,0 +1,59 @@
+import type { ChangeEvent, KeyboardEvent, PointerEvent } from 'react'
+import { useRef } from 'react'
+import { isRangeKey } from '../../utils/dom'
+import { createRangeCommit } from '../../utils/rangeCommit'
+
+interface Props {
+  min: number
+  max: number
+  step?: number
+  value: number
+  disabled?: boolean
+  title?: string
+  className?: string
+  onLive?: (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) {
+  const machine = useRef(createRangeCommit())
+
+  function end() {
+    const next = machine.current.end()
+    if (next !== null) onCommit(next)
+  }
+
+  function pointerDown(e: PointerEvent<HTMLInputElement>) {
+    machine.current.pointerDown()
+    try {
+      e.currentTarget.setPointerCapture(e.pointerId)
+    } catch {
+      // the pointer can already be gone; the drag flag still tracks moves over the input
+    }
+  }
+
+  return (
+    <input
+      type="range"
+      min={min}
+      max={max}
+      step={step}
+      value={value}
+      disabled={disabled}
+      title={title}
+      className={`w-full touch-none accent-accent-500 disabled:opacity-50 ${className ?? ''}`}
+      onPointerDown={pointerDown}
+      onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => { machine.current.keyDown(e.key) }}
+      onChange={(e: ChangeEvent<HTMLInputElement>) => {
+        const next = machine.current.change(e.target.value)
+        if (next !== null) onLive?.(next)
+      }}
+      onPointerUp={end}
+      onPointerCancel={end}
+      onLostPointerCapture={end}
+      onBlur={end}
+      onKeyUp={(e: KeyboardEvent<HTMLInputElement>) => { if (isRangeKey(e.key)) end() }}
+    />
+  )
+}

+ 4 - 4
src/renderer/src/components/library/WallpaperCard.tsx

@@ -23,6 +23,7 @@ import {
   SteamAction
 } from '../common/GridCard'
 import { t, tagLabel } from '../../i18n'
+import { useApplyWallpaper } from '../../hooks/useWallpaperActions'
 
 interface WallpaperCardProps {
   wallpaper: WallpaperMeta
@@ -56,6 +57,7 @@ export default function WallpaperCard({
   onContextMenu
 }: WallpaperCardProps) {
   const { showToast } = useToast()
+  const applyWallpaper = useApplyWallpaper()
   const queryClient = useQueryClient()
   const [isApplying, setIsApplying] = useState(false)
   const [unsubState, setUnsubState] = useState<'idle' | 'confirm' | 'pending'>('idle')
@@ -106,10 +108,8 @@ export default function WallpaperCard({
     setIsApplying(true)
     setError(null)
     try {
-      await window.electronAPI.wallpaper.apply({ wallpaperId: wallpaper.id })
-      refreshLibrary()
-    } catch (err) {
-      setError((err as Error).message)
+      // no screen yet: the hook asks which monitor when per-screen mode has two or more
+      await applyWallpaper(wallpaper.id)
     } finally {
       setIsApplying(false)
     }

+ 14 - 0
src/renderer/src/components/settings/SettingsView.tsx

@@ -92,6 +92,7 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
   const [trayEnabled, setTrayEnabled] = useState(false)
   const [killLweOnQuit, setKillLweOnQuit] = useState(false)
   const [skipPlaylistResume, setSkipPlaylistResume] = useState(false)
+  const [freshProcessOnPathChange, setFreshProcessOnPathChange] = useState(false)
   const [steamIdentity, setSteamIdentityState] = useState<SteamIdentity>('wallpaper-engine')
   const [steamIdentitySaved, setSteamIdentitySaved] = useState(false)
   const [autostartSupported, setAutostartSupported] = useState(false)
@@ -126,6 +127,7 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
       setTrayEnabled(cfg.trayEnabled)
       setKillLweOnQuit(cfg.killLweOnQuit)
       setSkipPlaylistResume(cfg.skipPlaylistResume)
+      setFreshProcessOnPathChange(cfg.freshProcessOnPathChange)
       setSteamIdentityState(cfg.steamIdentity)
       setAutostartSupported(cfg.autostartSupported)
       setAutostartCompositorLine(cfg.autostartCompositorLine)
@@ -347,6 +349,12 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
     await window.electronAPI.config.setSkipPlaylistResume(newVal)
   }
 
+  async function handleFreshProcessToggle() {
+    const newVal = !freshProcessOnPathChange
+    setFreshProcessOnPathChange(newVal)
+    await window.electronAPI.config.setFreshProcessOnPathChange(newVal)
+  }
+
   async function handleScriptLimitsToggle() {
     const newVal = !scriptLimits
     setScriptLimits(newVal)
@@ -838,6 +846,12 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
                   <Toggle on={skipPlaylistResume} onClick={() => void handleSkipPlaylistResumeToggle()} />
                   <span className="text-sm text-gray-300">{t('settings.skipPlaylistResume')}</span>
                 </label>
+                <p className="mt-1 text-xs text-gray-600">{t('settings.skipPlaylistResumeHint')}</p>
+                <label className="mt-3 flex items-center gap-3 cursor-pointer">
+                  <Toggle on={freshProcessOnPathChange} onClick={() => void handleFreshProcessToggle()} />
+                  <span className="text-sm text-gray-300">{t('settings.freshProcessOnPathChange')}</span>
+                </label>
+                <p className="mt-1 text-xs text-gray-600">{t('settings.freshProcessOnPathChangeHint')}</p>
               </div>
             </div>
 

+ 15 - 1
src/renderer/src/hooks/useWallpaperActions.ts

@@ -1,6 +1,8 @@
 import { useQueryClient } from '@tanstack/react-query'
 import type { ScreenTarget } from '@shared/types'
+import { cardPlayNeedsScreenChoice } from '@shared/playScreen'
 import { useToast } from '../components/common/Toast'
+import { askPlayScreen } from '../components/common/PlayScreenPrompt'
 import { forEachIgnoringErrors } from '../utils/async'
 import { t } from '../i18n'
 
@@ -10,7 +12,19 @@ export function useApplyWallpaper(): (id: string, screen?: ScreenTarget) => Prom
 
   return async (id, screen) => {
     try {
-      await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen })
+      let chosen = screen
+      if (chosen === undefined) {
+        const [cfg, targets] = await Promise.all([
+          window.electronAPI.config.get(),
+          window.electronAPI.wallpaper.getTargets()
+        ])
+        if (cardPlayNeedsScreenChoice(cfg.displayMode, targets)) {
+          const picked = await askPlayScreen(targets.filter((name) => name !== '*'))
+          if (picked === null) return
+          chosen = picked
+        }
+      }
+      await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen: chosen })
       void queryClient.invalidateQueries({ queryKey: ['library'] })
     } catch (err) {
       showToast((err as Error).message)

+ 35 - 0
src/renderer/src/utils/rangeCommit.test.ts

@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { createRangeCommit } from './rangeCommit'
+
+describe('range commit', () => {
+  it('ignores a max-value change that arrives with no drag', () => {
+    const range = createRangeCommit()
+    expect(range.change('128')).toBeNull()
+    expect(range.end()).toBeNull()
+  })
+
+  it('commits the dragged value, including 0, and then ignores a later max event', () => {
+    const range = createRangeCommit()
+    range.pointerDown()
+    expect(range.change('0')).toBe(0)
+    expect(range.end()).toBe(0)
+    expect(range.change('128')).toBeNull()
+    expect(range.end()).toBeNull()
+  })
+
+  it('ends the drag on cancel, so a stray event afterwards is ignored', () => {
+    const range = createRangeCommit()
+    range.pointerDown()
+    range.change('40')
+    expect(range.end()).toBe(40)
+    range.change('128')
+    expect(range.end()).toBeNull()
+  })
+
+  it('tracks keyboard changes and commits on keyup', () => {
+    const range = createRangeCommit()
+    range.keyDown('ArrowRight')
+    expect(range.change('15')).toBe(15)
+    expect(range.end()).toBe(15)
+  })
+})

+ 30 - 0
src/renderer/src/utils/rangeCommit.ts

@@ -0,0 +1,30 @@
+import { isRangeKey } from './dom'
+
+/** Remembers a range drag so a change event that arrives on its own cannot commit the max. */
+export function createRangeCommit() {
+  let dragging = false
+  let live: number | null = null
+
+  return {
+    pointerDown() {
+      dragging = true
+    },
+    keyDown(key: string) {
+      if (isRangeKey(key)) dragging = true
+    },
+    change(raw: string): number | null {
+      if (!dragging) return null
+      const value = Number(raw)
+      if (!Number.isFinite(value)) return null
+      live = value
+      return value
+    },
+    end(): number | null {
+      const value = live
+      const active = dragging || value !== null
+      live = null
+      dragging = false
+      return active && value !== null ? value : null
+    }
+  }
+}

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

@@ -814,6 +814,9 @@ export const en = {
   '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.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.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.lweHint': 'Required for animated/scene wallpapers on Linux. Renders Wallpaper Engine scenes directly on your desktop.',
   'settings.none': 'None',
   'settings.notConfigured': 'Not configured',

+ 1 - 0
src/shared/ipc-channels.ts

@@ -124,6 +124,7 @@ export const IpcChannels = {
   CONFIG_SET_TRAY_ENABLED: 'config:set-tray-enabled',
   CONFIG_SET_KILL_LWE_ON_QUIT: 'config:set-kill-lwe-on-quit',
   CONFIG_SET_SKIP_PLAYLIST_RESUME: 'config:set-skip-playlist-resume',
+  CONFIG_SET_FRESH_PROCESS_ON_PATH_CHANGE: 'config:set-fresh-process-on-path-change',
   CONFIG_SET_CARD_BORDERS: 'config:set-card-borders',
   CONFIG_SET_CARD_BADGES: 'config:set-card-badges',
   CONFIG_SET_APPEARANCE: 'config:set-appearance',

+ 18 - 0
src/shared/playScreen.test.ts

@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+import { CARD_PLAY_DEFAULT_SCREEN, cardPlayNeedsScreenChoice } from './playScreen'
+
+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('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('defaults to every screen, which is what Enter used to do', () => {
+    expect(CARD_PLAY_DEFAULT_SCREEN).toBe('*')
+  })
+})

+ 8 - 0
src/shared/playScreen.ts

@@ -0,0 +1,8 @@
+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 const CARD_PLAY_DEFAULT_SCREEN = '*'

+ 1 - 0
src/shared/types.ts

@@ -680,6 +680,7 @@ export interface AppConfigSnapshot {
   autostartPlaylistId: string | null
   killLweOnQuit: boolean
   skipPlaylistResume: boolean
+  freshProcessOnPathChange: boolean
   cardBorders: CardBorders
   cardBadges: CardBadges
   audioScreen: string | null