瀏覽代碼

Ask on card Play, and leave a screen that changed while restoring

Card Play uses the same screen question as the other Play buttons. All screens stays the default. Esc cancels, and Tab stays in the dialog.

Applying one wallpaper clears that screen's split, so the next start does not bring the split back just because the wallpaper is its first slot.

Restore checks each screen again before launching it. A screen whose assignment changed, or that was launched or stopped while an earlier screen was starting, is left as it is. A missing dependency on that path is skipped instead of opening a dialog.

The don't-resume hint says those screens stay blank after a restart.
Lennydev 3 周之前
父節點
當前提交
b9b7412b33

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

+ 35 - 8
src/main/services/display.service.ts

@@ -30,12 +30,22 @@ import {
 } from './lwe.service'
 } from './lwe.service'
 import { resolveEngineFlags } from '@shared/engineFlags'
 import { resolveEngineFlags } from '@shared/engineFlags'
 import { clearAssignment, getAssignments, setAssignment } from './wallpaper-state.service'
 import { clearAssignment, getAssignments, setAssignment } from './wallpaper-state.service'
-import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens } from './config.service'
-import { planRestore } from './restore-plan'
+import { getDefaultFps, getDisplayMode, getGlobalEngineFlags, getSplitScreens, setSplitScreen } from './config.service'
+import { planRestore, restoreSuperseded } from './restore-plan'
 import { ensureDependencyInstalled } from './dependency.service'
 import { ensureDependencyInstalled } from './dependency.service'
 import { t } from '../i18n'
 import { t } from '../i18n'
 
 
 const LAUNCH_CHECK_MS = 20_000
 const LAUNCH_CHECK_MS = 20_000
+// bumped when a screen is launched or stopped, so a later restore does not replace that
+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
 // automatic relaunches after a runtime crash, at most one per screen in this window
 const RELAUNCH_COOLDOWN_MS = 60_000
 const RELAUNCH_COOLDOWN_MS = 60_000
 
 
@@ -124,7 +134,7 @@ export async function showWallpaper(
   options: {
   options: {
     volume?: number
     volume?: number
     backend?: WallpaperBackend
     backend?: WallpaperBackend
-    dependencyPrompt?: 'always' | 'once'
+    dependencyPrompt?: 'always' | 'once' | 'never'
     forceFresh?: boolean
     forceFresh?: boolean
   } = {}
   } = {}
 ): Promise<string> {
 ): Promise<string> {
@@ -133,8 +143,12 @@ export async function showWallpaper(
 
 
   let appliedPath = ''
   let appliedPath = ''
   for (const target of targets) {
   for (const target of targets) {
+    markScreenUsed(target)
     appliedPath = await applyWallpaperMeta(wallpaper, { ...options, screen: target })
     appliedPath = await applyWallpaperMeta(wallpaper, { ...options, screen: target })
     setAssignment(target, wallpaper.id)
     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
     // only a wallpaper that crashed on launch before needs its fresh launches watched
     if (wallpaper.compat?.freshLaunch === 'crash') watchLaunch(wallpaper.id, target)
     if (wallpaper.compat?.freshLaunch === 'crash') watchLaunch(wallpaper.id, target)
   }
   }
@@ -143,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 */
 /** 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 (getDisplayMode() !== 'per-screen' || screen === ALL_SCREENS) throw new Error(t('split.needsPerScreen'))
   if (!getDisplayTargets().includes(screen)) throw new Error(`Screen ${screen} is not connected`)
   if (!getDisplayTargets().includes(screen)) throw new Error(`Screen ${screen} is not connected`)
   if (!supportsSplitScreens()) throw new Error(t('split.engineTooOld'))
   if (!supportsSplitScreens()) throw new Error(t('split.engineTooOld'))
@@ -154,7 +172,7 @@ export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () =>
   for (const slot of split?.slots ?? []) {
   for (const slot of split?.slots ?? []) {
     const wallpaper = getWallpaper(slot.wallpaperId)
     const wallpaper = getWallpaper(slot.wallpaperId)
     if (!wallpaper?.localPath || !isAnimatedWallpaper(wallpaper) || !wallpaperIsOnDisk(wallpaper.localPath)) continue
     if (!wallpaper?.localPath || !isAnimatedWallpaper(wallpaper) || !wallpaperIsOnDisk(wallpaper.localPath)) continue
-    await ensureDependencyInstalled(wallpaper)
+    await ensureDependencyInstalled(wallpaper, dependencyPrompt)
     slots.push({
     slots.push({
       path: wallpaper.localPath,
       path: wallpaper.localPath,
       scalingMode: slot.scalingMode ?? wallpaper.scalingMode,
       scalingMode: slot.scalingMode ?? wallpaper.scalingMode,
@@ -167,6 +185,7 @@ export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () =>
     shown.push(wallpaper)
     shown.push(wallpaper)
   }
   }
   if (slots.length === 0 || !split) throw new Error(t('split.empty'))
   if (slots.length === 0 || !split) throw new Error(t('split.empty'))
+  markScreenUsed(screen)
   beforeLaunch?.()
   beforeLaunch?.()
 
 
   // overrides would hit every slot by id, so slots play as published
   // overrides would hit every slot by id, so slots play as published
@@ -182,6 +201,7 @@ export async function showSplitScreen(screen: ScreenTarget, beforeLaunch?: () =>
 }
 }
 
 
 export async function stopDisplay(screen?: ScreenTarget): Promise<void> {
 export async function stopDisplay(screen?: ScreenTarget): Promise<void> {
+  for (const target of expandScreen(screen)) markScreenUsed(target)
   if (screen === undefined || screen === ALL_SCREENS) {
   if (screen === undefined || screen === ALL_SCREENS) {
     await stopLwe()
     await stopLwe()
     clearAssignment()
     clearAssignment()
@@ -342,9 +362,11 @@ function splitSlotId(screen: ScreenTarget): string | null {
  */
  */
 export async function restoreAssignedWallpapers(skipScreens: ReadonlySet<ScreenTarget> = new Set()): Promise<void> {
 export async function restoreAssignedWallpapers(skipScreens: ReadonlySet<ScreenTarget> = new Set()): Promise<void> {
   if (!getLweStatus().installed) return
   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 targets = new Set(getDisplayTargets())
   const running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
   const running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
-  for (const [screen, wallpaperId] of Object.entries(getAssignments())) {
+  for (const [screen, wallpaperId] of Object.entries(saved)) {
     const wallpaper = getWallpaper(wallpaperId)
     const wallpaper = getWallpaper(wallpaperId)
     const localPath = wallpaper?.localPath ?? ''
     const localPath = wallpaper?.localPath ?? ''
     const inst = running.get(screen)
     const inst = running.get(screen)
@@ -359,13 +381,18 @@ export async function restoreAssignedWallpapers(skipScreens: ReadonlySet<ScreenT
       wallpaperId
       wallpaperId
     })
     })
     if (plan === 'skip' || !wallpaper) continue
     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 {
     try {
       if (plan === 'split') {
       if (plan === 'split') {
         console.log(`[Display] Restoring split on ${screen}`)
         console.log(`[Display] Restoring split on ${screen}`)
-        await showSplitScreen(screen)
+        await showSplitScreen(screen, undefined, 'never')
       } else {
       } else {
         console.log(`[Display] Restoring ${wallpaper.title} on ${screen}`)
         console.log(`[Display] Restoring ${wallpaper.title} on ${screen}`)
-        await showWallpaper(wallpaper, screen, { dependencyPrompt: 'once' })
+        await showWallpaper(wallpaper, screen, { dependencyPrompt: 'never' })
       }
       }
     } catch (err) {
     } catch (err) {
       console.error(`[Display] Could not restore ${wallpaper?.title ?? wallpaperId} on ${screen}:`, (err as Error).message)
       console.error(`[Display] Could not restore ${wallpaper?.title ?? wallpaperId} on ${screen}:`, (err as Error).message)

+ 19 - 1
src/main/services/restore-plan.test.ts

@@ -1,5 +1,5 @@
 import { describe, expect, it } from 'vitest'
 import { describe, expect, it } from 'vitest'
-import { mergeSkipScreens, planRestore, playlistSkipScreens, type RestoreInput } from './restore-plan'
+import { mergeSkipScreens, planRestore, playlistSkipScreens, restoreSuperseded, type RestoreInput } from './restore-plan'
 
 
 function input(patch: Partial<RestoreInput> = {}): RestoreInput {
 function input(patch: Partial<RestoreInput> = {}): RestoreInput {
   return {
   return {
@@ -58,6 +58,24 @@ describe('playlistSkipScreens', () => {
   })
   })
 })
 })
 
 
+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', () => {
 describe('mergeSkipScreens', () => {
   it('keeps playlist, autostart and schedule screens together', () => {
   it('keeps playlist, autostart and schedule screens together', () => {
     expect([...mergeSkipScreens(['HDMI-A-2'], ['*'], ['HDMI-A-3'])]).toEqual(['HDMI-A-2', '*', 'HDMI-A-3'])
     expect([...mergeSkipScreens(['HDMI-A-2'], ['*'], ['HDMI-A-3'])]).toEqual(['HDMI-A-2', '*', 'HDMI-A-3'])

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

@@ -30,3 +30,13 @@ export function playlistSkipScreens(skipResume: boolean, saved: readonly string[
 export function mergeSkipScreens(...groups: readonly (readonly string[])[]): Set<string> {
 export function mergeSkipScreens(...groups: readonly (readonly string[])[]): Set<string> {
   return new Set(groups.flat())
   return new Set(groups.flat())
 }
 }
+
+/** True when something else took the screen after restore read it. The newer launch stays. */
+export function restoreSuperseded(
+  assignedAtStart: string,
+  assignedNow: string | undefined,
+  useAtStart: number,
+  useNow: number
+): boolean {
+  return assignedNow !== assignedAtStart || useNow !== useAtStart
+}

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

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

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

@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'
 import type { ScreenTarget } from '@shared/types'
 import type { ScreenTarget } from '@shared/types'
 import { CARD_PLAY_DEFAULT_SCREEN } from '@shared/playScreen'
 import { CARD_PLAY_DEFAULT_SCREEN } from '@shared/playScreen'
 import { t } from '../../i18n'
 import { t } from '../../i18n'
@@ -20,6 +20,7 @@ export function askPlayScreen(targets: ScreenTarget[]): Promise<ScreenTarget | n
 export default function PlayScreenPrompt() {
 export default function PlayScreenPrompt() {
   const [pending, setPending] = useState<Pending | null>(null)
   const [pending, setPending] = useState<Pending | null>(null)
   const [value, setValue] = useState<ScreenTarget>(CARD_PLAY_DEFAULT_SCREEN)
   const [value, setValue] = useState<ScreenTarget>(CARD_PLAY_DEFAULT_SCREEN)
+  const dialogRef = useRef<HTMLDivElement>(null)
 
 
   useEffect(() => {
   useEffect(() => {
     openPrompt = (targets) => new Promise((resolve) => {
     openPrompt = (targets) => new Promise((resolve) => {
@@ -29,17 +30,48 @@ export default function PlayScreenPrompt() {
     return () => { openPrompt = null }
     return () => { openPrompt = null }
   }, [])
   }, [])
 
 
-  if (!pending) return null
-
   function finish(screen: ScreenTarget | null) {
   function finish(screen: ScreenTarget | null) {
     pending?.resolve(screen)
     pending?.resolve(screen)
     setPending(null)
     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 (
   return (
     <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-8">
     <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-8">
-      <div className="w-full max-w-sm rounded-xl border border-fg/10 bg-popup p-4 shadow-2xl">
-        <h3 className="text-sm font-semibold text-gray-100">{t('playlist.whichScreen')}</h3>
+      <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">
         <div className="mt-3">
           <ScreenSelect targets={pending.targets} value={value} onChange={setValue} title={t('playlist.whichScreen')} />
           <ScreenSelect targets={pending.targets} value={value} onChange={setValue} title={t('playlist.whichScreen')} />
         </div>
         </div>

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

@@ -23,6 +23,7 @@ import {
   SteamAction
   SteamAction
 } from '../common/GridCard'
 } from '../common/GridCard'
 import { t, tagLabel } from '../../i18n'
 import { t, tagLabel } from '../../i18n'
+import { useApplyWallpaper } from '../../hooks/useWallpaperActions'
 
 
 interface WallpaperCardProps {
 interface WallpaperCardProps {
   wallpaper: WallpaperMeta
   wallpaper: WallpaperMeta
@@ -56,6 +57,7 @@ export default function WallpaperCard({
   onContextMenu
   onContextMenu
 }: WallpaperCardProps) {
 }: WallpaperCardProps) {
   const { showToast } = useToast()
   const { showToast } = useToast()
+  const applyWallpaper = useApplyWallpaper()
   const queryClient = useQueryClient()
   const queryClient = useQueryClient()
   const [isApplying, setIsApplying] = useState(false)
   const [isApplying, setIsApplying] = useState(false)
   const [unsubState, setUnsubState] = useState<'idle' | 'confirm' | 'pending'>('idle')
   const [unsubState, setUnsubState] = useState<'idle' | 'confirm' | 'pending'>('idle')
@@ -106,10 +108,8 @@ export default function WallpaperCard({
     setIsApplying(true)
     setIsApplying(true)
     setError(null)
     setError(null)
     try {
     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 {
     } finally {
       setIsApplying(false)
       setIsApplying(false)
     }
     }

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

@@ -846,6 +846,7 @@ function SettingsPanels({ onReset }: { onReset: () => void }) {
                   <Toggle on={skipPlaylistResume} onClick={() => void handleSkipPlaylistResumeToggle()} />
                   <Toggle on={skipPlaylistResume} onClick={() => void handleSkipPlaylistResumeToggle()} />
                   <span className="text-sm text-gray-300">{t('settings.skipPlaylistResume')}</span>
                   <span className="text-sm text-gray-300">{t('settings.skipPlaylistResume')}</span>
                 </label>
                 </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">
                 <label className="mt-3 flex items-center gap-3 cursor-pointer">
                   <Toggle on={freshProcessOnPathChange} onClick={() => void handleFreshProcessToggle()} />
                   <Toggle on={freshProcessOnPathChange} onClick={() => void handleFreshProcessToggle()} />
                   <span className="text-sm text-gray-300">{t('settings.freshProcessOnPathChange')}</span>
                   <span className="text-sm text-gray-300">{t('settings.freshProcessOnPathChange')}</span>

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

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