Переглянути джерело

added check for newer versions and option to rebackup the new version, added hdr badge to hdr wallpapers

UwU 1 місяць тому
батько
коміт
caf39daa10

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "we-manager",
-  "version": "0.7.4",
+  "version": "0.7.5",
   "type": "module",
   "description": "Wallpaper Engine workshop manager",
   "author": "UwU <260361707+WallpaperEngineLover@users.noreply.github.com>",

+ 20 - 2
src/main/index.ts

@@ -3,8 +3,9 @@ import path from 'path'
 import { pathToFileURL } from 'url'
 import { IpcChannels } from '@shared/ipc-channels'
 import { isSteamRunning, startVotedItemsSync, onFailedVotesChange, bindSteamToWindow } from './services/steam.service'
-import { initLibrary, checkUnavailableWallpapers, backfillResolutions } from './services/library.service'
+import { initLibrary, checkUnavailableWallpapers, backfillResolutions, onHdrDetected, queueHdrCheck } from './services/library.service'
 import { startWatcher } from './services/watcher.service'
+import { checkOutdatedBackups } from './services/backup.service'
 import { registerAllHandlers } from './ipc'
 import { initDesktopIcons, cleanupDesktopIcons } from './services/desktop-icons.service'
 import { getTrayEnabled, getAutostartPlaylistId, getKillLweOnQuit } from './services/config.service'
@@ -36,7 +37,23 @@ function startBackgroundSync(win: BrowserWindow): void {
       win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
     }
   }
-  win.webContents.once('did-finish-load', () => void syncResolutions())
+  onHdrDetected(() => {
+    if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
+  })
+  const syncOutdatedBackups = async (): Promise<void> => {
+    try {
+      if (await checkOutdatedBackups() && !win.isDestroyed()) {
+        win.webContents.send(IpcChannels.EVENT_LIBRARY_CHANGED)
+      }
+    } catch (err) {
+      console.warn('[Backup] Outdated check failed:', err)
+    }
+  }
+  win.webContents.once('did-finish-load', () => {
+    void syncResolutions()
+    void syncOutdatedBackups()
+    queueHdrCheck()
+  })
 
   const pushSteamStatus = (): void => {
     if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_STEAM_STATUS, isSteamRunning())
@@ -48,6 +65,7 @@ function startBackgroundSync(win: BrowserWindow): void {
     if (win.isDestroyed()) return
     const running = isSteamRunning()
     win.webContents.send(IpcChannels.EVENT_STEAM_STATUS, running)
+    await syncOutdatedBackups()
     if (!running) return
 
     try {

+ 5 - 3
src/main/ipc/backup.handlers.ts

@@ -34,7 +34,7 @@ async function backupOne(id: string, win: BrowserWindow): Promise<BackupItemResu
     if (!alreadyBackedUp) {
       backupDir = await backup.backupWallpaper(id, sourcePath, win)
     }
-    library.updateWallpaper(id, { backedUp: true, backupDir: backupDir! })
+    library.updateWallpaper(id, { backedUp: true, backupDir: backupDir!, backupOutdated: false })
 
     let unsubscribed = false
     if (getAutoUnsubscribeAfterBackup()) {
@@ -91,8 +91,10 @@ export function registerBackupHandlers(win: BrowserWindow): void {
     return { backedUp, alreadyBackedUp, failed, unsubscribed }
   })
 
-  ipcMain.handle(IpcChannels.BACKUP_SCAN, () => {
-    return backup.scanBackupFolder()
+  ipcMain.handle(IpcChannels.BACKUP_SCAN, async () => {
+    const result = await backup.scanBackupFolder()
+    await backup.checkOutdatedBackups()
+    return result
   })
 
   ipcMain.handle(IpcChannels.BACKUP_REMOVE, async (_e, itemIds: string[]) => {

+ 5 - 2
src/main/ipc/library.handlers.ts

@@ -1,6 +1,7 @@
 import { ipcMain } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
 import * as library from '../services/library.service'
+import { checkOutdatedBackups } from '../services/backup.service'
 import type { LibraryFilters, WallpaperMeta } from '@shared/types'
 
 export function registerLibraryHandlers(): void {
@@ -40,8 +41,10 @@ export function registerLibraryHandlers(): void {
     return library.getAllWallpapers({ searchText: query })
   })
 
-  ipcMain.handle(IpcChannels.LIBRARY_SCAN, () => {
-    return library.scanLibrary()
+  ipcMain.handle(IpcChannels.LIBRARY_SCAN, async () => {
+    const result = await library.scanLibrary()
+    await checkOutdatedBackups()
+    return result
   })
 
   ipcMain.handle(IpcChannels.LIBRARY_DISTINCT_TAGS, () => {

+ 49 - 4
src/main/services/backup.service.test.ts

@@ -67,6 +67,15 @@ describe('backupWallpaper', () => {
     expect(fs.existsSync(path.join(backupRoot, '123'))).toBe(false)
   })
 
+  it('ignores the shader cache Wallpaper Engine writes into the wallpaper', async () => {
+    writeFiles(source, { 'shaders/blobsSM40/abc.dxs': 'blob', 'shaders/custom.frag': 'void main() {}' })
+    const dir = await backup.backupWallpaper('123', source, win)
+    expect(fs.existsSync(path.join(dir, 'shaders/blobsSM40'))).toBe(false)
+    expect(fs.existsSync(path.join(dir, 'shaders/custom.frag'))).toBe(true)
+    writeFiles(source, { 'shaders/blobsSM40/def.dxs': 'another blob' })
+    expect(await backup.backupMatchesSource(source, dir)).toBe(true)
+  })
+
   it('replaces a corrupted backup', async () => {
     const dir = await backup.backupWallpaper('123', source, win)
     fs.writeFileSync(path.join(dir, 'materials/a.tex'), 'aaab')
@@ -149,15 +158,51 @@ describe('scanBackupFolder', () => {
     expect(wallpapers.get('moved')?.localPath).toBe(path.join(backupRoot, 'moved'))
   })
 
-  it('unlinks a workshop entry whose backup differs from the workshop copy', async () => {
+  it('keeps a workshop entry linked when its backup differs from the workshop copy', async () => {
     const dir = await backup.backupWallpaper('123', source, win)
     wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
-    expect((await backup.scanBackupFolder()).unlinked).toBe(0)
+    writeFiles(source, { 'scene.pkg': 'updated-by-the-author', 'materials/b.tex': 'bbbb' })
+    const result = await backup.scanBackupFolder()
+    expect(result.unlinked).toBe(0)
+    expect(result.corrupted).toEqual([])
+    expect(wallpapers.get('123')?.backedUp).toBe(true)
+  })
 
-    fs.writeFileSync(path.join(dir, 'scene.pkg'), 'truncated-and-longer')
-    const result = (await backup.scanBackupFolder())
+  it('links an unlinked workshop entry to an older backup', async () => {
+    const dir = await backup.backupWallpaper('123', source, win)
+    wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: false })
+    writeFiles(source, { 'scene.pkg': 'updated-by-the-author' })
+    const result = await backup.scanBackupFolder()
+    expect(result.linked).toBe(1)
+    expect(wallpapers.get('123')).toMatchObject({ backedUp: true, backupDir: dir })
+  })
+
+  it('flags a backup that is older than the workshop copy', async () => {
+    const dir = await backup.backupWallpaper('123', source, win)
+    wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
+    writeFiles(source, { 'shaders/blobsSM40/abc.dxs': 'blob' })
+    await backup.checkOutdatedBackups()
+    expect(wallpapers.get('123')?.backupOutdated).toBeFalsy()
+
+    writeFiles(source, { 'scene.pkg': 'updated-by-the-author' })
+    fs.utimesSync(source, new Date(), new Date(Date.now() + 5000))
+    expect(await backup.checkOutdatedBackups()).toBe(true)
+    expect(wallpapers.get('123')?.backupOutdated).toBe(true)
+
+    await backup.backupWallpaper('123', source, win)
+    fs.utimesSync(source, new Date(), new Date(Date.now() + 10000))
+    await backup.checkOutdatedBackups()
+    expect(wallpapers.get('123')?.backupOutdated).toBe(false)
+  })
+
+  it('unlinks a workshop entry whose backup lost its project.json', async () => {
+    const dir = await backup.backupWallpaper('123', source, win)
+    wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
+    fs.rmSync(path.join(dir, 'project.json'))
+    const result = await backup.scanBackupFolder()
     expect(result.unlinked).toBe(1)
     expect(result.corrupted).toEqual(['123'])
     expect(wallpapers.get('123')?.backedUp).toBe(false)
   })
+
 })

+ 48 - 18
src/main/services/backup.service.ts

@@ -67,13 +67,9 @@ export async function findBackupProblem(dir: string): Promise<string | null> {
 }
 
 async function sameFileList(sourcePath: string, backupDir: string): Promise<boolean> {
-  try {
-    const [src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
-    const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
-    return src.length === dst.length && src.every((f) => dstSizes.get(f.relPath) === f.size)
-  } catch {
-    return false
-  }
+  const [src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
+  const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
+  return src.length === dst.length && src.every((f) => dstSizes.get(f.relPath) === f.size)
 }
 
 function hashFile(filePath: string): Promise<string> {
@@ -86,12 +82,17 @@ function hashFile(filePath: string): Promise<string> {
   })
 }
 
+// Wallpaper Engine writes its compiled shaders (shaders/blobsSM40/*.dxs) into the wallpaper folder
+function isShaderCache(relPath: string): boolean {
+  return /^shaders[\\/]blobs/i.test(relPath)
+}
+
 async function walkFiles(dirPath: string, baseDir = dirPath): Promise<{ relPath: string; size: number }[]> {
   const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
   const nested = await Promise.all(
     entries.map(async (entry) => {
       const full = path.join(dirPath, entry.name)
-      if (entry.isDirectory()) return walkFiles(full, baseDir)
+      if (entry.isDirectory()) return isShaderCache(path.relative(baseDir, full)) ? [] : walkFiles(full, baseDir)
       if (!entry.isFile()) return []
       return [{ relPath: path.relative(baseDir, full), size: (await fs.promises.stat(full)).size }]
     })
@@ -356,11 +357,6 @@ export async function scanBackupFolder(): Promise<{
     if (!problems.has(key)) problems.set(key, findBackupProblem(dir))
     return problems.get(key)!
   }
-  const isValidFor = async (w: WallpaperMeta, dir: string): Promise<boolean> => {
-    if (await problemOf(dir)) return false
-    if (w.source !== 'workshop' || !w.localPath || !(await isDir(w.localPath))) return true
-    return sameFileList(w.localPath, dir)
-  }
 
   const upserts: WallpaperMeta[] = []
   const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
@@ -371,8 +367,8 @@ export async function scanBackupFolder(): Promise<{
     const dir = resolveBackupDir(w)
     // the drive holding it is not mounted
     if (dir && !(await isDir(path.dirname(dir)))) return
-    if (dir && (await isValidFor(w, dir))) return
-    const reason = dir ? ((await problemOf(dir)) ?? 'does not match the workshop copy') : 'no backup folder'
+    const reason = dir ? await problemOf(dir) : 'no backup folder'
+    if (!reason) return
     console.warn(`[Backup] Dropping broken backup of ${w.id} at ${dir}: ${reason}`)
     if (w.source === 'backup') {
       deletes.push(w.id)
@@ -397,11 +393,10 @@ export async function scanBackupFolder(): Promise<{
     if (existing?.source === 'workshop') {
       if ((existing.backedUp && !dropped.has(id)) || existing.downloading) {
         result.skipped++
-      } else if (await isValidFor(existing, dir)) {
+      } else {
+        // an older version than the workshop copy is still a backup, backing up again refreshes it
         patches.push({ id, patch: { backedUp: true, backupDir: dir } })
         result.linked++
-      } else {
-        result.corrupted.push(id)
       }
       return
     }
@@ -428,3 +423,38 @@ export async function scanBackupFolder(): Promise<{
   result.corrupted.sort()
   return result
 }
+
+// what each entry was last compared at, so only items whose workshop folder changed get re-walked
+const outdatedCheckedAt = new Map<string, string>()
+
+export async function checkOutdatedBackups(): Promise<boolean> {
+  const candidates = library
+    .getAllWallpapers()
+    .filter((w) => w.source === 'workshop' && w.backedUp && !w.downloading && w.localPath)
+  const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
+
+  await forEachLimit(candidates, SCAN_CONCURRENCY, async (w) => {
+    const dir = resolveBackupDir(w)
+    if (!dir) return
+    let key: string
+    try {
+      const stat = await fs.promises.stat(w.localPath!)
+      key = `${w.updatedAt}|${dir}|${stat.mtimeMs}`
+    } catch {
+      return
+    }
+    if (outdatedCheckedAt.get(w.id) === key) return
+    let outdated: boolean
+    try {
+      outdated = !(await sameFileList(w.localPath!, dir))
+    } catch {
+      // backup drive not mounted, or the folder is being replaced right now
+      return
+    }
+    outdatedCheckedAt.set(w.id, key)
+    if (!!w.backupOutdated !== outdated) patches.push({ id: w.id, patch: { backupOutdated: outdated } })
+  })
+
+  if (patches.length > 0) library.applyWallpaperChanges({ patches })
+  return patches.length > 0
+}

+ 81 - 1
src/main/services/library.service.ts

@@ -13,6 +13,7 @@ import {
 } from './workshop.service'
 import { findAndMutate } from '../utils/collections'
 import { resolutionsFromTags } from '@shared/resolutions'
+import { detectHdr } from '../utils/hdr'
 import {
   isSteamRunning,
   getItemDownloadStatus,
@@ -348,7 +349,9 @@ function buildMeta(
     backupDir: existing?.backupDir ?? (existing?.source === 'backup' ? existing.localPath : undefined),
     tags: pj?.tags ?? existing?.tags ?? [],
     resolutions: liveWorkshopTags ? resolutionsFromTags(liveWorkshopTags) : existing?.resolutions,
-    authorSteamId: authorSteamId ?? existing?.authorSteamId
+    authorSteamId: authorSteamId ?? existing?.authorSteamId,
+    // content may have changed, let the HDR pass look again
+    hdr: undefined
   }
 }
 
@@ -385,6 +388,7 @@ async function buildIncompleteMeta(
     downloadFailed: failed,
     authorSteamId: authorSteamId ?? existing?.authorSteamId,
     backedUp: existing?.backedUp,
+    backupOutdated: existing?.backupOutdated,
     backupDir: existing?.backupDir ?? (existing?.source === 'backup' ? existing.localPath : undefined)
   }
 }
@@ -416,6 +420,9 @@ export async function importWallpaperById(workshopId: string): Promise<Wallpaper
     liveTags.get(workshopId)
   )
   upsertWallpaper(meta)
+  // a preset waiting on this item as its dependency can be decided now
+  hdrUndecided.clear()
+  queueHdrCheck()
   return meta
 }
 
@@ -609,6 +616,7 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
   // Auto-cleanup folder/playlist items that reference non-existent wallpapers
   cleanupFolders()
   cleanupPlaylists(new Set(Object.keys(wallpapers)))
+  queueHdrCheck()
 
   return { imported, skipped, removed }
 }
@@ -695,6 +703,78 @@ export async function backfillResolutions(): Promise<boolean> {
   return changed
 }
 
+// Ids the HDR pass could not decide this session (no ffprobe, unreadable files), so a big
+// library on a slow disk is not re-read every background tick
+const hdrUndecided = new Set<string>()
+let hdrPassRunning = false
+let hdrPassQueued = false
+let hdrListener: (() => void) | undefined
+
+export function onHdrDetected(listener: () => void): void {
+  hdrListener = listener
+}
+
+export function queueHdrCheck(): void {
+  void backfillHdr().then((changed) => {
+    if (changed) hdrListener?.()
+  })
+}
+
+// Detects HDR for items that have no answer stored yet. After the first run only new or
+// updated items get read, so this is cheap to call often.
+export async function backfillHdr(): Promise<boolean> {
+  if (hdrPassRunning) {
+    hdrPassQueued = true
+    return false
+  }
+  hdrPassRunning = true
+  try {
+    const pending = Object.values(store.get('wallpapers')).filter(
+      (w) => w.hdr === undefined && !!w.localPath && !w.downloading && !hdrUndecided.has(w.id)
+    )
+    if (pending.length === 0) return false
+
+    let changed = false
+    let results = new Map<string, boolean>()
+    const flush = (): void => {
+      if (results.size === 0) return
+      const wallpapers = store.get('wallpapers')
+      for (const [id, hdr] of results) {
+        if (wallpapers[id]) wallpapers[id] = { ...wallpapers[id], hdr }
+      }
+      store.set('wallpapers', wallpapers)
+      results = new Map()
+      changed = true
+    }
+
+    // a few reads in flight keeps SSDs busy without making an HDD seek back and forth
+    let next = 0
+    const worker = async (): Promise<void> => {
+      while (next < pending.length) {
+        const w = pending[next++]
+        const hdr = await detectHdr(w).catch(() => undefined)
+        if (hdr === undefined) {
+          hdrUndecided.add(w.id)
+        } else {
+          results.set(w.id, hdr)
+          if (results.size >= 500) flush()
+        }
+      }
+    }
+    await Promise.all(Array.from({ length: 4 }, worker))
+    flush()
+
+    console.log(`[Library] HDR check: ${pending.length} items read, ${hdrUndecided.size} undecided`)
+    return changed
+  } finally {
+    hdrPassRunning = false
+    if (hdrPassQueued) {
+      hdrPassQueued = false
+      queueHdrCheck()
+    }
+  }
+}
+
 export function getAllFolders(): WallpaperFolder[] {
   return store.get('folders')
 }

+ 70 - 0
src/main/utils/hdr.test.ts

@@ -0,0 +1,70 @@
+import { describe, expect, it, afterAll } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { readPkgEntry, sceneUsesHdr } from './hdr'
+
+function u32(v: number): Buffer {
+  const b = Buffer.alloc(4)
+  b.writeUInt32LE(v)
+  return b
+}
+
+function str(s: string): Buffer {
+  return Buffer.concat([u32(Buffer.byteLength(s)), Buffer.from(s)])
+}
+
+function makePkg(files: Record<string, string>): Buffer {
+  const parts: Buffer[] = []
+  const names = Object.keys(files)
+  parts.push(str('PKGV0023'), u32(names.length))
+  let offset = 0
+  for (const name of names) {
+    const len = Buffer.byteLength(files[name])
+    parts.push(str(name), u32(offset), u32(len))
+    offset += len
+  }
+  for (const name of names) parts.push(Buffer.from(files[name]))
+  return Buffer.concat(parts)
+}
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hdr-test-'))
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))
+
+describe('readPkgEntry', () => {
+  it('reads one entry without the rest of the package', async () => {
+    const pkg = path.join(dir, 'scene.pkg')
+    fs.writeFileSync(pkg, makePkg({ 'materials/a.json': '{"a":1}', 'scene.json': '{"general":{"hdr":true}}' }))
+    expect((await readPkgEntry(pkg, 'scene.json'))?.toString()).toBe('{"general":{"hdr":true}}')
+    expect(await readPkgEntry(pkg, 'missing.json')).toBeUndefined()
+  })
+
+  it('handles an entry table bigger than the first read', async () => {
+    const files: Record<string, string> = {}
+    for (let i = 0; i < 3000; i++) files[`materials/some/long/path/texture_${i}.tex`] = 'x'
+    files['scene.json'] = '{}'
+    const pkg = path.join(dir, 'big.pkg')
+    fs.writeFileSync(pkg, makePkg(files))
+    expect((await readPkgEntry(pkg, 'scene.json'))?.toString()).toBe('{}')
+  })
+
+  it('rejects garbage', async () => {
+    const pkg = path.join(dir, 'bad.pkg')
+    fs.writeFileSync(pkg, Buffer.from([0xff, 0xff, 0xff, 0x7f, 1, 2, 3]))
+    expect(await readPkgEntry(pkg, 'scene.json')).toBeUndefined()
+  })
+})
+
+describe('sceneUsesHdr', () => {
+  it('needs both bloom and hdr', () => {
+    expect(sceneUsesHdr({ general: { hdr: true, bloom: true } }, {})).toBe(true)
+    expect(sceneUsesHdr({ general: { hdr: true, bloom: false } }, {})).toBe(false)
+    expect(sceneUsesHdr({ general: { bloom: true } }, {})).toBe(false)
+  })
+
+  it('resolves user property bindings', () => {
+    const scene = { general: { hdr: true, bloom: { user: 'hdr', value: true } } }
+    expect(sceneUsesHdr(scene, {})).toBe(true)
+    expect(sceneUsesHdr(scene, { hdr: { value: false } })).toBe(false)
+  })
+})

+ 168 - 0
src/main/utils/hdr.ts

@@ -0,0 +1,168 @@
+import * as fs from 'fs'
+import * as path from 'path'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import type { WallpaperMeta } from '@shared/types'
+import { isCommandAvailable } from './platform'
+import { findWallpaperVideoFile } from './video'
+
+const execFileAsync = promisify(execFile)
+
+// scene.pkg can be hundreds of MB, and libraries sit on HDDs, so only the entry table and the
+// one wanted entry are read. The table is small, 64KB covers it for all but huge packages.
+const PKG_HEADER_CHUNK = 64 * 1024
+
+export function parsePkgHeader(buf: Buffer): { dataStart: number; entries: Map<string, { offset: number; length: number }> } | undefined {
+  let pos = 0
+  const u32 = (): number => {
+    if (pos + 4 > buf.length) throw new RangeError('short pkg header')
+    const v = buf.readUInt32LE(pos)
+    pos += 4
+    return v
+  }
+  const str = (): string => {
+    const len = u32()
+    if (pos + len > buf.length) throw new RangeError('short pkg header')
+    const s = buf.toString('utf8', pos, pos + len)
+    pos += len
+    return s
+  }
+
+  try {
+    str()
+    const count = u32()
+    if (count > 1_000_000) return undefined
+    const entries = new Map<string, { offset: number; length: number }>()
+    for (let i = 0; i < count; i++) {
+      const name = str()
+      entries.set(name, { offset: u32(), length: u32() })
+    }
+    return { dataStart: pos, entries }
+  } catch {
+    return undefined
+  }
+}
+
+export async function readPkgEntry(pkgPath: string, name: string): Promise<Buffer | undefined> {
+  const fh = await fs.promises.open(pkgPath, 'r')
+  try {
+    const size = (await fh.stat()).size
+    let chunk = PKG_HEADER_CHUNK
+    let header: ReturnType<typeof parsePkgHeader>
+    for (;;) {
+      const buf = Buffer.alloc(Math.min(chunk, size))
+      const { bytesRead } = await fh.read(buf, 0, buf.length, 0)
+      header = parsePkgHeader(buf.subarray(0, bytesRead))
+      if (header || chunk >= size) break
+      chunk *= 4
+    }
+    const entry = header?.entries.get(name)
+    if (!header || !entry) return undefined
+    const start = header.dataStart + entry.offset
+    if (start + entry.length > size) return undefined
+    const out = Buffer.alloc(entry.length)
+    await fh.read(out, 0, entry.length, start)
+    return out
+  } finally {
+    await fh.close()
+  }
+}
+
+async function readSceneJson(localPath: string, sceneFile: string): Promise<unknown> {
+  try {
+    let raw: Buffer | undefined
+    try {
+      raw = await fs.promises.readFile(path.join(localPath, sceneFile))
+    } catch {
+      // packed next to its json name, gifscene.json -> gifscene.pkg, and scene.pkg for everything else
+      const named = path.join(localPath, sceneFile.replace(/\.json$/i, '') + '.pkg')
+      raw = fs.existsSync(named) ? await readPkgEntry(named, sceneFile) : undefined
+      raw ??= await readPkgEntry(path.join(localPath, 'scene.pkg'), sceneFile)
+    }
+    if (!raw) return undefined
+    // same leniency as the engine's JSON::parseAsset: authors ship trailing commas
+    return JSON.parse(raw.toString('utf8').replace(/^\uFEFF/, '').replace(/,(\s*[}\]])/g, '$1'))
+  } catch {
+    return undefined
+  }
+}
+
+type ProjectProperties = Record<string, { value?: unknown }>
+
+interface Project {
+  type?: string
+  file?: string
+  dependency?: string
+  general?: { properties?: ProjectProperties }
+}
+
+async function readProject(localPath: string): Promise<Project | undefined> {
+  try {
+    return JSON.parse(await fs.promises.readFile(path.join(localPath, 'project.json'), 'utf8'))
+  } catch {
+    return undefined
+  }
+}
+
+// general values are either plain or bound to a user property: { "user": "name", "value": default }
+function generalFlag(general: Record<string, unknown>, key: string, properties: ProjectProperties): boolean {
+  const v = general[key]
+  if (v && typeof v === 'object') {
+    const { user, value } = v as { user?: unknown; value?: unknown }
+    const bound = typeof user === 'string' ? properties[user]?.value : undefined
+    return !!(bound ?? value)
+  }
+  return !!v
+}
+
+// Same condition the engine renders HDR under (with ultra post processing): bloom and hdr both on
+export function sceneUsesHdr(scene: unknown, properties: ProjectProperties): boolean {
+  const general = (scene as { general?: Record<string, unknown> } | undefined)?.general ?? {}
+  return generalFlag(general, 'bloom', properties) && generalFlag(general, 'hdr', properties)
+}
+
+async function videoIsHdr(file: string): Promise<boolean | undefined> {
+  if (!isCommandAvailable('ffprobe')) return undefined
+  try {
+    const { stdout } = await execFileAsync('ffprobe', [
+      '-v', 'error',
+      '-select_streams', 'v:0',
+      '-show_entries', 'stream=color_transfer',
+      '-of', 'csv=p=0',
+      file
+    ], { timeout: 10_000, encoding: 'utf8' })
+    const transfer = stdout.trim().split('\n')[0]?.trim()
+    return transfer === 'smpte2084' || transfer === 'arib-std-b67'
+  } catch {
+    return undefined
+  }
+}
+
+/** undefined = could not tell (files missing, no ffprobe) */
+export async function detectHdr(w: WallpaperMeta): Promise<boolean | undefined> {
+  if (!w.localPath) return undefined
+  let dir = w.localPath
+  let project = await readProject(dir)
+  if (!project) return undefined
+  let properties = project.general?.properties ?? {}
+
+  // presets ship only properties, the wallpaper itself is the dependency in a sibling folder
+  if (project.dependency && !project.file) {
+    dir = path.join(path.dirname(dir), String(project.dependency))
+    const base = await readProject(dir)
+    if (!base) return undefined
+    properties = { ...base.general?.properties, ...properties }
+    project = base
+  }
+
+  const type = (project.type ?? w.type).toLowerCase()
+  if (type === 'scene') {
+    const scene = await readSceneJson(dir, project.file ?? 'scene.json')
+    return scene === undefined ? undefined : sceneUsesHdr(scene, properties)
+  }
+  if (type === 'video') {
+    const video = findWallpaperVideoFile(dir, project.file)
+    return video ? videoIsHdr(video) : undefined
+  }
+  return false
+}

+ 41 - 3
src/renderer/src/components/library/LibraryView.tsx

@@ -21,6 +21,7 @@ import {
   ThumbsDown,
   Eraser,
   Archive,
+  ArchiveRestore,
   AlertTriangle,
   Heart,
   User,
@@ -31,7 +32,7 @@ import WallpaperCard from './WallpaperCard'
 import PreviewSizeToggle from '../common/PreviewSizeToggle'
 import DetailSidebar from '../common/DetailSidebar'
 import { useToast } from '../common/Toast'
-import type { LibraryFilters, WallpaperFolder, LweStatus, ScreenTarget } from '@shared/types'
+import type { LibraryFilters, WallpaperFolder, WallpaperMeta, LweStatus, ScreenTarget } from '@shared/types'
 import clsx from 'clsx'
 import {
   WE_TYPES,
@@ -62,6 +63,7 @@ interface LibraryFilterState {
   failedOnly: boolean
   likedOnly: boolean
   unavailableOnly: boolean
+  outdatedBackupOnly: boolean
 }
 
 const DEFAULT_STATE: LibraryFilterState = {
@@ -72,7 +74,8 @@ const DEFAULT_STATE: LibraryFilterState = {
   sources: [],
   failedOnly: false,
   likedOnly: false,
-  unavailableOnly: false
+  unavailableOnly: false,
+  outdatedBackupOnly: false
 }
 
 const TYPE_MAP: Record<string, string> = {
@@ -92,6 +95,11 @@ const SOURCE_MAP: Record<string, string> = {
   Backup: 'backup'
 }
 
+// removed items can't be updated anymore, those belong to the Unavailable filter
+function isBackupOutdated(w: WallpaperMeta): boolean {
+  return w.source === 'workshop' && !!w.backedUp && !!w.backupOutdated && !w.unavailable
+}
+
 function loadFilters(): LibraryFilterState {
   try {
     const raw = localStorage.getItem(STORAGE_KEY)
@@ -415,6 +423,10 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     setFilterState((prev) => ({ ...prev, unavailableOnly: !prev.unavailableOnly }))
   }
 
+  function toggleOutdatedBackupOnly() {
+    setFilterState((prev) => ({ ...prev, outdatedBackupOnly: !prev.outdatedBackupOnly }))
+  }
+
   const activeCount =
     filterState.types.length +
     filterState.ageRatings.length +
@@ -423,7 +435,8 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     filterState.sources.length +
     (filterState.failedOnly ? 1 : 0) +
     (filterState.likedOnly ? 1 : 0) +
-    (filterState.unavailableOnly ? 1 : 0)
+    (filterState.unavailableOnly ? 1 : 0) +
+    (filterState.outdatedBackupOnly ? 1 : 0)
 
   // Refresh the library once a background download (subscribe or redownload) settles,
   // so the downloading/downloadFailed badges stay in sync without a manual Scan.
@@ -493,6 +506,7 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
       if (filterState.failedOnly && !w.downloadFailed) return false
       if (filterState.likedOnly && !votedSet.has(w.id)) return false
       if (filterState.unavailableOnly && !w.unavailable) return false
+      if (filterState.outdatedBackupOnly && !isBackupOutdated(w)) return false
       return true
     })
   }, [allWallpapers, filterState, votedSet])
@@ -512,6 +526,11 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     [allWallpapers]
   )
 
+  const outdatedBackupCount = useMemo(
+    () => allWallpapers.filter(isBackupOutdated).length,
+    [allWallpapers]
+  )
+
   // Removed-from-workshop items with local content that hasn't been backed up yet
   const unavailableNotBackedUp = useMemo(
     () => allWallpapers.filter((w) => w.unavailable && !w.backedUp),
@@ -1231,6 +1250,25 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
           )}
         </button>
 
+        <button
+          onClick={toggleOutdatedBackupOnly}
+          title="Show only wallpapers whose backup is an older version than the one on the Steam Workshop"
+          className={clsx(
+            'flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
+            filterState.outdatedBackupOnly
+              ? 'bg-sky-600 text-white'
+              : outdatedBackupCount > 0
+                ? 'text-sky-400 hover:bg-white/5'
+                : 'text-gray-400 hover:bg-white/5 hover:text-gray-200'
+          )}
+        >
+          <ArchiveRestore size={12} />
+          Outdated backup
+          {outdatedBackupCount > 0 && (
+            <span className="rounded-full bg-black/30 px-1.5">{outdatedBackupCount}</span>
+          )}
+        </button>
+
         <div className="h-3 w-px bg-white/10" />
 
         <TagDropdown

+ 12 - 0
src/renderer/src/components/library/WallpaperCard.tsx

@@ -262,6 +262,18 @@ export default function WallpaperCard({
             </div>
           </div>
         )}
+        {wallpaper.hdr && (
+          <span
+            className="absolute right-2 top-2 rounded bg-black/70 px-1 py-0.5 text-[10px] font-semibold leading-none tracking-wide text-amber-300"
+            title={
+              wallpaper.type === 'video'
+                ? 'HDR video - shown in HDR with the HDR output setting on an HDR monitor'
+                : 'Uses HDR rendering - needs post processing set to Ultra'
+            }
+          >
+            HDR
+          </span>
+        )}
         {backupProgress == null && (wallpaper.backedUp || wallpaper.source === 'backup') && (
           <div
             className="absolute bottom-2 right-2 flex h-5 w-5 items-center justify-center rounded bg-black/60 text-indigo-300"

+ 4 - 0
src/shared/types.ts

@@ -88,6 +88,8 @@ export interface WallpaperMeta {
   playbackSpeed?: number
   backedUp?: boolean
   backupDir?: string
+  /** The workshop copy no longer matches the backup (file list or sizes), e.g. the author published an update */
+  backupOutdated?: boolean
   /** Set by a "check unavailable" scan: true if the item has been removed from the Steam Workshop */
   unavailable?: boolean
   /** Object/layer ids or names to force-hide via linux-wallpaperengine --disable-object */
@@ -121,6 +123,8 @@ export interface WallpaperMeta {
   /** Launch-only engine flags, each one unset here falls back to the global setting */
   engineFlags?: EngineFlags
   compat?: WallpaperCompat
+  /** Scene with general.hdr on, or a PQ/HLG video. Unset until the background HDR pass has looked at it */
+  hdr?: boolean
   /** Thumbnail made by the app (a screenshot of the running wallpaper, or an image the user picked) */
   customPreview?: string
   /** Show the Workshop/project preview even though a custom one exists */