WallpaperEngineLover 2 недель назад
Родитель
Сommit
6a3d55da28

+ 2 - 1
src/main/index.ts

@@ -17,6 +17,7 @@ import { cancelRestore, expandScreen, getDisplayTargets, initDisplay, restoreAss
 import { mergeSkipScreens } from './services/restore-plan'
 import { initSchedule, takeCatchUp } from './services/schedule.service'
 import { initAppRules } from './services/app-rules.service'
+import { actionScreens } from './services/rule-actions.service'
 import { initUpdates } from './services/update.service'
 import { detectDesktopEnv, hasStatusNotifierHost } from './utils/platform'
 import { needsSoftwareCompositing, readGpuVendors } from './utils/gpuWorkaround'
@@ -264,7 +265,7 @@ app.whenReady().then(async () => {
     }
   }
   const catchUp = takeCatchUp()
-  const scheduleScreens = catchUp.flatMap((rule) => expandScreen(rule.screen, targets))
+  const scheduleScreens = catchUp.flatMap((rule) => actionScreens(rule.action, rule.screen, targets))
   initSchedule(win, catchUp)
   initAppRules(win)
   initUpdates(win)

+ 5 - 20
src/main/ipc/lwe.handlers.ts

@@ -1,12 +1,12 @@
 import { BrowserWindow, dialog, ipcMain } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
-import { getLweStatus, detectDistro, installLweDeps, installLwe, uninstallLwe, launchLweAsync, isLweRunning, killAllLweProcesses, listLweObjects, hotswapLweSettings, listLweProperties, listLweAudioObjects, listLweEffects, listLweFonts, listAudioInputs, listInputFiles, type HotswapOptions } from '../services/lwe.service'
+import { getLweStatus, detectDistro, installLweDeps, installLwe, uninstallLwe, launchLweAsync, isLweRunning, listLweObjects, hotswapLweSettings, listLweProperties, listLweAudioObjects, listLweEffects, listLweFonts, listAudioInputs, listInputFiles, type HotswapOptions } from '../services/lwe.service'
 import { getPrebuiltTarget, installLwePrebuilt } from '../services/lwe-prebuilt.service'
 import { installLibnode, libnodeNeeded } from '../services/lwe-libnode.service'
 import { addUserFonts, listUserFonts, removeUserFont } from '../services/fonts.service'
-import { forgetAssignments, stopDisplay } from '../services/display.service'
-import { getPlaybackStates, pausePlaylist, stopPlaylist, suspendPlaylist } from '../services/playlist-player.service'
-import { getForgetOnKillAll, getStopPlaylistsOnKillAll } from '../services/config.service'
+import { stopDisplay } from '../services/display.service'
+import { stopPlaylist } from '../services/playlist-player.service'
+import { killAllEngines } from '../services/kill-all.service'
 import type { ScreenTarget } from '@shared/types'
 import { invalidateEnvCache } from '../services/wallpaper.service'
 import { refreshEngineUpdate } from '../services/update.service'
@@ -104,22 +104,7 @@ export function registerLweHandlers(win: BrowserWindow): void {
     return { ok: true }
   })
 
-  ipcMain.handle(IpcChannels.LWE_KILL_ALL, async () => {
-    if (!getForgetOnKillAll()) {
-      if (getStopPlaylistsOnKillAll()) pausePlaylist()
-      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_KILL_ALL, () => killAllEngines())
 
   ipcMain.handle(IpcChannels.LWE_LIST_OBJECTS, async (_e, wallpaperPath: string) => {
     // a parse failure means "no objects"

+ 126 - 0
src/main/services/app-rules.service.test.ts

@@ -0,0 +1,126 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const h = vi.hoisted(() => ({
+  rules: [] as unknown[],
+  hostPids: [] as (number | undefined)[],
+  slowFrom: 0,
+  asked: 0
+}))
+
+vi.mock('../utils/safeStore', () => ({
+  openStore: () => {
+    const data: Record<string, unknown> = { rules: h.rules, layers: {}, active: [] }
+    return { get: (key: string) => data[key], set: (key: string, value: unknown) => { data[key] = value } }
+  }
+}))
+vi.mock('../utils/processes', () => ({ listProcessNames: async () => new Set<string>() }))
+vi.mock('../utils/audio-activity', () => ({ isAudioPlaying: vi.fn<(owners: Set<number>) => Promise<boolean>>(async () => false) }))
+vi.mock('../utils/flatpak', () => ({
+  isFlatpak: () => true,
+  hostPidOf: vi.fn<() => Promise<number | undefined>>(async () => {
+    if (h.slowFrom > 0 && ++h.asked >= h.slowFrom) await new Promise<void>(() => {})
+    return h.hostPids.shift()
+  })
+}))
+vi.mock('./lwe.service', () => ({ getRunningInstances: () => [], isLweRunning: () => false }))
+vi.mock('./profile.service', () => ({ captureScreens: () => ({}) }))
+vi.mock('./library.service', () => ({ getWallpaper: () => undefined }))
+vi.mock('./rule-actions.service', () => ({ actionScreens: () => [], runAction: async () => {}, runScreenAction: async () => {} }))
+
+const rule = (type: 'audio' | 'process') => ({
+  id: type,
+  name: type,
+  enabled: true,
+  condition: type === 'audio' ? { type } : { type, names: ['game'] },
+  action: { type: 'stop' },
+  screen: '*',
+  revert: false
+})
+
+async function start(rules: unknown[]) {
+  vi.resetModules()
+  h.rules = rules
+  const flatpak = await import('../utils/flatpak')
+  const service = await import('./app-rules.service')
+  service.initAppRules({ isDestroyed: () => false, webContents: { send: () => {} } } as never)
+  const audio = await import('../utils/audio-activity')
+  return { lookup: vi.mocked(flatpak.hostPidOf), audioCheck: vi.mocked(audio.isAudioPlaying) }
+}
+
+beforeEach(() => {
+  h.slowFrom = 0
+  h.asked = 0
+  vi.useFakeTimers()
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+describe('the app own pid on the host', () => {
+  it('is not looked up while no rule watches audio', async () => {
+    h.hostPids = [undefined]
+    const { lookup } = await start([rule('process')])
+
+    await vi.advanceTimersByTimeAsync(120_000)
+
+    expect(lookup).not.toHaveBeenCalled()
+  })
+
+  it('is looked up again after a failure, less often each time', async () => {
+    h.hostPids = [undefined, undefined, 4242]
+    const { lookup } = await start([rule('audio')])
+
+    await vi.advanceTimersByTimeAsync(50_000)
+    expect(lookup).toHaveBeenCalledTimes(1)
+
+    await vi.advanceTimersByTimeAsync(20_000)
+    expect(lookup).toHaveBeenCalledTimes(2)
+
+    await vi.advanceTimersByTimeAsync(60_000)
+    expect(lookup).toHaveBeenCalledTimes(2)
+
+    await vi.advanceTimersByTimeAsync(70_000)
+    expect(lookup).toHaveBeenCalledTimes(3)
+  })
+
+  it('is kept once found', async () => {
+    h.hostPids = [4242]
+    const { lookup } = await start([rule('audio')])
+
+    await vi.advanceTimersByTimeAsync(300_000)
+
+    expect(lookup).toHaveBeenCalledTimes(1)
+  })
+
+  it('is handed to the audio check once found', async () => {
+    h.hostPids = [4242]
+    const { audioCheck } = await start([rule('audio')])
+
+    await vi.advanceTimersByTimeAsync(10_000)
+
+    const owners = audioCheck.mock.calls.at(-1)?.[0] as Set<number>
+    expect(owners.has(4242)).toBe(true)
+  })
+
+  it('waits for the first answer before it asks the audio check', async () => {
+    h.slowFrom = 1
+    const { audioCheck } = await start([rule('audio')])
+
+    await vi.advanceTimersByTimeAsync(20_000)
+
+    expect(audioCheck).not.toHaveBeenCalled()
+  })
+
+  it('does not hold the check back for a slow lookup after the first', async () => {
+    h.slowFrom = 2
+    h.hostPids = [undefined]
+    const { audioCheck } = await start([rule('audio')])
+
+    await vi.advanceTimersByTimeAsync(65_000)
+    const before = audioCheck.mock.calls.length
+    await vi.advanceTimersByTimeAsync(30_000)
+
+    expect(audioCheck.mock.calls.length).toBeGreaterThan(before + 3)
+  })
+})

+ 33 - 10
src/main/services/app-rules.service.ts

@@ -92,21 +92,44 @@ export function getActiveRuleIds(): string[] {
     .map(([id]) => id)
 }
 
-let ownHostPid: Promise<number | undefined> | undefined
-
-function ownHostPidOnce(): Promise<number | undefined> {
-  if (!isFlatpak()) return Promise.resolve(undefined)
-  ownHostPid ??= hostPidOf(process.pid)
-  return ownHostPid
+const HOST_PID_RETRY_MS = 60_000
+const HOST_PID_RETRY_MAX_MS = 15 * 60_000
+
+let ownHostPid: number | undefined
+let ownHostPidLookup: Promise<void> | null = null
+let ownHostPidFailures = 0
+let ownHostPidRetryAt = 0
+
+/**
+ * The first answer is waited for, until it is there the app's own sound would count as another app's.
+ * Only a found pid is kept. A failed lookup is tried again in the background, less often each time: it scans
+ * the processes of the host, takes up to 10 s, and the checks must not wait for it
+ */
+async function findOwnHostPid(): Promise<void> {
+  if (!isFlatpak() || ownHostPid !== undefined || ownHostPidLookup || Date.now() < ownHostPidRetryAt) return
+
+  const first = ownHostPidFailures === 0
+  ownHostPidLookup = hostPidOf(process.pid).then((pid) => {
+    ownHostPid = pid
+    ownHostPidLookup = null
+    if (pid === undefined) {
+      ownHostPidRetryAt = Date.now() + Math.min(HOST_PID_RETRY_MS * 2 ** ownHostPidFailures, HOST_PID_RETRY_MAX_MS)
+      ownHostPidFailures++
+    }
+  })
+  if (first) await ownHostPidLookup
 }
 
 async function observe(rules: AppRule[]): Promise<Observation> {
   const enabled = rules.filter((r) => r.enabled)
   const processes = enabled.some((r) => r.condition.type === 'process') ? await listProcessNames() : new Set<string>()
-  const owners = new Set([process.pid, ...getRunningInstances().flatMap((i) => (i.hostPid === null ? [i.pid] : [i.pid, i.hostPid]))])
-  const hostPid = await ownHostPidOnce()
-  if (hostPid) owners.add(hostPid)
-  const audioPlaying = enabled.some((r) => r.condition.type === 'audio') ? await isAudioPlaying(owners) : false
+  let audioPlaying = false
+  if (enabled.some((r) => r.condition.type === 'audio')) {
+    await findOwnHostPid()
+    const owners = new Set([process.pid, ...getRunningInstances().flatMap((i) => (i.hostPid === null ? [i.pid] : [i.pid, i.hostPid]))])
+    if (ownHostPid !== undefined) owners.add(ownHostPid)
+    audioPlaying = await isAudioPlaying(owners)
+  }
   return { processes, audioPlaying }
 }
 

+ 6 - 4
src/main/services/display.service.ts

@@ -231,6 +231,8 @@ export async function showWallpaper(
   return appliedPath
 }
 
+export class SplitUnavailableError extends Error {}
+
 /** 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,
@@ -238,9 +240,9 @@ export async function showSplitScreen(
   dependencyPrompt: 'always' | 'once' | 'never' = 'always',
   skipMissing = false
 ): 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'))
+  if (getDisplayMode() !== 'per-screen' || screen === ALL_SCREENS) throw new SplitUnavailableError(t('split.needsPerScreen'))
+  if (!getDisplayTargets().includes(screen)) throw new SplitUnavailableError(`Screen ${screen} is not connected`)
+  if (!supportsSplitScreens()) throw new SplitUnavailableError(t('split.engineTooOld'))
   const claim = { stamp: claimScreen(screen) }
   try {
     await launchSplit(screen, claim, beforeLaunch, dependencyPrompt, skipMissing)
@@ -278,7 +280,7 @@ async function launchSplit(
     })
     shown.push(wallpaper)
   }
-  if (slots.length === 0 || !split) throw new Error(t('split.empty'))
+  if (slots.length === 0 || !split) throw new SplitUnavailableError(t('split.empty'))
   if (newerLaunchTakes(screen, claim.stamp)) {
     // restore leaves the screen to whoever took it, a split somebody asked for goes on
     if (!beforeLaunch) return

+ 88 - 0
src/main/services/kill-all.service.test.ts

@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const h = vi.hoisted(() => ({ forget: false, stopPlaylists: false }))
+
+const killAll = vi.fn<() => Promise<{ ok: boolean; message: string }>>()
+const resume = vi.fn<() => void>()
+const suspendPlaylist = vi.fn<(screen: string) => () => void>(() => resume)
+const pausePlaylist = vi.fn<() => void>()
+const stopPlaylist = vi.fn<() => void>()
+const forgetAssignments = vi.fn<() => void>()
+
+vi.mock('./config.service', () => ({
+  getForgetOnKillAll: () => h.forget,
+  getStopPlaylistsOnKillAll: () => h.stopPlaylists
+}))
+vi.mock('./lwe.service', () => ({ killAllLweProcesses: killAll }))
+vi.mock('./display.service', () => ({ forgetAssignments }))
+vi.mock('./playlist-player.service', () => ({
+  getPlaybackStates: () => [
+    { screen: 'DP-1', isPlaying: true },
+    { screen: 'DP-2', isPlaying: false }
+  ],
+  suspendPlaylist,
+  pausePlaylist,
+  stopPlaylist
+}))
+
+beforeEach(() => {
+  h.forget = false
+  h.stopPlaylists = false
+  for (const fn of [killAll, resume, suspendPlaylist, pausePlaylist, stopPlaylist, forgetAssignments]) fn.mockClear()
+  killAll.mockResolvedValue({ ok: true, message: '' })
+})
+
+async function run() {
+  const { killAllEngines } = await import('./kill-all.service')
+  return await killAllEngines()
+}
+
+describe('Kill All', () => {
+  it('leaves the playlists alone when neither setting is on', async () => {
+    await run()
+
+    expect(killAll).toHaveBeenCalledTimes(1)
+    expect(suspendPlaylist).not.toHaveBeenCalled()
+    expect(pausePlaylist).not.toHaveBeenCalled()
+  })
+
+  it('pauses the playlists that played once the engines are gone', async () => {
+    h.stopPlaylists = true
+
+    await run()
+
+    expect(suspendPlaylist).toHaveBeenCalledTimes(1)
+    expect(suspendPlaylist).toHaveBeenCalledWith('DP-1')
+    expect(pausePlaylist).toHaveBeenCalledTimes(1)
+    expect(resume).not.toHaveBeenCalled()
+  })
+
+  it('stops the playlists and forgets the screens with forget on', async () => {
+    h.forget = true
+
+    await run()
+
+    expect(stopPlaylist).toHaveBeenCalledTimes(1)
+    expect(forgetAssignments).toHaveBeenCalledTimes(1)
+    expect(pausePlaylist).not.toHaveBeenCalled()
+  })
+
+  it('lets the playlists go on when the kill did not work', async () => {
+    h.stopPlaylists = true
+    killAll.mockResolvedValue({ ok: false, message: 'pkill is missing' })
+
+    const result = await run()
+
+    expect(result.ok).toBe(false)
+    expect(resume).toHaveBeenCalledTimes(1)
+    expect(pausePlaylist).not.toHaveBeenCalled()
+  })
+
+  it('lets them go on and passes the error on when the kill threw', async () => {
+    h.stopPlaylists = true
+    killAll.mockRejectedValue(new Error('instances file'))
+
+    await expect(run()).rejects.toThrow('instances file')
+    expect(resume).toHaveBeenCalledTimes(1)
+  })
+})

+ 35 - 0
src/main/services/kill-all.service.ts

@@ -0,0 +1,35 @@
+import { forgetAssignments } from './display.service'
+import { getForgetOnKillAll, getStopPlaylistsOnKillAll } from './config.service'
+import { killAllLweProcesses } from './lwe.service'
+import { getPlaybackStates, pausePlaylist, stopPlaylist, suspendPlaylist } from './playlist-player.service'
+
+type KillResult = Awaited<ReturnType<typeof killAllLweProcesses>>
+
+/**
+ * Playlists are held while the engines are killed, so their timers do not start the next item in the middle of it
+ * (a launch already under way is not stopped). They are stopped (and the screens forgotten) or paused once the
+ * kill worked, and go on as before when it did not
+ */
+export async function killAllEngines(): Promise<KillResult> {
+  const forget = getForgetOnKillAll()
+  if (!forget && !getStopPlaylistsOnKillAll()) return await killAllLweProcesses()
+
+  const resumes = getPlaybackStates().filter((state) => state.isPlaying).map((state) => suspendPlaylist(state.screen))
+  let result: KillResult
+  try {
+    result = await killAllLweProcesses()
+  } catch (err) {
+    for (const resume of resumes) resume()
+    throw err
+  }
+
+  if (!result.ok) {
+    for (const resume of resumes) resume()
+  } else if (forget) {
+    stopPlaylist()
+    forgetAssignments()
+  } else {
+    pausePlaylist()
+  }
+  return result
+}

+ 96 - 0
src/main/services/library.service.test.ts

@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { EngineFlags, WallpaperMeta } from '@shared/types'
+
+const h = vi.hoisted(() => ({
+  data: { wallpapers: {}, tags: [], folders: [], resolutionsVersion: 0, seen: {} } as Record<string, unknown>,
+  writes: [] as string[]
+}))
+
+vi.mock('../utils/safeStore', () => ({
+  openStore: () => ({
+    path: '/tmp/library.json',
+    get: (key: string) => h.data[key],
+    set: (key: string, value: unknown) => {
+      h.writes.push(key)
+      h.data[key] = value
+    }
+  })
+}))
+vi.mock('../utils/paths', () => ({ getExtraLibraryRoots: () => [], getThumbnailsPath: () => '/tmp', getWorkshopPath: () => '/tmp' }))
+vi.mock('../utils/localLibrary', () => ({ findLocalWallpapers: () => [], localWallpaperId: () => '' }))
+vi.mock('../utils/contained', () => ({ containedPath: () => null }))
+vi.mock('../utils/projectJson', () => ({ readProjectJsonSync: () => null }))
+vi.mock('../utils/shaderCache', () => ({ isShaderCache: () => false }))
+vi.mock('../utils/collections', () => ({ findAndMutate: () => false }))
+vi.mock('../utils/hdr', () => ({ detectFeatures: () => ({}) }))
+vi.mock('./config.service', () => ({ getSteamIdentity: () => ({}) }))
+vi.mock('./playlist.service', () => ({ cleanupPlaylists: () => {} }))
+vi.mock('./backup.service', () => ({ backupMatchesSource: () => false, hasBackupFiles: () => false }))
+vi.mock('./workshop.service', () => ({ getWorkshopDetails: () => null, getUnavailableWorkshopItems: () => [] }))
+vi.mock('./steam.service', () => ({
+  isSteamRunning: () => false,
+  getItemDownloadStatus: () => null,
+  getSubscribedItems: () => [],
+  isItemStuckNeverDownloaded: () => false,
+  downloadItem: () => {}
+}))
+
+// the service keeps the wallpaper map in memory, so every test starts from a fresh import
+async function boot() {
+  vi.resetModules()
+  return await import('./library.service')
+}
+
+// flags with global-only keys are what older versions stored
+function meta(id: string, engineFlags?: EngineFlags): WallpaperMeta {
+  return { id, title: id, engineFlags } as WallpaperMeta
+}
+
+function stored(): Record<string, WallpaperMeta> {
+  return h.data.wallpapers as Record<string, WallpaperMeta>
+}
+
+describe('stored engine flags', () => {
+  beforeEach(() => {
+    h.data.wallpapers = {}
+    h.writes.length = 0
+  })
+
+  it('drops global-only flags at startup and keeps the rest', async () => {
+    h.data.wallpapers = {
+      a: meta('a', { silent: true, windowed: true, audioInput: 'usb-mic' }),
+      b: meta('b', { windowed: true }),
+      c: meta('c', { silent: true })
+    }
+    const { initLibrary } = await boot()
+    initLibrary()
+    expect(stored().a.engineFlags).toEqual({ silent: true })
+    expect(stored().b.engineFlags).toBeUndefined()
+    expect(stored().c.engineFlags).toEqual({ silent: true })
+    expect(h.writes).toEqual(['wallpapers'])
+  })
+
+  it('removes flags that only hold undefined values', async () => {
+    h.data.wallpapers = { a: meta('a', { silent: undefined }) }
+    const { initLibrary } = await boot()
+    initLibrary()
+    expect(stored().a.engineFlags).toBeUndefined()
+  })
+
+  it('does not write the store again once it is clean', async () => {
+    h.data.wallpapers = { a: meta('a', { silent: true, windowed: true }), b: meta('b') }
+    const { initLibrary } = await boot()
+    initLibrary()
+    h.writes.length = 0
+    initLibrary()
+    expect(h.writes).toEqual([])
+  })
+
+  it('strips global-only flags when a wallpaper is written', async () => {
+    const { getWallpaper, upsertWallpaper } = await boot()
+    upsertWallpaper(meta('a', { silent: false, kdeBackgroundLayer: true }))
+    expect(getWallpaper('a')?.engineFlags).toEqual({ silent: false })
+    upsertWallpaper(meta('b', { windowed: true }))
+    expect(getWallpaper('b')?.engineFlags).toBeUndefined()
+  })
+})

+ 10 - 3
src/main/services/library.service.ts

@@ -14,6 +14,7 @@ import { backupMatchesSource, hasBackupFiles } from './backup.service'
 import { getWorkshopDetails, getUnavailableWorkshopItems, type WorkshopDetails } from './workshop.service'
 import { findAndMutate } from '../utils/collections'
 import { resolutionsFromTags } from '@shared/resolutions'
+import { normalizeWallpaperFlags } from '@shared/engineFlags'
 import { detectFeatures, type WallpaperFeatures } from '../utils/hdr'
 import {
   isSteamRunning,
@@ -61,10 +62,10 @@ const store = {
 
 export function initLibrary(): void {
   console.log('[Library] Store initialized at', store.path)
-  repairStaleDownloadFlags()
+  repairStoredWallpapers()
 }
 
-function repairStaleDownloadFlags(): void {
+function repairStoredWallpapers(): void {
   const wallpapers = store.get('wallpapers')
   let changed = false
   for (const wallpaper of Object.values(wallpapers)) {
@@ -73,6 +74,12 @@ function repairStaleDownloadFlags(): void {
       wallpaper.downloadFailed = false
       changed = true
     }
+    const flags = wallpaper.engineFlags
+    const kept = flags && normalizeWallpaperFlags(flags)
+    if (flags && (!kept || Object.keys(kept).length !== Object.keys(flags).length)) {
+      wallpaper.engineFlags = kept
+      changed = true
+    }
   }
   if (changed) store.set('wallpapers', wallpapers)
 }
@@ -133,7 +140,7 @@ export function getWallpaper(id: string): WallpaperMeta | null {
 
 export function upsertWallpaper(meta: WallpaperMeta): void {
   const wallpapers = store.get('wallpapers')
-  wallpapers[meta.id] = meta
+  wallpapers[meta.id] = meta.engineFlags ? { ...meta, engineFlags: normalizeWallpaperFlags(meta.engineFlags) } : meta
   store.set('wallpapers', wallpapers)
 }
 

+ 314 - 1
src/main/services/playlist-player.service.test.ts

@@ -7,6 +7,7 @@ const h = vi.hoisted(() => ({
   assignments: {} as Record<string, string>,
   gate: null as Promise<string> | null,
   overtaken: false,
+  crashed: new Set<string>(),
   release: (_value: string) => {},
   playlist: {
     id: 'p',
@@ -38,7 +39,16 @@ vi.mock('./playlist.service', () => ({
   getAllPlaylists: () => [h.playlist]
 }))
 vi.mock('./library.service', () => ({
-  getWallpaper: (id: string) => ({ id, title: id, type: 'scene', localPath: `/w/${id}` }),
+  getWallpaper: (id: string) =>
+    id === 'ghost'
+      ? null
+      : {
+          id,
+          title: id,
+          type: 'scene',
+          localPath: `/w/${id}`,
+          compat: h.crashed.has(id) ? { freshLaunch: 'crash' } : undefined
+        },
   updateWallpaper: () => {}
 }))
 vi.mock('./lwe.service', () => ({ getLweStatus: () => ({ installed: true }), ALL_SCREENS: '*' }))
@@ -108,6 +118,7 @@ beforeEach(() => {
   h.assignments = {}
   h.gate = null
   h.overtaken = false
+  h.crashed.clear()
   h.playlist.items = [{ wallpaperId: 'a' }, { wallpaperId: 'b', volume: 30 }, { wallpaperId: 'c' }]
   showWallpaper.mockClear()
 })
@@ -576,3 +587,305 @@ describe('stopping during an apply', () => {
     expect(showWallpaper).toHaveBeenCalledTimes(1)
   })
 })
+
+describe('items that crash', () => {
+  it('are still tried when the only other item is gone from the library', async () => {
+    h.playlist.items = [{ wallpaperId: 'a' }, { wallpaperId: 'ghost' }]
+    h.crashed.add('a')
+    const service = await boot()
+
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(h.assignments['DP-1']).toBe('a')
+  })
+})
+
+describe('a daytime playlist', () => {
+  const settings = h.playlist.settings as Record<string, unknown>
+
+  beforeEach(() => {
+    settings.mode = 'daytime'
+  })
+
+  afterEach(() => {
+    delete settings.mode
+    showWallpaper.mockReset()
+  })
+
+  it('keeps a pick made while the first apply was still waiting', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    h.gate = new Promise<string>((resolve) => {
+      h.release = resolve
+    })
+    const service = await boot()
+
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    h.gate = null
+    void service.playItem('p', 'a', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    h.overtaken = true
+    h.release('')
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    await vi.advanceTimersByTimeAsync(120_000)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('tries only the clock item again after it failed, the stand-in stays on the screen', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b') throw new Error('declined')
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    showWallpaper.mockClear()
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+    expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['b', 'c'])
+
+    showWallpaper.mockClear()
+    await vi.advanceTimersByTimeAsync(300_000)
+
+    const shown = showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)
+    expect(shown.length).toBeGreaterThan(0)
+    expect(new Set(shown)).toEqual(new Set(['b']))
+  })
+
+  it('tries the clock item again when every item is flagged as crashing, as it was not skipped on purpose', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    for (const id of ['a', 'b', 'c']) h.crashed.add(id)
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b') throw new Error('declined')
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    showWallpaper.mockClear()
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+    expect(showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)).toEqual(['b', 'c'])
+
+    showWallpaper.mockClear()
+    await vi.advanceTimersByTimeAsync(300_000)
+
+    const shown = showWallpaper.mock.calls.map(([wallpaper]) => wallpaper.id)
+    expect(shown.length).toBeGreaterThan(0)
+    expect(new Set(shown)).toEqual(new Set(['b']))
+  })
+
+  it('goes on from the stand-in when the failed item is skipped on purpose later', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b') throw new Error('declined')
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+    h.crashed.add('b')
+    await vi.advanceTimersByTimeAsync(70_000)
+    showWallpaper.mockClear()
+    const changed = vi.fn<() => void>()
+    service.onPlaybackStateChanged(changed)
+
+    await vi.advanceTimersByTimeAsync(600_000)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+    expect(changed).not.toHaveBeenCalled()
+  })
+
+  it('shows the stand-in again when the retry of the failed item took the screen with it', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    let triedB = 0
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b') {
+        if (++triedB > 1) {
+          delete h.assignments[screen]
+          h.crashed.add('b')
+        }
+        throw new Error('crashed')
+      }
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(300_000)
+
+    expect(h.assignments['DP-1']).toBe('c')
+  })
+
+  it('leaves the position of a pick alone when the retry it overtook fails', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    let failRetry: ((reason: Error) => void) | undefined
+    let triedB = 0
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b') {
+        if (++triedB === 1) throw new Error('declined')
+        return await new Promise<string>((_resolve, reject) => { failRetry = reject })
+      }
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(70_000)
+    expect(triedB).toBe(2)
+
+    void service.playItem('p', 'a', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    failRetry?.(new Error('declined again'))
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(service.getPlaybackStates()[0].currentIndex).toBe(0)
+  })
+
+  it('remembers where the clock is when a pause came during the apply', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    let launched: (() => void) | undefined
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      await new Promise<void>((resolve) => { launched = resolve })
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+    service.pausePlaylist('DP-1')
+    launched?.()
+    await vi.advanceTimersByTimeAsync(0)
+    showWallpaper.mockClear()
+
+    service.resumePlaylist('DP-1')
+    await vi.advanceTimersByTimeAsync(30_000)
+
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('tries the item that did not launch at the start again', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    let triedB = 0
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b' && ++triedB < 3) throw new Error('drive not mounted')
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    const service = await boot()
+
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    expect(h.assignments['DP-1']).toBe('c')
+
+    await vi.advanceTimersByTimeAsync(70_000)
+    expect(triedB).toBe(2)
+
+    await vi.advanceTimersByTimeAsync(70_000)
+    expect(h.assignments['DP-1']).toBe('b')
+  })
+
+  it('goes on trying the item that did not launch after a pause and resume', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    let triedB = 0
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'b' && ++triedB < 3) throw new Error('drive not mounted')
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    const service = await boot()
+
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+    service.pausePlaylist('DP-1')
+    service.resumePlaylist('DP-1')
+
+    await vi.advanceTimersByTimeAsync(70_000)
+    expect(triedB).toBe(2)
+
+    await vi.advanceTimersByTimeAsync(70_000)
+    expect(h.assignments['DP-1']).toBe('b')
+  })
+
+  it('tells the window when a pause came during the apply', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    let launched: (() => void) | undefined
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      await new Promise<void>((resolve) => { launched = resolve })
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+    service.pausePlaylist('DP-1')
+    const changed = vi.fn<() => void>()
+    service.onPlaybackStateChanged(changed)
+    launched?.()
+    await vi.advanceTimersByTimeAsync(0)
+
+    expect(service.getPlaybackStates()[0].currentItemId).toBe('b')
+    expect(changed).toHaveBeenCalled()
+  })
+
+  it('retries a wallpaper in the slot of the clock when it is in two slots', async () => {
+    h.playlist.items = [{ wallpaperId: 'a' }, { wallpaperId: 'b' }, { wallpaperId: 'a' }]
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    let triedA = 0
+    showWallpaper.mockImplementation(async (wallpaper, screen) => {
+      if (wallpaper.id === 'a' && ++triedA <= 2) throw new Error('drive not mounted')
+      h.assignments[screen] = wallpaper.id
+      return ''
+    })
+    vi.setSystemTime(new Date(2026, 0, 5, 20, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+    expect(h.assignments['DP-1']).toBe('b')
+
+    await vi.advanceTimersByTimeAsync(70_000)
+
+    expect(h.assignments['DP-1']).toBe('a')
+    expect(service.getPlaybackStates()[0].currentIndex).toBe(2)
+  })
+
+  it('saves what the clock put on the screen', async () => {
+    vi.setSystemTime(new Date(2026, 0, 5, 7, 0))
+    const service = await boot()
+    service.startPlaylist('p', 'DP-1')
+    await vi.advanceTimersByTimeAsync(0)
+
+    vi.setSystemTime(new Date(2026, 0, 5, 10, 0))
+    await vi.advanceTimersByTimeAsync(10_000)
+
+    const saved = (h.disk.data as { players: Record<string, { shownId: string }> }).players
+    expect(saved['DP-1'].shownId).toBe('b')
+  })
+})

+ 84 - 33
src/main/services/playlist-player.service.ts

@@ -56,6 +56,7 @@ interface Player {
   clockItem: number | null
   clockWallpaper: string | null
   clockRetryAt: number
+  clockFellBack: string | null
   scheduledMode: string | null
 }
 
@@ -103,6 +104,10 @@ function firstWeekday(): number {
   }
 }
 
+function wallpaperAt(playlist: Playlist, index: number): string | null {
+  return playlist.items[index]?.wallpaperId ?? null
+}
+
 /** The item the clock wants now, an index into the playlist's items (which is also the order of these modes) */
 function clockIndex(playlist: Playlist, mode: ScheduledMode, now = new Date()): number {
   const ends =
@@ -160,6 +165,14 @@ function persist(stopped: readonly ScreenTarget[] = [], prune = true): void {
   store.set('players', mergePlayers(saved, live, [...stopped, ...players.keys()]))
 }
 
+function savePlayers(): void {
+  try {
+    persist([], false)
+  } catch (err) {
+    console.error('[PlaylistPlayer] Could not save the playlist state:', err)
+  }
+}
+
 function clearTimer(player: Player): void {
   player.scheduleToken++
   if (player.timer) {
@@ -194,24 +207,33 @@ function known(id: string): boolean {
   return compatStatus(getWallpaper(id)?.compat) !== 'crashes'
 }
 
+function anyPlayableIn(order: string[], inRotation: (id: string) => boolean): boolean {
+  return order.some((id) => getWallpaper(id) !== null && inRotation(id) && known(id))
+}
+
 /** True when applyCurrent would not have skipped this item on purpose, so not showing it means the launch failed */
 function wasPlayable(playlist: Playlist, order: string[], id: string): boolean {
-  return rotationFilter(playlist, order)(id) && known(id)
+  const inRotation = rotationFilter(playlist, order)
+  return getWallpaper(id) !== null && inRotation(id) && (known(id) || !anyPlayableIn(order, inRotation))
 }
 
-/** Skips crashing items and non-favorites while something else is left. `picked` always plays */
-async function applyCurrent(player: Player, playlist: Playlist, picked?: string): Promise<boolean> {
+/**
+ * Skips crashing items and non-favorites while something else is left. `picked` always plays.
+ * `only` is an index to try on its own: when it fails nothing else is shown and the position stays
+ */
+async function applyCurrent(player: Player, playlist: Playlist, mine: number, { picked, only }: { picked?: string; only?: number } = {}): Promise<boolean> {
   const { state } = player
   const count = state.order.length
+  const from = state.currentIndex
+  if (only !== undefined) state.currentIndex = only
   const inRotation = rotationFilter(playlist, state.order)
-  const anyPlayable = state.order.some((id) => inRotation(id) && known(id))
+  const anyPlayable = anyPlayableIn(state.order, inRotation)
 
-  const mine = ++player.applyId
   const stale = (): boolean => player.state !== state || players.get(state.screen) !== player || player.applyId !== mine
 
   player.applying = true
   try {
-    for (let tries = 0; tries < count; tries++, state.currentIndex = (state.currentIndex + 1) % count) {
+    for (let tries = 0; tries < (only === undefined ? count : 1); tries++, state.currentIndex = (state.currentIndex + 1) % count) {
       if (stale()) return false
       const wallpaper = getWallpaper(state.order[state.currentIndex])
       if (!wallpaper) continue
@@ -225,6 +247,8 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
         })
       } catch (err) {
         console.error('[PlaylistPlayer] Failed to apply wallpaper:', err)
+        // the step to the next item would move the position of whatever overtook this apply
+        if (stale()) return false
         continue
       }
       if (stale()) return false
@@ -238,8 +262,11 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
         player.lastShown = wallpaper.id
         return true
       }
+      if (only !== undefined) state.currentIndex = from
       return false
     }
+    // a newer apply set the position it needs, only this one's own step is undone
+    if (only !== undefined && !stale()) state.currentIndex = from
     return false
   } finally {
     if (player.applyId === mine) player.applying = false
@@ -248,15 +275,13 @@ async function applyCurrent(player: Player, playlist: Playlist, picked?: string)
 
 async function showCurrent(player: Player, playlist: Playlist, picked?: string, applied?: (shown: boolean) => void): Promise<void> {
   const state = player.state
-  const shown = await applyCurrent(player, playlist, picked)
-  if (player.state !== state) return
+  const mine = ++player.applyId
+  const shown = await applyCurrent(player, playlist, mine, { picked })
+  // a newer apply on this player decides what is shown and arms the timer
+  if (player.state !== state || player.applyId !== mine) return
   applied?.(shown)
   scheduleNext(player, playlist)
-  try {
-    persist([], false)
-  } catch (err) {
-    console.error('[PlaylistPlayer] Could not save the playlist state:', err)
-  }
+  savePlayers()
   emitState()
 }
 
@@ -330,40 +355,64 @@ async function followClock(player: Player, playlist: Playlist, mode: ScheduledMo
   }
 
   const target = clockIndex(current, mode)
-  const targetWallpaper = current.items[target]?.wallpaperId ?? null
+  const targetWallpaper = wallpaperAt(current, target)
   if ((target !== player.clockItem || targetWallpaper !== player.clockWallpaper) && !player.applying && Date.now() >= player.clockRetryAt) {
     const token = player.scheduleToken
-    player.state.order = buildOrder(current)
-    player.state.currentIndex = target
-    const shown = await applyCurrent(player, current)
-    const fellBack = shown && targetWallpaper !== null && player.state.currentItemId !== targetWallpaper && wasPlayable(current, player.state.order, targetWallpaper)
-    if (shown && !fellBack) {
-      player.clockItem = target
-      player.clockWallpaper = targetWallpaper
-    } else player.clockRetryAt = Date.now() + CLOCK_RETRY_MS
-    if (token !== player.scheduleToken || players.get(player.state.screen) !== player) return
-    emitState()
+    if (player.clockFellBack !== targetWallpaper) player.clockFellBack = null
+    // the clock's slot, not the first place the wallpaper has in the order: it may be in two slots
+    const retryIndex = player.state.order[target] === targetWallpaper ? target : player.state.order.indexOf(targetWallpaper ?? '')
+    const only = player.clockFellBack === null || retryIndex === -1 ? undefined : retryIndex
+    if (only === undefined) {
+      player.state.order = buildOrder(current)
+      player.state.currentIndex = target
+    }
+    const mine = ++player.applyId
+    const shown = await applyCurrent(player, current, mine, { only })
+    // a newer apply on this player decides what is shown, a pause only keeps the timer from being armed
+    if (players.get(player.state.screen) !== player || player.applyId !== mine) return
+    noteClockApply(player, current, target, shown, only !== undefined)
+    const changed = only === undefined || shown
+    if (changed) {
+      savePlayers()
+      emitState()
+    }
+    if (token !== player.scheduleToken) return
   }
   scheduleNext(player, current)
 }
 
-/** Only a shown item counts as the clock's position, a failed one is tried again after a while */
-function noteClockApply(player: Player, playlist: Playlist, target: number, shown: boolean): void {
-  if (shown) {
+function standsIn(player: Player, playlist: Playlist, wanted: string | null, shown: boolean): boolean {
+  return shown && wanted !== null && player.state.currentItemId !== wanted && wasPlayable(playlist, player.state.order, wanted)
+}
+
+/**
+ * Only a shown item counts as the clock's position. One that did not launch is tried again after a while, on its
+ * own while something stands in for it (`retried`: this apply was such a try)
+ */
+function noteClockApply(player: Player, playlist: Playlist, target: number, shown: boolean, retried = false): void {
+  const wanted = wallpaperAt(playlist, target)
+  const standIn = standsIn(player, playlist, wanted, shown)
+  const heldByStandIn = retried && owns(player)
+  const skipped = heldByStandIn && wanted !== null && !wasPlayable(playlist, player.state.order, wanted)
+
+  if ((shown && !standIn) || skipped) {
     player.clockItem = target
-    player.clockWallpaper = playlist.items[target]?.wallpaperId ?? null
-  } else {
-    player.clockItem = null
-    player.clockWallpaper = null
-    player.clockRetryAt = Date.now() + CLOCK_RETRY_MS
+    player.clockWallpaper = wanted
+    player.clockFellBack = null
+    return
   }
+  player.clockItem = null
+  player.clockWallpaper = null
+  player.clockRetryAt = Date.now() + CLOCK_RETRY_MS
+  player.clockFellBack = standIn || heldByStandIn ? wanted : null
 }
 
 /** A manual pick holds until the clock moves on from where it is now */
 function holdClock(player: Player, playlist: Playlist): void {
   const mode = clockMode(playlist)
   player.clockItem = mode ? clockIndex(playlist, mode) : null
-  player.clockWallpaper = player.clockItem === null ? null : (playlist.items[player.clockItem]?.wallpaperId ?? null)
+  player.clockWallpaper = player.clockItem === null ? null : wallpaperAt(playlist, player.clockItem)
+  player.clockFellBack = null
 }
 
 async function advance(player: Player): Promise<void> {
@@ -397,6 +446,7 @@ function playerFor(screen: ScreenTarget): Player {
       clockItem: null,
       clockWallpaper: null,
       clockRetryAt: 0,
+      clockFellBack: null,
       scheduledMode: null
     }
     players.set(screen, player)
@@ -435,6 +485,7 @@ function startOn(screen: ScreenTarget, playlist: Playlist, paused = false, shown
   player.clockItem = null
   player.clockWallpaper = null
   player.clockRetryAt = 0
+  player.clockFellBack = null
   player.state = {
     screen,
     playlistId: playlist.id,

+ 5 - 3
src/main/services/profile.service.ts

@@ -4,7 +4,7 @@ import { openStore } from '../utils/safeStore'
 import { getWallpaper } from './library.service'
 import { getPlaybackStates } from './playlist-player.service'
 import { getDisplayTargets } from './display.service'
-import { getAssignments } from './wallpaper-state.service'
+import { getAssignments, isSplitActive } from './wallpaper-state.service'
 
 interface ProfileStore {
   profiles: Profile[]
@@ -37,14 +37,16 @@ export function deleteProfile(id: string): void {
   store.set('profiles', getProfiles().filter((p) => p.id !== id))
 }
 
-/** What a screen shows now: its playlist while one plays, else its wallpaper, else nothing */
+/** What a screen shows now: its playlist while one plays, else its split or wallpaper, else nothing */
 export function currentScreenAction(screen: ScreenTarget): ScreenAction {
   const playing = getPlaybackStates().find((s) => s.screen === screen && s.playlistId && s.isPlaying)
   if (playing?.playlistId) return { type: 'playlist', playlistId: playing.playlistId }
 
   const assignments = getAssignments()
   const wallpaperId = assignments[screen] ?? assignments['*']
-  if (wallpaperId && getWallpaper(wallpaperId)) return { type: 'wallpaper', wallpaperId }
+  if (wallpaperId && getWallpaper(wallpaperId)) {
+    return isSplitActive(screen) ? { type: 'split', wallpaperId } : { type: 'wallpaper', wallpaperId }
+  }
   return { type: 'stop' }
 }
 

+ 138 - 0
src/main/services/rule-actions.service.test.ts

@@ -0,0 +1,138 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const h = vi.hoisted(() => ({
+  targets: ['DP-1', 'DP-2'],
+  assignments: {} as Record<string, string>,
+  splitScreens: new Set<string>(),
+  playing: [] as { screen: string; playlistId: string; isPlaying: boolean }[],
+  profiles: {} as Record<string, unknown>,
+  library: new Set(['a', 'b']),
+  splits: {} as Record<string, { slots: { wallpaperId: string }[] }>
+}))
+
+vi.mock('../utils/safeStore', () => ({ openStore: () => ({ get: () => [], set: () => {} }) }))
+vi.mock('../i18n', () => ({ t: (key: string) => key }))
+vi.mock('./library.service', () => ({
+  getWallpaper: (id: string) => (h.library.has(id) ? { id, title: id } : undefined),
+  updateWallpaper: () => {}
+}))
+vi.mock('./playlist.service', () => ({ getPlaylist: () => undefined }))
+vi.mock('./config.service', () => ({ getSplitScreens: () => h.splits }))
+vi.mock('./wallpaper-state.service', () => ({
+  getAssignments: () => h.assignments,
+  isSplitActive: (screen: string) => h.splitScreens.has(screen)
+}))
+vi.mock('./playlist-player.service', () => ({
+  getPlaybackStates: () => h.playing,
+  startPlaylist: vi.fn<() => void>(),
+  stopPlaylist: vi.fn<() => void>()
+}))
+
+const showSplitScreen = vi.fn<(screen: string, beforeLaunch?: () => void) => Promise<void>>(async () => {})
+const showWallpaper = vi.fn<(wallpaper: { id: string }, screen: string) => Promise<string>>(async () => '')
+vi.mock('./display.service', () => ({
+  expandScreen: (screen?: string) => (screen && screen !== '*' ? (h.targets.includes(screen) ? [screen] : []) : h.targets),
+  getDisplayTargets: () => h.targets,
+  isShownOn: () => false,
+  showSplitScreen,
+  showWallpaper,
+  SplitUnavailableError: class SplitUnavailableError extends Error {},
+  stopDisplay: async () => {}
+}))
+vi.mock('./profile.service', async () => {
+  const real = await vi.importActual<typeof import('./profile.service')>('./profile.service')
+  return { ...real, getProfile: (id: string) => h.profiles[id] }
+})
+
+beforeEach(() => {
+  h.targets = ['DP-1', 'DP-2']
+  h.assignments = {}
+  h.splitScreens.clear()
+  h.playing = []
+  h.profiles = {}
+  h.splits = {}
+  showSplitScreen.mockReset()
+  showWallpaper.mockClear()
+})
+
+describe('what a screen goes back to', () => {
+  it('is its split when one is showing, with the first wallpaper to fall back on', async () => {
+    const { currentScreenAction } = await import('./profile.service')
+    h.assignments = { 'DP-1': 'a', 'DP-2': 'b' }
+    h.splitScreens.add('DP-1')
+
+    expect(currentScreenAction('DP-1')).toEqual({ type: 'split', wallpaperId: 'a' })
+    expect(currentScreenAction('DP-2')).toEqual({ type: 'wallpaper', wallpaperId: 'b' })
+  })
+
+  it('stays its playlist while one plays on the split screen', async () => {
+    const { currentScreenAction } = await import('./profile.service')
+    h.assignments = { 'DP-1': 'a' }
+    h.splitScreens.add('DP-1')
+    h.playing = [{ screen: 'DP-1', playlistId: 'p', isPlaying: true }]
+
+    expect(currentScreenAction('DP-1')).toEqual({ type: 'playlist', playlistId: 'p' })
+  })
+})
+
+describe('going back to a split', () => {
+  it('shows the split again', async () => {
+    const { runScreenAction } = await import('./rule-actions.service')
+
+    await runScreenAction({ type: 'split', wallpaperId: 'a' }, 'DP-1')
+
+    expect(showSplitScreen).toHaveBeenCalledWith('DP-1', expect.any(Function), 'once', true)
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('keeps the wallpapers of its slots from being optimized or deleted while it starts', async () => {
+    const { runScreenAction, runningWallpaperIds } = await import('./rule-actions.service')
+    h.splits = { 'DP-1': { slots: [{ wallpaperId: 'a' }, { wallpaperId: 'b' }] } }
+    let during: string[] = []
+    showSplitScreen.mockImplementationOnce(async () => { during = runningWallpaperIds() })
+
+    await runScreenAction({ type: 'split', wallpaperId: 'a' }, 'DP-1')
+
+    expect(during.sort()).toEqual(['a', 'b'])
+    expect(runningWallpaperIds()).toEqual([])
+  })
+
+  it('shows its first wallpaper when the split can not be shown any more', async () => {
+    const { runScreenAction } = await import('./rule-actions.service')
+    const { SplitUnavailableError } = await import('./display.service')
+    showSplitScreen.mockRejectedValueOnce(new SplitUnavailableError('split.empty'))
+
+    await runScreenAction({ type: 'split', wallpaperId: 'a' }, 'DP-1')
+
+    expect(showWallpaper).toHaveBeenCalledTimes(1)
+    expect(showWallpaper.mock.calls[0][0].id).toBe('a')
+    expect(showWallpaper.mock.calls[0][1]).toBe('DP-1')
+  })
+
+  it('fails, to be tried again, when the launch of the split failed', async () => {
+    const { runScreenAction } = await import('./rule-actions.service')
+    showSplitScreen.mockRejectedValueOnce(new Error('engine exited'))
+
+    await expect(runScreenAction({ type: 'split', wallpaperId: 'a' }, 'DP-1')).rejects.toThrow('engine exited')
+    expect(showWallpaper).not.toHaveBeenCalled()
+  })
+
+  it('fails when the split and its first wallpaper are both gone', async () => {
+    const { runScreenAction } = await import('./rule-actions.service')
+    const { SplitUnavailableError } = await import('./display.service')
+    showSplitScreen.mockRejectedValueOnce(new SplitUnavailableError('split.empty'))
+
+    await expect(runScreenAction({ type: 'split', wallpaperId: 'gone' }, 'DP-1')).rejects.toThrow('rules.wallpaperGone')
+  })
+})
+
+describe('the screens an action touches', () => {
+  it('are the screens a profile names, not the rule screen left over in the editor', async () => {
+    const { actionScreens } = await import('./rule-actions.service')
+    h.profiles.p = { id: 'p', name: 'p', screens: { 'DP-1': { type: 'stop' } } }
+
+    expect(actionScreens({ type: 'profile', profileId: 'p' }, '*')).toEqual(['DP-1'])
+    expect(actionScreens({ type: 'stop' }, '*')).toEqual(['DP-1', 'DP-2'])
+    expect(actionScreens({ type: 'stop' }, 'DP-2')).toEqual(['DP-2'])
+  })
+})

+ 30 - 14
src/main/services/rule-actions.service.ts

@@ -1,7 +1,8 @@
 import type { Profile, ScheduleAction, ScreenAction, ScreenTarget } from '@shared/types'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getPlaylist } from './playlist.service'
-import { expandScreen, getDisplayTargets, isShownOn, showWallpaper, stopDisplay } from './display.service'
+import { getSplitScreens } from './config.service'
+import { expandScreen, getDisplayTargets, isShownOn, showSplitScreen, showWallpaper, SplitUnavailableError, stopDisplay } from './display.service'
 import { startPlaylist, stopPlaylist } from './playlist-player.service'
 import { getProfile } from './profile.service'
 import { t } from '../i18n'
@@ -13,22 +14,38 @@ export function runningWallpaperIds(): string[] {
   return [...runningWallpapers.keys()]
 }
 
+async function whileStarting<T>(ids: string[], work: () => Promise<T>): Promise<T> {
+  for (const id of ids) runningWallpapers.set(id, (runningWallpapers.get(id) ?? 0) + 1)
+  try {
+    return await work()
+  } finally {
+    for (const id of ids) {
+      const left = (runningWallpapers.get(id) ?? 1) - 1
+      if (left > 0) runningWallpapers.set(id, left)
+      else runningWallpapers.delete(id)
+    }
+  }
+}
+
 export async function runScreenAction(action: ScreenAction, screen: ScreenTarget): Promise<void> {
   if (action.type === 'wallpaper') {
     const wallpaper = getWallpaper(action.wallpaperId)
     if (!wallpaper) throw new Error(t('rules.wallpaperGone'))
     for (const s of expandScreen(screen)) stopPlaylist(s)
-    runningWallpapers.set(wallpaper.id, (runningWallpapers.get(wallpaper.id) ?? 0) + 1)
-    try {
-      await showWallpaper(wallpaper, screen, { dependencyPrompt: 'once' })
-    } finally {
-      const left = (runningWallpapers.get(wallpaper.id) ?? 1) - 1
-      if (left > 0) runningWallpapers.set(wallpaper.id, left)
-      else runningWallpapers.delete(wallpaper.id)
-    }
+    await whileStarting([wallpaper.id], () => showWallpaper(wallpaper, screen, { dependencyPrompt: 'once' }))
     if (isShownOn(wallpaper.id, screen)) {
       updateWallpaper(wallpaper.id, { appliedCount: (wallpaper.appliedCount ?? 0) + 1, lastAppliedAt: Date.now() })
     }
+  } else if (action.type === 'split') {
+    const slotIds = (getSplitScreens()[screen]?.slots ?? []).map((slot) => slot.wallpaperId)
+    try {
+      // nobody is there to see a launch fail on a drive that is not mounted, so those slots are left out
+      await whileStarting(slotIds, () => showSplitScreen(screen, () => { stopPlaylist(screen) }, 'once', true))
+    } catch (err) {
+      if (!(err instanceof SplitUnavailableError)) throw err
+      console.error(`[Rules] the split on ${screen} can't be shown, going back to its first wallpaper:`, err)
+      await runScreenAction({ type: 'wallpaper', wallpaperId: action.wallpaperId }, screen)
+    }
   } else if (action.type === 'playlist') {
     if (!getPlaylist(action.playlistId)) throw new Error(t('rules.playlistGone'))
     startPlaylist(action.playlistId, screen)
@@ -43,8 +60,7 @@ export async function runScreenAction(action: ScreenAction, screen: ScreenTarget
  * A profile from the other display mode or with a monitor that is gone is not lost: entries for screens that are
  * not there are skipped, and in shared mode (one '*' target) the first of them stands in for all screens
  */
-function profileEntries(profile: Profile): [ScreenTarget, ScreenAction][] {
-  const targets = getDisplayTargets()
+function profileEntries(profile: Profile, targets = getDisplayTargets()): [ScreenTarget, ScreenAction][] {
   const entries = Object.entries(profile.screens)
   const known = entries.filter(([screen]) => screen === '*' || targets.includes(screen))
   if (known.length === 0 && targets.includes('*') && entries.length > 0) known.push(['*', entries[0][1]])
@@ -52,10 +68,10 @@ function profileEntries(profile: Profile): [ScreenTarget, ScreenAction][] {
 }
 
 /** The screens an action touches: a profile names its own, anything else the screen of the rule */
-export function actionScreens(action: ScheduleAction, screen: ScreenTarget): ScreenTarget[] {
-  if (action.type !== 'profile') return expandScreen(screen)
+export function actionScreens(action: ScheduleAction, screen: ScreenTarget, targets = getDisplayTargets()): ScreenTarget[] {
+  if (action.type !== 'profile') return expandScreen(screen, targets)
   const profile = getProfile(action.profileId)
-  return profile ? profileEntries(profile).flatMap(([s]) => expandScreen(s)) : []
+  return profile ? profileEntries(profile, targets).flatMap(([s]) => expandScreen(s, targets)) : []
 }
 
 export async function applyProfile(profileId: string): Promise<void> {

+ 38 - 12
src/main/services/video-tools.service.ts

@@ -300,9 +300,22 @@ function newestAsset(assets: GithubAsset[]): GithubAsset | undefined {
 }
 
 let downloading = false
+let removing = false
+
+function ffmpegFolderBusy(): boolean {
+  return downloading || removing
+}
+
+function optimizeBusy(): boolean {
+  return job !== null || staged !== null || ffmpegFolderBusy()
+}
+
+function downloadedFfmpegBusy(): boolean {
+  return ffmpegFolderBusy() || job !== null || quickRunning
+}
 
 export async function downloadFfmpeg(win: BrowserWindow): Promise<void> {
-  if (downloading) throw new OptimizeError('busy', t('optimize.errBusy'))
+  if (downloadedFfmpegBusy()) throw new OptimizeError('busy', t('optimize.errBusy'))
   downloading = true
   const send = (progress: Omit<OptimizeProgress, 'itemId'>) => {
     if (!win.isDestroyed())
@@ -360,15 +373,22 @@ export async function downloadFfmpeg(win: BrowserWindow): Promise<void> {
     send({ stage: 'error', percentage: 0, message: (err as Error).message })
     throw err
   } finally {
+    // the files of this run are gone before another download may use the same names
+    await fs.promises.rm(archive, { force: true }).catch(() => undefined)
+    await fs.promises.rm(staging, { recursive: true, force: true }).catch(() => undefined)
     downloading = false
-    await fs.promises.rm(archive, { force: true })
-    await fs.promises.rm(staging, { recursive: true, force: true })
   }
 }
 
 export async function removeDownloadedFfmpeg(): Promise<void> {
-  await fs.promises.rm(getFfmpegDir(), { recursive: true, force: true })
-  encoderCache.delete('downloaded')
+  if (downloadedFfmpegBusy()) throw new OptimizeError('busy', t('optimize.errBusy'))
+  removing = true
+  try {
+    await fs.promises.rm(getFfmpegDir(), { recursive: true, force: true })
+    encoderCache.delete('downloaded')
+  } finally {
+    removing = false
+  }
 }
 
 interface FfprobeStream {
@@ -649,8 +669,6 @@ export async function startOptimize(
     return { ...result, skipped: [...new Set([...exclude, ...result.skipped])] }
   } catch (err) {
     if (err instanceof WrongPictureError && options.encoder === 'auto') {
-      // the next encoder's result is what counts, the rejected file would only sit in the folder
-      if (err.kept) await fs.promises.rm(err.kept, { force: true }).catch(() => undefined)
       return startOptimize(id, options, win, [...exclude, err.encoder])
     }
     throw err
@@ -663,11 +681,19 @@ async function runOptimize(
   win: BrowserWindow,
   exclude: HevcEncoder[]
 ): Promise<OptimizeResult> {
-  if (job || staged || downloading) throw new OptimizeError('busy', t('optimize.errBusy'))
+  if (optimizeBusy()) throw new OptimizeError('busy', t('optimize.errBusy'))
   const current: Job = { id, helpers: new Set(), cancelled: quickRunning && quickCancelled }
   job = current
   try {
     return await runOptimizeJob(current, id, options, win, exclude)
+  } catch (err) {
+    if (err instanceof WrongPictureError && options.encoder === 'auto') {
+      // the next encoder's result is what counts, the rejected file would only sit in the folder.
+      // The job is held until then, so nothing can start or be cancelled in between
+      if (err.kept) await fs.promises.rm(err.kept, { force: true }).catch(() => undefined)
+      if (current.cancelled) throw new OptimizeError('cancelled', t('optimize.errCancelled'))
+    }
+    throw err
   } finally {
     job = null
   }
@@ -980,12 +1006,12 @@ let quickCancelled = false
  * listed with the reason. The size never grows: a video that is not larger than the target keeps its size.
  */
 export async function quickOptimize(ids: string[], win: BrowserWindow, trimAnswer = false): Promise<QuickReport> {
-  if (quickRunning) throw new OptimizeError('busy', t('optimize.errBusy'))
-  quickRunning = true
-  quickCancelled = false
+  if (quickRunning || ffmpegFolderBusy()) throw new OptimizeError('busy', t('optimize.errBusy'))
   const report: QuickReport = { lines: [], optimized: 0, savedBytes: 0, originalsKept: false }
   let settings = getVideoToolSettings()
   const trim = settings.trimMode === 'auto' || (settings.trimMode === 'ask' && trimAnswer)
+  quickRunning = true
+  quickCancelled = false
   try {
     const { encoders } = await getVideoToolsStatus()
     if (settings.encoder !== 'auto' && !encoders.some((o) => o.encoder === settings.encoder)) {
@@ -1003,7 +1029,7 @@ export async function quickOptimize(ids: string[], win: BrowserWindow, trimAnswe
       if (!win.isDestroyed()) {
         win.webContents.send(IpcChannels.EVENT_VIDEO_TOOLS_QUICK, { done: index, total: ids.length, id, title })
       }
-      if (job || staged || downloading) {
+      if (optimizeBusy()) {
         skip(t('quick.reasonBusy'))
         continue
       }

+ 11 - 4
src/renderer/src/components/common/CutRangesEditor.tsx

@@ -32,6 +32,9 @@ export function cutProblem(parts: CutPartText[], duration: number): 'range' | 'o
 const SEAM_LEAD = 2
 const SLIDER_STEP = 10
 
+// whole milliseconds, 1.1 * 10 is 11.000000000000002 and would count as a step more
+const toSteps = (seconds: number): number => Math.round(seconds * 1000) / (1000 / SLIDER_STEP)
+
 interface Props {
   parts: CutPartText[]
   duration: number
@@ -48,6 +51,10 @@ export default function CutRangesEditor({ parts, duration, previewUrl, onChange
   const parsed = parseParts(parts)
   const problem = cutProblem(parts, duration)
   const valid = parsed.filter((r): r is CutRange => r !== null && r.end > r.start)
+  const steps = toSteps(duration)
+  const endMax = Math.max(1, Math.ceil(steps))
+  // the end of the video sits on the last step, which can be short of a whole one, any other time on the nearest
+  const endStep = (end: number): number => (Math.abs(end - duration) < 0.001 ? endMax : Math.min(Math.round(toSteps(end)), endMax))
   const kept = valid.reduce((sum, r) => sum + Math.min(r.end, duration) - r.start, 0)
   const validRef = useRef<CutRange[]>([])
   const validKey = valid.map((r) => `${r.start}-${r.end}`).join(',')
@@ -168,7 +175,7 @@ export default function CutRangesEditor({ parts, duration, previewUrl, onChange
           <input
             type="range"
             min={0}
-            max={Math.max(1, Math.floor(duration * SLIDER_STEP))}
+            max={Math.max(1, Math.floor(steps))}
             value={Math.round(part.start * SLIDER_STEP)}
             onChange={(e) => { setPart(index, { start: formatVideoTimeExact(Number(e.target.value) / SLIDER_STEP) }) }}
             className="w-full"
@@ -176,9 +183,9 @@ export default function CutRangesEditor({ parts, duration, previewUrl, onChange
           <input
             type="range"
             min={0}
-            max={Math.max(1, Math.floor(duration * SLIDER_STEP))}
-            value={Math.round(part.end * SLIDER_STEP)}
-            onChange={(e) => { setPart(index, { end: formatVideoTimeExact(Number(e.target.value) / SLIDER_STEP) }) }}
+            max={endMax}
+            value={endStep(part.end)}
+            onChange={(e) => { setPart(index, { end: formatVideoTimeExact(Math.min(Number(e.target.value) / SLIDER_STEP, duration)) }) }}
             className="w-full"
           />
         </>

+ 2 - 2
src/renderer/src/components/common/DetailSidebar.tsx

@@ -57,7 +57,7 @@ import { useConfig, useLweInstalled } from '../../hooks/queries'
 import { useKeyedCommits } from '../../hooks/useKeyedCommits'
 import ScreenSelect from './ScreenSelect'
 import { getPreviewSrc } from '../../utils/preview'
-import { hasEngineFlags } from '@shared/engineFlags'
+import { normalizeWallpaperFlags } from '@shared/engineFlags'
 import EngineFlagsSection from './sidebar/EngineFlagsSection'
 import ImageAdjustmentsSection from './sidebar/ImageAdjustmentsSection'
 import VideoTrimSection from './sidebar/VideoTrimSection'
@@ -660,7 +660,7 @@ export default function DetailSidebar({
     else next.automute = false
     setTogglingAutomute(true)
     try {
-      await persistAndMaybeRelaunch({ engineFlags: hasEngineFlags(next) ? next : undefined })
+      await persistAndMaybeRelaunch({ engineFlags: normalizeWallpaperFlags(next) })
     } finally {
       setTogglingAutomute(false)
     }

+ 10 - 7
src/renderer/src/components/common/sidebar/EngineFlagsSection.tsx

@@ -1,14 +1,14 @@
 import { useState } from 'react'
 import { Gauge, TriangleAlert } from 'lucide-react'
-import type { EngineFlags, FullscreenPauseMode, WallpaperMeta } from '@shared/types'
-import { hasEngineFlags } from '@shared/engineFlags'
+import type { EngineFlags, FullscreenPauseMode, WallpaperEngineFlags, WallpaperMeta } from '@shared/types'
+import { hasEngineFlags, normalizeWallpaperFlags } from '@shared/engineFlags'
 import { BOOLEAN_FLAGS, CHOICE_FLAGS, FULLSCREEN_PAUSE_OPTIONS, optionLabel, presetName } from '../../../constants/engineFlags'
 import { useConfig } from '../../../hooks/queries'
 import { t } from '../../../i18n'
 import SidebarSection, { CustomBadge } from './SidebarSection'
 
 interface Props {
-  flags?: EngineFlags
+  flags?: WallpaperEngineFlags
   onChange: (patch: Pick<WallpaperMeta, 'engineFlags' | 'fpsOverride'>) => Promise<void>
 }
 
@@ -33,18 +33,21 @@ export default function EngineFlagsSection({ flags = {}, onChange }: Props) {
     }
   }
 
-  function setFlag<K extends keyof EngineFlags>(key: K, value: EngineFlags[K] | undefined) {
+  function setFlag<K extends keyof WallpaperEngineFlags>(key: K, value: WallpaperEngineFlags[K] | undefined) {
     const next = { ...flags, [key]: value }
     if (value === undefined) delete next[key]
-    void commit({ engineFlags: hasEngineFlags(next) ? next : undefined })
+    void commit({ engineFlags: normalizeWallpaperFlags(next) })
   }
 
   function applyPreset(id: string) {
     const preset = presets.find((p) => p.id === id)
     if (!preset) return
-    const patch: Pick<WallpaperMeta, 'engineFlags' | 'fpsOverride'> = { engineFlags: { ...flags, ...preset.flags } }
+    const presetFlags = normalizeWallpaperFlags(preset.flags)
+    // engine flags in a patch restart a playing engine, so they only go in when the preset has some for a wallpaper
+    const patch: Pick<WallpaperMeta, 'engineFlags' | 'fpsOverride'> = {}
+    if (presetFlags) patch.engineFlags = { ...flags, ...presetFlags }
     if (preset.fps !== undefined) patch.fpsOverride = preset.fps ?? undefined
-    void commit(patch)
+    if (Object.keys(patch).length > 0) void commit(patch)
   }
 
   return (

+ 2 - 2
src/renderer/src/components/settings/AutomuteIgnoreSettings.tsx

@@ -1,7 +1,7 @@
 import { useQueryClient } from '@tanstack/react-query'
 import { BellOff, X } from 'lucide-react'
 import { useAllWallpapers, useConfig } from '../../hooks/queries'
-import { hasEngineFlags } from '@shared/engineFlags'
+import { normalizeWallpaperFlags } from '@shared/engineFlags'
 import { t } from '../../i18n'
 
 export default function AutomuteIgnoreSettings() {
@@ -16,7 +16,7 @@ export default function AutomuteIgnoreSettings() {
     if (!wallpaper) return
     const next = { ...wallpaper.engineFlags }
     delete next.automute
-    await window.electronAPI.library.update(id, { engineFlags: hasEngineFlags(next) ? next : undefined })
+    await window.electronAPI.library.update(id, { engineFlags: normalizeWallpaperFlags(next) })
     void queryClient.invalidateQueries({ queryKey: ['library'] })
   }
 

+ 2 - 12
src/renderer/src/constants/engineFlags.ts

@@ -1,5 +1,6 @@
 import type { EngineFlagPreset, EngineFlags, FullscreenPauseMode } from '@shared/types'
 import type { MessageKey } from '@shared/i18n'
+import type { GlobalOnlyFlag } from '@shared/engineFlags'
 import { t } from '../i18n'
 
 type ChoiceFlag =
@@ -16,18 +17,7 @@ type ChoiceFlag =
   | 'transitionDuration'
   | 'batteryFps'
   | 'idlePause'
-// kdeBackgroundLayer, windowed and windowBackground are global only
-type BooleanFlag = Exclude<
-  keyof EngineFlags,
-  | 'fullscreenPause'
-  | 'kdeBackgroundLayer'
-  | 'windowed'
-  | 'windowBackground'
-  | 'audioInput'
-  | 'audioInputVolume'
-  | 'audioInputThreshold'
-  | ChoiceFlag
->
+type BooleanFlag = Exclude<keyof EngineFlags, 'fullscreenPause' | GlobalOnlyFlag | ChoiceFlag>
 
 export const BOOLEAN_FLAGS: { key: BooleanFlag; label: MessageKey; hint?: MessageKey }[] = [
   { key: 'disableParticles', label: 'flags.disableParticles.label', hint: 'flags.disableParticles.hint' },

+ 35 - 1
src/shared/engineFlags.test.ts

@@ -1,5 +1,5 @@
 import { describe, expect, it } from 'vitest'
-import { engineFlagArgs, filterSupportedArgs, hasEngineFlags, resolveEngineFlags } from './engineFlags'
+import { engineFlagArgs, filterSupportedArgs, hasEngineFlags, normalizeWallpaperFlags, resolveEngineFlags, withoutGlobalOnlyFlags } from './engineFlags'
 
 describe('resolveEngineFlags', () => {
   it('lets a wallpaper override the global flags, unset ones fall through', () => {
@@ -11,6 +11,40 @@ describe('resolveEngineFlags', () => {
   })
 })
 
+describe('withoutGlobalOnlyFlags', () => {
+  it('drops the settings of the whole engine and keeps the other flags', () => {
+    expect(
+      withoutGlobalOnlyFlags({
+        silent: true,
+        audioInput: 'usb-mic',
+        audioInputVolume: 70,
+        audioInputThreshold: 10,
+        windowed: true,
+        windowBackground: true,
+        kdeBackgroundLayer: true
+      })
+    ).toEqual({ silent: true })
+  })
+
+  it('keeps a wallpaper from overriding them or counting as customized because of them', () => {
+    expect(resolveEngineFlags({ audioInput: 'monitor', windowed: false }, { audioInput: 'usb-mic', windowed: true, silent: true })).toEqual({
+      audioInput: 'monitor',
+      windowed: false,
+      silent: true
+    })
+    expect(hasEngineFlags({ audioInput: 'usb-mic', windowed: true })).toBe(false)
+    expect(hasEngineFlags({ silent: false })).toBe(true)
+  })
+})
+
+describe('normalizeWallpaperFlags', () => {
+  it('keeps what a wallpaper may have and nothing when that is all gone', () => {
+    expect(normalizeWallpaperFlags({ silent: true, windowed: true })).toEqual({ silent: true })
+    expect(normalizeWallpaperFlags({ windowed: true, audioInput: 'usb-mic' })).toBeUndefined()
+    expect(normalizeWallpaperFlags({ silent: undefined })).toBeUndefined()
+  })
+})
+
 describe('engineFlagArgs', () => {
   it('maps flags to linux-wallpaperengine arguments', () => {
     expect(

+ 25 - 3
src/shared/engineFlags.ts

@@ -1,4 +1,4 @@
-import type { EngineFlagPreset, EngineFlags } from './types'
+import type { EngineFlagPreset, EngineFlags, WallpaperEngineFlags } from './types'
 
 export const BUILT_IN_PRESETS: EngineFlagPreset[] = [
   {
@@ -60,9 +60,31 @@ export const BUILT_IN_PRESETS: EngineFlagPreset[] = [
   }
 ]
 
+export const GLOBAL_ONLY_FLAGS = [
+  'audioInput',
+  'audioInputVolume',
+  'audioInputThreshold',
+  'windowed',
+  'windowBackground',
+  'kdeBackgroundLayer'
+] as const satisfies readonly (keyof EngineFlags)[]
+
+export type GlobalOnlyFlag = (typeof GLOBAL_ONLY_FLAGS)[number]
+
+export function withoutGlobalOnlyFlags(flags: EngineFlags): WallpaperEngineFlags {
+  const rest = { ...flags }
+  for (const key of GLOBAL_ONLY_FLAGS) delete rest[key]
+  return rest
+}
+
+export function normalizeWallpaperFlags(flags: EngineFlags): WallpaperEngineFlags | undefined {
+  const rest = withoutGlobalOnlyFlags(flags)
+  return Object.values(rest).some((value) => value !== undefined) ? rest : undefined
+}
+
 export function resolveEngineFlags(global: EngineFlags, wallpaper?: EngineFlags): EngineFlags {
   const resolved: EngineFlags = { ...global }
-  for (const [key, value] of Object.entries(wallpaper ?? {})) {
+  for (const [key, value] of Object.entries(wallpaper ? withoutGlobalOnlyFlags(wallpaper) : {})) {
     if (value !== undefined) (resolved as Record<string, unknown>)[key] = value
   }
   return resolved
@@ -121,5 +143,5 @@ export function filterSupportedArgs(args: string[], supports: (flag: string) =>
 }
 
 export function hasEngineFlags(flags: EngineFlags | undefined): boolean {
-  return !!flags && Object.values(flags).some((v) => v !== undefined)
+  return !!flags && normalizeWallpaperFlags(flags) !== undefined
 }

+ 13 - 3
src/shared/types.ts

@@ -2,6 +2,7 @@ import type { ImageAdjustments } from './imageAdjustments'
 import type { VideoSegment } from './videoTrim'
 import type { DesktopEnvironment } from './desktop'
 import type { Appearance } from './appearance'
+import type { GlobalOnlyFlag } from './engineFlags'
 import type { Language, LanguagePreference } from './i18n'
 import type { CardBorders } from './cardBorders'
 import type { CardBadges } from './cardBadges'
@@ -166,7 +167,7 @@ export interface WallpaperMeta {
   /** Extra launch arguments, changing them always restarts the engine */
   customArgs?: string
   /** Unset flags fall back to the global setting */
-  engineFlags?: EngineFlags
+  engineFlags?: WallpaperEngineFlags
   compat?: WallpaperCompat
   /** Scene with general.hdr on, or a PQ/HLG video. Unset until detected */
   hdr?: boolean
@@ -254,6 +255,9 @@ export interface EngineFlags {
   kdeBackgroundLayer?: boolean
 }
 
+/** What a wallpaper can override: the flags of a whole session are not per wallpaper */
+export type WallpaperEngineFlags = Omit<EngineFlags, GlobalOnlyFlag>
+
 export interface EngineFlagPreset {
   id: string
   name: string
@@ -316,12 +320,18 @@ export interface SplitScreen {
   slots: SplitSlot[]
 }
 
-export type ScreenAction =
+type PickedAction =
   | { type: 'wallpaper'; wallpaperId: string }
   | { type: 'playlist'; playlistId: string }
   | { type: 'stop' }
 
-export type ScheduleAction = ScreenAction | { type: 'profile'; profileId: string }
+/**
+ * What a screen can go back to: a captured screen may also have been a split, which is not a choice in the editors.
+ * It goes back to the screen's split as configured then, wallpaperId is its first slot, shown instead when it can't be shown any more
+ */
+export type ScreenAction = PickedAction | { type: 'split'; wallpaperId: string }
+
+export type ScheduleAction = PickedAction | { type: 'profile'; profileId: string }
 
 export interface Profile {
   id: string