Kaynağa Gözat

Keep mute and bring the last wallpaper back after a restart

Hotswapping a different wallpaper left the previous audio running, and the new wallpaper often stayed blank until something else changed, such as moving it. A path change now starts a new engine process. Volume 0 is included in that swap, so a muted wallpaper stays muted when it is applied on another screen.

The volume slider ignored its own 100% event. That event fired when the panel re-rendered and overwrote a real 0, so the slider did nothing until it was muted and dragged back to 100%.

Assigned wallpapers are launched again on startup. A live engine already showing the same wallpaper is left alone, and a screen a playlist just resumed is left to the playlist.

Play from a card in per-screen mode asks which screen to use.
Lennydev 3 hafta önce
ebeveyn
işleme
337525f112

+ 3 - 2
src/main/index.ts

@@ -11,9 +11,9 @@ import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.
 import { getTrayEnabled, getAutostartEnabled, getAutostartMinimized, getAutostartPlaylistId, getKillLweOnQuit, getConfiguredBackupPath } from './services/config.service'
 import { refreshAutostartExec } from './services/autostart.service'
 import { createTray } from './services/tray.service'
-import { initPlaylistPlayer, startPlaylist } from './services/playlist-player.service'
+import { activePlaylistScreens, initPlaylistPlayer, startPlaylist } from './services/playlist-player.service'
 import { checkEarlierRunEngines, killAllLweProcesses, getLweStatus } from './services/lwe.service'
-import { initDisplay } from './services/display.service'
+import { initDisplay, restoreAssignedWallpapers } from './services/display.service'
 import { initSchedule } from './services/schedule.service'
 import { initUpdates } from './services/update.service'
 import { detectDesktopEnv, hasStatusNotifierHost } from './utils/platform'
@@ -244,6 +244,7 @@ app.whenReady().then(async () => {
   await checkEarlierRunEngines()
   initDisplay(win)
   const resumed = initPlaylistPlayer(win)
+  await restoreAssignedWallpapers(new Set(activePlaylistScreens()))
 
   if (getTrayEnabled()) createTray(win)
 

+ 34 - 3
src/main/ipc/wallpaper.handlers.ts

@@ -14,10 +14,30 @@ import {
   testFreshLaunch
 } from '../services/display.service'
 import type { ApplyWallpaperOptions, ScreenTarget, SplitScreen } from '@shared/types'
-import { setSplitScreen } from '../services/config.service'
+import { getDisplayMode, setSplitScreen } from '../services/config.service'
+import { ALL_SCREENS } from '../services/lwe.service'
 import { deleteThumbnail, generateThumbnail, IMAGE_EXTENSIONS, useThumbnailFile } from '../services/thumbnail.service'
 import { t } from '../i18n'
 
+/** null means the user cancelled. undefined means every screen. */
+async function askWhichScreen(targets: ScreenTarget[]): Promise<ScreenTarget | undefined | null> {
+  const buttons = [...targets, t('common.allScreens'), t('common.cancel')]
+  const cancelId = buttons.length - 1
+  const parent = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0]
+  const box = {
+    type: 'question' as const,
+    title: t('playlist.whichScreen'),
+    message: t('playlist.whichScreen'),
+    buttons,
+    defaultId: 0,
+    cancelId
+  }
+  const { response } = parent ? await dialog.showMessageBox(parent, box) : await dialog.showMessageBox(box)
+  if (response === cancelId || response < 0) return null
+  if (response < targets.length) return targets[response]
+  return undefined
+}
+
 export function registerWallpaperHandlers(): void {
   ipcMain.handle(IpcChannels.WALLPAPER_DETECT_ENV, () => {
     return detectEnvironment()
@@ -36,10 +56,21 @@ export function registerWallpaperHandlers(): void {
     const wallpaper = getWallpaper(options.wallpaperId)
     if (!wallpaper) throw new Error(`Wallpaper ${options.wallpaperId} not found in library`)
 
+    // the detail panel already picked a screen. Play from a card has not, and per-screen mode asks.
+    let screen = options.screen
+    if ((screen === undefined || screen === null) && getDisplayMode() === 'per-screen') {
+      const targets = expandScreen(undefined).filter((name) => name !== ALL_SCREENS)
+      if (targets.length > 1) {
+        const chosen = await askWhichScreen(targets)
+        if (chosen === null) return { ok: false, appliedPath: '' }
+        screen = chosen
+      }
+    }
+
     // a playlist would replace it again on its next switch
-    for (const screen of expandScreen(options.screen)) pausePlaylist(screen)
+    for (const target of expandScreen(screen)) pausePlaylist(target)
 
-    const appliedPath = await showWallpaper(wallpaper, options.screen, { backend: options.backend })
+    const appliedPath = await showWallpaper(wallpaper, screen, { backend: options.backend })
 
     updateWallpaper(options.wallpaperId, {
       appliedCount: (wallpaper.appliedCount ?? 0) + 1,

+ 25 - 0
src/main/services/display.service.ts

@@ -15,6 +15,7 @@ import { applyWallpaperMeta, isAnimatedWallpaper } from './wallpaper.service'
 import {
   ALL_SCREENS,
   getActiveScreens,
+  getLweStatus,
   getRunningInstances,
   hotswapLweSettings,
   launchLweAsync,
@@ -308,3 +309,27 @@ export function initDisplay(window: BrowserWindow): void {
     void handleExit(info).catch((err: unknown) => { console.error('[Display] Crash handling failed:', err) })
   })
 }
+
+/**
+ * Puts the last wallpaper back on each screen after a restart. A live engine already showing it is left
+ * alone. Screens a playlist just claimed are skipped so the two restores do not launch over each other.
+ */
+export async function restoreAssignedWallpapers(skipScreens: ReadonlySet<ScreenTarget> = new Set()): Promise<void> {
+  if (!getLweStatus().installed) return
+  const targets = new Set(getDisplayTargets())
+  const running = new Map(getRunningInstances().map((inst) => [inst.screen, inst]))
+  for (const [screen, wallpaperId] of Object.entries(getAssignments())) {
+    if (skipScreens.has(screen) || !targets.has(screen)) continue
+    const wallpaper = getWallpaper(wallpaperId)
+    if (!wallpaper?.localPath) continue
+    const inst = running.get(screen)
+    // same wallpaper, still on this screen: nothing to reload
+    if (inst && !inst.split && inst.wallpaperPath === wallpaper.localPath) continue
+    try {
+      console.log(`[Display] Restoring ${wallpaper.title} on ${screen}`)
+      await showWallpaper(wallpaper, screen, { dependencyPrompt: 'once', forceFresh: !inst })
+    } catch (err) {
+      console.error(`[Display] Could not restore ${wallpaper.title} on ${screen}:`, (err as Error).message)
+    }
+  }
+}

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

@@ -27,6 +27,7 @@ const {
   buildLweEnvVars,
   buildHotswapLines,
   buildLweArgs,
+  hotswapOptionsFor,
   lwePackageOwner,
   nodeDevelPackage,
   parsePacmanRepos,
@@ -171,6 +172,10 @@ describe('buildHotswapLines', () => {
     ])
   })
 
+  it('keeps a muted wallpaper muted when the swap is built', () => {
+    expect(buildHotswapLines(hotswapOptionsFor('/w/quiet', { volume: 0, soundVolume: { '7': 0 } }))).toContain('volume=0')
+  })
+
   it('writes a full wallpaper swap in the order the engine expects', () => {
     expect(
       buildHotswapLines({

+ 7 - 2
src/main/services/lwe.service.ts

@@ -1726,7 +1726,7 @@ export function liveEngineFlagOptions(
   }
 }
 
-function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): HotswapOptions {
+export function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): HotswapOptions {
   const defaultSensitivity = getDefaultAudioSensitivity()
   return {
     path: wallpaperPath,
@@ -1753,6 +1753,9 @@ function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): Ho
       ...options.audioSensitivity
     },
     soundVolume: options.soundVolume ?? {},
+    // 0 must be sent. Leaving volume out keeps the previous wallpaper's level, so a muted wallpaper
+    // comes back audible when it is applied to another screen.
+    ...(options.volume !== undefined ? { volume: options.volume } : {}),
     ...(supportsEffectHotswap()
       ? { disabledEffects: options.disabledEffects ?? [], enabledEffects: options.enabledEffects ?? [] }
       : {}),
@@ -1772,8 +1775,10 @@ export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOp
   }
 
   const existing = liveInstance(screen)
+  // A different wallpaper has to be a new process. Hotswapping the path leaves the previous
+  // wallpaper's audio playing, and the new one often does not start until a later change (such as moving it).
   const canHotswap =
-    existing &&
+    existing?.wallpaperPath === wallpaperPath &&
     !options.forceFresh &&
     !options.customArgs?.trim() &&
     existing.launchKey === key &&

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

@@ -382,6 +382,11 @@ function savedPlayers(): Record<ScreenTarget, SavedPlayer> {
   return legacyId ? { [ALL_SCREENS]: { playlistId: legacyId, isPlaying: store.get('isPlaying') } } : {}
 }
 
+/** Screens a playlist owns after init, so wallpaper restore does not launch over them */
+export function activePlaylistScreens(): ScreenTarget[] {
+  return [...players.values()].filter((player) => player.state.playlistId).map((player) => player.state.screen)
+}
+
 /** Resumes the playlists active at the last close, true if any (the autostart playlist is then skipped) */
 
 export function initPlaylistPlayer(window: BrowserWindow): boolean {

+ 28 - 4
src/renderer/src/components/common/DetailSidebar.tsx

@@ -708,9 +708,13 @@ export default function DetailSidebar({
 
   const [volumeDraft, setVolumeDraft] = useState<number | null>(null)
   const [isCommittingVolume, setIsCommittingVolume] = useState(false)
+  // the range input emits its max (100%) on its own when the panel re-renders, which turned a muted wallpaper back on
+  const volumeDragging = useRef(false)
+  const volumeLive = useRef<number | null>(null)
   const volume = volumeDraft ?? libraryMeta?.volumeOverride ?? 15
 
   async function commitVolume(v: number) {
+    volumeDragging.current = false
     setIsCommittingVolume(true)
     try {
       await persistAndMaybeRelaunch({ volumeOverride: v })
@@ -1355,15 +1359,35 @@ export default function DetailSidebar({
               max={128}
               value={volume}
               disabled={isCommittingVolume}
+              onPointerDown={(e) => {
+                volumeDragging.current = true
+                e.currentTarget.setPointerCapture(e.pointerId)
+              }}
+              onKeyDown={(e) => {
+                if (isRangeKey(e.key)) volumeDragging.current = true
+              }}
               onChange={(e) => {
+                if (!volumeDragging.current) return
                 const v = Number(e.target.value)
+                if (!Number.isFinite(v)) return
+                volumeLive.current = v
                 setVolumeDraft(v)
                 previewLive({ volume: v })
               }}
-              onMouseUp={(e) => void commitVolume(Number(e.currentTarget.value))}
-              onTouchEnd={(e) => void commitVolume(Number(e.currentTarget.value))}
-              onKeyUp={(e) => void (isRangeKey(e.key) && commitVolume(Number(e.currentTarget.value)))}
-              className="w-full accent-accent-500 disabled:opacity-50"
+              onPointerUp={() => {
+                const v = volumeLive.current
+                volumeLive.current = null
+                volumeDragging.current = false
+                if (v !== null) void commitVolume(v)
+              }}
+              onKeyUp={(e) => {
+                if (!isRangeKey(e.key)) return
+                const v = volumeLive.current ?? Number(e.currentTarget.value)
+                volumeLive.current = null
+                volumeDragging.current = false
+                if (Number.isFinite(v)) void commitVolume(v)
+              }}
+              className="w-full touch-none accent-accent-500 disabled:opacity-50"
             />
           </div>
         )}