瀏覽代碼

added support for v8 instead of quickjs

added function to trim video
UwU 1 月之前
父節點
當前提交
2339117037
共有 50 個文件被更改,包括 2468 次插入 和 2399 次删除
  1. 1 1
      package.json
  2. 7 0
      src/main/ipc/lwe.handlers.ts
  3. 0 4
      src/main/ipc/shell.handlers.ts
  4. 18 18
      src/main/ipc/steam.handlers.ts
  5. 二進制
      src/main/services/__pycache__/desktop-icons-overlay.cpython-313.pyc
  6. 0 13
      src/main/services/desktop-icons-overlay.py
  7. 0 3
      src/main/services/desktop-icons.service.ts
  8. 23 63
      src/main/services/library.service.ts
  9. 12 16
      src/main/services/lwe-prebuilt.service.ts
  10. 25 1
      src/main/services/lwe.service.test.ts
  11. 50 9
      src/main/services/lwe.service.ts
  12. 3 1
      src/main/services/playlist-player.service.ts
  13. 2 0
      src/main/services/wallpaper.service.ts
  14. 35 64
      src/main/services/workshop.service.ts
  15. 5 0
      src/preload/index.ts
  16. 23 1
      src/renderer/src/assets/index.css
  17. 136 0
      src/renderer/src/components/common/ContextMenu.tsx
  18. 65 73
      src/renderer/src/components/common/DetailSidebar.tsx
  19. 168 0
      src/renderer/src/components/common/FilterPanel.tsx
  20. 227 0
      src/renderer/src/components/common/GridCard.tsx
  21. 157 0
      src/renderer/src/components/common/GridControls.tsx
  22. 141 0
      src/renderer/src/components/common/WallpaperContextMenu.tsx
  23. 2 5
      src/renderer/src/components/common/sidebar/EngineFlagsSection.tsx
  24. 182 0
      src/renderer/src/components/common/sidebar/VideoTrimSection.tsx
  25. 3 12
      src/renderer/src/components/layout/StatusBar.tsx
  26. 189 723
      src/renderer/src/components/library/LibraryView.tsx
  27. 107 212
      src/renderer/src/components/library/WallpaperCard.tsx
  28. 34 339
      src/renderer/src/components/playlist/PlaylistsView.tsx
  29. 3 5
      src/renderer/src/components/settings/DisplaySettings.tsx
  30. 3 5
      src/renderer/src/components/settings/PerformanceSettings.tsx
  31. 3 8
      src/renderer/src/components/settings/ScheduleSettings.tsx
  32. 2 2
      src/renderer/src/components/settings/SettingsView.tsx
  33. 286 626
      src/renderer/src/components/workshop/WorkshopBrowser.tsx
  34. 54 170
      src/renderer/src/components/workshop/WorkshopCard.tsx
  35. 101 0
      src/renderer/src/hooks/queries.ts
  36. 28 0
      src/renderer/src/hooks/usePersistentState.ts
  37. 27 8
      src/renderer/src/hooks/useSelectableGrid.ts
  38. 7 0
      src/renderer/src/hooks/useSubscriptionQueue.ts
  39. 2 4
      src/renderer/src/hooks/useVoteBorders.ts
  40. 80 0
      src/renderer/src/hooks/useVotes.ts
  41. 36 0
      src/renderer/src/hooks/useWallpaperActions.ts
  42. 1 1
      src/renderer/src/main.tsx
  43. 5 0
      src/renderer/src/utils/dom.ts
  44. 45 0
      src/renderer/src/utils/searchQuery.test.ts
  45. 40 0
      src/renderer/src/utils/searchQuery.ts
  46. 52 0
      src/renderer/src/utils/wallpaper.ts
  47. 1 12
      src/shared/ipc-channels.ts
  48. 6 0
      src/shared/types.ts
  49. 44 0
      src/shared/videoTrim.test.ts
  50. 27 0
      src/shared/videoTrim.ts

+ 1 - 1
package.json

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

+ 7 - 0
src/main/ipc/lwe.handlers.ts

@@ -8,6 +8,7 @@ import type { ScreenTarget } from '@shared/types'
 import { invalidateEnvCache } from '../services/wallpaper.service'
 import { getConnectedScreens } from '../utils/platform'
 import { listDesktopApplications } from '../services/shortcuts.service'
+import { findWallpaperVideoFile, getVideoDurationSec } from '../utils/video'
 
 export function registerLweHandlers(win: BrowserWindow): void {
   ipcMain.handle(IpcChannels.LWE_STATUS, () => {
@@ -79,6 +80,12 @@ export function registerLweHandlers(win: BrowserWindow): void {
 
   ipcMain.handle(IpcChannels.LWE_LIST_APPLICATIONS, () => listDesktopApplications())
 
+  // null when there is no video file or no ffprobe to measure it
+  ipcMain.handle(IpcChannels.LWE_VIDEO_DURATION, async (_e, wallpaperPath: string, projectFile?: string) => {
+    const videoFile = findWallpaperVideoFile(wallpaperPath, projectFile)
+    return videoFile ? ((await getVideoDurationSec(videoFile)) ?? null) : null
+  })
+
   ipcMain.handle(IpcChannels.LWE_PICK_SHORTCUT_PATH, async (_e, kind: 'file' | 'directory') => {
     const result = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow() ?? win, {
       properties: [kind === 'directory' ? 'openDirectory' : 'openFile'],

+ 0 - 4
src/main/ipc/shell.handlers.ts

@@ -6,7 +6,6 @@ import { spawn } from 'child_process'
 import { isCommandAvailable } from '../utils/platform'
 
 export function registerShellHandlers(): void {
-  // Open a file with the OS default application (e.g. video in media player)
   ipcMain.handle(IpcChannels.SHELL_OPEN_WITH_DEFAULT, async (_e, filePath: string) => {
     const resolved = path.resolve(filePath)
     if (!fs.existsSync(resolved)) return { ok: false, error: 'File not found' }
@@ -14,7 +13,6 @@ export function registerShellHandlers(): void {
     return { ok: !result, error: result || undefined }
   })
 
-  // Open a folder in the system file manager
   ipcMain.handle(IpcChannels.SHELL_OPEN_IN_FILE_MANAGER, async (_e, folderPath: string) => {
     const resolved = path.resolve(folderPath)
     if (!fs.existsSync(resolved)) return { ok: false, error: 'Path not found' }
@@ -22,7 +20,6 @@ export function registerShellHandlers(): void {
     return { ok: true }
   })
 
-  // Open a path (file or folder) with shell.openPath
   ipcMain.handle(IpcChannels.SHELL_OPEN_PATH, async (_e, targetPath: string) => {
     const resolved = path.resolve(targetPath)
     const result = await shell.openPath(resolved)
@@ -52,7 +49,6 @@ export function registerShellHandlers(): void {
     return { ok: true }
   })
 
-  // Open a URL or protocol link (e.g. steam://, https://) with the OS handler
   ipcMain.handle(IpcChannels.SHELL_OPEN_EXTERNAL, async (_e, url: string) => {
     try {
       await shell.openExternal(url)

+ 18 - 18
src/main/ipc/steam.handlers.ts

@@ -42,23 +42,29 @@ function startDownloadPoll(win: BrowserWindow, itemId: string): void {
   }, 1000)
 }
 
+async function subscribeAndDownload(win: BrowserWindow, itemId: string): Promise<void> {
+  await steam.subscribeToItem(BigInt(itemId))
+  // Steam doesn't always actually start fetching content just because we subscribed - see
+  // downloadItem()'s comment. This is the reliable kick.
+  await steam.downloadItem(BigInt(itemId))
+  startDownloadPoll(win, itemId)
+}
+
+// async: an unresponsive mount here must not block the main process (and every other
+// pending IPC call) while it deletes
+async function removeLocalFiles(dir: string): Promise<void> {
+  try { await fs.promises.rm(dir, { recursive: true, force: true }) } catch { /* ignore */ }
+}
+
 export function registerSteamHandlers(win: BrowserWindow): void {
-  setDependencyInstaller(async (itemId) => {
-    await steam.subscribeToItem(BigInt(itemId))
-    await steam.downloadItem(BigInt(itemId))
-    startDownloadPoll(win, itemId)
-  })
+  setDependencyInstaller((itemId) => subscribeAndDownload(win, itemId))
 
   ipcMain.handle(IpcChannels.STEAM_IS_RUNNING, () => {
     return steam.isSteamRunning()
   })
 
   ipcMain.handle(IpcChannels.STEAM_SUBSCRIBE, async (_e, itemId: string) => {
-    await steam.subscribeToItem(BigInt(itemId))
-    // Steam doesn't always actually start fetching content just because we subscribed - see
-    // downloadItem()'s comment. This is the reliable kick.
-    await steam.downloadItem(BigInt(itemId))
-    startDownloadPoll(win, itemId)
+    await subscribeAndDownload(win, itemId)
     return { ok: true }
   })
 
@@ -70,11 +76,7 @@ export function registerSteamHandlers(win: BrowserWindow): void {
       library.updateWallpaper(itemId, { subscribed: false, downloading: false, downloadFailed: false })
       return { ok: true }
     }
-    if (wallpaper?.localPath) {
-      // async: an unresponsive mount here must not block the main process (and every other
-      // pending IPC call) while it deletes
-      try { await fs.promises.rm(wallpaper.localPath, { recursive: true, force: true }) } catch { /* ignore */ }
-    }
+    if (wallpaper?.localPath) await removeLocalFiles(wallpaper.localPath)
     const backupDir = wallpaper?.backedUp ? backup.resolveBackupDir(wallpaper) : null
     if (wallpaper && backupDir && (await backup.hasBackupFiles(backupDir))) {
       library.updateWallpaper(itemId, {
@@ -95,9 +97,7 @@ export function registerSteamHandlers(win: BrowserWindow): void {
   ipcMain.handle(IpcChannels.STEAM_REDOWNLOAD, async (_e, itemId: string) => {
     const wallpaper = library.getWallpaper(itemId)
     await steam.unsubscribeFromItem(BigInt(itemId))
-    if (wallpaper?.localPath && wallpaper.source === 'workshop') {
-      try { await fs.promises.rm(wallpaper.localPath, { recursive: true, force: true }) } catch { /* ignore */ }
-    }
+    if (wallpaper?.localPath && wallpaper.source === 'workshop') await removeLocalFiles(wallpaper.localPath)
     if (wallpaper) {
       library.updateWallpaper(itemId, { downloading: true, downloadFailed: false })
     }

二進制
src/main/services/__pycache__/desktop-icons-overlay.cpython-313.pyc


+ 0 - 13
src/main/services/desktop-icons-overlay.py

@@ -25,8 +25,6 @@ gi.require_version('Gtk', '4.0')
 from gi.repository import Gtk4LayerShell, Gtk, Gdk, Gio, GLib
 
 
-# --- KDE desktop config parsing ---
-
 def get_desktop_dir():
     try:
         result = subprocess.run(
@@ -184,8 +182,6 @@ def get_mime_icon(path):
     return 'folder' if os.path.isdir(path) else 'text-x-generic'
 
 
-# --- KDE settings auto-detection ---
-
 # Kirigami icon size table (index to pixels), matching FolderTools.js
 _ICON_SIZE_TABLE = [22, 32, 48, 64, 96, 128, 256]
 
@@ -254,7 +250,6 @@ def detect_kde_settings():
                     pass
                 try:
                     kde_weight = int(parts[4])
-                    # Find closest CSS weight
                     closest = min(_KDE_WEIGHT_MAP.keys(),
                                   key=lambda k: abs(k - kde_weight))
                     settings['font_weight'] = _KDE_WEIGHT_MAP[closest]
@@ -275,8 +270,6 @@ def detect_kde_settings():
     return settings
 
 
-# --- Layout ---
-
 _kde = detect_kde_settings()
 ICON_SIZE = _kde['icon_size']
 CELL_WIDTH = 120
@@ -353,7 +346,6 @@ def main():
         Gtk4LayerShell.set_layer(window, Gtk4LayerShell.Layer.BOTTOM)
         Gtk4LayerShell.set_namespace(window, 'desktop')
 
-        # Target monitor
         if monitor_name:
             display = Gdk.Display.get_default()
             monitors = display.get_monitors()
@@ -371,7 +363,6 @@ def main():
         Gtk4LayerShell.set_exclusive_zone(window, -1)
         Gtk4LayerShell.set_keyboard_mode(window, Gtk4LayerShell.KeyboardMode.NONE)
 
-        # CSS built from the auto-detected font settings
         font_style = 'italic' if _kde['font_italic'] else 'normal'
         font_weight = _kde['font_weight']
         css = Gtk.CssProvider()
@@ -392,7 +383,6 @@ def main():
 
         build_icons()
 
-        # Watch ~/Desktop for changes
         desktop_file = Gio.File.new_for_path(desktop_dir)
         file_monitor = desktop_file.monitor_directory(
             Gio.FileMonitorFlags.NONE, None
@@ -408,7 +398,6 @@ def main():
         if not window:
             return
 
-        # Get monitor resolution
         display = Gdk.Display.get_default()
         monitors = display.get_monitors()
         screen_w, screen_h = 2560, 1440
@@ -421,10 +410,8 @@ def main():
             screen_h = geo.height
             break
 
-        # Get panel offset
         panel_left, panel_right, panel_top, panel_bottom = get_panel_offset()
 
-        # Parse KDE positions
         screen_key = f'{screen_w}x{screen_h}'
         kde_positions, grid_cols, grid_rows = parse_kde_positions(screen_key)
 

+ 0 - 3
src/main/services/desktop-icons.service.ts

@@ -18,9 +18,7 @@ function getOverlayScriptPath(): string {
   // In dev: __dirname is out/main, project root is two levels up
   // In prod: script is copied to resources/
   const candidates = [
-    // Dev: source tree
     path.join(__dirname, '..', '..', 'src', 'main', 'services', 'desktop-icons-overlay.py'),
-    // Prod: bundled in resources
     path.join(process.resourcesPath ?? '', 'desktop-icons-overlay.py'),
     // Fallback: next to compiled output
     path.join(__dirname, 'desktop-icons-overlay.py')
@@ -123,7 +121,6 @@ export function initDesktopIcons(): void {
   }
 }
 
-/** Call on app quit to clean up overlay processes. */
 export function cleanupDesktopIcons(): void {
   stopDesktopIconsOverlay()
 }

+ 23 - 63
src/main/services/library.service.ts

@@ -5,12 +5,7 @@ import * as path from 'path'
 import * as fs from 'fs'
 import { randomUUID } from 'crypto'
 import { cleanupPlaylists } from './playlist.service'
-import {
-  getWorkshopTimesUpdated,
-  getWorkshopTags,
-  getWorkshopAuthors,
-  getUnavailableWorkshopItems
-} from './workshop.service'
+import { getWorkshopDetails, getUnavailableWorkshopItems, type WorkshopDetails } from './workshop.service'
 import { findAndMutate } from '../utils/collections'
 import { resolutionsFromTags } from '@shared/resolutions'
 import { detectHdr } from '../utils/hdr'
@@ -268,17 +263,9 @@ function stricterRating(a: ContentRating, b?: ContentRating): ContentRating {
   return RATING_RESTRICTIVENESS[b] > RATING_RESTRICTIVENESS[a] ? b : a
 }
 
-async function safeGetWorkshopTags(ids: string[]): Promise<Map<string, string[]>> {
-  try {
-    return await getWorkshopTags(ids)
-  } catch {
-    return new Map()
-  }
-}
-
-async function safeGetWorkshopAuthors(ids: string[]): Promise<Map<string, string>> {
+async function safeGetWorkshopDetails(ids: string[]): Promise<Map<string, WorkshopDetails>> {
   try {
-    return await getWorkshopAuthors(ids)
+    return await getWorkshopDetails(ids)
   } catch {
     return new Map()
   }
@@ -299,14 +286,6 @@ export function getDirSize(dirPath: string): number {
   return total
 }
 
-async function safeGetWorkshopTimesUpdated(ids: string[]): Promise<Map<string, number>> {
-  try {
-    return await getWorkshopTimesUpdated(ids)
-  } catch {
-    return new Map()
-  }
-}
-
 function buildMeta(
   workshopId: string,
   localPath: string,
@@ -398,27 +377,16 @@ export async function importWallpaperById(workshopId: string): Promise<Wallpaper
   if (!fs.existsSync(localPath)) return null
 
   const existing = getWallpaper(workshopId) ?? undefined
-  const authorSteamId =
-    existing?.authorSteamId ?? (await safeGetWorkshopAuthors([workshopId])).get(workshopId)
+  const details = (await safeGetWorkshopDetails([workshopId])).get(workshopId)
+  const authorSteamId = existing?.authorSteamId ?? details?.authorSteamId
   const pj = readProjectJson(localPath)
   if (!pj) {
-    const tags = await safeGetWorkshopTags([workshopId])
-    const meta = await buildIncompleteMeta(workshopId, localPath, existing, tags.get(workshopId), authorSteamId)
+    const meta = await buildIncompleteMeta(workshopId, localPath, existing, details?.tags, authorSteamId)
     upsertWallpaper(meta)
     return meta
   }
 
-  const timesUpdated = await safeGetWorkshopTimesUpdated([workshopId])
-  const liveTags = await safeGetWorkshopTags([workshopId])
-  const meta = buildMeta(
-    workshopId,
-    localPath,
-    pj,
-    existing,
-    timesUpdated.get(workshopId),
-    authorSteamId,
-    liveTags.get(workshopId)
-  )
+  const meta = buildMeta(workshopId, localPath, pj, existing, details?.timeUpdated, authorSteamId, details?.tags)
   upsertWallpaper(meta)
   // a preset waiting on this item as its dependency can be decided now
   hdrUndecided.clear()
@@ -491,18 +459,20 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     incomplete.push({ id, localPath: path.join(workshopPath, id) })
   }
 
-  // Author never changes once known, so only fetch it for items that don't have it yet
-  const missingAuthorIds = [
+  const details = await safeGetWorkshopDetails([
     ...incomplete.map((i) => i.id),
     ...toRebuild.map(({ entry }) => entry.name),
     ...cacheHits
-  ].filter((id) => !wallpapers[id]?.authorSteamId)
-  const authors = await safeGetWorkshopAuthors(missingAuthorIds)
+  ])
+  // Author never changes once known, only take Steam's for items that don't have it yet
+  const authors = new Map<string, string>()
+  for (const [id, d] of details) {
+    if (!wallpapers[id]?.authorSteamId) authors.set(id, d.authorSteamId)
+  }
 
-  const incompleteTags = await safeGetWorkshopTags(incomplete.map((i) => i.id))
   for (const { id, localPath } of incomplete) {
     const existing = wallpapers[id]
-    const meta = await buildIncompleteMeta(id, localPath, existing, incompleteTags.get(id), authors.get(id))
+    const meta = await buildIncompleteMeta(id, localPath, existing, details.get(id)?.tags, authors.get(id))
     if (!existing) {
       wallpapers[id] = meta
       imported++
@@ -531,32 +501,23 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     }
   }
 
-  const timesUpdated = await safeGetWorkshopTimesUpdated([
-    ...toRebuild.map(({ entry }) => entry.name),
-    ...cacheHits
-  ])
-  const liveTags = await safeGetWorkshopTags([
-    ...toRebuild.map(({ entry }) => entry.name),
-    ...cacheHits
-  ])
-
   for (const { entry, localPath, pj } of toRebuild) {
     wallpapers[entry.name] = buildMeta(
       entry.name,
       localPath,
       pj,
       wallpapers[entry.name] ?? undefined,
-      timesUpdated.get(entry.name),
+      details.get(entry.name)?.timeUpdated,
       authors.get(entry.name),
-      liveTags.get(entry.name)
+      details.get(entry.name)?.tags
     )
     imported++
   }
 
   for (const id of cacheHits) {
-    const seconds = timesUpdated.get(id)
+    const seconds = details.get(id)?.timeUpdated
     const authorId = authors.get(id)
-    const live = liveTags.get(id)
+    const live = details.get(id)?.tags
 
     // A time_updated bump means the author changed something on the Workshop side
     // (tags, content rating, a republish) - re-read project.json instead of just
@@ -613,7 +574,6 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
 
   console.log(`[Library] Scan complete: ${imported} imported, ${skipped} skipped, ${removed} removed`)
 
-  // Auto-cleanup folder/playlist items that reference non-existent wallpapers
   cleanupFolders()
   cleanupPlaylists(new Set(Object.keys(wallpapers)))
   queueHdrCheck()
@@ -673,10 +633,10 @@ export async function backfillResolutions(): Promise<boolean> {
     .filter((w) => w.source === 'workshop' && (rederive || w.resolutions === undefined))
     .map((w) => w.id)
 
-  let tags = new Map<string, string[]>()
+  let details = new Map<string, WorkshopDetails>()
   if (ids.length > 0) {
     try {
-      tags = await getWorkshopTags(ids)
+      details = await getWorkshopDetails(ids)
     } catch {
       return false
     }
@@ -688,7 +648,7 @@ export async function backfillResolutions(): Promise<boolean> {
   for (const id of ids) {
     const w = wallpapers[id]
     if (!w) continue
-    const live = tags.get(id)
+    const live = details.get(id)?.tags
     // Steam no longer returns removed or private items, record "none" instead of asking every tick
     const resolutions = live ? resolutionsFromTags(live) : (w.resolutions ?? [])
     if (sameTags(w.resolutions, resolutions)) continue
@@ -698,7 +658,7 @@ export async function backfillResolutions(): Promise<boolean> {
   if (changed) store.set('wallpapers', wallpapers)
   store.set('resolutionsVersion', RESOLUTIONS_VERSION)
   if (ids.length > 0) {
-    console.log(`[Library] Resolution tags fetched for ${tags.size} of ${ids.length} items`)
+    console.log(`[Library] Resolution tags fetched for ${details.size} of ${ids.length} items`)
   }
   return changed
 }

+ 12 - 16
src/main/services/lwe-prebuilt.service.ts

@@ -14,12 +14,12 @@ import { buildCleanBuildEnv, readPrebuiltRelease, resetLweDetection } from './lw
 
 const execFileAsync = promisify(execFile)
 
-type PrebuiltDistro = 'ubuntu-24.04' | 'fedora-44' | 'arch'
+// Arch builds are paused: V8 (libnode) is only in the AUR there, so the release CI can't build them
+type PrebuiltDistro = 'ubuntu-24.04' | 'fedora-44'
 
 const DISTRO_LABELS: Record<PrebuiltDistro, string> = {
   'ubuntu-24.04': 'Ubuntu 24.04',
-  'fedora-44': 'Fedora 44',
-  arch: 'Arch'
+  'fedora-44': 'Fedora 44'
 }
 
 // Libraries the engine and CEF load from the system. Fedora installs missing ones by soname instead
@@ -30,13 +30,9 @@ const RUNTIME_DEPS_UBUNTU = [
   'libdbus-1-3', 'libfreetype6', 'libglfw3', 'libharfbuzz0b', 'liblz4-1', 'libmpv2', 'libpulse0',
   'libwayland-client0', 'libwayland-cursor0', 'libwayland-egl1', 'libegl1', 'libgl1',
   'libnss3', 'libatk1.0-0t64', 'libatk-bridge2.0-0t64', 'libcups2t64', 'libxcomposite1', 'libxdamage1',
-  'libgbm1', 'libxkbcommon0', 'libasound2t64', 'libpango-1.0-0', 'libcairo2'
-]
-
-const RUNTIME_DEPS_ARCH = [
-  'glew', 'sdl2-compat', 'libx11', 'libxrandr', 'ffmpeg', 'dbus', 'freetype2', 'glfw', 'harfbuzz', 'lz4',
-  'mpv', 'libpulse', 'wayland', 'mesa', 'libglvnd', 'nss', 'at-spi2-core', 'libcups', 'libxcomposite',
-  'libxdamage', 'libxkbcommon', 'alsa-lib', 'pango', 'cairo'
+  'libgbm1', 'libxkbcommon0', 'libasound2t64', 'libpango-1.0-0', 'libcairo2',
+  // V8 for scene scripts
+  'libnode109'
 ]
 
 function readOsRelease(): Record<string, string> {
@@ -53,7 +49,6 @@ function readOsRelease(): Record<string, string> {
 function detectPrebuiltDistro(): PrebuiltDistro | undefined {
   const release = readOsRelease()
   const ids = [release.ID, ...(release.ID_LIKE ?? '').split(/\s+/)].filter(Boolean)
-  if (ids.includes('arch')) return 'arch'
   // Mint 22 and Pop!_OS 24.04 are built on noble and carry its libraries
   if (release.UBUNTU_CODENAME === 'noble' || (release.ID === 'ubuntu' && release.VERSION_ID === '24.04')) {
     return 'ubuntu-24.04'
@@ -72,10 +67,14 @@ export function getPrebuiltTarget(): LwePrebuiltTarget {
   }
   const distro = detectPrebuiltDistro()
   if (!distro) {
-    const name = readOsRelease().PRETTY_NAME ?? 'this distribution'
+    const release = readOsRelease()
+    const isArch = [release.ID, ...(release.ID_LIKE ?? '').split(/\s+/)].includes('arch')
+    const name = release.PRETTY_NAME ?? 'this distribution'
     return {
       supported: false,
-      reason: `There is no prebuilt build for ${name} (only Ubuntu 24.04, Fedora 44 and Arch), build from source instead.`
+      reason: isArch
+        ? 'There is no prebuilt build for Arch for now (V8 is only in the AUR there), build from source instead.'
+        : `There is no prebuilt build for ${name} (only Ubuntu 24.04 and Fedora 44), build from source instead.`
     }
   }
   const variant = isKdeSession() ? 'kde' : 'generic'
@@ -141,9 +140,6 @@ async function installMissingLibraries(distro: PrebuiltDistro, missing: string[]
     case 'fedora-44':
       command = ['dnf', 'install', '-y', ...missing.map(soname => `${soname}()(64bit)`)]
       break
-    case 'arch':
-      command = ['pacman', '-S', '--noconfirm', '--needed', ...RUNTIME_DEPS_ARCH]
-      break
     case 'ubuntu-24.04':
       command = ['apt-get', 'install', '-y', ...RUNTIME_DEPS_UBUNTU]
       break

+ 25 - 1
src/main/services/lwe.service.test.ts

@@ -12,7 +12,7 @@ vi.mock('./config.service', () => ({
   getDisablePuppetAnimation: () => false
 }))
 
-const { buildCleanBuildEnv, buildHotswapLines, parseCustomArgs } = await import('./lwe.service')
+const { buildCleanBuildEnv, buildHotswapLines, nodeDevelPackage, parseCustomArgs } = await import('./lwe.service')
 
 describe('parseCustomArgs', () => {
   it('splits on whitespace and keeps quoted values together', () => {
@@ -35,6 +35,14 @@ describe('buildHotswapLines', () => {
     expect(buildHotswapLines({})).toEqual([])
   })
 
+  it('clears a side of the video trim with none and seeks after setting the range', () => {
+    expect(buildHotswapLines({ videoStart: 180, videoEnd: null, videoSeek: 237 })).toEqual([
+      'video-start=180',
+      'video-end=none',
+      'video-seek=237'
+    ])
+  })
+
   it('replaces the layer lists when either one is present, even empty', () => {
     expect(buildHotswapLines({ disabledObjects: [] })).toEqual(['layers=1'])
     expect(buildHotswapLines({ disabledObjects: ['12'], enabledObjects: ['fog'] })).toEqual([
@@ -85,3 +93,19 @@ describe('buildCleanBuildEnv', () => {
     }
   })
 })
+
+describe('nodeDevelPackage', () => {
+  it('takes the headers of the installed libnode', () => {
+    expect(nodeDevelPackage(['nodejs24-libs', ''])).toBe('nodejs24-devel')
+    expect(nodeDevelPackage(['nodejs-libs'])).toBe('nodejs-devel')
+  })
+
+  it('picks the newest of several installed versions', () => {
+    expect(nodeDevelPackage(['nodejs22-libs', 'nodejs24-libs', 'nodejs20-libs'])).toBe('nodejs24-devel')
+  })
+
+  it('leaves the choice to dnf without an installed libnode', () => {
+    expect(nodeDevelPackage([])).toBe('nodejs-devel')
+    expect(nodeDevelPackage(['nodejs24-docs'])).toBe('nodejs-devel')
+  })
+})

+ 50 - 9
src/main/services/lwe.service.ts

@@ -225,7 +225,9 @@ const DEPS_DEBIAN = [
   'libxxf86vm-dev', 'libglm-dev', 'libglfw3-dev',
   'libmpv-dev', 'mpv', 'libpulse-dev', 'libpulse0', 'libfftw3-dev', 'libfreetype-dev', 'libharfbuzz-dev', 'libdbus-1-dev',
   'libwayland-dev', 'wayland-protocols', 'libegl1-mesa-dev',
-  'libgmp-dev', 'patchelf'
+  'libgmp-dev', 'patchelf',
+  // V8 for scene scripts, from Node.js's shared library
+  'libnode-dev'
 ]
 
 // Fedora/Nobara: 'ffmpeg' conflicts with ffmpeg-free, so only ffmpeg-free-devel is listed
@@ -240,6 +242,30 @@ const DEPS_FEDORA = [
   'gmp-devel', 'patchelf'
 ]
 
+/**
+ * Fedora's Node.js packages are versioned (nodejs22, nodejs24, ...) and their -devel packages conflict, so the headers
+ * have to belong to the libnode already installed; with none installed dnf picks the default for nodejs-devel
+ */
+export function nodeDevelPackage(installedLibs: string[]): string {
+  let best: { name: string; version: number } | undefined
+  for (const name of installedLibs) {
+    const match = /^nodejs(\d*)-libs$/.exec(name.trim())
+    if (!match) continue
+    const version = match[1] ? Number(match[1]) : 0
+    if (!best || version > best.version) best = { name: `nodejs${match[1]}-devel`, version }
+  }
+  return best?.name ?? 'nodejs-devel'
+}
+
+function installedNodeLibs(): string[] {
+  try {
+    return execFileSync('rpm', ['-qa', '--qf', '%{NAME}\n', 'nodejs*-libs'], { encoding: 'utf8', timeout: 10_000 }).split('\n')
+  } catch {
+    return []
+  }
+}
+
+// Arch only has libnode in the AUR, see installLweDeps
 const DEPS_ARCH = [
   'git', 'base-devel', 'cmake', 'pkg-config',
   'glew', 'freeglut', 'sdl2', 'lz4', 'ffmpeg',
@@ -278,7 +304,7 @@ export async function installLweDeps(win: BrowserWindow): Promise<void> {
       pkgManager = 'dnf'
       // --skip-unavailable: avoid failing on missing/broken repos (e.g. Cursor 403) or package renames
       installArgs = ['install', '-y', '--skip-unavailable']
-      packages = DEPS_FEDORA
+      packages = [...DEPS_FEDORA, nodeDevelPackage(installedNodeLibs())]
       break
     case 'arch':
       pkgManager = 'pacman'
@@ -299,9 +325,13 @@ export async function installLweDeps(win: BrowserWindow): Promise<void> {
     await execFileAsync(elevate, [pkgManager, ...installArgs, ...packages], {
       timeout: 600_000
     })
+    // the AUR needs a helper running as the user and builds Node.js from source, that is left to the user
+    const libnodeMissing = distro === 'arch' && !fs.existsSync('/usr/lib/libnode.so')
     send({
       stage: 'done',
-      message: 'Build dependencies installed.',
+      message: libnodeMissing
+        ? 'Build dependencies installed, except V8: Arch only has it in the AUR, install the "libnode" package (e.g. paru -S libnode) before building.'
+        : 'Build dependencies installed.',
       percentage: 100
     })
   } catch (err) {
@@ -401,7 +431,6 @@ export async function installLwe(win: BrowserWindow): Promise<void> {
 
     const buildEnv = buildCleanBuildEnv()
 
-    // cmake configure downloads CEF on first run, which can take several minutes
     send({ stage: 'building', message: 'Running cmake (downloading CEF if needed, may take a few minutes)...', percentage: 25 })
     await execFileAsync('cmake', [
       '..',
@@ -611,7 +640,6 @@ export async function uninstallLwe(): Promise<{ ok: boolean; message: string }>
   }
 }
 
-/** Find the Wallpaper Engine assets directory from the Steam install. */
 function findWeAssetsDir(): string | undefined {
   const workshopPath = getWorkshopPath()
   // Workshop path looks like: .../steamapps/workshop/content/431960
@@ -632,7 +660,6 @@ function findWeAssetsDir(): string | undefined {
   return candidates.find(p => fs.existsSync(p))
 }
 
-/** Directory containing the LWE binary; used for LD_LIBRARY_PATH. */
 function getLweLibDir(): string {
   const p = findLweBinary()
   if (!p) return '/usr/local'
@@ -644,7 +671,6 @@ function getLweLibDir(): string {
   }
 }
 
-/** LD_LIBRARY_PATH value so the loader finds LWE's .so files. */
 function getLweLdLibraryPath(): string {
   const binDir = getLweLibDir()
   const candidates = [
@@ -674,7 +700,6 @@ function getLweBinaryPath(): string {
   }
 }
 
-/** Build env vars that must be set for LWE, as KEY=VALUE strings for use with `env` command. */
 function buildLweEnvVars(): string[] {
   const vars: string[] = []
 
@@ -915,6 +940,8 @@ export interface LweLaunchOptions {
   cornerColor?: string
   imageAdjustments?: ImageAdjustments
   speed?: number
+  videoStart?: number
+  videoEnd?: number
   audioSensitivity?: Record<string, number>
   soundVolume?: Record<string, number>
   customArgs?: string
@@ -924,7 +951,6 @@ export interface LweLaunchOptions {
   forceFresh?: boolean
 }
 
-/** Build the common LWE args (assets dir, screen roots, fps, volume, object overrides). */
 function buildLweArgs(
   wallpaperPath: string,
   options: LweLaunchOptions,
@@ -967,6 +993,10 @@ function buildLweArgs(
   if (options.expandCanvas && supportsExpandCanvas()) args.push('--expand-canvas')
   if (options.cornerColor) args.push('--corner-color', options.cornerColor)
   if (options.speed !== undefined) args.push('--speed', String(options.speed))
+  if (supportsFlag('--video-start')) {
+    if (options.videoStart !== undefined) args.push('--video-start', String(options.videoStart))
+    if (options.videoEnd !== undefined) args.push('--video-end', String(options.videoEnd))
+  }
   if ((options.disabledObjects?.length || options.enabledObjects?.length) && supportsObjectFlags()) {
     for (const id of options.disabledObjects ?? []) args.push('--disable-object', id)
     for (const id of options.enabledObjects ?? []) args.push('--enable-object', id)
@@ -1253,6 +1283,11 @@ export interface HotswapOptions {
   cornerColor?: string
   imageAdjustments?: ImageAdjustments
   speed?: number
+  /** null clears that side of the video trim */
+  videoStart?: number | null
+  videoEnd?: number | null
+  /** Jumps a video wallpaper to this many seconds, e.g. to watch the loop point */
+  videoSeek?: number
   propertyOverrides?: Record<string, string>
   /** Empty string clears the restriction back to "every screen can produce audio" */
   audioScreen?: string
@@ -1290,6 +1325,9 @@ export function buildHotswapLines(options: HotswapOptions): string[] {
   if (options.cornerColor !== undefined) lines.push(`corner-color=${options.cornerColor}`)
   lines.push(...imageAdjustmentLines(options.imageAdjustments))
   if (options.speed !== undefined) lines.push(`speed=${options.speed}`)
+  if (options.videoStart !== undefined) lines.push(`video-start=${options.videoStart ?? 'none'}`)
+  if (options.videoEnd !== undefined) lines.push(`video-end=${options.videoEnd ?? 'none'}`)
+  if (options.videoSeek !== undefined) lines.push(`video-seek=${options.videoSeek}`)
   if (options.audioScreen !== undefined) lines.push(`audio-screen=${options.audioScreen}`)
   if (options.ambientVolume !== undefined) lines.push(`ambient-volume=${options.ambientVolume}`)
   for (const [name, value] of Object.entries(options.propertyOverrides ?? {})) {
@@ -1387,6 +1425,9 @@ function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): Ho
     cornerColor: options.cornerColor ?? '000000',
     imageAdjustments: options.imageAdjustments,
     speed: options.speed ?? 1,
+    // the engine drops the trim on a path swap, so only a trimmed wallpaper has to send one
+    videoStart: options.videoStart,
+    videoEnd: options.videoEnd,
     propertyOverrides: options.propertyOverrides ?? {},
     audioSensitivity: {
       ...(defaultSensitivity !== 1 ? { '*': defaultSensitivity } : {}),

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

@@ -3,6 +3,7 @@ import type { BrowserWindow } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
 import type { Playlist, PlaylistItem, PlaylistPlaybackState, ScreenTarget } from '@shared/types'
 import { compatStatus } from '@shared/compat'
+import { trimmedVideoLength } from '@shared/videoTrim'
 import { getPlaylist } from './playlist.service'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getLweStatus, ALL_SCREENS } from './lwe.service'
@@ -156,7 +157,8 @@ async function getVideoLengthSec(wallpaperId: string): Promise<number | undefine
   const wallpaper = getWallpaper(wallpaperId)
   if (wallpaper?.type !== 'video' || !wallpaper.localPath) return undefined
   const videoFile = findWallpaperVideoFile(wallpaper.localPath, wallpaper.file)
-  return videoFile ? getVideoDurationSec(videoFile) : undefined
+  const duration = videoFile ? await getVideoDurationSec(videoFile) : undefined
+  return duration === undefined ? undefined : trimmedVideoLength(duration, wallpaper.videoStart, wallpaper.videoEnd)
 }
 
 function scheduleNext(player: Player, playlist: Playlist): void {

+ 2 - 0
src/main/services/wallpaper.service.ts

@@ -240,6 +240,8 @@ export async function lweOptionsFor(
     cornerColor: wallpaper.cornerColor,
     imageAdjustments: wallpaper.imageAdjustments,
     speed: wallpaper.playbackSpeed,
+    videoStart: wallpaper.type === 'video' ? wallpaper.videoStart : undefined,
+    videoEnd: wallpaper.type === 'video' ? wallpaper.videoEnd : undefined,
     audioSensitivity: wallpaper.audioSensitivity,
     soundVolume: wallpaper.soundVolume,
     customArgs: wallpaper.customArgs

+ 35 - 64
src/main/services/workshop.service.ts

@@ -45,24 +45,10 @@ export async function queryWorkshop(params: WorkshopQueryParams): Promise<Worksh
     13, // UGCType.All, since WE items span multiple subtypes
     appId,
     appId,
-    {
-      searchText: params.searchText,
-      requiredTags: params.tags,
-      excludedTags: params.excludedTags,
-      includeLongDescription: true
-    }
+    queryConfig(params)
   )
 
-  const subscribedSet = new Set(await getSubscribedItems())
-
-  const items = result.items.filter(Boolean).map((item) => transformItem(item!, subscribedSet))
-  await attachFileSizes(items)
-
-  return {
-    items,
-    page,
-    totalResults: result.totalResults
-  }
+  return toQueryResult(result, page)
 }
 
 export async function getWorkshopItem(publishedFileId: string): Promise<WorkshopItem | null> {
@@ -103,26 +89,28 @@ export async function queryWorkshopByCreator(
     13, // UGCType.All
     sortOrder,
     { consumer: WE_APP_ID },
-    {
-      searchText: params.searchText,
-      requiredTags: params.tags,
-      excludedTags: params.excludedTags,
-      includeLongDescription: true
-    }
+    queryConfig(params)
   )
 
-  const subscribedSet = new Set(await getSubscribedItems())
-
-  const items = result.items.filter(Boolean).map((item) => transformItem(item!, subscribedSet))
-  await attachFileSizes(items)
+  return toQueryResult(result, page)
+}
 
+function queryConfig(params: CreatorWorkshopQueryParams): workshop.WorkshopItemQueryConfig {
   return {
-    items,
-    page,
-    totalResults: result.totalResults
+    searchText: params.searchText,
+    requiredTags: params.tags,
+    excludedTags: params.excludedTags,
+    includeLongDescription: true
   }
 }
 
+async function toQueryResult(result: WorkshopPage, page: number): Promise<WorkshopQueryResult> {
+  const subscribedSet = new Set(await getSubscribedItems())
+  const items = result.items.filter(Boolean).map((item) => transformItem(item!, subscribedSet))
+  await attachFileSizes(items)
+  return { items, page, totalResults: result.totalResults }
+}
+
 // A details query only fetches its first result page, and Steam pages those at 50 items -
 // anything past that in a single getItems() call silently comes back missing.
 const DETAILS_QUERY_BATCH = 50
@@ -139,39 +127,27 @@ async function getItemsBatched(publishedFileIds: string[]) {
   return items
 }
 
-export async function getWorkshopTimesUpdated(
-  publishedFileIds: string[]
-): Promise<Map<string, number>> {
-  const map = new Map<string, number>()
-  if (publishedFileIds.length === 0) return map
-
-  for (const item of await getItemsBatched(publishedFileIds)) {
-    map.set(item.publishedFileId.toString(), item.timeUpdated)
-  }
-  return map
+export interface WorkshopDetails {
+  timeUpdated: number
+  // Steam tags an item's type ("Video", "Scene", ...) and age rating ("Everyone", ...)
+  // alongside its genre/resolution tags, so this works even for items that never
+  // finished downloading and have no local project.json to read that from.
+  tags: string[]
+  authorSteamId: string
 }
 
-// Steam tags an item's type ("Video", "Scene", ...) and age rating ("Everyone", ...)
-// alongside its genre/resolution tags, so this works even for items that never
-// finished downloading and have no local project.json to read that from.
-export async function getWorkshopTags(publishedFileIds: string[]): Promise<Map<string, string[]>> {
-  const map = new Map<string, string[]>()
+// One details query serves everything the library backfills (update time, live tags, author),
+// ids Steam no longer resolves are simply missing from the map
+export async function getWorkshopDetails(publishedFileIds: string[]): Promise<Map<string, WorkshopDetails>> {
+  const map = new Map<string, WorkshopDetails>()
   if (publishedFileIds.length === 0) return map
 
   for (const item of await getItemsBatched(publishedFileIds)) {
-    map.set(item.publishedFileId.toString(), item.tags ?? [])
-  }
-  return map
-}
-
-// Used to backfill authorSteamId on library items imported before this field existed
-// (and on items that never finished downloading, since they have no project.json).
-export async function getWorkshopAuthors(publishedFileIds: string[]): Promise<Map<string, string>> {
-  const map = new Map<string, string>()
-  if (publishedFileIds.length === 0) return map
-
-  for (const item of await getItemsBatched(publishedFileIds)) {
-    map.set(item.publishedFileId.toString(), item.owner.steamId64.toString())
+    map.set(item.publishedFileId.toString(), {
+      timeUpdated: item.timeUpdated,
+      tags: item.tags ?? [],
+      authorSteamId: item.owner.steamId64.toString()
+    })
   }
   return map
 }
@@ -182,13 +158,8 @@ export async function getWorkshopAuthors(publishedFileIds: string[]): Promise<Ma
 // propagate rather than swallowing it here - the caller decides what "we
 // couldn't tell" should mean, instead of this silently reporting "all clear".
 export async function getUnavailableWorkshopItems(publishedFileIds: string[]): Promise<Set<string>> {
-  const unavailable = new Set(publishedFileIds)
-  if (publishedFileIds.length === 0) return unavailable
-
-  for (const item of await getItemsBatched(publishedFileIds)) {
-    unavailable.delete(item.publishedFileId.toString())
-  }
-  return unavailable
+  const details = await getWorkshopDetails(publishedFileIds)
+  return new Set(publishedFileIds.filter((id) => !details.has(id)))
 }
 
 // steamworks.js's UGC query bindings don't surface a file's size (the underlying Steamworks SDK

+ 5 - 0
src/preload/index.ts

@@ -317,6 +317,9 @@ const api = {
       cornerColor?: string
       imageAdjustments?: ImageAdjustments
       speed?: number
+      videoStart?: number | null
+      videoEnd?: number | null
+      videoSeek?: number
       propertyOverrides?: Record<string, string>
       audioScreen?: string
       ambientVolume?: number
@@ -328,6 +331,8 @@ const api = {
       ipcRenderer.invoke(IpcChannels.LWE_LIST_PROPERTIES, wallpaperPath),
     listScreens: (): Promise<string[]> =>
       ipcRenderer.invoke(IpcChannels.LWE_LIST_SCREENS),
+    videoDuration: (wallpaperPath: string, projectFile?: string): Promise<number | null> =>
+      ipcRenderer.invoke(IpcChannels.LWE_VIDEO_DURATION, wallpaperPath, projectFile),
     listAudioObjects: (wallpaperPath: string): Promise<LweAudioObject[]> =>
       ipcRenderer.invoke(IpcChannels.LWE_LIST_AUDIO_OBJECTS, wallpaperPath),
     listEffects: (wallpaperPath: string): Promise<LweSceneEffect[]> =>

+ 23 - 1
src/renderer/src/assets/index.css

@@ -5,6 +5,10 @@
     box-sizing: border-box;
   }
 
+  :root {
+    color-scheme: dark;
+  }
+
   html, body, #root {
     height: 100%;
     margin: 0;
@@ -18,7 +22,25 @@
     -webkit-font-smoothing: antialiased;
   }
 
-  /* Custom scrollbar */
+  select {
+    color-scheme: dark;
+    cursor: pointer;
+  }
+
+  select:disabled {
+    cursor: default;
+  }
+
+  select option,
+  select optgroup {
+    background-color: #1a1a1a;
+    color: #d1d5db;
+  }
+
+  select option:disabled {
+    color: #6b7280;
+  }
+
   ::-webkit-scrollbar {
     width: 6px;
   }

+ 136 - 0
src/renderer/src/components/common/ContextMenu.tsx

@@ -0,0 +1,136 @@
+import { useRef, useState, type ReactNode } from 'react'
+import { ChevronRight, Folder, FolderInput, ThumbsDown, ThumbsUp, Trash2, type LucideIcon } from 'lucide-react'
+import clsx from 'clsx'
+import type { WallpaperFolder } from '@shared/types'
+import { useClickOutside } from '../../hooks/useClickOutside'
+import { useClampedPosition, useFlipSide } from '../../hooks/useContextMenuPosition'
+
+const POPUP_CLASS = 'rounded-lg border border-white/10 bg-[#1a1a1a] py-1 shadow-xl'
+
+export function ContextMenu({
+  x,
+  y,
+  onClose,
+  className = 'min-w-[200px]',
+  children
+}: {
+  x: number
+  y: number
+  onClose: () => void
+  className?: string
+  children: ReactNode
+}) {
+  const ref = useRef<HTMLDivElement>(null)
+  useClickOutside(ref, onClose)
+  const pos = useClampedPosition(ref, { x, y })
+
+  return (
+    <div
+      ref={ref}
+      className={clsx('fixed z-50 text-sm', POPUP_CLASS, className)}
+      style={{ left: pos?.x ?? x, top: pos?.y ?? y }}
+    >
+      {children}
+    </div>
+  )
+}
+
+export function MenuItem({
+  icon: Icon,
+  danger = false,
+  onClick,
+  children
+}: {
+  icon?: LucideIcon
+  danger?: boolean
+  onClick: () => void
+  children: ReactNode
+}) {
+  return (
+    <button
+      onClick={onClick}
+      className={clsx(
+        'flex w-full items-center gap-2 px-3 py-1.5 hover:bg-white/5',
+        danger ? 'text-red-400' : 'text-gray-300'
+      )}
+    >
+      {Icon && <Icon size={12} />}
+      {children}
+    </button>
+  )
+}
+
+export function MenuSeparator() {
+  return <div className="my-1 border-t border-white/5" />
+}
+
+export function MenuSelectionCount({ count }: { count: number }) {
+  if (count < 2) return null
+  return <div className="mb-1 border-b border-white/5 px-3 py-1 text-xs text-gray-600">{count} items selected</div>
+}
+
+export function VoteMenuItems({ onVote }: { onVote: (up: boolean) => void }) {
+  return (
+    <>
+      <MenuItem icon={ThumbsUp} onClick={() => onVote(true)}>
+        Like
+      </MenuItem>
+      <MenuItem icon={ThumbsDown} onClick={() => onVote(false)}>
+        Dislike
+      </MenuItem>
+    </>
+  )
+}
+
+// "Move to folder" submenu plus "Remove from folder" when anything selected is in one
+export function FolderMenuItems({
+  moveTargets,
+  hasFolder,
+  onMove,
+  onRemove
+}: {
+  moveTargets: WallpaperFolder[]
+  hasFolder: boolean
+  onMove: (folderId: string) => void
+  onRemove: () => void
+}) {
+  const [open, setOpen] = useState(false)
+  const subRef = useRef<HTMLDivElement>(null)
+  const side = useFlipSide(subRef, open)
+
+  return (
+    <>
+      <div className="relative">
+        <button
+          onClick={() => setOpen((v) => !v)}
+          className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
+        >
+          <FolderInput size={12} /> Move to folder
+          <ChevronRight size={12} className="ml-auto" />
+        </button>
+        {open && (
+          <div
+            ref={subRef}
+            className={clsx(
+              'absolute top-0 min-w-[160px]',
+              POPUP_CLASS,
+              side === 'left' ? 'right-full mr-1' : 'left-full ml-1'
+            )}
+          >
+            {moveTargets.length === 0 && <div className="px-3 py-1.5 text-gray-500">No other folders</div>}
+            {moveTargets.map((f) => (
+              <MenuItem key={f.id} icon={Folder} onClick={() => onMove(f.id)}>
+                {f.title}
+              </MenuItem>
+            ))}
+          </div>
+        )}
+      </div>
+      {hasFolder && (
+        <MenuItem icon={Trash2} danger onClick={onRemove}>
+          Remove from folder
+        </MenuItem>
+      )}
+    </>
+  )
+}

+ 65 - 73
src/renderer/src/components/common/DetailSidebar.tsx

@@ -1,4 +1,4 @@
-import { useState, useRef } from 'react'
+import { useState, useRef, type ReactNode } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import {
   X,
@@ -36,17 +36,20 @@ import {
   Music2,
   Terminal,
   Sparkles,
-  CloudFog
+  CloudFog,
+  type LucideIcon
 } from 'lucide-react'
 import clsx from 'clsx'
 import { openWorkshopPage, openProfilePage, isWorkshopId } from '../../utils/steam'
 import { WE_TYPES, WE_AGE_RATINGS, canonicalResolutionTag, resolutionsFromTags } from '../../constants/weFilters'
 import { formatFileSize } from '../../utils/format'
-import { useToast } from './Toast'
+import { useVoteAction, useVotedIds } from '../../hooks/useVotes'
+import { useLweInstalled } from '../../hooks/queries'
 import ScreenSelect from './ScreenSelect'
 import { getPreviewSrc } from '../../utils/preview'
 import EngineFlagsSection from './sidebar/EngineFlagsSection'
 import ImageAdjustmentsSection from './sidebar/ImageAdjustmentsSection'
+import VideoTrimSection from './sidebar/VideoTrimSection'
 import CompatSection from './sidebar/CompatSection'
 import ThumbnailSection from './sidebar/ThumbnailSection'
 import { ShortcutRow } from './ShortcutRow'
@@ -274,7 +277,7 @@ function PropertyRow({
           value={value}
           disabled={busy}
           onChange={(e) => onCommit(e.target.value)}
-          className="rounded bg-white/5 px-1.5 py-0.5 text-xs text-gray-300 outline-none disabled:opacity-50 [&>option]:bg-[#1a1a1a]"
+          className="rounded bg-white/5 px-1.5 py-0.5 text-xs text-gray-300 outline-none disabled:opacity-50"
         >
           {property.options?.map((opt) => (
             <option key={opt.value} value={opt.value}>
@@ -376,6 +379,18 @@ function SoundTrackRow({
   )
 }
 
+function SidebarButton({ icon: Icon, onClick, children }: { icon: LucideIcon; onClick: () => void; children: ReactNode }) {
+  return (
+    <button
+      onClick={onClick}
+      className="flex items-center justify-center gap-1.5 rounded-lg bg-white/5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10"
+    >
+      <Icon size={12} />
+      {children}
+    </button>
+  )
+}
+
 interface DetailSidebarProps {
   id: string
   fallbackTitle: string
@@ -384,13 +399,10 @@ interface DetailSidebarProps {
   fallbackAuthorSteamId?: string
   localFileSize?: number
   isSubscribed: boolean
-  isLiked: boolean
   canPlay: boolean
-  lweInstalled: boolean
   onClose: () => void
   onSubscribe: () => void
   onUnsubscribe: () => void | Promise<void>
-  onLiked: () => void
   onPlay: (screen?: ScreenTarget) => void | Promise<void>
   onBrowseCreator?: (steamId: string) => void
 }
@@ -403,21 +415,18 @@ export default function DetailSidebar({
   fallbackAuthorSteamId,
   localFileSize,
   isSubscribed,
-  isLiked: cachedLiked,
   canPlay,
-  lweInstalled,
   onClose,
   onSubscribe,
   onUnsubscribe,
-  onLiked,
   onPlay,
   onBrowseCreator
 }: DetailSidebarProps) {
   const workshopId = isWorkshopId(id)
   const queryClient = useQueryClient()
-  const { showToast } = useToast()
-  const [isLiking, setIsLiking] = useState(false)
-  const [isDisliking, setIsDisliking] = useState(false)
+  const lweInstalled = useLweInstalled()
+  const cachedLiked = useVotedIds().has(id)
+  const { vote, isLiking, isDisliking } = useVoteAction()
   const [isApplying, setIsApplying] = useState(false)
   const [unsubConfirm, setUnsubConfirm] = useState(false)
   const [isUnsubscribing, setIsUnsubscribing] = useState(false)
@@ -539,6 +548,14 @@ export default function DetailSidebar({
   const soundObjects = objects.filter((o) => o.type === 'sound')
   const soundVolume = libraryMeta?.soundVolume ?? {}
 
+  const { data: videoDuration = null } = useQuery({
+    queryKey: ['video-duration', localPath],
+    queryFn: () => window.electronAPI.lwe.videoDuration(localPath!, libraryMeta?.file),
+    enabled: !!localPath && libraryMeta?.type === 'video',
+    staleTime: Infinity,
+    retry: false
+  })
+
   // Persists a settings patch and, if this wallpaper is currently playing, pushes it live via
   // the control-file hotswap (no process restart). Falls back to a full stop+relaunch if the
   // push fails, e.g. an older linux-wallpaperengine build without the extended protocol.
@@ -564,6 +581,9 @@ export default function DetailSidebar({
             cornerColor: patch.cornerColor,
             imageAdjustments: patch.imageAdjustments,
             speed: patch.playbackSpeed,
+            // undefined in a patch that has the key clears that side of the trim
+            videoStart: 'videoStart' in patch ? (patch.videoStart ?? null) : undefined,
+            videoEnd: 'videoEnd' in patch ? (patch.videoEnd ?? null) : undefined,
             propertyOverrides: patch.propertyOverrides,
             audioSensitivity: patch.audioSensitivity,
             soundVolume: patch.soundVolume
@@ -595,6 +615,9 @@ export default function DetailSidebar({
     offsetY?: number
     speed?: number
     imageAdjustments?: ImageAdjustments
+    videoStart?: number | null
+    videoEnd?: number | null
+    videoSeek?: number
   }) {
     if (!isActive) return
     if (livePreviewTimer.current) clearTimeout(livePreviewTimer.current)
@@ -861,36 +884,9 @@ export default function DetailSidebar({
   // size (item.fileSize) - they can differ once extracted, and the local number is exact.
   const fileSizeLabel = formatFileSize(libraryMeta?.fileSize ?? item?.fileSize ?? localFileSize)
 
-  async function handleLike() {
-    if (isLiked || isLiking || unavailable) return
-    setIsLiking(true)
-    try {
-      const { confirmed } = await window.electronAPI.steam.vote(id, true)
-      if (confirmed) {
-        queryClient.setQueryData(['steam-vote', id], true)
-        onLiked()
-      } else {
-        showToast('Could not confirm the like on Steam - try again')
-      }
-    } catch (err) {
-      showToast((err as Error).message)
-    } finally {
-      setIsLiking(false)
-    }
-  }
-
-  async function handleDislike() {
-    if (isDisliking || unavailable) return
-    setIsDisliking(true)
-    try {
-      const { confirmed } = await window.electronAPI.steam.vote(id, false)
-      if (confirmed) queryClient.setQueryData(['steam-vote', id], false)
-      if (!confirmed) showToast('Could not confirm the dislike on Steam - try again')
-    } catch (err) {
-      showToast((err as Error).message)
-    } finally {
-      setIsDisliking(false)
-    }
+  function handleVote(up: boolean) {
+    if (unavailable || (up && isLiked)) return
+    void vote(id, up)
   }
 
   async function handlePlay() {
@@ -1079,7 +1075,7 @@ export default function DetailSidebar({
               value={scalingMode}
               disabled={isCommittingScaling}
               onChange={(e) => commitScaling(e.target.value as ScalingMode)}
-              className="w-full rounded bg-white/5 px-1.5 py-1 text-xs text-gray-300 outline-none disabled:opacity-50 [&>option]:bg-[#1a1a1a]"
+              className="w-full rounded bg-white/5 px-1.5 py-1 text-xs text-gray-300 outline-none disabled:opacity-50"
             >
               {SCALING_MODE_OPTIONS.map((opt) => (
                 <option key={opt.value} value={opt.value}>
@@ -1271,6 +1267,19 @@ export default function DetailSidebar({
           </div>
         )}
 
+        {localPath && lweInstalled && libraryMeta?.type === 'video' && (
+          <VideoTrimSection
+            start={libraryMeta.videoStart}
+            end={libraryMeta.videoEnd}
+            duration={videoDuration}
+            live={isActive}
+            onCommit={({ start, end }) => persistAndMaybeRelaunch({ videoStart: start, videoEnd: end })}
+            onPreview={({ start, end }, seek) =>
+              previewLive({ videoStart: start ?? null, videoEnd: end ?? null, videoSeek: seek })
+            }
+          />
+        )}
+
         {localPath && lweInstalled && (libraryMeta?.type === 'scene' || libraryMeta?.type === 'video') && (
           <ImageAdjustmentsSection
             adjustments={libraryMeta.imageAdjustments}
@@ -1553,7 +1562,6 @@ export default function DetailSidebar({
               onUpdated={(updated) => {
                 queryClient.setQueryData(['library-item', id], updated)
                 queryClient.invalidateQueries({ queryKey: ['library'] })
-                queryClient.invalidateQueries({ queryKey: ['library-all'] })
               }}
             />
           </>
@@ -1562,8 +1570,8 @@ export default function DetailSidebar({
         <div className="flex flex-col gap-1.5 border-t border-white/5 pt-3">
           <div className="flex gap-1.5">
             <button
-              onClick={handleLike}
-              disabled={isLiked || isLiking || unavailable}
+              onClick={() => handleVote(true)}
+              disabled={isLiked || isLiking || isDisliking || unavailable}
               title={unavailable ? 'Removed from the Steam Workshop - voting is no longer possible' : undefined}
               className={clsx(
                 'flex flex-1 items-center justify-center gap-1.5 rounded-lg py-1.5 text-xs transition-colors disabled:cursor-not-allowed',
@@ -1578,8 +1586,8 @@ export default function DetailSidebar({
               {isLiked ? 'Liked' : 'Like'}
             </button>
             <button
-              onClick={handleDislike}
-              disabled={isDisliking || unavailable}
+              onClick={() => handleVote(false)}
+              disabled={isLiking || isDisliking || unavailable}
               title={unavailable ? 'Removed from the Steam Workshop - voting is no longer possible' : undefined}
               className={clsx(
                 'flex flex-1 items-center justify-center gap-1.5 rounded-lg py-1.5 text-xs transition-colors disabled:cursor-not-allowed',
@@ -1625,42 +1633,26 @@ export default function DetailSidebar({
               {unsubConfirm ? 'Click again to confirm' : 'Unsubscribe'}
             </button>
           ) : (
-            <button
-              onClick={onSubscribe}
-              className="flex items-center justify-center gap-1.5 rounded-lg bg-white/5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10"
-            >
-              <Download size={12} />
+            <SidebarButton icon={Download} onClick={onSubscribe}>
               Subscribe
-            </button>
+            </SidebarButton>
           )}
 
           {workshopId && (
             <>
-              <button
-                onClick={() => window.electronAPI.steam.openWorkshopItem(id)}
-                className="flex items-center justify-center gap-1.5 rounded-lg bg-white/5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10"
-              >
-                <MessageCircle size={12} />
+              <SidebarButton icon={MessageCircle} onClick={() => window.electronAPI.steam.openWorkshopItem(id)}>
                 Comment
-              </button>
-              <button
-                onClick={() => openWorkshopPage(id)}
-                className="flex items-center justify-center gap-1.5 rounded-lg bg-white/5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10"
-              >
-                <ExternalLink size={12} />
+              </SidebarButton>
+              <SidebarButton icon={ExternalLink} onClick={() => openWorkshopPage(id)}>
                 Open in Steam Workshop
-              </button>
+              </SidebarButton>
             </>
           )}
 
           {creatorSteamId && (
-            <button
-              onClick={() => openProfilePage(creatorSteamId)}
-              className="flex items-center justify-center gap-1.5 rounded-lg bg-white/5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10"
-            >
-              <User size={12} />
+            <SidebarButton icon={User} onClick={() => openProfilePage(creatorSteamId)}>
               View creator's Steam profile
-            </button>
+            </SidebarButton>
           )}
         </div>
       </div>

+ 168 - 0
src/renderer/src/components/common/FilterPanel.tsx

@@ -0,0 +1,168 @@
+import { useState, type ReactNode } from 'react'
+import { ChevronDown, ChevronRight } from 'lucide-react'
+import { WE_RESOLUTION_GROUPS, setGroupSelected, type FilterItem } from '../../constants/weFilters'
+import { toggle } from '../../utils/array'
+
+// Collapsible filter sidebar shared by the workshop and library views
+
+export function FilterPanel({ children }: { children: ReactNode }) {
+  return (
+    <div className="w-52 flex-shrink-0 space-y-3 overflow-y-auto border-r border-white/5 bg-[#0d0d0d] px-3 py-3">
+      {children}
+    </div>
+  )
+}
+
+export function CheckItem({
+  label,
+  checked,
+  count,
+  title,
+  onChange
+}: {
+  label: string
+  checked: boolean
+  count?: number
+  title?: string
+  onChange: () => void
+}) {
+  return (
+    <label
+      title={title}
+      className="flex cursor-pointer items-center gap-2 py-0.5 text-xs text-gray-400 hover:text-gray-200"
+    >
+      <input type="checkbox" checked={checked} onChange={onChange} className="cursor-pointer accent-indigo-500" />
+      <span className="flex-1 truncate">{label}</span>
+      {count !== undefined && <span className="text-[11px] text-gray-600">{count}</span>}
+    </label>
+  )
+}
+
+export function AllNoneButtons({ onAll, onNone }: { onAll: () => void; onNone: () => void }) {
+  return (
+    <div className="flex gap-2">
+      <button onClick={onAll} className="text-[10px] text-gray-600 hover:text-gray-400">all</button>
+      <button onClick={onNone} className="text-[10px] text-gray-600 hover:text-gray-400">none</button>
+    </div>
+  )
+}
+
+export function FilterSection({
+  title,
+  children,
+  defaultOpen = true,
+  activeCount = 0,
+  onAll,
+  onNone
+}: {
+  title: string
+  children: ReactNode
+  defaultOpen?: boolean
+  activeCount?: number
+  onAll?: () => void
+  onNone?: () => void
+}) {
+  const [open, setOpen] = useState(defaultOpen)
+  return (
+    <div>
+      <button
+        onClick={() => setOpen((v) => !v)}
+        className="flex w-full items-center gap-1 py-1 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300"
+      >
+        {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+        <span className="flex-1 text-left">{title}</span>
+        {activeCount > 0 && <span className="rounded-full bg-indigo-600/40 px-1.5 text-indigo-300">{activeCount}</span>}
+      </button>
+      {open && (
+        <div className="mt-1 space-y-0.5 pl-1">
+          {onAll && onNone && (
+            <div className="pb-0.5">
+              <AllNoneButtons onAll={onAll} onNone={onNone} />
+            </div>
+          )}
+          {children}
+        </div>
+      )}
+    </div>
+  )
+}
+
+export function TagFilterSection({
+  title,
+  options,
+  selected,
+  activeCount = selected.length,
+  defaultOpen,
+  onChange
+}: {
+  title: string
+  options: FilterItem[]
+  selected: string[]
+  activeCount?: number
+  defaultOpen?: boolean
+  onChange: (tags: string[]) => void
+}) {
+  return (
+    <FilterSection
+      title={title}
+      defaultOpen={defaultOpen}
+      activeCount={activeCount}
+      onAll={() => onChange(options.map((i) => i.tag))}
+      onNone={() => onChange([])}
+    >
+      {options.map((item) => (
+        <CheckItem
+          key={item.tag}
+          label={item.label}
+          checked={selected.includes(item.tag)}
+          onChange={() => onChange(toggle(selected, item.tag))}
+        />
+      ))}
+    </FilterSection>
+  )
+}
+
+export function ResolutionFilterSection({
+  selected,
+  allTags,
+  activeCount = selected.length,
+  counts,
+  onChange
+}: {
+  selected: string[]
+  allTags: string[]
+  activeCount?: number
+  counts?: Map<string, number>
+  onChange: (resolutions: string[]) => void
+}) {
+  return (
+    <FilterSection
+      title="Resolution"
+      defaultOpen={false}
+      activeCount={activeCount}
+      onAll={() => onChange(allTags)}
+      onNone={() => onChange([])}
+    >
+      {WE_RESOLUTION_GROUPS.map((group) => (
+        <div key={group.label} className="mt-2">
+          <div className="mb-0.5 flex items-center justify-between pl-0.5">
+            <p className="text-xs text-gray-600">{group.label}</p>
+            <AllNoneButtons
+              onAll={() => onChange(setGroupSelected(selected, group, true))}
+              onNone={() => onChange(setGroupSelected(selected, group, false))}
+            />
+          </div>
+          {group.items.map((item) => (
+            <CheckItem
+              key={item.tag}
+              label={item.label}
+              checked={selected.includes(item.tag)}
+              count={counts ? (counts.get(item.tag) ?? 0) : undefined}
+              onChange={() => onChange(toggle(selected, item.tag))}
+            />
+          ))}
+        </div>
+      ))}
+    </FilterSection>
+  )
+}

+ 227 - 0
src/renderer/src/components/common/GridCard.tsx

@@ -0,0 +1,227 @@
+import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from 'react'
+import { Check, ExternalLink, Loader2, Play, ThumbsUp, type LucideIcon } from 'lucide-react'
+import clsx from 'clsx'
+import { voteBorderClass } from '../../hooks/useVoteBorders'
+import { useVoteAction } from '../../hooks/useVotes'
+import { openWorkshopPage } from '../../utils/steam'
+
+// Building blocks shared by the workshop and library wallpaper cards
+
+interface GridCardProps extends HTMLAttributes<HTMLDivElement> {
+  selected: boolean
+  isDetailOpen: boolean
+  isLiked: boolean
+  voteError?: string
+  showVoteBorder: boolean
+  [dataAttr: `data-${string}`]: string
+}
+
+export function GridCard({
+  selected,
+  isDetailOpen,
+  isLiked,
+  voteError,
+  showVoteBorder,
+  className,
+  children,
+  ...rest
+}: GridCardProps) {
+  return (
+    <div
+      {...rest}
+      title={showVoteBorder ? voteError : undefined}
+      className={clsx(
+        'group relative cursor-pointer select-none overflow-hidden rounded-lg bg-[#1a1a1a] transition-all',
+        isDetailOpen ? 'ring-2 ring-sky-400' : selected ? 'ring-2 ring-indigo-500' : 'hover:ring-1 hover:ring-indigo-500/50',
+        showVoteBorder && voteBorderClass(voteError, isLiked),
+        className
+      )}
+    >
+      <div
+        className={clsx(
+          'absolute left-2 top-2 z-10 flex h-5 w-5 items-center justify-center rounded border transition-all',
+          selected
+            ? 'border-indigo-500 bg-indigo-600 text-white opacity-100'
+            : 'border-white/30 bg-black/50 text-transparent opacity-0 group-hover:opacity-100'
+        )}
+      >
+        <Check size={12} />
+      </div>
+      {children}
+    </div>
+  )
+}
+
+export function CardPreview({
+  src,
+  alt,
+  dimmed = false,
+  children
+}: {
+  src?: string
+  alt: string
+  dimmed?: boolean
+  children?: ReactNode
+}) {
+  return (
+    <div className="relative aspect-video overflow-hidden bg-[#111]">
+      {src ? (
+        <img
+          src={src}
+          alt={alt}
+          className={clsx(
+            'h-full w-full object-cover transition-transform duration-300 group-hover:scale-105',
+            dimmed && 'brightness-50'
+          )}
+          loading="lazy"
+          draggable={false}
+        />
+      ) : (
+        <div className="flex h-full items-center justify-center text-gray-600">No preview</div>
+      )}
+      {children}
+    </div>
+  )
+}
+
+// full-preview status layer (downloading, failed, backing up)
+export function CardOverlay({ children }: { children: ReactNode }) {
+  return (
+    <div className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-black/70 px-4 text-center">
+      {children}
+    </div>
+  )
+}
+
+export function ProgressBar({ percentage, className }: { percentage: number; className: string }) {
+  return (
+    <div className={clsx('overflow-hidden', className)}>
+      <div className="h-full bg-indigo-500 transition-[width]" style={{ width: `${percentage}%` }} />
+    </div>
+  )
+}
+
+// small square status icon in a preview corner
+export function CornerBadge({ className, title, children }: { className: string; title: string; children: ReactNode }) {
+  return (
+    <div className={clsx('absolute flex h-5 w-5 items-center justify-center rounded', className)} title={title}>
+      {children}
+    </div>
+  )
+}
+
+type ActionTone = 'default' | 'active' | 'danger' | 'muted'
+
+const TONE_CLASS: Record<ActionTone, string> = {
+  default: 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-gray-200 disabled:cursor-not-allowed disabled:opacity-50',
+  active: 'bg-green-600/30 text-green-300 disabled:cursor-default',
+  danger: 'bg-white/5 text-gray-400 hover:bg-red-500/20 hover:text-red-400 disabled:cursor-not-allowed disabled:opacity-50',
+  muted: 'bg-white/5 text-gray-600 opacity-50 disabled:cursor-not-allowed'
+}
+
+interface CardActionProps extends ButtonHTMLAttributes<HTMLButtonElement> {
+  icon: LucideIcon
+  label: string
+  busy?: boolean
+  compact?: boolean
+  tone?: ActionTone
+}
+
+// row button under a card's title, icon-only when compact
+export function CardAction({ icon: Icon, label, busy, compact = false, tone = 'default', onClick, ...rest }: CardActionProps) {
+  return (
+    <button
+      {...rest}
+      onClick={(e) => {
+        e.stopPropagation()
+        onClick?.(e)
+      }}
+      className={clsx(
+        'flex items-center gap-1 rounded text-xs transition-colors',
+        compact ? 'p-1.5' : 'px-2 py-1',
+        TONE_CLASS[tone]
+      )}
+    >
+      {busy ? <Loader2 size={11} className="animate-spin" /> : <Icon size={11} />}
+      {!compact && label}
+    </button>
+  )
+}
+
+export function LikeAction({
+  id,
+  isLiked,
+  unavailable = false,
+  compact,
+  onError
+}: {
+  id: string
+  isLiked: boolean
+  unavailable?: boolean
+  compact?: boolean
+  onError?: (message: string) => void
+}) {
+  const { vote, isLiking } = useVoteAction(onError)
+  return (
+    <CardAction
+      icon={ThumbsUp}
+      label={isLiked ? 'Liked' : 'Like'}
+      busy={isLiking}
+      compact={compact}
+      tone={unavailable ? 'muted' : isLiked ? 'active' : 'default'}
+      disabled={isLiked || isLiking || unavailable}
+      title={
+        unavailable
+          ? 'Removed from the Steam Workshop - voting is no longer possible'
+          : isLiked
+            ? 'Already liked on Steam'
+            : 'Like on Steam'
+      }
+      onClick={() => vote(id, true)}
+    />
+  )
+}
+
+export function SteamAction({ id, compact }: { id: string; compact?: boolean }) {
+  return (
+    <CardAction
+      icon={ExternalLink}
+      label="Steam"
+      compact={compact}
+      title="Open in Steam Workshop"
+      onClick={() => openWorkshopPage(id)}
+    />
+  )
+}
+
+// round button in the preview's top right corner, shown on hover
+export function PlayButton({
+  busy,
+  ready,
+  disabled,
+  title,
+  onClick
+}: {
+  busy: boolean
+  ready: boolean
+  disabled: boolean
+  title: string
+  onClick: () => void
+}) {
+  return (
+    <button
+      onClick={(e) => {
+        e.stopPropagation()
+        onClick()
+      }}
+      disabled={disabled}
+      title={title}
+      className={clsx(
+        'flex h-7 w-7 items-center justify-center rounded-full bg-black/60 opacity-0 transition-opacity group-hover:opacity-100 disabled:cursor-not-allowed',
+        ready ? 'text-white hover:bg-indigo-600' : 'text-gray-500'
+      )}
+    >
+      {busy ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
+    </button>
+  )
+}

+ 157 - 0
src/renderer/src/components/common/GridControls.tsx

@@ -0,0 +1,157 @@
+import type { ReactNode } from 'react'
+import { Loader2, Search, SlidersHorizontal, X, type LucideIcon } from 'lucide-react'
+import clsx from 'clsx'
+import type { MarqueeRect } from '../../hooks/useSelectableGrid'
+
+// Toolbar and grid pieces shared by the workshop and library views
+
+// shows/hides a side panel; stays highlighted while the panel's filters are active even when hidden
+export function PanelToggle({
+  icon: Icon,
+  label,
+  open,
+  activeCount = 0,
+  onClick
+}: {
+  icon: LucideIcon
+  label: string
+  open: boolean
+  activeCount?: number
+  onClick: () => void
+}) {
+  return (
+    <button
+      onClick={onClick}
+      title={open ? `Hide ${label.toLowerCase()}` : `Show ${label.toLowerCase()}`}
+      className={clsx(
+        'flex items-center gap-2 rounded-lg px-3 py-2 text-sm transition-colors',
+        open || activeCount > 0 ? 'bg-indigo-600 text-white' : 'bg-white/5 text-gray-300 hover:bg-white/10'
+      )}
+    >
+      <Icon size={14} />
+      {label}
+      {activeCount > 0 && <span className="rounded-full bg-white/20 px-1.5 text-xs">{activeCount}</span>}
+    </button>
+  )
+}
+
+export function FiltersToggle({ open, activeCount, onClick }: { open: boolean; activeCount: number; onClick: () => void }) {
+  return <PanelToggle icon={SlidersHorizontal} label="Filters" open={open} activeCount={activeCount} onClick={onClick} />
+}
+
+export function ResetFiltersButton({ onClick }: { onClick: () => void }) {
+  return (
+    <button
+      onClick={onClick}
+      className="flex items-center gap-1 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-300 hover:bg-white/10"
+    >
+      <X size={14} /> Reset
+    </button>
+  )
+}
+
+export function SearchInput({
+  value,
+  placeholder,
+  title,
+  onChange
+}: {
+  value: string
+  placeholder: string
+  title?: string
+  onChange: (value: string) => void
+}) {
+  return (
+    <div className="relative max-w-md flex-1">
+      <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+      <input
+        type="text"
+        placeholder={placeholder}
+        title={title}
+        value={value}
+        onChange={(e) => onChange(e.target.value)}
+        className="w-full rounded-lg bg-white/5 py-2 pl-9 pr-3 text-sm text-gray-200 placeholder-gray-500 outline-none focus:ring-1 focus:ring-indigo-500"
+      />
+    </div>
+  )
+}
+
+export function ToolbarButton({
+  icon,
+  busy = false,
+  disabled,
+  title,
+  onClick,
+  children
+}: {
+  icon: ReactNode
+  busy?: boolean
+  disabled?: boolean
+  title?: string
+  onClick: () => void
+  children: ReactNode
+}) {
+  return (
+    <button
+      onClick={onClick}
+      disabled={disabled}
+      title={title}
+      className="flex items-center gap-2 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-300 hover:bg-white/10 disabled:opacity-50"
+    >
+      {busy ? <Loader2 size={14} className="animate-spin" /> : icon}
+      {children}
+    </button>
+  )
+}
+
+export function LoadingSpinner() {
+  return (
+    <div className="flex h-40 items-center justify-center text-gray-500">
+      <Loader2 size={24} className="animate-spin" />
+    </div>
+  )
+}
+
+export function MarqueeOverlay({ rect }: { rect: MarqueeRect | null }) {
+  if (!rect || rect.width <= 3 || rect.height <= 3) return null
+  return (
+    <div
+      className="pointer-events-none absolute z-20 border border-indigo-500 bg-indigo-500/15"
+      style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height }}
+    />
+  )
+}
+
+export function Pagination({
+  page,
+  totalPages,
+  canNext = page < totalPages,
+  onPage,
+  children
+}: {
+  page: number
+  totalPages: number
+  canNext?: boolean
+  onPage: (page: number) => void
+  children: ReactNode
+}) {
+  return (
+    <div className="flex items-center gap-2 text-xs text-gray-400">
+      <button
+        disabled={page <= 1}
+        onClick={() => onPage(Math.max(1, page - 1))}
+        className="rounded bg-white/5 px-2.5 py-1 text-gray-300 hover:bg-white/10 disabled:opacity-40"
+      >
+        Prev
+      </button>
+      <span>{children}</span>
+      <button
+        disabled={!canNext}
+        onClick={() => onPage(page + 1)}
+        className="rounded bg-white/5 px-2.5 py-1 text-gray-300 hover:bg-white/10 disabled:opacity-40"
+      >
+        Next
+      </button>
+    </div>
+  )
+}

+ 141 - 0
src/renderer/src/components/common/WallpaperContextMenu.tsx

@@ -0,0 +1,141 @@
+import { useQueryClient } from '@tanstack/react-query'
+import { Archive, ExternalLink, Eye, FolderOpen, Trash2, User } from 'lucide-react'
+import type { WallpaperMeta } from '@shared/types'
+import { ContextMenu, FolderMenuItems, MenuItem, MenuSelectionCount, MenuSeparator, VoteMenuItems } from './ContextMenu'
+import { useToast } from './Toast'
+import { useConfig, useFolders } from '../../hooks/queries'
+import { useBatchVote } from '../../hooks/useVotes'
+import { useUnsubscribe } from '../../hooks/useWallpaperActions'
+import { openWorkshopPage } from '../../utils/steam'
+import { backupSummary, canBrowseCreator, hasBackup, resolveCreatorSteamId, videoPath } from '../../utils/wallpaper'
+
+// Right-click menu for library wallpapers, shared by the library grid and playlists.
+// ids is what was right-clicked (the selection), wallpapers the ones of those that are loaded.
+export default function WallpaperContextMenu({
+  x,
+  y,
+  ids,
+  wallpapers,
+  onClose,
+  onBrowseCreator
+}: {
+  x: number
+  y: number
+  ids: string[]
+  wallpapers: WallpaperMeta[]
+  onClose: () => void
+  onBrowseCreator?: (creatorSteamId: string) => void
+}) {
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+  const isBackupConfigured = useConfig()?.isBackupConfigured ?? false
+  const { moveToFolder, removeFromFolders, menuState } = useFolders()
+  const batchVote = useBatchVote()
+  const unsubscribe = useUnsubscribe()
+
+  const backupable = wallpapers.filter((w) => w.source === 'workshop')
+  const backups = wallpapers.filter(hasBackup)
+  const video = wallpapers.map(videoPath).find(Boolean)
+  const creatorSource = wallpapers.length === 1 && canBrowseCreator(wallpapers[0]) ? wallpapers[0] : undefined
+  const { hasFolder, moveTargets } = menuState(ids)
+
+  function run(action: () => unknown) {
+    return () => {
+      onClose()
+      void action()
+    }
+  }
+
+  async function backup() {
+    try {
+      if (backupable.length === 1) {
+        const result = await window.electronAPI.backup.item(backupable[0].id)
+        const done = result.alreadyBackedUp ? 'Backup already up to date' : 'Backed up'
+        showToast(result.unsubscribed ? `${done}, unsubscribed` : done)
+      } else {
+        showToast(backupSummary(await window.electronAPI.backup.selection(backupable.map((w) => w.id))))
+      }
+    } catch (err) {
+      showToast(`Backup failed: ${(err as Error).message}`)
+    }
+    queryClient.invalidateQueries({ queryKey: ['library'] })
+  }
+
+  async function removeBackup() {
+    const backupOnly = backups.filter((w) => w.source === 'backup').length
+    const what = backups.length === 1 ? `the backup of "${backups[0].title}"` : `${backups.length} backups`
+    const note =
+      backupOnly > 0
+        ? `\n\n${backupOnly === 1 && backups.length === 1 ? 'It is' : `${backupOnly} of them are`} not subscribed on Steam anymore and will be removed from the library.`
+        : ''
+    if (!confirm(`Delete ${what} from the backup folder?${note}`)) return
+
+    const result = await window.electronAPI.backup.remove(backups.map((w) => w.id))
+    showToast(
+      `Removed ${result.removed} backup${result.removed === 1 ? '' : 's'}${result.keptDirs.length > 0 ? ` (${result.keptDirs.length} outside the backup folder kept on disk)` : ''}${result.failed > 0 ? `, ${result.failed} failed` : ''}`
+    )
+    queryClient.invalidateQueries({ queryKey: ['library'] })
+    queryClient.invalidateQueries({ queryKey: ['folders'] })
+  }
+
+  async function openLocally() {
+    const paths = wallpapers.filter((w) => w.localPath).map((w) => w.localPath!)
+    if (paths.length > 0) await window.electronAPI.shell.openPaths(paths)
+  }
+
+  async function browseCreator() {
+    if (!creatorSource) return
+    const creatorSteamId = await resolveCreatorSteamId(creatorSource)
+    if (creatorSteamId) onBrowseCreator?.(creatorSteamId)
+    else showToast('Could not find creator info for this wallpaper')
+  }
+
+  return (
+    <ContextMenu x={x} y={y} onClose={onClose}>
+      <MenuSelectionCount count={ids.length} />
+
+      {backupable.length > 0 && isBackupConfigured && (
+        <MenuItem icon={Archive} onClick={run(backup)}>
+          Backup
+        </MenuItem>
+      )}
+      {backups.length > 0 && (
+        <MenuItem icon={Trash2} danger onClick={run(removeBackup)}>
+          Delete backup
+        </MenuItem>
+      )}
+      <MenuItem danger onClick={run(() => unsubscribe(ids))}>
+        Unsubscribe
+      </MenuItem>
+
+      <MenuSeparator />
+      <VoteMenuItems onVote={(up) => run(() => batchVote(ids, up))()} />
+
+      <MenuSeparator />
+      <MenuItem icon={ExternalLink} onClick={run(() => ids.forEach(openWorkshopPage))}>
+        Open in Steam Workshop
+      </MenuItem>
+      <MenuItem icon={FolderOpen} onClick={run(openLocally)}>
+        Open wallpaper locally
+      </MenuItem>
+      {video && (
+        <MenuItem icon={Eye} onClick={run(() => window.electronAPI.shell.openWithDefault(video))}>
+          Preview in media player
+        </MenuItem>
+      )}
+      {creatorSource && (
+        <MenuItem icon={User} onClick={run(browseCreator)}>
+          Browse wallpapers from this creator
+        </MenuItem>
+      )}
+
+      <MenuSeparator />
+      <FolderMenuItems
+        moveTargets={moveTargets}
+        hasFolder={hasFolder}
+        onMove={(folderId) => run(() => moveToFolder(folderId, ids))()}
+        onRemove={run(() => removeFromFolders(ids))}
+      />
+    </ContextMenu>
+  )
+}

+ 2 - 5
src/renderer/src/components/common/sidebar/EngineFlagsSection.tsx

@@ -1,9 +1,9 @@
 import { useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
 import { ChevronDown, ChevronRight, Gauge, Loader2 } from 'lucide-react'
 import type { EngineFlags, FullscreenPauseMode, WallpaperMeta } from '@shared/types'
 import { hasEngineFlags } from '@shared/engineFlags'
 import { BOOLEAN_FLAGS, CHOICE_FLAGS, FULLSCREEN_PAUSE_OPTIONS } from '../../../constants/engineFlags'
+import { useConfig } from '../../../hooks/queries'
 
 interface Props {
   flags?: EngineFlags
@@ -18,10 +18,7 @@ export default function EngineFlagsSection({ flags = {}, onChange }: Props) {
   const [open, setOpen] = useState(false)
   const [busy, setBusy] = useState(false)
 
-  const { data: config } = useQuery({
-    queryKey: ['config'],
-    queryFn: () => window.electronAPI.config.get()
-  })
+  const config = useConfig()
   const global = config?.engineFlags ?? {}
   const presets = config?.engineFlagPresets ?? []
 

+ 182 - 0
src/renderer/src/components/common/sidebar/VideoTrimSection.tsx

@@ -0,0 +1,182 @@
+import { useState } from 'react'
+import { Loader2, Play, RotateCcw, Scissors } from 'lucide-react'
+import { formatVideoTime, parseVideoTime, trimmedVideoLength } from '@shared/videoTrim'
+
+export interface VideoTrim {
+  start?: number
+  end?: number
+}
+
+interface Props {
+  start?: number
+  end?: number
+  /** Length of the whole video in seconds, null when it couldn't be measured (no ffprobe) */
+  duration: number | null
+  live: boolean
+  onCommit: (trim: VideoTrim) => Promise<void>
+  /** seek is where playback should jump right after, to watch the loop point */
+  onPreview: (trim: VideoTrim, seek?: number) => void
+}
+
+// a loop shorter than this is almost always a slip of the slider
+const MIN_LENGTH = 0.5
+// how much before the end the loop point preview starts
+const SEAM_LEAD = 3
+
+const timeInputClass =
+  'w-16 rounded bg-white/5 px-1 py-0.5 text-right text-gray-300 outline-none focus:ring-1 focus:ring-indigo-500 disabled:opacity-50'
+
+export default function VideoTrimSection({ start, end, duration, live, onCommit, onPreview }: Props) {
+  const [draft, setDraft] = useState<VideoTrim | null>(null)
+  const [startText, setStartText] = useState<string | null>(null)
+  const [endText, setEndText] = useState<string | null>(null)
+  const [busy, setBusy] = useState(false)
+  const current = draft ?? { start, end }
+  const startValue = current.start ?? 0
+  const loopEnd = current.end ?? duration
+  const trimmed = start !== undefined || end !== undefined
+
+  // the very start and the very end are the same as no trim at all
+  function normalize(trim: VideoTrim): VideoTrim {
+    return {
+      start: trim.start !== undefined && trim.start > 0 ? trim.start : undefined,
+      end: trim.end !== undefined && (duration === null || trim.end < duration) ? trim.end : undefined
+    }
+  }
+
+  function seamSeek(trim: VideoTrim): number | undefined {
+    const endOfLoop = trim.end ?? duration
+    return endOfLoop === null ? undefined : Math.max(trim.start ?? 0, endOfLoop - SEAM_LEAD)
+  }
+
+  async function commit(next: VideoTrim) {
+    setBusy(true)
+    try {
+      await onCommit(normalize(next))
+    } finally {
+      setDraft(null)
+      setStartText(null)
+      setEndText(null)
+      setBusy(false)
+    }
+  }
+
+  function slideStart(value: number) {
+    const next = { ...current, start: loopEnd === null ? value : Math.min(value, loopEnd - MIN_LENGTH) }
+    setDraft(next)
+    onPreview(normalize(next))
+  }
+
+  function slideEnd(value: number) {
+    const next = { ...current, end: Math.max(value, startValue + MIN_LENGTH) }
+    setDraft(next)
+    onPreview(normalize(next), seamSeek(next))
+  }
+
+  function commitText(side: 'start' | 'end', text: string) {
+    const reset = () => (side === 'start' ? setStartText(null) : setEndText(null))
+    const value = text.trim() === '' ? undefined : parseVideoTime(text)
+    if (value === null) return reset()
+    const next = { ...current, [side]: value }
+    const length = (next.end ?? duration ?? Infinity) - (next.start ?? 0)
+    if (length < MIN_LENGTH || (side === 'start' && duration !== null && (value ?? 0) >= duration)) return reset()
+    if (value === current[side]) return reset()
+    void commit(next)
+  }
+
+  function timeInput(side: 'start' | 'end') {
+    const text = side === 'start' ? startText : endText
+    const setText = side === 'start' ? setStartText : setEndText
+    const value = side === 'start' ? startValue : loopEnd
+    return (
+      <input
+        type="text"
+        value={text ?? (value === null ? '' : formatVideoTime(value))}
+        placeholder={side === 'start' ? '0:00' : 'end'}
+        disabled={busy}
+        onChange={(e) => setText(e.target.value)}
+        onKeyDown={(e) => {
+          if (e.key === 'Enter') e.currentTarget.blur()
+          if (e.key === 'Escape') setText(null)
+        }}
+        onBlur={(e) => text !== null && commitText(side, e.currentTarget.value)}
+        title="Seconds, m:ss or h:mm:ss - applies on Enter or clicking away"
+        className={timeInputClass}
+      />
+    )
+  }
+
+  function slider(side: 'start' | 'end') {
+    if (duration === null) return null
+    const value = side === 'start' ? startValue : (loopEnd ?? duration)
+    return (
+      <input
+        type="range"
+        min={0}
+        max={duration}
+        step={0.1}
+        value={value}
+        disabled={busy}
+        onChange={(e) => (side === 'start' ? slideStart : slideEnd)(Number(e.target.value))}
+        onMouseUp={() => draft && commit(draft)}
+        onTouchEnd={() => draft && commit(draft)}
+        onKeyUp={() => draft && commit(draft)}
+        title={side === 'start' ? 'Where the loop starts' : 'Where the loop ends and jumps back to the start'}
+        className="w-full accent-indigo-500 disabled:opacity-50"
+      />
+    )
+  }
+
+  return (
+    <div className="border-t border-white/5 pt-3">
+      <div className="mb-1.5 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500">
+        <Scissors size={12} />
+        <span className="flex-1 text-left">Video trim</span>
+        {live && <span className="rounded-full bg-green-600/30 px-1.5 normal-case text-green-300">live</span>}
+        {busy && <Loader2 size={11} className="animate-spin" />}
+        {trimmed && (
+          <button
+            disabled={busy}
+            onClick={() => commit({})}
+            title="Play the whole video again"
+            className="text-gray-500 hover:text-gray-300 disabled:opacity-50"
+          >
+            <RotateCcw size={11} />
+          </button>
+        )}
+      </div>
+      <p className="mb-1.5 text-[11px] text-gray-600">Only this part of the video plays, over and over.</p>
+
+      <div className="space-y-1.5 text-[11px] text-gray-400">
+        <div className="flex items-center gap-1.5">
+          <span className="flex-1">Start</span>
+          {timeInput('start')}
+        </div>
+        {slider('start')}
+        <div className="flex items-center gap-1.5">
+          <span className="flex-1">End</span>
+          {timeInput('end')}
+        </div>
+        {slider('end')}
+
+        <div className="flex items-center gap-1.5 pt-0.5">
+          <span className="flex-1 text-gray-500">
+            {duration !== null &&
+              `Loops ${formatVideoTime(trimmedVideoLength(duration, current.start, current.end))} of ${formatVideoTime(duration)}`}
+          </span>
+          {live && trimmed && seamSeek({ start, end }) !== undefined && (
+            <button
+              disabled={busy}
+              onClick={() => onPreview({ start, end }, seamSeek({ start, end }))}
+              title={`Jumps ${SEAM_LEAD} seconds before the end, to see how the loop point looks`}
+              className="flex items-center gap-1 rounded bg-white/10 px-1.5 py-0.5 text-[10px] text-gray-300 hover:bg-white/15 disabled:opacity-40"
+            >
+              <Play size={9} />
+              Loop point
+            </button>
+          )}
+        </div>
+      </div>
+    </div>
+  )
+}

+ 3 - 12
src/renderer/src/components/layout/StatusBar.tsx

@@ -1,12 +1,10 @@
 import { useEffect, useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
 import { Wifi, WifiOff, ListVideo, Play, Pause, SkipForward } from 'lucide-react'
-import type { PlaylistPlaybackState } from '@shared/types'
 import { screenLabel } from '../../utils/screens'
+import { usePlaybackStates, usePlaylists } from '../../hooks/queries'
 
 export default function StatusBar() {
   const [steamRunning, setSteamRunning] = useState(false)
-  const [players, setPlayers] = useState<PlaylistPlaybackState[]>([])
 
   useEffect(() => {
     window.electronAPI.steam.isRunning().then(setSteamRunning).catch(() => setSteamRunning(false))
@@ -15,15 +13,8 @@ export default function StatusBar() {
     return unsub
   }, [])
 
-  useEffect(() => {
-    window.electronAPI.playlist.getState().then(setPlayers)
-    return window.electronAPI.on.playlistStateChanged(setPlayers)
-  }, [])
-
-  const { data: playlists } = useQuery({
-    queryKey: ['playlists'],
-    queryFn: () => window.electronAPI.playlist.getAll()
-  })
+  const players = usePlaybackStates()
+  const playlists = usePlaylists()
 
   const active = players.filter((p) => p.playlistId)
 

File diff suppressed because it is too large
+ 189 - 723
src/renderer/src/components/library/LibraryView.tsx


+ 107 - 212
src/renderer/src/components/library/WallpaperCard.tsx

@@ -1,33 +1,39 @@
 import { useState, useEffect } from 'react'
-import { Play, Loader2, Check, X, ThumbsUp, Trash2, ExternalLink, Download, Archive, AlertTriangle, RotateCw, Plus, FolderOpen, WifiOff } from 'lucide-react'
+import { useQueryClient } from '@tanstack/react-query'
+import { Loader2, Check, X, Trash2, Download, Archive, AlertTriangle, RotateCw, Plus, FolderOpen, WifiOff } from 'lucide-react'
 import type { WallpaperMeta } from '@shared/types'
 import clsx from 'clsx'
 import CompatBadge from '../common/CompatBadge'
 import { getPreviewSrc } from '../../utils/preview'
-import { openWorkshopPage } from '../../utils/steam'
+import { hasBackup } from '../../utils/wallpaper'
 import { useToast } from '../common/Toast'
 import type { PreviewSize } from '../../hooks/usePreviewSize'
-import { voteBorderClass } from '../../hooks/useVoteBorders'
+import {
+  CardAction,
+  CardOverlay,
+  CardPreview,
+  CornerBadge,
+  GridCard,
+  LikeAction,
+  PlayButton,
+  ProgressBar,
+  SteamAction
+} from '../common/GridCard'
 
 interface WallpaperCardProps {
   wallpaper: WallpaperMeta
-  selected?: boolean
-  isDetailOpen?: boolean
-  lweInstalled?: boolean
-  isLiked?: boolean
+  selected: boolean
+  isDetailOpen: boolean
+  lweInstalled: boolean
+  isLiked: boolean
   voteError?: string
-  showVoteBorder?: boolean
-  currentPlaylistId?: string | null
-  isInCurrentPlaylist?: boolean
-  previewSize?: PreviewSize
-  backupProgress?: { percentage: number; status: 'copying' | 'verifying' } | null
-  onApplied?: () => void
-  onLiked?: () => void
-  onUnsubscribed?: () => void
-  onAddedToPlaylist?: () => void
-  onRedownloaded?: () => void
-  onSelect?: (e: React.MouseEvent) => void
-  onContextMenu?: (e: React.MouseEvent) => void
+  showVoteBorder: boolean
+  currentPlaylistId: string | null
+  isInCurrentPlaylist: boolean
+  previewSize: PreviewSize
+  backupProgress: { percentage: number; status: 'copying' | 'verifying' } | null
+  onSelect: (e: React.MouseEvent) => void
+  onContextMenu: (e: React.MouseEvent) => void
 }
 
 export default function WallpaperCard({
@@ -35,24 +41,19 @@ export default function WallpaperCard({
   selected,
   isDetailOpen,
   lweInstalled,
-  isLiked = false,
+  isLiked,
   voteError,
-  showVoteBorder = false,
-  currentPlaylistId = null,
-  isInCurrentPlaylist = false,
-  previewSize = 'normal',
-  backupProgress = null,
-  onApplied,
-  onLiked,
-  onUnsubscribed,
-  onAddedToPlaylist,
-  onRedownloaded,
+  showVoteBorder,
+  currentPlaylistId,
+  isInCurrentPlaylist,
+  previewSize,
+  backupProgress,
   onSelect,
   onContextMenu
 }: WallpaperCardProps) {
   const { showToast } = useToast()
+  const queryClient = useQueryClient()
   const [isApplying, setIsApplying] = useState(false)
-  const [isLiking, setIsLiking] = useState(false)
   const [unsubState, setUnsubState] = useState<'idle' | 'confirm' | 'pending'>('idle')
   const [error, setError] = useState<string | null>(null)
   const [fpsInput, setFpsInput] = useState(wallpaper.fpsOverride != null ? String(wallpaper.fpsOverride) : '')
@@ -72,10 +73,14 @@ export default function WallpaperCard({
       } else {
         setDownloadPercentage(null)
         setIsRedownloading(false)
-        onRedownloaded?.()
+        queryClient.invalidateQueries({ queryKey: ['library'] })
       }
     })
-  }, [wallpaper.downloading, wallpaper.id, onRedownloaded])
+  }, [wallpaper.downloading, wallpaper.id, queryClient])
+
+  function refreshLibrary() {
+    queryClient.invalidateQueries({ queryKey: ['library'] })
+  }
 
   async function handleRedownload(e: React.MouseEvent) {
     e.stopPropagation()
@@ -84,20 +89,19 @@ export default function WallpaperCard({
     setError(null)
     try {
       await window.electronAPI.steam.redownload(wallpaper.id)
-      onRedownloaded?.()
+      refreshLibrary()
     } catch (err) {
       setError((err as Error).message)
       setIsRedownloading(false)
     }
   }
 
-  async function handleApply(e: React.MouseEvent) {
-    e.stopPropagation()
+  async function handleApply() {
     setIsApplying(true)
     setError(null)
     try {
       await window.electronAPI.wallpaper.apply({ wallpaperId: wallpaper.id })
-      onApplied?.()
+      refreshLibrary()
     } catch (err) {
       setError((err as Error).message)
     } finally {
@@ -105,24 +109,6 @@ export default function WallpaperCard({
     }
   }
 
-  async function handleLike(e: React.MouseEvent) {
-    e.stopPropagation()
-    if (isLiked || isLiking || wallpaper.unavailable) return
-    setIsLiking(true)
-    try {
-      const { confirmed } = await window.electronAPI.steam.vote(wallpaper.id, true)
-      if (confirmed) {
-        onLiked?.()
-      } else {
-        setError('Could not confirm the like on Steam - try again')
-      }
-    } catch (err) {
-      setError((err as Error).message)
-    } finally {
-      setIsLiking(false)
-    }
-  }
-
   function handleFpsBlur() {
     const trimmed = fpsInput.trim()
     const parsed = trimmed === '' ? undefined : parseInt(trimmed, 10)
@@ -132,15 +118,14 @@ export default function WallpaperCard({
     window.electronAPI.library.update(wallpaper.id, { fpsOverride: parsed })
   }
 
-  async function handleAddToPlaylist(e: React.MouseEvent) {
-    e.stopPropagation()
+  async function handleAddToPlaylist() {
     if (!currentPlaylistId || isAddingToPlaylist || isInCurrentPlaylist) return
     setIsAddingToPlaylist(true)
     setError(null)
     try {
       await window.electronAPI.playlist.addItems(currentPlaylistId, [wallpaper.id])
       showToast('Added to current playlist')
-      onAddedToPlaylist?.()
+      queryClient.invalidateQueries({ queryKey: ['playlists'] })
     } catch (err) {
       setError((err as Error).message)
     } finally {
@@ -155,15 +140,15 @@ export default function WallpaperCard({
     setUnsubState('pending')
     try {
       await window.electronAPI.steam.unsubscribe(wallpaper.id)
-      onUnsubscribed?.()
+      refreshLibrary()
+      queryClient.invalidateQueries({ queryKey: ['folders'] })
     } catch (err) {
       setError((err as Error).message)
       setUnsubState('idle')
     }
   }
 
-  async function handleOpenLocally(e: React.MouseEvent) {
-    e.stopPropagation()
+  async function handleOpenLocally() {
     if (!wallpaper.localPath) return
     await window.electronAPI.shell.openPath(wallpaper.localPath)
   }
@@ -171,9 +156,16 @@ export default function WallpaperCard({
   const previewSrc = getPreviewSrc(wallpaper)
   const compact = previewSize !== 'big'
 
+  const playBlocked = !lweInstalled || !!wallpaper.downloading || !!wallpaper.downloadFailed
+
   return (
-    <div
+    <GridCard
       data-wallpaper-id={wallpaper.id}
+      selected={selected}
+      isDetailOpen={isDetailOpen}
+      isLiked={isLiked}
+      voteError={voteError}
+      showVoteBorder={showVoteBorder}
       draggable
       onDragStart={(e) => {
         e.dataTransfer.setData('text/wallpaper-id', wallpaper.id)
@@ -182,58 +174,21 @@ export default function WallpaperCard({
       }}
       onClick={onSelect}
       onContextMenu={onContextMenu}
-      title={showVoteBorder ? voteError : undefined}
-      className={clsx(
-        'group relative overflow-hidden rounded-lg bg-[#1a1a1a] transition-all cursor-pointer select-none',
-        isDetailOpen
-          ? 'ring-2 ring-sky-400'
-          : selected
-            ? 'ring-2 ring-indigo-500'
-            : 'hover:ring-1 hover:ring-indigo-500/50',
-        showVoteBorder && voteBorderClass(voteError, isLiked)
-      )}
     >
-      <div
-        className={clsx(
-          'absolute left-2 top-2 z-10 flex h-5 w-5 items-center justify-center rounded border transition-all',
-          selected
-            ? 'border-indigo-500 bg-indigo-600 text-white opacity-100'
-            : 'border-white/30 bg-black/50 text-transparent opacity-0 group-hover:opacity-100'
-        )}
-      >
-        <Check size={12} />
-      </div>
-
-      <div className="aspect-video overflow-hidden bg-[#111] relative">
-        {previewSrc ? (
-          <img
-            src={previewSrc}
-            alt={wallpaper.title}
-            className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
-            loading="lazy"
-            draggable={false}
-          />
-        ) : (
-          <div className="flex h-full items-center justify-center text-gray-600">No preview</div>
-        )}
+      <CardPreview src={previewSrc} alt={wallpaper.title}>
         {wallpaper.downloading && (
-          <div className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-black/70 px-4">
+          <CardOverlay>
             <Download size={20} className="text-indigo-400 animate-bounce" />
             <span className="text-xs text-gray-300">
               {downloadPercentage != null ? `Downloading... ${downloadPercentage}%` : 'Downloading...'}
             </span>
             {downloadPercentage != null && (
-              <div className="h-1 w-full max-w-[140px] overflow-hidden rounded-full bg-white/10">
-                <div
-                  className="h-full bg-indigo-500 transition-[width]"
-                  style={{ width: `${downloadPercentage}%` }}
-                />
-              </div>
+              <ProgressBar percentage={downloadPercentage} className="h-1 w-full max-w-[140px] rounded-full bg-white/10" />
             )}
-          </div>
+          </CardOverlay>
         )}
         {wallpaper.downloadFailed && (
-          <div className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-black/70 px-4 text-center">
+          <CardOverlay>
             <AlertTriangle size={20} className="text-red-400" />
             <span className="text-xs text-gray-300">Download failed</span>
             <button
@@ -244,23 +199,18 @@ export default function WallpaperCard({
               {isRedownloading ? <Loader2 size={11} className="animate-spin" /> : <RotateCw size={11} />}
               Redownload
             </button>
-          </div>
+          </CardOverlay>
         )}
         {backupProgress != null && (
-          <div className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-black/70 px-4">
+          <CardOverlay>
             <Archive size={20} className="text-indigo-400 animate-pulse" />
             <span className="text-xs text-gray-300">
               {backupProgress.status === 'verifying'
                 ? `Verifying... ${backupProgress.percentage}%`
                 : `Backing up... ${backupProgress.percentage}%`}
             </span>
-            <div className="h-1 w-full max-w-[140px] overflow-hidden rounded-full bg-white/10">
-              <div
-                className="h-full bg-indigo-500 transition-[width]"
-                style={{ width: `${backupProgress.percentage}%` }}
-              />
-            </div>
-          </div>
+            <ProgressBar percentage={backupProgress.percentage} className="h-1 w-full max-w-[140px] rounded-full bg-white/10" />
+          </CardOverlay>
         )}
         {wallpaper.hdr && (
           <span
@@ -274,27 +224,24 @@ export default function WallpaperCard({
             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"
-            title="Backed up locally"
-          >
+        {backupProgress == null && hasBackup(wallpaper) && (
+          <CornerBadge className="bottom-2 right-2 bg-black/60 text-indigo-300" title="Backed up locally">
             <Archive size={12} />
-          </div>
+          </CornerBadge>
         )}
         {wallpaper.unavailable && (
-          <div
-            className="absolute bottom-2 left-2 flex h-5 w-5 items-center justify-center rounded bg-amber-600/80 text-white"
+          <CornerBadge
+            className="bottom-2 left-2 bg-amber-600/80 text-white"
             title="Removed from the Steam Workshop - back it up before it's lost"
           >
             <WifiOff size={12} />
-          </div>
+          </CornerBadge>
         )}
         <CompatBadge
           compat={wallpaper.compat}
           className={clsx('absolute bottom-2', wallpaper.unavailable ? 'left-8' : 'left-2')}
         />
-      </div>
+      </CardPreview>
 
       <div className="p-3">
         <h3 className="truncate text-sm font-medium text-gray-200" title={wallpaper.title}>
@@ -325,31 +272,19 @@ export default function WallpaperCard({
         </div>
         {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
         <div className={clsx('mt-2 flex items-center', compact ? 'gap-1' : 'gap-2')}>
-          <button
-            onClick={handleLike}
-            disabled={isLiked || isLiking || wallpaper.unavailable}
-            title={
-              wallpaper.unavailable
-                ? 'Removed from the Steam Workshop - voting is no longer possible'
-                : isLiked
-                  ? 'Already liked on Steam'
-                  : 'Like on Steam'
-            }
-            className={clsx(
-              'flex items-center gap-1 rounded text-xs transition-colors disabled:cursor-not-allowed',
-              compact ? 'p-1.5' : 'px-2 py-1',
-              wallpaper.unavailable
-                ? 'bg-white/5 text-gray-600 opacity-50'
-                : isLiked
-                  ? 'bg-green-600/30 text-green-300'
-                  : 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-gray-200'
-            )}
-          >
-            {isLiking ? <Loader2 size={11} className="animate-spin" /> : <ThumbsUp size={11} />}
-            {!compact && (isLiked ? 'Liked' : 'Like')}
-          </button>
-          <button
-            onClick={handleAddToPlaylist}
+          <LikeAction
+            id={wallpaper.id}
+            isLiked={isLiked}
+            unavailable={wallpaper.unavailable}
+            compact={compact}
+            onError={setError}
+          />
+          <CardAction
+            icon={isInCurrentPlaylist ? Check : Plus}
+            label={isInCurrentPlaylist ? 'Added' : 'Add'}
+            busy={isAddingToPlaylist}
+            compact={compact}
+            tone={isInCurrentPlaylist ? 'active' : 'default'}
             disabled={!currentPlaylistId || isAddingToPlaylist || isInCurrentPlaylist}
             title={
               !currentPlaylistId
@@ -358,23 +293,8 @@ export default function WallpaperCard({
                   ? 'Already in current playlist'
                   : 'Add to current playlist (+)'
             }
-            className={clsx(
-              'flex items-center gap-1 rounded text-xs transition-colors disabled:cursor-not-allowed',
-              compact ? 'p-1.5' : 'px-2 py-1',
-              isInCurrentPlaylist
-                ? 'bg-green-600/30 text-green-300'
-                : 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-gray-200 disabled:opacity-50'
-            )}
-          >
-            {isAddingToPlaylist ? (
-              <Loader2 size={11} className="animate-spin" />
-            ) : isInCurrentPlaylist ? (
-              <Check size={11} />
-            ) : (
-              <Plus size={11} />
-            )}
-            {!compact && (isInCurrentPlaylist ? 'Added' : 'Add')}
-          </button>
+            onClick={handleAddToPlaylist}
+          />
           {unsubState === 'confirm' ? (
             <div className="flex items-center gap-1">
               {!compact && <span className="text-xs text-gray-400">Sure?</span>}
@@ -394,52 +314,34 @@ export default function WallpaperCard({
               </button>
             </div>
           ) : (
-            <button
-              onClick={handleUnsubscribeClick}
+            <CardAction
+              icon={Trash2}
+              label="Unsub"
+              busy={unsubState === 'pending'}
+              compact={compact}
+              tone="danger"
               disabled={unsubState === 'pending'}
               title="Unsubscribe and delete files"
-              className={clsx(
-                'flex items-center gap-1 rounded bg-white/5 text-xs text-gray-400 transition-colors hover:bg-red-500/20 hover:text-red-400 disabled:cursor-not-allowed disabled:opacity-50',
-                compact ? 'p-1.5' : 'px-2 py-1'
-              )}
-            >
-              {unsubState === 'pending' ? <Loader2 size={11} className="animate-spin" /> : <Trash2 size={11} />}
-              {!compact && 'Unsub'}
-            </button>
+              onClick={handleUnsubscribeClick}
+            />
           )}
-          <button
-            onClick={(e) => {
-              e.stopPropagation()
-              openWorkshopPage(wallpaper.id)
-            }}
-            title="Open in Steam Workshop"
-            className={clsx(
-              'flex items-center gap-1 rounded bg-white/5 text-xs text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-200',
-              compact ? 'p-1.5' : 'px-2 py-1'
-            )}
-          >
-            <ExternalLink size={11} />
-            {!compact && 'Steam'}
-          </button>
-          <button
-            onClick={handleOpenLocally}
+          <SteamAction id={wallpaper.id} compact={compact} />
+          <CardAction
+            icon={FolderOpen}
+            label="Open"
+            compact={compact}
             disabled={!wallpaper.localPath}
             title={wallpaper.localPath ? 'Open wallpaper folder' : 'Local files not found'}
-            className={clsx(
-              'flex items-center gap-1 rounded bg-white/5 text-xs text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-200 disabled:cursor-not-allowed disabled:opacity-50',
-              compact ? 'p-1.5' : 'px-2 py-1'
-            )}
-          >
-            <FolderOpen size={11} />
-            {!compact && 'Open'}
-          </button>
+            onClick={handleOpenLocally}
+          />
         </div>
       </div>
 
       <div className="absolute right-2 top-2">
-        <button
-          onClick={handleApply}
-          disabled={isApplying || !lweInstalled || wallpaper.downloading || wallpaper.downloadFailed}
+        <PlayButton
+          busy={isApplying}
+          ready={!playBlocked}
+          disabled={isApplying || playBlocked}
           title={
             wallpaper.downloading
               ? 'Wallpaper is still downloading'
@@ -449,16 +351,9 @@ export default function WallpaperCard({
                   ? 'Install linux-wallpaperengine in Settings first'
                   : 'Play wallpaper'
           }
-          className={clsx(
-            'flex h-7 w-7 items-center justify-center rounded-full transition-opacity disabled:cursor-not-allowed',
-            !lweInstalled || wallpaper.downloading || wallpaper.downloadFailed
-              ? 'bg-black/60 text-gray-500 opacity-0 group-hover:opacity-100'
-              : 'bg-black/60 text-white opacity-0 hover:bg-indigo-600 group-hover:opacity-100'
-          )}
-        >
-          {isApplying ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
-        </button>
+          onClick={handleApply}
+        />
       </div>
-    </div>
+    </GridCard>
   )
 }

+ 34 - 339
src/renderer/src/components/playlist/PlaylistsView.tsx

@@ -1,5 +1,5 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useMemo, useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
 import {
   ListVideo,
   Plus,
@@ -12,28 +12,17 @@ import {
   SkipBack,
   Shuffle,
   Film,
-  ArrowDownWideNarrow,
-  ExternalLink,
-  FolderOpen,
-  FolderInput,
-  Folder,
-  ChevronRight,
-  Eye,
-  ThumbsUp,
-  ThumbsDown,
-  Archive,
-  User
+  ArrowDownWideNarrow
 } from 'lucide-react'
 import clsx from 'clsx'
-import type { Playlist, PlaylistPlaybackState, PlaylistSettings, ScreenTarget } from '@shared/types'
+import type { PlaylistSettings, ScreenTarget } from '@shared/types'
 import PlaylistItemRow from './PlaylistItemRow'
 import WallpaperPickerModal from './WallpaperPickerModal'
 import DetailSidebar from '../common/DetailSidebar'
-import { useClickOutside } from '../../hooks/useClickOutside'
-import { useClampedPosition, useFlipSide } from '../../hooks/useContextMenuPosition'
-import { openWorkshopPage, isWorkshopId } from '../../utils/steam'
-import { useToast } from '../common/Toast'
-import { getPreviewSrc } from '../../utils/preview'
+import WallpaperContextMenu from '../common/WallpaperContextMenu'
+import { useAllWallpapers, usePlaybackStates, usePlaylists } from '../../hooks/queries'
+import { useApplyWallpaper, useSubscribe, useUnsubscribe } from '../../hooks/useWallpaperActions'
+import { detailSidebarProps } from '../../utils/wallpaper'
 import ScreenSelect from '../common/ScreenSelect'
 import { useDisplayTargets } from '../../hooks/useDisplayTargets'
 import { screenLabel } from '../../utils/screens'
@@ -50,7 +39,6 @@ interface PlaylistsViewProps {
 
 export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
   const queryClient = useQueryClient()
-  const { showToast } = useToast()
   const [activePlaylistId, setActivePlaylistId] = useState<string | null>(null)
   const [creating, setCreating] = useState(false)
   const [newTitle, setNewTitle] = useState('')
@@ -62,71 +50,17 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
   const [error, setError] = useState<string | null>(null)
   const [detailId, setDetailId] = useState<string | null>(null)
 
-  const [ctxMenu, setCtxMenu] = useState<{
-    x: number
-    y: number
-    wallpaperId: string
-    showFolderSub: boolean
-  } | null>(null)
-  const ctxMenuRef = useRef<HTMLDivElement>(null)
-  const folderSubRef = useRef<HTMLDivElement>(null)
-  useClickOutside(ctxMenuRef, () => setCtxMenu(null), !!ctxMenu)
-  const ctxPos = useClampedPosition(ctxMenuRef, ctxMenu)
-  const folderSubSide = useFlipSide(folderSubRef, !!ctxMenu?.showFolderSub)
-
-  const { data: playlists = [] } = useQuery({
-    queryKey: ['playlists'],
-    queryFn: () => window.electronAPI.playlist.getAll()
-  })
-
-  const { data: wallpapers = [] } = useQuery({
-    queryKey: ['library-all'],
-    queryFn: () => window.electronAPI.library.getAll()
-  })
-  const wallpaperById = useMemo(() => new Map(wallpapers.map((w) => [w.id, w])), [wallpapers])
+  const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number; wallpaperId: string } | null>(null)
 
-  const { data: folders = [], refetch: refetchFolders } = useQuery({
-    queryKey: ['folders'],
-    queryFn: () => window.electronAPI.folders.getAll()
-  })
-  const folderOfItem = useMemo(() => {
-    const map = new Map<string, string>()
-    for (const f of folders) {
-      for (const id of f.items) map.set(id, f.id)
-    }
-    return map
-  }, [folders])
-
-  const { data: config } = useQuery({
-    queryKey: ['config'],
-    queryFn: () => window.electronAPI.config.get()
-  })
-  const isBackupConfigured = config?.isBackupConfigured ?? false
-
-  const { data: playbackStates = [] } = useQuery({
-    queryKey: ['playlist-playback-state'],
-    queryFn: () => window.electronAPI.playlist.getState()
-  })
+  const playlists = usePlaylists()
+  const wallpapers = useAllWallpapers()
+  const wallpaperById = useMemo(() => new Map(wallpapers.map((w) => [w.id, w])), [wallpapers])
+  const playbackStates = usePlaybackStates()
   const { targets, perScreen } = useDisplayTargets()
   const [screen, setScreen] = useState<ScreenTarget>('*')
-
-  const { data: lweStatus } = useQuery({
-    queryKey: ['lwe-status'],
-    queryFn: () => window.electronAPI.lwe.status()
-  })
-
-  const { data: votedIds } = useQuery({
-    queryKey: ['steam-voted-ids'],
-    queryFn: () => window.electronAPI.steam.getVotedIds(),
-    staleTime: Infinity
-  })
-  const votedSet = useMemo(() => new Set(votedIds ?? []), [votedIds])
-
-  useEffect(() => {
-    return window.electronAPI.on.playlistStateChanged((states: PlaylistPlaybackState[]) => {
-      queryClient.setQueryData(['playlist-playback-state'], states)
-    })
-  }, [queryClient])
+  const applyWallpaper = useApplyWallpaper()
+  const subscribe = useSubscribe()
+  const unsubscribe = useUnsubscribe()
 
   const activePlaylist = playlists.find((p) => p.id === activePlaylistId) ?? null
 
@@ -193,119 +127,7 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
 
   function openItemCtxMenu(e: React.MouseEvent, wallpaperId: string) {
     e.preventDefault()
-    setCtxMenu({ x: e.clientX, y: e.clientY, wallpaperId, showFolderSub: false })
-  }
-
-  function closeCtxMenu() {
-    setCtxMenu(null)
-  }
-
-  const ctxWallpaper = ctxMenu ? wallpaperById.get(ctxMenu.wallpaperId) : undefined
-  const ctxHasVideo = Boolean(ctxWallpaper?.type === 'video' && ctxWallpaper.file)
-  const ctxHasBackupable = ctxWallpaper?.source === 'workshop'
-  const ctxFolderId = ctxMenu ? folderOfItem.get(ctxMenu.wallpaperId) : undefined
-  const ctxMoveTargets = folders.filter((f) => f.id !== ctxFolderId)
-
-  async function ctxUnsubscribe() {
-    if (!ctxMenu) return
-    await window.electronAPI.steam.unsubscribe(ctxMenu.wallpaperId)
-    closeCtxMenu()
-    queryClient.invalidateQueries({ queryKey: ['library-all'] })
-    refetchFolders()
-  }
-
-  async function unsubscribeWallpaper(wallpaperId: string) {
-    await window.electronAPI.steam.unsubscribe(wallpaperId)
-    queryClient.invalidateQueries({ queryKey: ['library-all'] })
-    refetchFolders()
-  }
-
-  async function handleApplyDetail(wallpaperId: string, target?: ScreenTarget) {
-    try {
-      await window.electronAPI.wallpaper.apply({ wallpaperId, screen: target })
-      queryClient.invalidateQueries({ queryKey: ['library-all'] })
-    } catch (err) {
-      showToast((err as Error).message)
-    }
-  }
-
-  async function ctxVote(up: boolean) {
-    if (!ctxMenu) return
-    const wallpaperId = ctxMenu.wallpaperId
-    closeCtxMenu()
-    try {
-      const { confirmed } = await window.electronAPI.steam.vote(wallpaperId, up)
-      if (!confirmed) {
-        showToast(`Could not confirm the ${up ? 'like' : 'dislike'} on Steam - try again`)
-        return
-      }
-      if (up) {
-        queryClient.setQueryData<string[]>(['steam-voted-ids'], (old) =>
-          old ? [...new Set([...old, wallpaperId])] : [wallpaperId]
-        )
-      }
-    } catch (err) {
-      showToast((err as Error).message)
-    }
-  }
-
-  function ctxOpenInSteam() {
-    if (!ctxMenu) return
-    openWorkshopPage(ctxMenu.wallpaperId)
-    closeCtxMenu()
-  }
-
-  async function ctxBrowseCreator() {
-    if (!ctxMenu) return
-    const wallpaperId = ctxMenu.wallpaperId
-    closeCtxMenu()
-    let creatorSteamId = ctxWallpaper?.authorSteamId
-    if (!creatorSteamId && isWorkshopId(wallpaperId)) {
-      try {
-        const item = await window.electronAPI.workshop.getItem(wallpaperId)
-        creatorSteamId = item?.creatorSteamId
-      } catch {
-        creatorSteamId = undefined
-      }
-    }
-    if (creatorSteamId) {
-      onBrowseCreator?.(creatorSteamId)
-    } else {
-      showToast('Could not find creator info for this wallpaper')
-    }
-  }
-
-  async function ctxBackup() {
-    if (!ctxMenu) return
-    closeCtxMenu()
-    await window.electronAPI.backup.item(ctxMenu.wallpaperId)
-    queryClient.invalidateQueries({ queryKey: ['library-all'] })
-  }
-
-  async function ctxOpenLocally() {
-    if (!ctxMenu || !ctxWallpaper?.localPath) return closeCtxMenu()
-    await window.electronAPI.shell.openPath(ctxWallpaper.localPath)
-    closeCtxMenu()
-  }
-
-  async function ctxPreviewVideo() {
-    if (!ctxWallpaper?.localPath || !ctxWallpaper.file) return closeCtxMenu()
-    await window.electronAPI.shell.openWithDefault(ctxWallpaper.localPath + '/' + ctxWallpaper.file)
-    closeCtxMenu()
-  }
-
-  async function ctxMoveToFolder(folderId: string) {
-    if (!ctxMenu) return
-    await window.electronAPI.folders.addItems(folderId, [ctxMenu.wallpaperId])
-    refetchFolders()
-    closeCtxMenu()
-  }
-
-  async function ctxRemoveFromFolder() {
-    if (!ctxMenu || !ctxFolderId) return
-    await window.electronAPI.folders.removeItems(ctxFolderId, [ctxMenu.wallpaperId])
-    refetchFolders()
-    closeCtxMenu()
+    setCtxMenu({ x: e.clientX, y: e.clientY, wallpaperId })
   }
 
   function handleDragStart(index: number) {
@@ -377,6 +199,8 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
   const isThisPlaylistActive = thisStates.length > 0
   const isPlaying = thisStates.some((s) => s.isPlaying)
   const currentItemIds = new Set(thisStates.map((s) => s.currentItemId))
+  const ctxWallpaper = ctxMenu ? wallpaperById.get(ctxMenu.wallpaperId) : undefined
+  const detailWallpaper = detailId ? wallpaperById.get(detailId) : undefined
   const existingIds = useMemo(
     () => new Set(activePlaylist?.items.map((i) => i.wallpaperId) ?? []),
     [activePlaylist]
@@ -577,7 +401,7 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
                       onChange={(e) =>
                         updateSettings({ sortBy: e.target.value as PlaylistSettings['sortBy'] })
                       }
-                      className="rounded bg-white/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-indigo-500 [&>option]:bg-[#1a1a1a]"
+                      className="rounded bg-white/5 px-2 py-1 text-gray-200 outline-none focus:ring-1 focus:ring-indigo-500"
                     >
                       {SORT_OPTIONS.map((o) => (
                         <option key={o.value} value={o.value}>
@@ -684,37 +508,14 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
         )}
       </div>
 
-      {detailId && wallpaperById.get(detailId) && (
+      {detailWallpaper && (
         <DetailSidebar
-          id={detailId}
-          fallbackTitle={wallpaperById.get(detailId)!.title}
-          fallbackPreviewUrl={getPreviewSrc(wallpaperById.get(detailId))}
-          fallbackTags={[
-            ...wallpaperById.get(detailId)!.tags,
-            ...(wallpaperById.get(detailId)!.resolutions ?? [])
-          ]}
-          fallbackAuthorSteamId={wallpaperById.get(detailId)!.authorSteamId}
-          localFileSize={wallpaperById.get(detailId)!.fileSize}
-          isSubscribed={wallpaperById.get(detailId)!.subscribed}
-          isLiked={votedSet.has(detailId)}
-          canPlay={
-            !!wallpaperById.get(detailId)!.localPath &&
-            !wallpaperById.get(detailId)!.downloading &&
-            !wallpaperById.get(detailId)!.downloadFailed
-          }
-          lweInstalled={lweStatus?.installed ?? false}
+          id={detailWallpaper.id}
+          {...detailSidebarProps(detailWallpaper)}
           onClose={() => setDetailId(null)}
-          onSubscribe={async () => {
-            await window.electronAPI.steam.subscribe(detailId)
-            queryClient.invalidateQueries({ queryKey: ['library-all'] })
-          }}
-          onUnsubscribe={() => unsubscribeWallpaper(detailId)}
-          onLiked={() => {
-            queryClient.setQueryData<string[]>(['steam-voted-ids'], (old) =>
-              old ? [...old, detailId] : [detailId]
-            )
-          }}
-          onPlay={(target) => handleApplyDetail(detailId, target)}
+          onSubscribe={() => subscribe(detailWallpaper.id)}
+          onUnsubscribe={() => unsubscribe([detailWallpaper.id])}
+          onPlay={(target) => applyWallpaper(detailWallpaper.id, target)}
           onBrowseCreator={onBrowseCreator}
         />
       )}
@@ -729,120 +530,14 @@ export default function PlaylistsView({ onBrowseCreator }: PlaylistsViewProps) {
       )}
 
       {ctxMenu && (
-        <div
-          ref={ctxMenuRef}
-          className="fixed z-50 min-w-[200px] rounded-lg border border-white/10 bg-[#1a1a1a] py-1 shadow-xl text-sm"
-          style={{ left: ctxPos?.x ?? ctxMenu.x, top: ctxPos?.y ?? ctxMenu.y }}
-        >
-          {ctxHasBackupable && isBackupConfigured && (
-            <button
-              onClick={ctxBackup}
-              className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-            >
-              <Archive size={12} /> Backup
-            </button>
-          )}
-
-          <button
-            onClick={ctxUnsubscribe}
-            className="flex w-full items-center gap-2 px-3 py-1.5 text-red-400 hover:bg-white/5"
-          >
-            Unsubscribe
-          </button>
-
-          <div className="my-1 border-t border-white/5" />
-
-          <button
-            onClick={() => ctxVote(true)}
-            className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-          >
-            <ThumbsUp size={12} /> Like
-          </button>
-          <button
-            onClick={() => ctxVote(false)}
-            className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-          >
-            <ThumbsDown size={12} /> Dislike
-          </button>
-
-          <div className="my-1 border-t border-white/5" />
-
-          <button
-            onClick={ctxOpenInSteam}
-            className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-          >
-            <ExternalLink size={12} /> Open in Steam Workshop
-          </button>
-          <button
-            onClick={ctxOpenLocally}
-            className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-          >
-            <FolderOpen size={12} /> Open wallpaper locally
-          </button>
-
-          {ctxHasVideo && (
-            <button
-              onClick={ctxPreviewVideo}
-              className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-            >
-              <Eye size={12} /> Preview in media player
-            </button>
-          )}
-
-          {ctxWallpaper &&
-            ctxWallpaper.source !== 'local' &&
-            (ctxWallpaper.authorSteamId || isWorkshopId(ctxWallpaper.id)) && (
-            <button
-              onClick={ctxBrowseCreator}
-              className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-            >
-              <User size={12} /> Browse wallpapers from this creator
-            </button>
-          )}
-
-          <div className="my-1 border-t border-white/5" />
-
-          <div className="relative">
-            <button
-              onClick={() => setCtxMenu((prev) => prev ? { ...prev, showFolderSub: !prev.showFolderSub } : null)}
-              className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-            >
-              <FolderInput size={12} /> Move to folder
-              <ChevronRight size={12} className="ml-auto" />
-            </button>
-            {ctxMenu.showFolderSub && (
-              <div
-                ref={folderSubRef}
-                className={clsx(
-                  'absolute top-0 min-w-[160px] rounded-lg border border-white/10 bg-[#1a1a1a] py-1 shadow-xl',
-                  folderSubSide === 'left' ? 'right-full mr-1' : 'left-full ml-1'
-                )}
-              >
-                {ctxMoveTargets.length === 0 && (
-                  <div className="px-3 py-1.5 text-gray-500">No other folders</div>
-                )}
-                {ctxMoveTargets.map((f) => (
-                  <button
-                    key={f.id}
-                    onClick={() => ctxMoveToFolder(f.id)}
-                    className="flex w-full items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-white/5"
-                  >
-                    <Folder size={12} /> {f.title}
-                  </button>
-                ))}
-              </div>
-            )}
-          </div>
-
-          {ctxFolderId && (
-            <button
-              onClick={ctxRemoveFromFolder}
-              className="flex w-full items-center gap-2 px-3 py-1.5 text-red-400 hover:bg-white/5"
-            >
-              <Trash2 size={12} /> Remove from folder
-            </button>
-          )}
-        </div>
+        <WallpaperContextMenu
+          x={ctxMenu.x}
+          y={ctxMenu.y}
+          ids={[ctxMenu.wallpaperId]}
+          wallpapers={ctxWallpaper ? [ctxWallpaper] : []}
+          onClose={() => setCtxMenu(null)}
+          onBrowseCreator={onBrowseCreator}
+        />
       )}
     </div>
   )

+ 3 - 5
src/renderer/src/components/settings/DisplaySettings.tsx

@@ -1,7 +1,8 @@
 import { useState } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useQueryClient } from '@tanstack/react-query'
 import { Loader2, Monitor, MonitorSmartphone } from 'lucide-react'
 import type { DisplayMode } from '@shared/types'
+import { useConfig } from '../../hooks/queries'
 
 const MODES: { mode: DisplayMode; label: string; icon: typeof Monitor }[] = [
   { mode: 'shared', label: 'Same on every screen', icon: Monitor },
@@ -10,10 +11,7 @@ const MODES: { mode: DisplayMode; label: string; icon: typeof Monitor }[] = [
 
 export default function DisplaySettings({ screens }: { screens: string[] }) {
   const queryClient = useQueryClient()
-  const { data: config } = useQuery({
-    queryKey: ['config'],
-    queryFn: () => window.electronAPI.config.get()
-  })
+  const config = useConfig()
   const [switching, setSwitching] = useState(false)
   const current = config?.displayMode ?? 'shared'
 

+ 3 - 5
src/renderer/src/components/settings/PerformanceSettings.tsx

@@ -1,8 +1,9 @@
 import { useState } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useQueryClient } from '@tanstack/react-query'
 import { Check, Plus, Save, Trash2 } from 'lucide-react'
 import type { EngineFlagPreset, EngineFlags, FullscreenPauseMode } from '@shared/types'
 import { BOOLEAN_FLAGS, CHOICE_FLAGS, FULLSCREEN_PAUSE_OPTIONS } from '../../constants/engineFlags'
+import { useConfig } from '../../hooks/queries'
 
 interface Props {
   defaultFps: number | null
@@ -42,10 +43,7 @@ function describePreset(preset: EngineFlagPreset): string {
 
 export default function PerformanceSettings({ defaultFps, onDefaultFpsChanged }: Props) {
   const queryClient = useQueryClient()
-  const { data: config } = useQuery({
-    queryKey: ['config'],
-    queryFn: () => window.electronAPI.config.get()
-  })
+  const config = useConfig()
   const flags: EngineFlags = config?.engineFlags ?? {}
   const presets = config?.engineFlagPresets ?? []
   const [newName, setNewName] = useState('')

+ 3 - 8
src/renderer/src/components/settings/ScheduleSettings.tsx

@@ -8,6 +8,7 @@ import ScreenSelect from '../common/ScreenSelect'
 import { useDisplayTargets } from '../../hooks/useDisplayTargets'
 import { screenLabel } from '../../utils/screens'
 import { useToast } from '../common/Toast'
+import { useAllWallpapers, usePlaylists } from '../../hooks/queries'
 
 const DAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
 
@@ -42,14 +43,8 @@ export default function ScheduleSettings() {
     queryKey: ['schedule'],
     queryFn: () => window.electronAPI.schedule.getAll()
   })
-  const { data: wallpapers = [] } = useQuery({
-    queryKey: ['library-all'],
-    queryFn: () => window.electronAPI.library.getAll()
-  })
-  const { data: playlists = [] } = useQuery({
-    queryKey: ['playlists'],
-    queryFn: () => window.electronAPI.playlist.getAll()
-  })
+  const wallpapers = useAllWallpapers()
+  const playlists = usePlaylists()
 
   const wallpaperTitle = (id: string) => wallpapers.find((w) => w.id === id)?.title ?? 'missing wallpaper'
   const playlistTitle = (id: string) => playlists.find((p) => p.id === id)?.title ?? 'missing playlist'

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

@@ -606,7 +606,7 @@ export default function SettingsView() {
                 <select
                   value={audioScreen ?? ''}
                   onChange={(e) => handleAudioScreenChange(e.target.value || null)}
-                  className="w-56 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-indigo-500 [&>option]:bg-[#1a1a1a] [&>option]:text-gray-200"
+                  className="w-56 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-indigo-500"
                 >
                   <option value="">All screens (default)</option>
                   {screens.map((s) => (
@@ -1097,7 +1097,7 @@ export default function SettingsView() {
               <select
                 value={autostartPlaylistId ?? ''}
                 onChange={(e) => saveAutostart({ playlistId: e.target.value || null })}
-                className="w-56 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-indigo-500 [&>option]:bg-[#1a1a1a] [&>option]:text-gray-200"
+                className="w-56 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-200 outline-none focus:ring-1 focus:ring-indigo-500"
               >
                 <option value="">None</option>
                 {playlists.map((p) => (

File diff suppressed because it is too large
+ 286 - 626
src/renderer/src/components/workshop/WorkshopBrowser.tsx


+ 54 - 170
src/renderer/src/components/workshop/WorkshopCard.tsx

@@ -1,157 +1,85 @@
 import { useState } from 'react'
-import { Download, Check, Loader2, ThumbsUp, ExternalLink, Play, Clock, AlertTriangle } from 'lucide-react'
+import { Download, Check, Loader2, Clock, AlertTriangle } from 'lucide-react'
 import type { WorkshopItem } from '@shared/types'
-import type { SubscribeState } from '../../hooks/useSubscriptionQueue'
-import clsx from 'clsx'
-import { openWorkshopPage } from '../../utils/steam'
+import { isSubscribedState, type SubscribeState } from '../../hooks/useSubscriptionQueue'
 import { formatFileSize } from '../../utils/format'
-import { useToast } from '../common/Toast'
-import { voteBorderClass } from '../../hooks/useVoteBorders'
+import { CardPreview, CornerBadge, GridCard, LikeAction, PlayButton, ProgressBar, SteamAction } from '../common/GridCard'
 
 interface WorkshopCardProps {
   item: WorkshopItem
-  selected?: boolean
-  isDetailOpen?: boolean
-  ignored?: boolean
-  isLiked?: boolean
+  selected: boolean
+  isDetailOpen: boolean
+  ignored: boolean
+  isLiked: boolean
   voteError?: string
-  showVoteBorder?: boolean
-  canPlay?: boolean
-  lweInstalled?: boolean
+  showVoteBorder: boolean
+  canPlay: boolean
+  lweInstalled: boolean
   subscribeState?: SubscribeState
   downloadPercentage?: number
-  onSelect?: (e: React.MouseEvent) => void
-  onContextMenu?: (e: React.MouseEvent) => void
-  onLiked?: () => void
-  onPlay?: () => void | Promise<void>
-  onSubscribe?: () => void
+  onSelect: (e: React.MouseEvent) => void
+  onContextMenu: (e: React.MouseEvent) => void
+  onPlay: () => Promise<void>
+  onSubscribe: () => void
 }
 
+const STATUS_CLASS = 'flex h-7 w-7 items-center justify-center rounded-full'
+
 export default function WorkshopCard({
   item,
-  selected = false,
-  isDetailOpen = false,
-  ignored = false,
-  isLiked = false,
+  selected,
+  isDetailOpen,
+  ignored,
+  isLiked,
   voteError,
-  showVoteBorder = false,
-  canPlay = false,
-  lweInstalled = false,
+  showVoteBorder,
+  canPlay,
+  lweInstalled,
   subscribeState,
   downloadPercentage,
   onSelect,
   onContextMenu,
-  onLiked,
   onPlay,
   onSubscribe
 }: WorkshopCardProps) {
-  const { showToast } = useToast()
-  const [isLiking, setIsLiking] = useState(false)
   const [isApplying, setIsApplying] = useState(false)
-
   const fileSizeLabel = formatFileSize(item.fileSize)
-
-  const subscribed =
-    item.isSubscribed ||
-    subscribeState === 'download-queued' ||
-    subscribeState === 'downloading' ||
-    subscribeState === 'done' ||
-    subscribeState === 'download-error'
+  const subscribed = item.isSubscribed || isSubscribedState(subscribeState)
 
   function handleSubscribe(e: React.MouseEvent) {
     e.stopPropagation()
-    onSubscribe?.()
+    onSubscribe()
   }
 
-  async function handlePlay(e: React.MouseEvent) {
-    e.stopPropagation()
-    if (!canPlay || isApplying) return
+  async function handlePlay() {
+    if (isApplying) return
     setIsApplying(true)
     try {
-      await onPlay?.()
+      await onPlay()
     } finally {
       setIsApplying(false)
     }
   }
 
-  async function handleLike(e: React.MouseEvent) {
-    e.stopPropagation()
-    if (isLiked || isLiking) return
-    setIsLiking(true)
-    try {
-      const { confirmed } = await window.electronAPI.steam.vote(item.publishedFileId, true)
-      if (confirmed) {
-        onLiked?.()
-      } else {
-        showToast('Could not confirm the like on Steam - try again')
-      }
-    } catch (err) {
-      showToast((err as Error).message)
-    } finally {
-      setIsLiking(false)
-    }
-  }
-
   return (
-    <div
+    <GridCard
       data-workshop-id={item.publishedFileId}
-      title={showVoteBorder ? voteError : undefined}
-      className={clsx(
-        'group relative overflow-hidden rounded-lg bg-[#1a1a1a] transition-all cursor-pointer select-none',
-        isDetailOpen
-          ? 'ring-2 ring-sky-400'
-          : selected
-            ? 'ring-2 ring-indigo-500'
-            : 'hover:ring-1 hover:ring-indigo-500/50',
-        showVoteBorder && voteBorderClass(voteError, isLiked)
-      )}
+      selected={selected}
+      isDetailOpen={isDetailOpen}
+      isLiked={isLiked}
+      voteError={voteError}
+      showVoteBorder={showVoteBorder}
       onContextMenu={onContextMenu}
       onClick={onSelect}
     >
-      <div
-        className={clsx(
-          'absolute left-2 top-2 z-10 transition-opacity',
-          selected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
-        )}
-      >
-        <div
-          className={clsx(
-            'flex h-5 w-5 items-center justify-center rounded border',
-            selected
-              ? 'border-indigo-500 bg-indigo-500'
-              : 'border-white/40 bg-black/60'
-          )}
-        >
-          {selected && <Check size={12} className="text-white" />}
-        </div>
-      </div>
-
-      <div className="aspect-video overflow-hidden bg-[#111] relative">
-        {item.previewUrl ? (
-          <img
-            src={item.previewUrl}
-            alt={item.title}
-            className={clsx(
-              'h-full w-full object-cover transition-transform duration-300 group-hover:scale-105',
-              ignored && 'brightness-50'
-            )}
-            loading="lazy"
-          />
-        ) : (
-          <div className="flex h-full items-center justify-center text-gray-600">No preview</div>
-        )}
+      <CardPreview src={item.previewUrl} alt={item.title} dimmed={ignored}>
         {ignored && (
           <div className="absolute bottom-2 left-2 rounded bg-black/70 px-1.5 py-0.5 text-[10px] text-gray-300">
             Ignored
           </div>
         )}
         {subscribeState === 'downloading' && downloadPercentage != null && (
-          <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/40">
-            <div
-              className="h-full bg-indigo-500 transition-[width]"
-              style={{ width: `${downloadPercentage}%` }}
-            />
-          </div>
+          <ProgressBar percentage={downloadPercentage} className="absolute bottom-0 left-0 right-0 h-1 bg-black/40" />
         )}
         {subscribeState === 'download-error' && (
           <button
@@ -163,22 +91,18 @@ export default function WorkshopCard({
           </button>
         )}
         {(subscribeState === 'download-queued' || subscribeState === 'downloading') && (
-          <div
-            className="absolute bottom-2 right-2 flex h-5 w-5 items-center justify-center rounded bg-black/60 text-indigo-300"
+          <CornerBadge
+            className="bottom-2 right-2 bg-black/60 text-indigo-300"
             title={
               subscribeState === 'downloading' && downloadPercentage != null
                 ? `Downloading... ${downloadPercentage}%`
                 : 'Queued to download'
             }
           >
-            {subscribeState === 'downloading' ? (
-              <Loader2 size={12} className="animate-spin" />
-            ) : (
-              <Clock size={12} />
-            )}
-          </div>
+            {subscribeState === 'downloading' ? <Loader2 size={12} className="animate-spin" /> : <Clock size={12} />}
+          </CornerBadge>
         )}
-      </div>
+      </CardPreview>
 
       <div className="p-3">
         <h3 className="truncate text-sm font-medium text-gray-200" title={item.title}>
@@ -189,90 +113,50 @@ export default function WorkshopCard({
           {fileSizeLabel ? ` · ${fileSizeLabel}` : ''}
         </p>
         <div className="mt-2 flex items-center gap-1.5">
-          {onLiked && (
-            <button
-              onClick={handleLike}
-              disabled={isLiked || isLiking}
-              title={isLiked ? 'Already liked on Steam' : 'Like on Steam'}
-              className={clsx(
-                'flex items-center gap-1 rounded px-2 py-1 text-xs transition-colors disabled:cursor-default',
-                isLiked
-                  ? 'bg-green-600/30 text-green-300'
-                  : 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-gray-200'
-              )}
-            >
-              {isLiking ? <Loader2 size={11} className="animate-spin" /> : <ThumbsUp size={11} />}
-              {isLiked ? 'Liked' : 'Like'}
-            </button>
-          )}
-          <button
-            onClick={(e) => {
-              e.stopPropagation()
-              openWorkshopPage(item.publishedFileId)
-            }}
-            title="Open in Steam Workshop"
-            className="flex items-center gap-1 rounded bg-white/5 px-2 py-1 text-xs text-gray-400 transition-colors hover:bg-white/10 hover:text-gray-200"
-          >
-            <ExternalLink size={11} />
-            Steam
-          </button>
+          <LikeAction id={item.publishedFileId} isLiked={isLiked} />
+          <SteamAction id={item.publishedFileId} />
         </div>
       </div>
 
       <div className="absolute right-2 top-2 flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
         {canPlay && (
-          <button
-            onClick={handlePlay}
+          <PlayButton
+            busy={isApplying}
+            ready={lweInstalled}
             disabled={isApplying || !lweInstalled}
             title={lweInstalled ? 'Play wallpaper' : 'Install linux-wallpaperengine in Settings first'}
-            className={clsx(
-              'flex h-7 w-7 items-center justify-center rounded-full bg-black/60 text-white transition-opacity disabled:cursor-not-allowed',
-              lweInstalled
-                ? 'opacity-0 hover:bg-indigo-600 group-hover:opacity-100'
-                : 'text-gray-500 opacity-0 group-hover:opacity-100'
-            )}
-          >
-            {isApplying ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
-          </button>
+            onClick={handlePlay}
+          />
         )}
         {subscribed ? (
-          <div
-            className="flex h-7 w-7 items-center justify-center rounded-full bg-green-600/80 text-white"
-            title="Subscribed"
-          >
+          <div className={`${STATUS_CLASS} bg-green-600/80 text-white`} title="Subscribed">
             <Check size={14} />
           </div>
         ) : subscribeState === 'queued' ? (
-          <div
-            className="flex h-7 w-7 items-center justify-center rounded-full bg-black/60 text-gray-300"
-            title="Queued to subscribe"
-          >
+          <div className={`${STATUS_CLASS} bg-black/60 text-gray-300`} title="Queued to subscribe">
             <Clock size={14} />
           </div>
         ) : subscribeState === 'subscribing' ? (
-          <div
-            className="flex h-7 w-7 items-center justify-center rounded-full bg-black/60 text-indigo-300"
-            title="Subscribing..."
-          >
+          <div className={`${STATUS_CLASS} bg-black/60 text-indigo-300`} title="Subscribing...">
             <Loader2 size={14} className="animate-spin" />
           </div>
         ) : subscribeState === 'subscribe-error' ? (
           <button
             onClick={handleSubscribe}
             title="Subscribe failed, click to retry"
-            className="flex h-7 w-7 items-center justify-center rounded-full bg-red-600/80 text-white hover:bg-red-600"
+            className={`${STATUS_CLASS} bg-red-600/80 text-white hover:bg-red-600`}
           >
             <AlertTriangle size={14} />
           </button>
         ) : (
           <button
             onClick={handleSubscribe}
-            className="flex h-7 w-7 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-opacity hover:bg-indigo-600 group-hover:opacity-100"
+            className={`${STATUS_CLASS} bg-black/60 text-white opacity-0 transition-opacity hover:bg-indigo-600 group-hover:opacity-100`}
           >
             <Download size={14} />
           </button>
         )}
       </div>
-    </div>
+    </GridCard>
   )
 }

+ 101 - 0
src/renderer/src/hooks/queries.ts

@@ -0,0 +1,101 @@
+import { useEffect, useMemo } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import type { WallpaperFolder } from '@shared/types'
+
+export function useConfig() {
+  return useQuery({
+    queryKey: ['config'],
+    queryFn: () => window.electronAPI.config.get()
+  }).data
+}
+
+export function useLweInstalled(): boolean {
+  const { data } = useQuery({
+    queryKey: ['lwe-status'],
+    queryFn: () => window.electronAPI.lwe.status()
+  })
+  return data?.installed ?? false
+}
+
+// The whole library, unfiltered. Shares the ['library'] prefix so every library invalidation refreshes it.
+export function useAllWallpapers() {
+  const { data = [] } = useQuery({
+    queryKey: ['library'],
+    queryFn: () => window.electronAPI.library.getAll()
+  })
+  return data
+}
+
+export function usePlaylists() {
+  const { data = [] } = useQuery({
+    queryKey: ['playlists'],
+    queryFn: () => window.electronAPI.playlist.getAll()
+  })
+  return data
+}
+
+export function usePlaybackStates() {
+  const queryClient = useQueryClient()
+  const { data = [] } = useQuery({
+    queryKey: ['playlist-playback-state'],
+    queryFn: () => window.electronAPI.playlist.getState()
+  })
+
+  useEffect(() => {
+    return window.electronAPI.on.playlistStateChanged((states) => {
+      queryClient.setQueryData(['playlist-playback-state'], states)
+    })
+  }, [queryClient])
+
+  return data
+}
+
+export interface FolderMenuState {
+  hasFolder: boolean
+  // folders the selection isn't already fully inside
+  moveTargets: WallpaperFolder[]
+}
+
+export function useFolders() {
+  const queryClient = useQueryClient()
+  const { data: folders = [] } = useQuery({
+    queryKey: ['folders'],
+    queryFn: () => window.electronAPI.folders.getAll()
+  })
+
+  // each wallpaper lives in at most one folder
+  const folderOfItem = useMemo(() => {
+    const map = new Map<string, string>()
+    for (const f of folders) {
+      for (const id of f.items) map.set(id, f.id)
+    }
+    return map
+  }, [folders])
+
+  // invalidate rather than refetch: callers are often menus that are already unmounting
+  const refetchFolders = () => queryClient.invalidateQueries({ queryKey: ['folders'] })
+
+  async function moveToFolder(folderId: string, ids: string[]): Promise<void> {
+    if (ids.length === 0) return
+    await window.electronAPI.folders.addItems(folderId, ids)
+    refetchFolders()
+  }
+
+  async function removeFromFolders(ids: string[]): Promise<void> {
+    for (const folder of folders) {
+      const overlap = ids.filter((id) => folder.items.includes(id))
+      if (overlap.length > 0) await window.electronAPI.folders.removeItems(folder.id, overlap)
+    }
+    refetchFolders()
+  }
+
+  function menuState(ids: string[]): FolderMenuState {
+    const current = new Set(ids.map((id) => folderOfItem.get(id)).filter((id): id is string => !!id))
+    return {
+      hasFolder: current.size > 0,
+      moveTargets: folders.filter((f) => !(current.size === 1 && current.has(f.id)))
+    }
+  }
+
+  return { folders, folderOfItem, refetchFolders, moveToFolder, removeFromFolders, menuState }
+}

+ 28 - 0
src/renderer/src/hooks/usePersistentState.ts

@@ -0,0 +1,28 @@
+import { useEffect, useState, type Dispatch, type SetStateAction } from 'react'
+
+// useState backed by localStorage. load turns the stored JSON back into a value, returning the
+// fallback for anything it doesn't accept (wrong version, old shape).
+export function usePersistentState<T>(
+  key: string,
+  fallback: T,
+  load: (stored: unknown) => T = (stored) => ({ ...fallback, ...(stored as object) })
+): [T, Dispatch<SetStateAction<T>>] {
+  const [value, setValue] = useState<T>(() => {
+    try {
+      const raw = localStorage.getItem(key)
+      return raw ? load(JSON.parse(raw)) : fallback
+    } catch {
+      return fallback
+    }
+  })
+
+  useEffect(() => {
+    try {
+      localStorage.setItem(key, JSON.stringify(value))
+    } catch {
+      // storage disabled or full, the value just won't survive a restart
+    }
+  }, [key, value])
+
+  return [value, setValue]
+}

+ 27 - 8
src/renderer/src/hooks/useSelectableGrid.ts

@@ -1,4 +1,5 @@
 import { useState, useRef, useCallback, useEffect } from 'react'
+import { isEditingText } from '../utils/dom'
 
 export interface MarqueeRect {
   left: number
@@ -149,8 +150,7 @@ export function useSelectableGrid({ ids, dataAttr, onOpenDetail }: UseSelectable
         return
       }
       if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
-        const active = document.activeElement
-        if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA')) return
+        if (isEditingText()) return
         e.preventDefault()
         setSelectedIds(new Set(ids))
       }
@@ -159,6 +159,21 @@ export function useSelectableGrid({ ids, dataAttr, onOpenDetail }: UseSelectable
     return () => window.removeEventListener('keydown', onKeyDown)
   }, [ids])
 
+  // right-clicking a card outside the selection makes it the selection, like a file manager
+  const selectForContextMenu = useCallback(
+    (id: string): string[] => {
+      if (selectedIds.has(id)) return [...selectedIds]
+      setSelectedIds(new Set([id]))
+      return [id]
+    },
+    [selectedIds]
+  )
+
+  const clearSelection = useCallback(() => {
+    setSelectedIds(new Set())
+    setLastClickedId(null)
+  }, [])
+
   const marqueeRect: MarqueeRect | null = marquee
     ? {
         left: Math.min(marquee.startX, marquee.endX),
@@ -171,13 +186,17 @@ export function useSelectableGrid({ ids, dataAttr, onOpenDetail }: UseSelectable
   return {
     selectedIds,
     setSelectedIds,
-    lastClickedId,
-    setLastClickedId,
-    gridRef,
+    clearSelection,
+    selectForContextMenu,
     handleCardSelect,
-    handleMarqueeStart,
-    handleMarqueeMove,
-    handleMarqueeEnd,
+    // spread onto the scrolling grid container
+    containerProps: {
+      ref: gridRef,
+      onMouseDown: handleMarqueeStart,
+      onMouseMove: handleMarqueeMove,
+      onMouseUp: handleMarqueeEnd,
+      onMouseLeave: handleMarqueeEnd
+    },
     marqueeRect
   }
 }

+ 7 - 0
src/renderer/src/hooks/useSubscriptionQueue.ts

@@ -10,6 +10,13 @@ export type SubscribeState =
   | 'done'
   | 'download-error'
 
+const SUBSCRIBED_STATES = new Set<SubscribeState>(['download-queued', 'downloading', 'done', 'download-error'])
+
+// the subscribe call went through, whatever happened to the download after it
+export function isSubscribedState(state: SubscribeState | undefined): boolean {
+  return !!state && SUBSCRIBED_STATES.has(state)
+}
+
 export interface SubscribeEntry {
   state: SubscribeState
   percentage?: number

+ 2 - 4
src/renderer/src/hooks/useVoteBorders.ts

@@ -1,10 +1,8 @@
 import { useQuery } from '@tanstack/react-query'
+import { useConfig } from './queries'
 
 export function useVoteBorders(): { enabled: boolean; failed: Record<string, string> } {
-  const { data: config } = useQuery({
-    queryKey: ['config'],
-    queryFn: () => window.electronAPI.config.get()
-  })
+  const config = useConfig()
   const { data: failed } = useQuery({
     queryKey: ['steam-failed-votes'],
     queryFn: () => window.electronAPI.steam.getFailedVotes()

+ 80 - 0
src/renderer/src/hooks/useVotes.ts

@@ -0,0 +1,80 @@
+import { useCallback, useMemo, useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useToast } from '../components/common/Toast'
+
+const VOTED_IDS_KEY = ['steam-voted-ids']
+
+export function useVotedIds(): Set<string> {
+  const { data } = useQuery({
+    queryKey: VOTED_IDS_KEY,
+    queryFn: () => window.electronAPI.steam.getVotedIds(),
+    staleTime: Infinity
+  })
+  return useMemo(() => new Set(data ?? []), [data])
+}
+
+// Writes confirmed votes into both the liked list and the per-item check the detail sidebar runs,
+// so every view agrees right away instead of waiting for the next background sync
+export function useRecordVotes(): (ids: string[], up: boolean) => void {
+  const queryClient = useQueryClient()
+  return useCallback(
+    (ids: string[], up: boolean) => {
+      if (ids.length === 0) return
+      const changed = new Set(ids)
+      queryClient.setQueryData<string[]>(VOTED_IDS_KEY, (old = []) =>
+        up ? [...new Set([...old, ...ids])] : old.filter((id) => !changed.has(id))
+      )
+      for (const id of ids) queryClient.setQueryData(['steam-vote', id], up)
+    },
+    [queryClient]
+  )
+}
+
+// One item's like/dislike buttons. Failures go to onError, or a toast when there is none.
+export function useVoteAction(onError?: (message: string) => void) {
+  const { showToast } = useToast()
+  const recordVotes = useRecordVotes()
+  const [pending, setPending] = useState<'like' | 'dislike' | null>(null)
+  const report = onError ?? showToast
+
+  async function vote(id: string, up: boolean): Promise<void> {
+    if (pending) return
+    setPending(up ? 'like' : 'dislike')
+    try {
+      const { confirmed } = await window.electronAPI.steam.vote(id, up)
+      if (confirmed) recordVotes([id], up)
+      else report(`Could not confirm the ${up ? 'like' : 'dislike'} on Steam - try again`)
+    } catch (err) {
+      report((err as Error).message)
+    } finally {
+      setPending(null)
+    }
+  }
+
+  return { vote, isLiking: pending === 'like', isDisliking: pending === 'dislike' }
+}
+
+// Like/dislike for a whole selection from a context menu, reported as one toast
+export function useBatchVote(): (ids: string[], up: boolean) => Promise<void> {
+  const { showToast } = useToast()
+  const recordVotes = useRecordVotes()
+
+  return async (ids: string[], up: boolean) => {
+    if (ids.length > 1) showToast(`${up ? 'Liking' : 'Disliking'} ${ids.length} wallpapers on Steam...`)
+
+    const results = await Promise.allSettled(ids.map((id) => window.electronAPI.steam.vote(id, up)))
+    const confirmedIds = ids.filter((_, i) => {
+      const r = results[i]
+      return r.status === 'fulfilled' && r.value.confirmed
+    })
+    recordVotes(confirmedIds, up)
+
+    const failed = ids.length - confirmedIds.length
+    const done = up ? 'Liked' : 'Disliked'
+    showToast(
+      failed === 0
+        ? `${done} ${confirmedIds.length} on Steam`
+        : `${done} ${confirmedIds.length}, ${failed} could not be confirmed`
+    )
+  }
+}

+ 36 - 0
src/renderer/src/hooks/useWallpaperActions.ts

@@ -0,0 +1,36 @@
+import { useQueryClient } from '@tanstack/react-query'
+import type { ScreenTarget } from '@shared/types'
+import { useToast } from '../components/common/Toast'
+import { forEachIgnoringErrors } from '../utils/async'
+
+export function useApplyWallpaper(): (id: string, screen?: ScreenTarget) => Promise<void> {
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+
+  return async (id, screen) => {
+    try {
+      await window.electronAPI.wallpaper.apply({ wallpaperId: id, screen })
+      queryClient.invalidateQueries({ queryKey: ['library'] })
+    } catch (err) {
+      showToast((err as Error).message)
+    }
+  }
+}
+
+export function useSubscribe(): (id: string) => Promise<void> {
+  const queryClient = useQueryClient()
+  return async (id) => {
+    await window.electronAPI.steam.subscribe(id)
+    queryClient.invalidateQueries({ queryKey: ['library'] })
+  }
+}
+
+// unsubscribing can drop a wallpaper from the library, and with it from its folder
+export function useUnsubscribe(): (ids: string[]) => Promise<void> {
+  const queryClient = useQueryClient()
+  return async (ids) => {
+    await forEachIgnoringErrors(ids, (id) => window.electronAPI.steam.unsubscribe(id))
+    queryClient.invalidateQueries({ queryKey: ['library'] })
+    queryClient.invalidateQueries({ queryKey: ['folders'] })
+  }
+}

+ 1 - 1
src/renderer/src/main.tsx

@@ -9,7 +9,7 @@ const queryClient = new QueryClient({
   defaultOptions: {
     queries: {
       retry: 1,
-      staleTime: 1000 * 60 * 5 // 5 minutes
+      staleTime: 1000 * 60 * 5
     }
   }
 })

+ 5 - 0
src/renderer/src/utils/dom.ts

@@ -0,0 +1,5 @@
+// keyboard shortcuts must not fire while the user types into a field
+export function isEditingText(): boolean {
+  const active = document.activeElement
+  return !!active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA')
+}

+ 45 - 0
src/renderer/src/utils/searchQuery.test.ts

@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest'
+import { matchesSearchTerms, parseSearchQuery } from './searchQuery'
+
+describe('parseSearchQuery', () => {
+  it('leaves plain words to Steam', () => {
+    expect(parseSearchQuery('luna god')).toEqual({ steamText: 'luna god', requiredTerms: [], excludeTerms: [] })
+  })
+
+  it('turns a + joined token into required terms', () => {
+    expect(parseSearchQuery('Luna+God')).toEqual({
+      steamText: 'Luna God',
+      requiredTerms: ['luna', 'god'],
+      excludeTerms: []
+    })
+  })
+
+  it('treats a leading + as required too', () => {
+    expect(parseSearchQuery('luna +god').requiredTerms).toEqual(['god'])
+  })
+
+  it('mixes required, excluded and plain words', () => {
+    expect(parseSearchQuery(' anime  luna+god -hololive ')).toEqual({
+      steamText: 'anime luna god',
+      requiredTerms: ['luna', 'god'],
+      excludeTerms: ['hololive']
+    })
+  })
+
+  it('keeps a lone + or - as plain text', () => {
+    expect(parseSearchQuery('+ -')).toEqual({ steamText: '+ -', requiredTerms: [], excludeTerms: [] })
+  })
+})
+
+describe('matchesSearchTerms', () => {
+  const query = parseSearchQuery('luna+god -hololive')
+
+  it('needs every required term', () => {
+    expect(matchesSearchTerms('Luna, the moon God', query)).toBe(true)
+    expect(matchesSearchTerms('Luna only', query)).toBe(false)
+  })
+
+  it('drops excluded terms', () => {
+    expect(matchesSearchTerms('Luna God hololive', query)).toBe(false)
+  })
+})

+ 40 - 0
src/renderer/src/utils/searchQuery.ts

@@ -0,0 +1,40 @@
+export interface SearchQuery {
+  // what goes to Steam's own search
+  steamText: string
+  // every one of these must appear in the item, "luna+god"
+  requiredTerms: string[]
+  // none of these may appear, "-hololive"
+  excludeTerms: string[]
+}
+
+// Steam's search has no AND or exclusion syntax (several words match any of them), so "+" and "-"
+// terms are pulled out here and applied to each result client-side.
+export function parseSearchQuery(raw: string): SearchQuery {
+  const steamTokens: string[] = []
+  const requiredTerms: string[] = []
+  const excludeTerms: string[] = []
+
+  for (const token of raw.trim().split(/\s+/).filter(Boolean)) {
+    if (token.length > 1 && token.startsWith('-')) {
+      excludeTerms.push(token.slice(1).toLowerCase())
+      continue
+    }
+    const parts = token.split('+').filter(Boolean)
+    if (token.includes('+') && parts.length > 0) {
+      requiredTerms.push(...parts.map((p) => p.toLowerCase()))
+      steamTokens.push(...parts)
+    } else {
+      steamTokens.push(token)
+    }
+  }
+
+  return { steamText: steamTokens.join(' '), requiredTerms, excludeTerms }
+}
+
+export function matchesSearchTerms(haystack: string, query: SearchQuery): boolean {
+  const text = haystack.toLowerCase()
+  return (
+    query.requiredTerms.every((term) => text.includes(term)) &&
+    !query.excludeTerms.some((term) => text.includes(term))
+  )
+}

+ 52 - 0
src/renderer/src/utils/wallpaper.ts

@@ -0,0 +1,52 @@
+import type { WallpaperMeta } from '@shared/types'
+import { getPreviewSrc } from './preview'
+import { isWorkshopId } from './steam'
+
+export function isPlayable(w: Pick<WallpaperMeta, 'localPath' | 'downloading' | 'downloadFailed'>): boolean {
+  return !!w.localPath && !w.downloading && !w.downloadFailed
+}
+
+export function hasBackup(w: WallpaperMeta): boolean {
+  return !!w.backedUp || w.source === 'backup'
+}
+
+// removed items can't be updated anymore, those belong to the Unavailable filter
+export function isBackupOutdated(w: WallpaperMeta): boolean {
+  return w.source === 'workshop' && !!w.backedUp && !!w.backupOutdated && !w.unavailable
+}
+
+export function videoPath(w: WallpaperMeta): string | undefined {
+  return w.type === 'video' && w.localPath && w.file ? `${w.localPath}/${w.file}` : undefined
+}
+
+export function canBrowseCreator(w: WallpaperMeta): boolean {
+  return w.source !== 'local' && (!!w.authorSteamId || isWorkshopId(w.id))
+}
+
+// items imported before authorSteamId was stored only have it on the Workshop
+export async function resolveCreatorSteamId(w: WallpaperMeta): Promise<string | undefined> {
+  if (w.authorSteamId) return w.authorSteamId
+  if (!isWorkshopId(w.id)) return undefined
+  try {
+    return (await window.electronAPI.workshop.getItem(w.id))?.creatorSteamId
+  } catch {
+    return undefined
+  }
+}
+
+export function backupSummary(result: { backedUp: number; alreadyBackedUp: number; failed: number; unsubscribed: number }): string {
+  return `Backed up ${result.backedUp}${result.alreadyBackedUp > 0 ? `, ${result.alreadyBackedUp} already up to date` : ''}${result.unsubscribed > 0 ? ` (${result.unsubscribed} unsubscribed)` : ''}${result.failed > 0 ? `, ${result.failed} failed` : ''}`
+}
+
+// what DetailSidebar shows for a library item until its own queries have loaded
+export function detailSidebarProps(w: WallpaperMeta) {
+  return {
+    fallbackTitle: w.title,
+    fallbackPreviewUrl: getPreviewSrc(w),
+    fallbackTags: [...w.tags, ...(w.resolutions ?? [])],
+    fallbackAuthorSteamId: w.authorSteamId,
+    localFileSize: w.fileSize,
+    isSubscribed: w.subscribed,
+    canPlay: isPlayable(w)
+  }
+}

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

@@ -1,10 +1,8 @@
 export const IpcChannels = {
-  // Workshop browsing (steamworks.js)
   WORKSHOP_QUERY: 'workshop:query',
   WORKSHOP_GET_ITEM: 'workshop:get-item',
   WORKSHOP_QUERY_BY_CREATOR: 'workshop:query-by-creator',
 
-  // Steamworks operations
   STEAM_SUBSCRIBE: 'steam:subscribe',
   STEAM_UNSUBSCRIBE: 'steam:unsubscribe',
   STEAM_GET_SUBSCRIBED: 'steam:get-subscribed',
@@ -20,7 +18,6 @@ export const IpcChannels = {
   STEAM_REDOWNLOAD: 'steam:redownload',
   STEAM_GET_AUTHOR_INFO: 'steam:get-author-info',
 
-  // Library management
   LIBRARY_GET_ALL: 'library:get-all',
   LIBRARY_GET_ONE: 'library:get-one',
   LIBRARY_UPDATE: 'library:update',
@@ -34,7 +31,6 @@ export const IpcChannels = {
   LIBRARY_RESET_FPS_OVERRIDES: 'library:reset-fps-overrides',
   LIBRARY_CHECK_UNAVAILABLE: 'library:check-unavailable',
 
-  // Folders
   FOLDERS_GET_ALL: 'folders:get-all',
   FOLDERS_CREATE: 'folders:create',
   FOLDERS_RENAME: 'folders:rename',
@@ -44,7 +40,6 @@ export const IpcChannels = {
   FOLDERS_IMPORT_WE_CONFIG: 'folders:import-we-config',
   FOLDERS_CLEANUP: 'folders:cleanup',
 
-  // Wallpaper application
   WALLPAPER_APPLY: 'wallpaper:apply',
   WALLPAPER_GET_ACTIVE: 'wallpaper:get-active',
   WALLPAPER_DETECT_ENV: 'wallpaper:detect-env',
@@ -56,13 +51,11 @@ export const IpcChannels = {
   WALLPAPER_PICK_THUMBNAIL: 'wallpaper:pick-thumbnail',
   WALLPAPER_DELETE_THUMBNAIL: 'wallpaper:delete-thumbnail',
 
-  // Scheduling
   SCHEDULE_GET_ALL: 'schedule:get-all',
   SCHEDULE_SAVE: 'schedule:save',
   SCHEDULE_DELETE: 'schedule:delete',
   SCHEDULE_RUN: 'schedule:run',
 
-  // Configuration
   CONFIG_GET: 'config:get',
   CONFIG_SET_WORKSHOP_PATH: 'config:set-workshop-path',
   CONFIG_SET_DEFAULT_FPS: 'config:set-default-fps',
@@ -87,13 +80,11 @@ export const IpcChannels = {
   CONFIG_IMPORT_WE: 'config:import-we',
   CONFIG_CREATE_FRESH: 'config:create-fresh',
 
-  // Backup
   BACKUP_ITEM: 'backup:item',
   BACKUP_SELECTION: 'backup:selection',
   BACKUP_SCAN: 'backup:scan',
   BACKUP_REMOVE: 'backup:remove',
 
-  // Playlists
   PLAYLIST_GET_ALL: 'playlist:get-all',
   PLAYLIST_GET_ONE: 'playlist:get-one',
   PLAYLIST_CREATE: 'playlist:create',
@@ -120,14 +111,12 @@ export const IpcChannels = {
   CONFIG_SET_AUTOSTART: 'config:set-autostart',
   CONFIG_GET_AUTOSTART_SUPPORTED: 'config:get-autostart-supported',
 
-  // Shell operations
   SHELL_OPEN_PATH: 'shell:open-path',
   SHELL_OPEN_PATHS: 'shell:open-paths',
   SHELL_OPEN_IN_FILE_MANAGER: 'shell:open-in-file-manager',
   SHELL_OPEN_WITH_DEFAULT: 'shell:open-with-default',
   SHELL_OPEN_EXTERNAL: 'shell:open-external',
 
-  // linux-wallpaperengine
   LWE_STATUS: 'lwe:status',
   LWE_DETECT_DISTRO: 'lwe:detect-distro',
   LWE_INSTALL_DEPS: 'lwe:install-deps',
@@ -146,8 +135,8 @@ export const IpcChannels = {
   LWE_LIST_EFFECTS: 'lwe:list-effects',
   LWE_LIST_APPLICATIONS: 'lwe:list-applications',
   LWE_PICK_SHORTCUT_PATH: 'lwe:pick-shortcut-path',
+  LWE_VIDEO_DURATION: 'lwe:video-duration',
 
-  // Desktop icons overlay
   DESKTOP_ICONS_SET_ENABLED: 'desktop-icons:set-enabled',
   DESKTOP_ICONS_GET_ENABLED: 'desktop-icons:get-enabled',
 

+ 6 - 0
src/shared/types.ts

@@ -86,6 +86,12 @@ export interface WallpaperMeta {
    * linux-wallpaperengine --speed (1 = normal speed, less than 1 = slower)
    */
   playbackSpeed?: number
+  /**
+   * Video wallpapers only: loop just this part of the video (seconds, either side open), via
+   * linux-wallpaperengine --video-start/--video-end
+   */
+  videoStart?: number
+  videoEnd?: number
   backedUp?: boolean
   backupDir?: string
   /** The workshop copy no longer matches the backup (file list or sizes), e.g. the author published an update */

+ 44 - 0
src/shared/videoTrim.test.ts

@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest'
+import { formatVideoTime, parseVideoTime, trimmedVideoLength } from './videoTrim'
+
+describe('formatVideoTime', () => {
+  it('pads seconds and only shows hours when there are some', () => {
+    expect(formatVideoTime(0)).toBe('0:00')
+    expect(formatVideoTime(185)).toBe('3:05')
+    expect(formatVideoTime(3723)).toBe('1:02:03')
+  })
+
+  it('keeps tenths of a second', () => {
+    expect(formatVideoTime(65.5)).toBe('1:05.5')
+    expect(formatVideoTime(59.96)).toBe('1:00')
+  })
+})
+
+describe('parseVideoTime', () => {
+  it('reads seconds, m:ss and h:mm:ss', () => {
+    expect(parseVideoTime('90')).toBe(90)
+    expect(parseVideoTime(' 3:00 ')).toBe(180)
+    expect(parseVideoTime('0:01:30.5')).toBe(90.5)
+  })
+
+  it('rejects anything else', () => {
+    expect(parseVideoTime('')).toBeNull()
+    expect(parseVideoTime('1:')).toBeNull()
+    expect(parseVideoTime('-5')).toBeNull()
+    expect(parseVideoTime('1:2:3:4')).toBeNull()
+    expect(parseVideoTime('abc')).toBeNull()
+  })
+
+  it('reads back what formatVideoTime writes', () => {
+    for (const t of [0, 7.5, 185, 3723.4]) expect(parseVideoTime(formatVideoTime(t))).toBe(t)
+  })
+})
+
+describe('trimmedVideoLength', () => {
+  it('measures the trimmed part, open sides going to the start or end', () => {
+    expect(trimmedVideoLength(300, 180, 240)).toBe(60)
+    expect(trimmedVideoLength(300, 180)).toBe(120)
+    expect(trimmedVideoLength(300, undefined, 60)).toBe(60)
+    expect(trimmedVideoLength(300, 100, 900)).toBe(200)
+  })
+})

+ 27 - 0
src/shared/videoTrim.ts

@@ -0,0 +1,27 @@
+/** "3:05" or "1:02:03", with tenths when the time isn't a whole second */
+export function formatVideoTime(seconds: number): string {
+  const tenths = Math.round(seconds * 10)
+  const whole = Math.floor(tenths / 10)
+  const fraction = tenths % 10 ? `.${tenths % 10}` : ''
+  const h = Math.floor(whole / 3600)
+  const m = Math.floor((whole % 3600) / 60)
+  const s = String(whole % 60).padStart(2, '0') + fraction
+  return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}`
+}
+
+/** Seconds from "90", "1:30" or "0:01:30.5" (what the engine takes too), null for anything else */
+export function parseVideoTime(text: string): number | null {
+  const parts = text.trim().split(':')
+  if (parts.length > 3) return null
+  let seconds = 0
+  for (const part of parts) {
+    if (!/^\d+(\.\d+)?$/.test(part)) return null
+    seconds = seconds * 60 + Number(part)
+  }
+  return seconds
+}
+
+/** How long one pass of the trimmed part lasts */
+export function trimmedVideoLength(duration: number, start?: number, end?: number): number {
+  return Math.max(0, Math.min(end ?? duration, duration) - (start ?? 0))
+}

Some files were not shown because too many files changed in this diff