Prechádzať zdrojové kódy

full support for new linux-wallpaperengine-kde

UwU 1 mesiac pred
rodič
commit
bf4a703341
31 zmenil súbory, kde vykonal 1336 pridanie a 268 odobranie
  1. 1 1
      package.json
  2. 18 3
      src/main/ipc/config.handlers.ts
  3. 1 1
      src/main/ipc/index.ts
  4. 7 2
      src/main/ipc/library.handlers.ts
  5. 45 14
      src/main/services/backup.service.ts
  6. 14 1
      src/main/services/config.service.ts
  7. 133 0
      src/main/services/library-transfer.service.test.ts
  8. 128 0
      src/main/services/library-transfer.service.ts
  9. 102 10
      src/main/services/library.service.ts
  10. 31 6
      src/main/services/lwe.service.test.ts
  11. 52 22
      src/main/services/lwe.service.ts
  12. 2 2
      src/main/services/playlist-player.service.ts
  13. 4 7
      src/main/services/wallpaper.service.ts
  14. 42 26
      src/main/services/watcher.service.ts
  15. 59 0
      src/main/utils/localLibrary.test.ts
  16. 62 0
      src/main/utils/localLibrary.ts
  17. 14 1
      src/main/utils/paths.ts
  18. 17 6
      src/preload/index.ts
  19. 49 30
      src/renderer/src/components/common/ContextMenu.tsx
  20. 36 15
      src/renderer/src/components/common/DetailSidebar.tsx
  21. 69 5
      src/renderer/src/components/common/WallpaperContextMenu.tsx
  22. 167 91
      src/renderer/src/components/common/sidebar/VideoTrimSection.tsx
  23. 10 7
      src/renderer/src/components/library/LibraryView.tsx
  24. 4 4
      src/renderer/src/components/library/WallpaperCard.tsx
  25. 110 0
      src/renderer/src/components/settings/LibraryFoldersSettings.tsx
  26. 3 0
      src/renderer/src/components/settings/SettingsView.tsx
  27. 20 1
      src/renderer/src/utils/wallpaper.ts
  28. 2 0
      src/shared/ipc-channels.ts
  29. 14 4
      src/shared/types.ts
  30. 73 6
      src/shared/videoTrim.test.ts
  31. 47 3
      src/shared/videoTrim.ts

+ 1 - 1
package.json

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

+ 18 - 3
src/main/ipc/config.handlers.ts

@@ -1,11 +1,14 @@
 import { ipcMain, dialog, BrowserWindow } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
-import type { DisplayMode, EngineFlagPreset, EngineFlags, SteamIdentity } from '@shared/types'
+import * as path from 'path'
+import type { DisplayMode, EngineFlagPreset, EngineFlags, ExtraLibrary, SteamIdentity } from '@shared/types'
 import { BUILT_IN_PRESETS } from '@shared/engineFlags'
 import {
   getConfiguredWorkshopPath,
   setConfiguredWorkshopPath,
   isWorkshopPathConfigured,
+  getExtraLibraries,
+  setExtraLibraries,
   getDefaultFps,
   setDefaultFps,
   getRecommendedFpsEnabled,
@@ -69,6 +72,7 @@ export function registerConfigHandlers(): void {
   ipcMain.handle(IpcChannels.CONFIG_GET, () => ({
     workshopPath: getConfiguredWorkshopPath(),
     defaultWorkshopPath: getDefaultWorkshopPath(),
+    extraLibraries: getExtraLibraries(),
     isConfigured: isWorkshopPathConfigured(),
     defaultFps: getDefaultFps(),
     recommendedFpsEnabled: getRecommendedFpsEnabled(),
@@ -227,11 +231,22 @@ export function registerConfigHandlers(): void {
     return { ok: true }
   })
 
-  ipcMain.handle(IpcChannels.CONFIG_PICK_FOLDER, async (_e) => {
+  ipcMain.handle(IpcChannels.CONFIG_SET_EXTRA_LIBRARIES, (_e, libraries: ExtraLibrary[]) => {
+    setExtraLibraries(
+      libraries
+        .map((l) => ({ path: l.path.trim(), name: l.name.trim() }))
+        .filter((l) => l.path)
+        .map((l) => ({ ...l, name: l.name || path.basename(l.path) || l.path }))
+    )
+    restartWatcher()
+    return { ok: true }
+  })
+
+  ipcMain.handle(IpcChannels.CONFIG_PICK_FOLDER, async (_e, title?: string) => {
     const win = BrowserWindow.getFocusedWindow()
     const result = await dialog.showOpenDialog(win!, {
       properties: ['openDirectory'],
-      title: 'Select Wallpaper Engine Workshop folder'
+      title: title ?? 'Select Wallpaper Engine Workshop folder'
     })
     if (result.canceled || result.filePaths.length === 0) return null
     return result.filePaths[0]

+ 1 - 1
src/main/ipc/index.ts

@@ -15,7 +15,7 @@ import { registerScheduleHandlers } from './schedule.handlers'
 export function registerAllHandlers(win: BrowserWindow): void {
   registerSteamHandlers(win)
   registerWorkshopHandlers()
-  registerLibraryHandlers()
+  registerLibraryHandlers(win)
   registerWallpaperHandlers()
   registerConfigHandlers()
   registerFolderHandlers()

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

@@ -1,10 +1,15 @@
-import { ipcMain } from 'electron'
+import { ipcMain, BrowserWindow } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
 import * as library from '../services/library.service'
 import { checkOutdatedBackups } from '../services/backup.service'
+import { transferWallpapers, type TransferMode } from '../services/library-transfer.service'
 import type { LibraryFilters, WallpaperMeta } from '@shared/types'
 
-export function registerLibraryHandlers(): void {
+export function registerLibraryHandlers(win: BrowserWindow): void {
+  ipcMain.handle(IpcChannels.LIBRARY_TRANSFER, (_e, ids: string[], libraryPath: string, mode: TransferMode) => {
+    return transferWallpapers(ids, libraryPath, mode, win)
+  })
+
   ipcMain.handle(IpcChannels.LIBRARY_GET_ALL, (_e, filters?: LibraryFilters) => {
     return library.getAllWallpapers(filters)
   })

+ 45 - 14
src/main/services/backup.service.ts

@@ -66,7 +66,7 @@ export async function findBackupProblem(dir: string): Promise<string | null> {
   return `${pj.file} is missing`
 }
 
-async function sameFileList(sourcePath: string, backupDir: string): Promise<boolean> {
+export async function sameFileList(sourcePath: string, backupDir: string): Promise<boolean> {
   const [src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
   const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
   return src.length === dst.length && src.every((f) => dstSizes.get(f.relPath) === f.size)
@@ -169,26 +169,54 @@ export async function backupMatchesSource(sourcePath: string, backupDir: string)
   return true
 }
 
+// fsync destDir, drop it from the page cache and re-hash every file against the source
+export async function verifyOnDisk(sourcePath: string, destDir: string): Promise<boolean> {
+  try {
+    for (const file of await walkFiles(destDir)) await fsyncPath(path.join(destDir, file.relPath))
+    for (const dir of await walkDirs(destDir)) await fsyncPath(dir)
+  } catch {
+    return false
+  }
+  await dropPageCache(destDir)
+  return backupMatchesSource(sourcePath, destDir)
+}
+
+export async function syncDir(dir: string): Promise<void> {
+  await fsyncPath(dir)
+}
+
 export async function backupWallpaper(
   id: string,
   sourcePath: string,
   win: BrowserWindow
 ): Promise<string> {
   const destDir = getBackupDir(id)
-  const backupRoot = path.dirname(destDir)
   if (path.resolve(sourcePath) === path.resolve(destDir)) {
     throw new Error('Wallpaper already lives in the backup folder')
   }
+  return copyWallpaperFolder(id, sourcePath, destDir, win, 'backup')
+}
+
+// staged, fsynced copy, hash-checked against the source before it replaces destDir
+export async function copyWallpaperFolder(
+  id: string,
+  sourcePath: string,
+  destDir: string,
+  win: BrowserWindow,
+  action: BackupProgressEvent['action']
+): Promise<string> {
+  const destRoot = path.dirname(destDir)
+  const name = path.basename(destDir)
 
   const files = await walkFiles(sourcePath)
   if (!files.some((f) => f.relPath === 'project.json')) {
-    throw new Error('Source folder has no project.json, refusing to back up an incomplete wallpaper')
+    throw new Error('Source folder has no project.json, refusing to copy an incomplete wallpaper')
   }
   const bytesTotal = files.reduce((sum, f) => sum + f.size, 0)
 
-  await fs.promises.mkdir(backupRoot, { recursive: true })
-  const stagingDir = path.join(backupRoot, `.${id}.partial`)
-  const oldDir = path.join(backupRoot, `.${id}.old`)
+  await fs.promises.mkdir(destRoot, { recursive: true })
+  const stagingDir = path.join(destRoot, `.${name}.partial`)
+  const oldDir = path.join(destRoot, `.${name}.old`)
   await fs.promises.rm(stagingDir, { recursive: true, force: true })
   await fs.promises.mkdir(stagingDir)
 
@@ -202,10 +230,10 @@ export async function backupWallpaper(
       try {
         srcStat = await fs.promises.stat(srcFile)
       } catch {
-        throw new Error(`Source file is gone, refusing to back up: ${file.relPath}`)
+        throw new Error(`Source file is gone, refusing to copy: ${file.relPath}`)
       }
       if (!srcStat.isFile() || srcStat.size !== file.size) {
-        throw new Error(`Source file changed since it was scanned, refusing to back up: ${file.relPath}`)
+        throw new Error(`Source file changed since it was scanned, refusing to copy: ${file.relPath}`)
       }
 
       await fs.promises.mkdir(path.dirname(destFile), { recursive: true })
@@ -214,6 +242,7 @@ export async function backupWallpaper(
       bytesDone += file.size
       sendProgress(win, {
         itemId: id,
+        action,
         bytesCopied: bytesDone,
         bytesTotal,
         percentage: percent(bytesDone, bytesTotal),
@@ -229,7 +258,7 @@ export async function backupWallpaper(
       const destSize = (await fs.promises.stat(destFile)).size
       if (destSize !== file.size) {
         throw new Error(
-          `Backup verification failed for ${file.relPath}: expected ${file.size} bytes, got ${destSize}`
+          `Verification failed for ${file.relPath}: expected ${file.size} bytes, got ${destSize}`
         )
       }
       const [srcHash, destHash] = await Promise.all([
@@ -237,11 +266,12 @@ export async function backupWallpaper(
         hashFile(destFile)
       ])
       if (srcHash !== destHash) {
-        throw new Error(`Backup verification failed for ${file.relPath}: hash mismatch`)
+        throw new Error(`Verification failed for ${file.relPath}: hash mismatch`)
       }
       bytesDone += file.size
       sendProgress(win, {
         itemId: id,
+        action,
         bytesCopied: bytesDone,
         bytesTotal,
         percentage: percent(bytesDone, bytesTotal),
@@ -253,12 +283,13 @@ export async function backupWallpaper(
     const hadOld = await exists(destDir)
     if (hadOld) await fs.promises.rename(destDir, oldDir)
     await fs.promises.rename(stagingDir, destDir)
-    await fsyncPath(backupRoot)
+    await fsyncPath(destRoot)
     if (hadOld) await fs.promises.rm(oldDir, { recursive: true, force: true })
   } catch (err) {
     await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {})
     sendProgress(win, {
       itemId: id,
+      action,
       bytesCopied: bytesDone,
       bytesTotal,
       percentage: 0,
@@ -268,7 +299,7 @@ export async function backupWallpaper(
     throw err
   }
 
-  sendProgress(win, { itemId: id, bytesCopied: bytesTotal, bytesTotal, percentage: 100, status: 'completed' })
+  sendProgress(win, { itemId: id, action, bytesCopied: bytesTotal, bytesTotal, percentage: 100, status: 'completed' })
   return destDir
 }
 
@@ -288,7 +319,7 @@ export async function removeBackup(id: string): Promise<{ keptDir: string | null
 
   if (dir && (await exists(dir))) {
     const isWorkshopCopy =
-      wallpaper.source === 'workshop' && !!wallpaper.localPath && path.resolve(wallpaper.localPath) === path.resolve(dir)
+      wallpaper.source !== 'backup' && !!wallpaper.localPath && path.resolve(wallpaper.localPath) === path.resolve(dir)
     if (isWorkshopCopy || !isDeletableBackupDir(wallpaper, dir)) {
       keptDir = dir
       console.warn(`[Backup] Not deleting ${dir} for ${id}, only dropping the reference`)
@@ -390,7 +421,7 @@ export async function scanBackupFolder(): Promise<{
     }
     const existing = wallpapers.get(id)
 
-    if (existing?.source === 'workshop') {
+    if (existing?.source === 'workshop' || existing?.source === 'local') {
       if ((existing.backedUp && !dropped.has(id)) || existing.downloading) {
         result.skipped++
       } else {

+ 14 - 1
src/main/services/config.service.ts

@@ -3,10 +3,12 @@ import * as fs from 'fs'
 import * as path from 'path'
 import { app } from 'electron'
 import { WE_APP_ID } from '@shared/constants'
-import type { DisplayMode, EngineFlagPreset, EngineFlags, SteamIdentity } from '@shared/types'
+import type { DisplayMode, EngineFlagPreset, EngineFlags, ExtraLibrary, SteamIdentity } from '@shared/types'
 
 interface AppConfig {
   workshopPath: string | null
+  /** Extra wallpaper folders (source 'local'), plain strings are the old unnamed format */
+  extraLibraryPaths: (string | ExtraLibrary)[]
   defaultFps: number | null
   lweRepoUrl: string | null
   lweRepoBranch: string | null
@@ -43,6 +45,7 @@ const store = new Store<AppConfig>({
   name: 'config',
   defaults: {
     workshopPath: null,
+    extraLibraryPaths: [],
     defaultFps: null,
     recommendedFpsEnabled: false,
     recommendedWebFpsEnabled: true,
@@ -82,6 +85,16 @@ export function isWorkshopPathConfigured(): boolean {
   return store.get('workshopPath') !== null
 }
 
+export function getExtraLibraries(): ExtraLibrary[] {
+  return store
+    .get('extraLibraryPaths')
+    .map((entry) => (typeof entry === 'string' ? { path: entry, name: path.basename(entry) || entry } : entry))
+}
+
+export function setExtraLibraries(libraries: ExtraLibrary[]): void {
+  store.set('extraLibraryPaths', libraries)
+}
+
 export function getConfiguredBackupPath(): string | null {
   return store.get('backupPath')
 }

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

@@ -0,0 +1,133 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import type { WallpaperMeta } from '@shared/types'
+
+let roots: string[] = []
+let onScreen: string[] = []
+const wallpapers = new Map<string, WallpaperMeta>()
+const unsubscribe = vi.fn<(id: bigint) => Promise<void>>(async () => {})
+
+vi.mock('electron', () => ({ app: { getPath: () => os.tmpdir() } }))
+vi.mock('./config.service', () => ({ getConfiguredBackupPath: () => null }))
+vi.mock('../utils/paths', () => ({ getExtraLibraryRoots: () => roots }))
+vi.mock('./display.service', () => ({
+  getScreenAssignments: () => onScreen.map((wallpaperId) => ({ screen: 'DP-1', wallpaperId }))
+}))
+vi.mock('./steam.service', () => ({ unsubscribeFromItem: (id: bigint) => unsubscribe(id) }))
+vi.mock('./library.service', () => ({
+  getWallpaper: (id: string) => wallpapers.get(id) ?? null,
+  updateWallpaper: (id: string, patch: Partial<WallpaperMeta>) =>
+    wallpapers.set(id, { ...wallpapers.get(id)!, ...patch }),
+  normalizeType: (t?: string) => t ?? 'scene',
+  normalizeRating: () => 'everyone'
+}))
+
+const { transferWallpapers } = await import('./library-transfer.service')
+
+const win = { isDestroyed: () => false, webContents: { send: vi.fn<() => void>() } } as never
+
+let tmp = ''
+let target = ''
+
+function addWallpaper(id: string, dir: string, source: WallpaperMeta['source']): void {
+  fs.mkdirSync(dir, { recursive: true })
+  fs.writeFileSync(path.join(dir, 'project.json'), JSON.stringify({ preview: 'preview.jpg' }))
+  fs.writeFileSync(path.join(dir, 'preview.jpg'), 'jpg')
+  wallpapers.set(id, {
+    id,
+    title: id,
+    type: 'scene',
+    localPath: dir,
+    previewLocal: path.join(dir, 'preview.jpg'),
+    createdAt: 0,
+    updatedAt: 0,
+    subscribed: source === 'workshop',
+    appliedCount: 0,
+    source,
+    tags: [],
+    categories: []
+  })
+}
+
+beforeEach(() => {
+  tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-transfer-'))
+  target = path.join(tmp, 'hdd')
+  fs.mkdirSync(target)
+  roots = [path.join(tmp, 'ssd'), target]
+  onScreen = []
+  wallpapers.clear()
+  unsubscribe.mockClear()
+})
+
+afterEach(() => fs.rmSync(tmp, { recursive: true, force: true }))
+
+describe('transferWallpapers', () => {
+  it('copies without touching the entry or the original', async () => {
+    const src = path.join(tmp, 'ssd', '111')
+    addWallpaper('111', src, 'local')
+    const result = await transferWallpapers(['111'], target, 'copy', win)
+    expect(result).toEqual({ done: 1, alreadyThere: 0, failed: [] })
+    expect(fs.existsSync(path.join(target, '111', 'project.json'))).toBe(true)
+    expect(fs.existsSync(src)).toBe(true)
+    expect(wallpapers.get('111')!.localPath).toBe(src)
+  })
+
+  it('moves a local wallpaper and points the entry at the new folder', async () => {
+    const src = path.join(tmp, 'ssd', 'mine')
+    addWallpaper('mine', src, 'local')
+    await transferWallpapers(['mine'], target, 'move', win)
+    const dest = path.join(target, 'mine')
+    expect(fs.existsSync(src)).toBe(false)
+    expect(wallpapers.get('mine')).toMatchObject({ localPath: dest, previewLocal: path.join(dest, 'preview.jpg') })
+    expect(unsubscribe).not.toHaveBeenCalled()
+  })
+
+  it('unsubscribes a moved workshop wallpaper and makes it local', async () => {
+    addWallpaper('222', path.join(tmp, 'workshop', '222'), 'workshop')
+    await transferWallpapers(['222'], target, 'move', win)
+    expect(unsubscribe).toHaveBeenCalledWith(222n)
+    expect(wallpapers.get('222')).toMatchObject({ source: 'local', subscribed: false })
+  })
+
+  it('keeps the original when unsubscribing fails', async () => {
+    const src = path.join(tmp, 'workshop', '333')
+    addWallpaper('333', src, 'workshop')
+    unsubscribe.mockRejectedValueOnce(new Error('Steam is not running'))
+    const result = await transferWallpapers(['333'], target, 'move', win)
+    expect(result.failed[0].reason).toMatch(/unsubscribing failed/)
+    expect(fs.existsSync(src)).toBe(true)
+    expect(wallpapers.get('333')!.source).toBe('workshop')
+  })
+
+  it('refuses to overwrite a different folder and to move what is on a screen', async () => {
+    addWallpaper('444', path.join(tmp, 'ssd', '444'), 'local')
+    fs.mkdirSync(path.join(target, '444'))
+    fs.writeFileSync(path.join(target, '444', 'other.txt'), 'x')
+    addWallpaper('555', path.join(tmp, 'ssd', '555'), 'local')
+    onScreen = ['555']
+
+    const result = await transferWallpapers(['444', '555'], target, 'move', win)
+    expect(result.failed.map((f) => f.id)).toEqual(['444', '555'])
+    expect(fs.existsSync(path.join(tmp, 'ssd', '555'))).toBe(true)
+    expect(fs.existsSync(path.join(target, '444', 'other.txt'))).toBe(true)
+  })
+
+  it('reuses an identical folder left by an earlier copy after checking it on disk', async () => {
+    const src = path.join(tmp, 'ssd', '777')
+    addWallpaper('777', src, 'local')
+    fs.cpSync(src, path.join(target, '777'), { recursive: true })
+    expect(await transferWallpapers(['777'], target, 'move', win)).toMatchObject({ done: 1, failed: [] })
+    expect(fs.existsSync(src)).toBe(false)
+    expect(wallpapers.get('777')!.localPath).toBe(path.join(target, '777'))
+  })
+
+  it('counts wallpapers already in that library and rejects unknown folders', async () => {
+    addWallpaper('666', path.join(target, '666'), 'local')
+    expect(await transferWallpapers(['666'], target, 'copy', win)).toMatchObject({ done: 0, alreadyThere: 1 })
+    await expect(transferWallpapers(['666'], path.join(tmp, 'elsewhere'), 'copy', win)).rejects.toThrow(
+      /not a library folder/
+    )
+  })
+})

+ 128 - 0
src/main/services/library-transfer.service.ts

@@ -0,0 +1,128 @@
+import { BrowserWindow } from 'electron'
+import * as fs from 'fs'
+import * as path from 'path'
+import type { WallpaperMeta } from '@shared/types'
+import * as library from './library.service'
+import { copyWallpaperFolder, hasBackupFiles, sameFileList, syncDir, verifyOnDisk } from './backup.service'
+import { getScreenAssignments } from './display.service'
+import { unsubscribeFromItem } from './steam.service'
+import { getExtraLibraryRoots } from '../utils/paths'
+
+export type TransferMode = 'copy' | 'move'
+
+export interface TransferResult {
+  done: number
+  alreadyThere: number
+  failed: { id: string; title: string; reason: string }[]
+}
+
+const inFlight = new Set<string>()
+
+function rebase(file: string | undefined, from: string, to: string): string | undefined {
+  if (!file) return file
+  const rel = path.relative(from, file)
+  return rel.startsWith('..') || path.isAbsolute(rel) ? file : path.join(to, rel)
+}
+
+async function exists(p: string): Promise<boolean> {
+  try {
+    await fs.promises.access(p)
+    return true
+  } catch {
+    return false
+  }
+}
+
+// returns false when it already was in that library
+async function transferOne(
+  wallpaper: WallpaperMeta,
+  root: string,
+  mode: TransferMode,
+  win: BrowserWindow
+): Promise<boolean> {
+  const sourcePath = wallpaper.localPath ? path.resolve(wallpaper.localPath) : null
+  if (!sourcePath || wallpaper.downloading || !(await hasBackupFiles(sourcePath))) {
+    throw new Error('no complete local files')
+  }
+  if (path.dirname(sourcePath) === root) return false
+  if (mode === 'move' && getScreenAssignments().some((a) => a.wallpaperId === wallpaper.id)) {
+    throw new Error('it is on a screen right now')
+  }
+
+  const destDir = path.join(root, path.basename(sourcePath))
+  if (await exists(destDir)) {
+    // reuse an identical copy from an earlier run, anything else is someone's data
+    if (!(await verifyOnDisk(sourcePath, destDir))) {
+      throw new Error(`a different folder ${destDir} already exists`)
+    }
+  } else {
+    await copyWallpaperFolder(wallpaper.id, sourcePath, destDir, win, mode)
+  }
+  if (mode === 'copy') return true
+
+  // make sure the final folder is complete before the original goes away
+  if (!(await hasBackupFiles(destDir)) || !(await sameFileList(sourcePath, destDir).catch(() => false))) {
+    throw new Error(`the copy at ${destDir} does not match the original, nothing was deleted`)
+  }
+
+  // Steam would download a moved item again while subscribed
+  if (wallpaper.source === 'workshop' && wallpaper.subscribed) {
+    try {
+      await unsubscribeFromItem(BigInt(wallpaper.id))
+    } catch (err) {
+      throw new Error(
+        `copied to ${destDir}, but unsubscribing failed so the original was kept: ${(err as Error).message}`,
+        { cause: err }
+      )
+    }
+  }
+
+  const patch: Partial<WallpaperMeta> = {
+    source: 'local',
+    localPath: destDir,
+    previewLocal: rebase(wallpaper.previewLocal, sourcePath, destDir),
+    subscribed: false,
+    downloading: false,
+    downloadFailed: false
+  }
+  if (wallpaper.source === 'backup') {
+    patch.backedUp = false
+    patch.backupDir = undefined
+  }
+  library.updateWallpaper(wallpaper.id, patch)
+  await fs.promises.rm(sourcePath, { recursive: true, force: true })
+  await syncDir(path.dirname(sourcePath)).catch(() => {})
+  return true
+}
+
+export async function transferWallpapers(
+  ids: string[],
+  libraryPath: string,
+  mode: TransferMode,
+  win: BrowserWindow
+): Promise<TransferResult> {
+  const root = path.resolve(libraryPath)
+  if (!getExtraLibraryRoots().includes(root)) throw new Error(`${libraryPath} is not a library folder`)
+  if (!(await exists(root))) throw new Error(`${libraryPath} is not available, is the drive mounted?`)
+
+  const result: TransferResult = { done: 0, alreadyThere: 0, failed: [] }
+  for (const id of ids) {
+    const wallpaper = library.getWallpaper(id)
+    if (!wallpaper) continue
+    if (inFlight.has(id)) {
+      result.failed.push({ id, title: wallpaper.title, reason: 'already being copied' })
+      continue
+    }
+    inFlight.add(id)
+    try {
+      if (await transferOne(wallpaper, root, mode, win)) result.done++
+      else result.alreadyThere++
+    } catch (err) {
+      console.error(`[Library] ${mode} of ${id} to ${root} failed:`, err)
+      result.failed.push({ id, title: wallpaper.title, reason: (err as Error).message })
+    } finally {
+      inFlight.delete(id)
+    }
+  }
+  return result
+}

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

@@ -1,6 +1,7 @@
 import Store from 'electron-store'
 import type { WallpaperMeta, WallpaperType, ContentRating, LibraryFilters, WallpaperFolder } from '@shared/types'
-import { getThumbnailsPath, getWorkshopPath } from '../utils/paths'
+import { getExtraLibraryRoots, getThumbnailsPath, getWorkshopPath } from '../utils/paths'
+import { findLocalWallpapers, localWallpaperId } from '../utils/localLibrary'
 import * as path from 'path'
 import * as fs from 'fs'
 import { randomUUID } from 'crypto'
@@ -286,6 +287,26 @@ export function getDirSize(dirPath: string): number {
   return total
 }
 
+// extra folders are often on HDDs, don't block the main process
+async function getDirSizeAsync(dirPath: string): Promise<number> {
+  let total = 0
+  let entries: fs.Dirent[]
+  try {
+    entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
+  } catch {
+    return 0
+  }
+  for (const entry of entries) {
+    const full = path.join(dirPath, entry.name)
+    if (entry.isDirectory()) {
+      total += await getDirSizeAsync(full)
+    } else if (entry.isFile()) {
+      try { total += (await fs.promises.stat(full)).size } catch { /* skip */ }
+    }
+  }
+  return total
+}
+
 function buildMeta(
   workshopId: string,
   localPath: string,
@@ -293,7 +314,8 @@ function buildMeta(
   existing?: WallpaperMeta,
   workshopTimeUpdated?: number,
   authorSteamId?: string,
-  liveWorkshopTags?: string[]
+  liveWorkshopTags?: string[],
+  fileSize?: number
 ): WallpaperMeta {
   const now = Date.now()
   const { downloading: _d, downloadFailed: _df, ...existingRest } = existing ?? { appliedCount: 0, categories: [] }
@@ -320,7 +342,7 @@ function buildMeta(
     previewUrl: undefined,
     localPath,
     file: pj?.file,
-    fileSize: getDirSize(localPath),
+    fileSize: fileSize ?? getDirSize(localPath),
     createdAt: existing?.createdAt ?? now,
     updatedAt: workshopTimeUpdated ? workshopTimeUpdated * 1000 : (existing?.updatedAt ?? now),
     subscribed: true,
@@ -394,11 +416,48 @@ export async function importWallpaperById(workshopId: string): Promise<Wallpaper
   return meta
 }
 
+async function buildLocalMeta(
+  id: string,
+  localPath: string,
+  existing?: WallpaperMeta,
+  details?: WorkshopDetails
+): Promise<WallpaperMeta | null> {
+  const pj = readProjectJson(localPath)
+  if (!pj) return null
+  const fileSize = await getDirSizeAsync(localPath)
+  const authorSteamId = existing?.authorSteamId ?? details?.authorSteamId
+  return {
+    ...buildMeta(id, localPath, pj, existing, details?.timeUpdated, authorSteamId, details?.tags, fileSize),
+    subscribed: false,
+    source: 'local'
+  }
+}
+
+export async function importLocalWallpaper(localPath: string): Promise<WallpaperMeta | null> {
+  const id = await localWallpaperId(localPath)
+  if (!id) return null
+  const existing = getWallpaper(id) ?? undefined
+  if (existing && existing.source !== 'local') return null
+  // the first library holding an id wins
+  if (existing?.localPath && existing.localPath !== localPath && fs.existsSync(path.join(existing.localPath, 'project.json'))) {
+    const roots = getExtraLibraryRoots()
+    const rank = (p: string): number => roots.indexOf(path.dirname(path.resolve(p)))
+    if (rank(existing.localPath) !== -1 && rank(existing.localPath) <= rank(localPath)) return null
+  }
+
+  const details = /^\d+$/.test(id) ? (await safeGetWorkshopDetails([id])).get(id) : undefined
+  const meta = await buildLocalMeta(id, localPath, existing, details)
+  if (!meta) return null
+  upsertWallpaper(meta)
+  queueHdrCheck()
+  return meta
+}
+
 export async function scanLibrary(): Promise<{ imported: number; skipped: number; removed: number }> {
   const workshopPath = getWorkshopPath()
-  if (!fs.existsSync(workshopPath)) return { imported: 0, skipped: 0, removed: 0 }
-
-  const entries = fs.readdirSync(workshopPath, { withFileTypes: true })
+  // unmounted drive must not empty the library
+  const workshopMounted = fs.existsSync(workshopPath)
+  const entries = workshopMounted ? fs.readdirSync(workshopPath, { withFileTypes: true }) : []
   const onDisk = new Set(entries.filter(e => e.isDirectory()).map(e => e.name))
   const subscribedIds = isSteamRunning()
     ? new Set(await getSubscribedItems().catch(() => []))
@@ -417,7 +476,7 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
   // entries live under workshopPath - local imports and backups (source:'local'/'backup') are
   // never on disk here, so including them in this check would delete them on every scan.
   for (const id of Object.keys(wallpapers)) {
-    if (wallpapers[id].source !== 'workshop') continue
+    if (wallpapers[id].source !== 'workshop' || !workshopMounted) continue
     if (!onDisk.has(id) && !subscribedIds.has(id)) {
       delete wallpapers[id]
       removed++
@@ -439,7 +498,7 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     }
 
     const existing = wallpapers[entry.name]
-    if (!existing?.downloading && existing?.previewLocal !== undefined && existing?.contentRating !== undefined && existing?.fileSize !== undefined) {
+    if (existing?.localPath === localPath && !existing.downloading && existing.previewLocal !== undefined && existing?.contentRating !== undefined && existing?.fileSize !== undefined) {
       cacheHits.push(entry.name)
       skipped++
       continue
@@ -459,10 +518,32 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     incomplete.push({ id, localPath: path.join(workshopPath, id) })
   }
 
+  const roots = getExtraLibraryRoots()
+  const { found, mounted } = await findLocalWallpapers(roots)
+  const claimed = new Set([...onDisk, ...subscribedIds])
+  for (const w of Object.values(wallpapers)) {
+    if (w.source !== 'local') claimed.add(w.id)
+  }
+  const localFound = found.filter((f) => !claimed.has(f.id))
+  const localIds = new Set(localFound.map((f) => f.id))
+  for (const [id, w] of Object.entries(wallpapers)) {
+    if (w.source !== 'local' || localIds.has(id) || claimed.has(id)) continue
+    const root = path.dirname(path.resolve(w.localPath ?? ''))
+    if (roots.includes(root) && !mounted.includes(root)) continue
+    delete wallpapers[id]
+    removed++
+  }
+  const localToBuild = localFound.filter((f) => {
+    const existing = wallpapers[f.id]
+    return !(existing?.source === 'local' && existing.localPath === f.localPath && existing.fileSize !== undefined)
+  })
+  skipped += localFound.length - localToBuild.length
+
   const details = await safeGetWorkshopDetails([
     ...incomplete.map((i) => i.id),
     ...toRebuild.map(({ entry }) => entry.name),
-    ...cacheHits
+    ...cacheHits,
+    ...localToBuild.map((f) => f.id).filter((id) => /^\d+$/.test(id))
   ])
   // Author never changes once known, only take Steam's for items that don't have it yet
   const authors = new Map<string, string>()
@@ -514,6 +595,13 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     imported++
   }
 
+  for (const { id, localPath } of localToBuild) {
+    const meta = await buildLocalMeta(id, localPath, wallpapers[id], details.get(id))
+    if (!meta) continue
+    wallpapers[id] = meta
+    imported++
+  }
+
   for (const id of cacheHits) {
     const seconds = details.get(id)?.timeUpdated
     const authorId = authors.get(id)
@@ -620,6 +708,10 @@ export async function checkUnavailableWallpapers(): Promise<{
   return { checked: candidates.length, unavailable: unavailableIds.size, changed }
 }
 
+function isFromWorkshop(w: WallpaperMeta): boolean {
+  return w.source === 'workshop' || (w.source === 'local' && /^\d+$/.test(w.id))
+}
+
 // Bump whenever resolutionsFromTags() changes, stored resolutions then get re-derived once
 const RESOLUTIONS_VERSION = 2
 
@@ -630,7 +722,7 @@ export async function backfillResolutions(): Promise<boolean> {
 
   const rederive = store.get('resolutionsVersion') !== RESOLUTIONS_VERSION
   const ids = Object.values(store.get('wallpapers'))
-    .filter((w) => w.source === 'workshop' && (rederive || w.resolutions === undefined))
+    .filter((w) => isFromWorkshop(w) && (rederive || w.resolutions === undefined))
     .map((w) => w.id)
 
   let details = new Map<string, WorkshopDetails>()

+ 31 - 6
src/main/services/lwe.service.test.ts

@@ -31,15 +31,40 @@ describe('parseCustomArgs', () => {
 
 describe('buildHotswapLines', () => {
   it('writes only the fields that were given', () => {
-    expect(buildHotswapLines({ volume: 40, xray: false })).toEqual(['volume=40', 'xray=off'])
+    expect(buildHotswapLines({ volume: 40, xray: 'normal' })).toEqual(['volume=40', 'xray=off'])
+    expect(buildHotswapLines({ xray: 'full' })).toEqual(['xray=on'])
+    expect(buildHotswapLines({ xray: 'disabled' })).toEqual(['xray=disabled'])
     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('sends the video parts and seeks after setting them', () => {
+    expect(
+      buildHotswapLines({
+        videoSegments: [
+          { start: 120, end: 180 },
+          { start: 240 }
+        ],
+        videoSeek: 177
+      })
+    ).toEqual(['video-segments=120-180,240-', 'video-seek=177'])
+  })
+
+  it('plays the whole video again with no parts', () => {
+    expect(buildHotswapLines({ videoSegments: [] })).toEqual(['video-segments=none'])
+  })
+
+  it('replaces the effect lists the same way and switches animations live', () => {
+    expect(buildHotswapLines({ disabledEffects: [] })).toEqual(['effects=1'])
+    expect(buildHotswapLines({ disabledEffects: ['51', '74'], disableAnimations: false })).toEqual([
+      'effects=1',
+      'disable-effect=51',
+      'disable-effect=74',
+      'disable-animations=off'
+    ])
+    expect(buildHotswapLines({ enabledEffects: ['glow'], disableAnimations: true })).toEqual([
+      'effects=1',
+      'enable-effect=glow',
+      'disable-animations=on'
     ])
   })
 

+ 52 - 22
src/main/services/lwe.service.ts

@@ -15,7 +15,8 @@ import type {
   LweSceneEffect,
   CrashPhase,
   EngineFlags,
-  ScreenTarget
+  ScreenTarget,
+  XrayMode
 } from '@shared/types'
 import {
   isCommandAvailable,
@@ -38,6 +39,7 @@ import {
 import { DEFAULT_LWE_FPS, DEFAULT_LWE_REPO } from '@shared/constants'
 import { engineFlagArgs, filterSupportedArgs } from '@shared/engineFlags'
 import { imageAdjustmentArgs, imageAdjustmentLines, type ImageAdjustments } from '@shared/imageAdjustments'
+import { formatVideoSegments, type VideoSegment } from '@shared/videoTrim'
 
 export const ALL_SCREENS: ScreenTarget = '*'
 
@@ -930,7 +932,7 @@ export interface LweLaunchOptions {
   disabledEffects?: string[]
   enabledEffects?: string[]
   propertyOverrides?: Record<string, string>
-  xrayFullReveal?: boolean
+  xrayMode?: XrayMode
   scalingMode?: string
   zoom?: number
   offsetX?: number
@@ -940,8 +942,7 @@ export interface LweLaunchOptions {
   cornerColor?: string
   imageAdjustments?: ImageAdjustments
   speed?: number
-  videoStart?: number
-  videoEnd?: number
+  videoSegments?: VideoSegment[]
   audioSensitivity?: Record<string, number>
   soundVolume?: Record<string, number>
   customArgs?: string
@@ -993,9 +994,13 @@ 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))
+  const segments = options.videoSegments ?? []
+  if (segments.length > 0 && supportsFlag('--video-segments')) {
+    args.push('--video-segments', formatVideoSegments(segments))
+  } else if (segments.length === 1 && supportsFlag('--video-start')) {
+    // fallback for engines without --video-segments
+    args.push('--video-start', String(segments[0].start))
+    if (segments[0].end !== undefined) args.push('--video-end', String(segments[0].end))
   }
   if ((options.disabledObjects?.length || options.enabledObjects?.length) && supportsObjectFlags()) {
     for (const id of options.disabledObjects ?? []) args.push('--disable-object', id)
@@ -1255,14 +1260,22 @@ export function getRunningInstances(): RunningInstance[] {
   }))
 }
 
+function supportsEffectHotswap(): boolean {
+  return supportsFlag('effects=1')
+}
+
+function supportsAnimationHotswap(): boolean {
+  return supportsFlag('disable-animations=on')
+}
+
 // flags a hotswap can't change, a running engine launched with different ones has to be restarted
 function launchKey(options: LweLaunchOptions): string {
   const flags = options.engineFlags ?? {}
   return JSON.stringify({
     customArgs: options.customArgs?.trim() ?? '',
-    disabledEffects: options.disabledEffects ?? [],
-    enabledEffects: options.enabledEffects ?? [],
-    disableAnimations: !!flags.disableAnimations,
+    disabledEffects: supportsEffectHotswap() ? [] : (options.disabledEffects ?? []),
+    enabledEffects: supportsEffectHotswap() ? [] : (options.enabledEffects ?? []),
+    disableAnimations: supportsAnimationHotswap() ? false : !!flags.disableAnimations,
     flags: engineFlagArgs(flags)
   })
 }
@@ -1273,7 +1286,7 @@ export interface HotswapOptions {
   enabledObjects?: string[]
   volume?: number
   fps?: number
-  xray?: boolean
+  xray?: XrayMode
   scaling?: string
   zoom?: number
   offsetX?: number
@@ -1283,9 +1296,7 @@ export interface HotswapOptions {
   cornerColor?: string
   imageAdjustments?: ImageAdjustments
   speed?: number
-  /** null clears that side of the video trim */
-  videoStart?: number | null
-  videoEnd?: number | null
+  videoSegments?: VideoSegment[]
   /** Jumps a video wallpaper to this many seconds, e.g. to watch the loop point */
   videoSeek?: number
   propertyOverrides?: Record<string, string>
@@ -1296,6 +1307,10 @@ export interface HotswapOptions {
   audioSensitivity?: Record<string, number>
   /** Sound object id -> volume (0-1), applied live without a reload */
   soundVolume?: Record<string, number>
+  /** Either being present replaces the engine's effect lists */
+  disabledEffects?: string[]
+  enabledEffects?: string[]
+  disableAnimations?: boolean
 }
 
 /**
@@ -1312,9 +1327,18 @@ export function buildHotswapLines(options: HotswapOptions): string[] {
     for (const id of options.disabledObjects ?? []) lines.push(`disable-object=${id}`)
     for (const id of options.enabledObjects ?? []) lines.push(`enable-object=${id}`)
   }
+  if (options.disabledEffects !== undefined || options.enabledEffects !== undefined) {
+    lines.push('effects=1')
+    for (const id of options.disabledEffects ?? []) lines.push(`disable-effect=${id}`)
+    for (const id of options.enabledEffects ?? []) lines.push(`enable-effect=${id}`)
+  }
+  if (options.disableAnimations !== undefined) lines.push(`disable-animations=${options.disableAnimations ? 'on' : 'off'}`)
   if (options.volume !== undefined) lines.push(`volume=${options.volume}`)
   if (options.fps !== undefined) lines.push(`fps=${options.fps}`)
-  if (options.xray !== undefined) lines.push(`xray=${options.xray ? 'on' : 'off'}`)
+  // on/off keeps engines without the disabled mode working
+  if (options.xray !== undefined) {
+    lines.push(`xray=${options.xray === 'full' ? 'on' : options.xray === 'normal' ? 'off' : options.xray}`)
+  }
   if (options.scaling !== undefined) lines.push(`scaling=${options.scaling}`)
   if (options.zoom !== undefined) lines.push(`zoom=${options.zoom}`)
   if (options.offsetX !== undefined || options.offsetY !== undefined) {
@@ -1325,8 +1349,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.videoSegments !== undefined) {
+    lines.push(`video-segments=${options.videoSegments.length ? formatVideoSegments(options.videoSegments) : '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}`)
@@ -1415,7 +1440,7 @@ function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): Ho
     // the running engine keeps the previous wallpaper's limit, so a wallpaper without one has to
     // put it back to what a fresh launch without --fps gets
     fps: options.fps ?? DEFAULT_LWE_FPS,
-    xray: options.xrayFullReveal,
+    xray: options.xrayMode,
     scaling: options.scalingMode ?? 'default',
     zoom: options.zoom ?? 1,
     offsetX: options.offsetX ?? 0,
@@ -1426,14 +1451,17 @@ function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): Ho
     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,
+    videoSegments: options.videoSegments?.length ? options.videoSegments : undefined,
     propertyOverrides: options.propertyOverrides ?? {},
     audioSensitivity: {
       ...(defaultSensitivity !== 1 ? { '*': defaultSensitivity } : {}),
       ...options.audioSensitivity
     },
-    soundVolume: options.soundVolume ?? {}
+    soundVolume: options.soundVolume ?? {},
+    ...(supportsEffectHotswap()
+      ? { disabledEffects: options.disabledEffects ?? [], enabledEffects: options.enabledEffects ?? [] }
+      : {}),
+    ...(supportsAnimationHotswap() ? { disableAnimations: !!options.engineFlags?.disableAnimations } : {})
   }
 }
 
@@ -1552,7 +1580,9 @@ export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOp
     setTimeout(() => {
       if (!settled && instances.get(screen) === inst && child.exitCode === null) {
         settled = true
-        if (options.xrayFullReveal) void hotswapLweSettings({ xray: true }, { screens: [screen] })
+        if (options.xrayMode && options.xrayMode !== 'normal') {
+          void hotswapLweSettings({ xray: options.xrayMode }, { screens: [screen] })
+        }
         resolve()
       }
     }, 2000)

+ 2 - 2
src/main/services/playlist-player.service.ts

@@ -3,7 +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 { trimmedVideoLength, videoSegmentsOf } from '@shared/videoTrim'
 import { getPlaylist } from './playlist.service'
 import { getWallpaper, updateWallpaper } from './library.service'
 import { getLweStatus, ALL_SCREENS } from './lwe.service'
@@ -158,7 +158,7 @@ async function getVideoLengthSec(wallpaperId: string): Promise<number | undefine
   if (wallpaper?.type !== 'video' || !wallpaper.localPath) return undefined
   const videoFile = findWallpaperVideoFile(wallpaper.localPath, wallpaper.file)
   const duration = videoFile ? await getVideoDurationSec(videoFile) : undefined
-  return duration === undefined ? undefined : trimmedVideoLength(duration, wallpaper.videoStart, wallpaper.videoEnd)
+  return duration === undefined ? undefined : trimmedVideoLength(duration, videoSegmentsOf(wallpaper))
 }
 
 function scheduleNext(player: Player, playlist: Playlist): void {

+ 4 - 7
src/main/services/wallpaper.service.ts

@@ -17,6 +17,7 @@ import { findWallpaperVideoFile, getVideoFps } from '../utils/video'
 import { RECOMMENDED_WEB_FPS } from '@shared/constants'
 import { resolveEngineFlags } from '@shared/engineFlags'
 import { needsFreshLaunch } from '@shared/compat'
+import { videoSegmentsOf } from '@shared/videoTrim'
 
 const execFileAsync = promisify(execFile)
 
@@ -226,22 +227,18 @@ export async function lweOptionsFor(
     disabledEffects: wallpaper.disabledEffects,
     enabledEffects: wallpaper.enabledEffects,
     propertyOverrides: wallpaper.propertyOverrides,
-    // Explicit even when off: xray state lives on the running LWE process, not per-wallpaper,
-    // so a hot-reload into a wallpaper with xray off must actively clear a previous wallpaper's "on".
-    xrayFullReveal: wallpaper.xrayFullReveal ?? false,
+    // always sent: xray state lives in the running engine, a hotswap must clear it
+    xrayMode: wallpaper.xrayDisabled ? 'disabled' : wallpaper.xrayFullReveal ? 'full' : 'normal',
     scalingMode: wallpaper.scalingMode,
     zoom: wallpaper.zoom,
     offsetX: wallpaper.offsetX,
     offsetY: wallpaper.offsetY,
-    // Explicit even when off, same reasoning as xrayFullReveal above.
     disableParallax: wallpaper.disableParallax ?? false,
-    // Explicit even when off, same reasoning as xrayFullReveal above.
     expandCanvas: wallpaper.expandCanvas ?? false,
     cornerColor: wallpaper.cornerColor,
     imageAdjustments: wallpaper.imageAdjustments,
     speed: wallpaper.playbackSpeed,
-    videoStart: wallpaper.type === 'video' ? wallpaper.videoStart : undefined,
-    videoEnd: wallpaper.type === 'video' ? wallpaper.videoEnd : undefined,
+    videoSegments: wallpaper.type === 'video' ? videoSegmentsOf(wallpaper) : undefined,
     audioSensitivity: wallpaper.audioSensitivity,
     soundVolume: wallpaper.soundVolume,
     customArgs: wallpaper.customArgs

+ 42 - 26
src/main/services/watcher.service.ts

@@ -2,10 +2,11 @@ import * as fs from 'fs'
 import * as path from 'path'
 import { BrowserWindow } from 'electron'
 import { IpcChannels } from '@shared/ipc-channels'
-import { importWallpaperById } from './library.service'
-import { getWorkshopPath } from '../utils/paths'
+import type { WallpaperMeta } from '@shared/types'
+import { importLocalWallpaper, importWallpaperById } from './library.service'
+import { getExtraLibraryRoots, getWorkshopPath } from '../utils/paths'
 
-let activeWatcher: fs.FSWatcher | null = null
+let activeWatchers: fs.FSWatcher[] = []
 let watcherWin: BrowserWindow | null = null
 
 export function startWatcher(win: BrowserWindow): void {
@@ -13,30 +14,16 @@ export function startWatcher(win: BrowserWindow): void {
   restartWatcher()
 }
 
-export function restartWatcher(): void {
-  if (activeWatcher) {
-    activeWatcher.close()
-    activeWatcher = null
-  }
-  if (!watcherWin) return
-
-  const watchPath = getWorkshopPath()
-
-  if (!fs.existsSync(watchPath)) {
-    console.warn(`[Watcher] Workshop path does not exist: ${watchPath}`)
-    try {
-      fs.mkdirSync(watchPath, { recursive: true })
-    } catch {
-      return
-    }
-  }
-
+function watchNewFolders(
+  watchPath: string,
+  importFolder: (name: string, fullPath: string) => Promise<WallpaperMeta | null>
+): void {
   console.log('[Watcher] Watching', watchPath)
 
-  activeWatcher = fs.watch(watchPath, { persistent: false }, (event, filename) => {
-    if (event !== 'rename' || !filename) return
+  const watcher = fs.watch(watchPath, { persistent: false }, (event, filename) => {
+    if (event !== 'rename' || !filename || filename.startsWith('.')) return
 
-    // Give Steam a moment to finish creating the directory before importing
+    // give Steam a moment to finish creating the directory
     const fullPath = path.join(watchPath, filename)
     setTimeout(() => {
       let isDirectory = false
@@ -47,12 +34,41 @@ export function restartWatcher(): void {
       }
       if (!isDirectory) return
 
-      console.log('[Watcher] New wallpaper detected:', filename)
-      importWallpaperById(filename).then((meta) => {
+      console.log('[Watcher] New wallpaper detected:', fullPath)
+      importFolder(filename, fullPath).then((meta) => {
         if (meta && watcherWin && !watcherWin.isDestroyed()) {
           watcherWin.webContents.send(IpcChannels.EVENT_WALLPAPER_IMPORTED, meta)
         }
       })
     }, 1000)
   })
+  watcher.on('error', (err) => console.warn(`[Watcher] ${watchPath}: ${err.message}`))
+  activeWatchers.push(watcher)
+}
+
+export function restartWatcher(): void {
+  for (const watcher of activeWatchers) watcher.close()
+  activeWatchers = []
+  if (!watcherWin) return
+
+  const workshopPath = getWorkshopPath()
+  let workshopReady = fs.existsSync(workshopPath)
+  if (!workshopReady) {
+    console.warn(`[Watcher] Workshop path does not exist: ${workshopPath}`)
+    try {
+      fs.mkdirSync(workshopPath, { recursive: true })
+      workshopReady = true
+    } catch {
+    }
+  }
+  if (workshopReady) watchNewFolders(workshopPath, (name) => importWallpaperById(name))
+
+  // never created here, a missing one is usually an unmounted drive
+  for (const root of getExtraLibraryRoots()) {
+    if (!fs.existsSync(root)) {
+      console.warn(`[Watcher] Library folder is not available: ${root}`)
+      continue
+    }
+    watchNewFolders(root, (_name, fullPath) => importLocalWallpaper(fullPath))
+  }
 }

+ 59 - 0
src/main/utils/localLibrary.test.ts

@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { findLocalWallpapers, localWallpaperId } from './localLibrary'
+
+let tmp = ''
+
+function wallpaper(dir: string, project: unknown = {}): string {
+  fs.mkdirSync(dir, { recursive: true })
+  fs.writeFileSync(path.join(dir, 'project.json'), JSON.stringify(project))
+  return dir
+}
+
+beforeEach(() => {
+  tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-local-'))
+})
+
+afterEach(() => fs.rmSync(tmp, { recursive: true, force: true }))
+
+describe('localWallpaperId', () => {
+  it('keeps a workshop folder name', async () => {
+    expect(await localWallpaperId(wallpaper(path.join(tmp, '123'), { workshopid: '999' }))).toBe('123')
+  })
+
+  it('takes the workshop id from project.json for a renamed folder', async () => {
+    expect(await localWallpaperId(wallpaper(path.join(tmp, 'renamed'), { workshopid: 456 }))).toBe('456')
+  })
+
+  it('falls back to the folder name', async () => {
+    expect(await localWallpaperId(wallpaper(path.join(tmp, 'mine'), { workshopid: 'abc' }))).toBe('mine')
+    expect(await localWallpaperId(wallpaper(path.join(tmp, 'nulljson'), null))).toBe('nulljson')
+  })
+
+  it('is null without a project.json', async () => {
+    fs.mkdirSync(path.join(tmp, 'empty'))
+    expect(await localWallpaperId(path.join(tmp, 'empty'))).toBeNull()
+  })
+})
+
+describe('findLocalWallpapers', () => {
+  it('lists wallpapers of every root, first root wins, missing roots are not mounted', async () => {
+    const a = path.join(tmp, 'a')
+    const b = path.join(tmp, 'b')
+    const gone = path.join(tmp, 'gone')
+    wallpaper(path.join(a, '1'))
+    wallpaper(path.join(a, '.staging'))
+    fs.mkdirSync(path.join(a, 'incomplete'))
+    wallpaper(path.join(b, '1'))
+    wallpaper(path.join(b, '2'))
+
+    const { found, mounted } = await findLocalWallpapers([a, gone, b])
+    expect(mounted).toEqual([a, b])
+    expect(found.sort((x, y) => x.id.localeCompare(y.id))).toEqual([
+      { id: '1', localPath: path.join(a, '1') },
+      { id: '2', localPath: path.join(b, '2') }
+    ])
+  })
+})

+ 62 - 0
src/main/utils/localLibrary.ts

@@ -0,0 +1,62 @@
+import * as fs from 'fs'
+import * as path from 'path'
+
+export interface LocalWallpaperFolder {
+  id: string
+  localPath: string
+}
+
+const WORKSHOP_ID = /^\d+$/
+
+/** Numeric folder name, else project.json's workshopid, else the folder name; null without a readable project.json */
+export async function localWallpaperId(dir: string): Promise<string | null> {
+  let pj: { workshopid?: unknown } | null
+  try {
+    pj = JSON.parse(await fs.promises.readFile(path.join(dir, 'project.json'), 'utf8'))
+  } catch {
+    return null
+  }
+  const name = path.basename(dir)
+  if (WORKSHOP_ID.test(name)) return name
+  const fromProject = pj?.workshopid === undefined ? '' : String(pj.workshopid)
+  return WORKSHOP_ID.test(fromProject) ? fromProject : name
+}
+
+/** Wallpaper folders per root, the first root wins on duplicate ids; missing roots aren't in `mounted` */
+export async function findLocalWallpapers(
+  roots: string[]
+): Promise<{ found: LocalWallpaperFolder[]; mounted: string[] }> {
+  const found: LocalWallpaperFolder[] = []
+  const mounted: string[] = []
+  const seen = new Set<string>()
+
+  for (const root of roots) {
+    let entries: fs.Dirent[]
+    try {
+      entries = await fs.promises.readdir(root, { withFileTypes: true })
+    } catch {
+      continue
+    }
+    mounted.push(root)
+
+    const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name)
+    const ids: (string | null)[] = Array.from({ length: dirs.length }, () => null)
+    let next = 0
+    const worker = async (): Promise<void> => {
+      while (next < dirs.length) {
+        const i = next++
+        ids[i] = await localWallpaperId(path.join(root, dirs[i]))
+      }
+    }
+    await Promise.all(Array.from({ length: 4 }, worker))
+
+    dirs.forEach((name, i) => {
+      const id = ids[i]
+      if (!id || seen.has(id)) return
+      seen.add(id)
+      found.push({ id, localPath: path.join(root, name) })
+    })
+  }
+
+  return { found, mounted }
+}

+ 14 - 1
src/main/utils/paths.ts

@@ -3,12 +3,25 @@ import * as fs from 'fs'
 import * as os from 'os'
 import { app } from 'electron'
 import { WE_APP_ID } from '@shared/constants'
-import { getConfiguredWorkshopPath } from '../services/config.service'
+import { getConfiguredBackupPath, getConfiguredWorkshopPath, getExtraLibraries } from '../services/config.service'
 
 export function getWorkshopPath(): string {
   return getConfiguredWorkshopPath() ?? getDefaultWorkshopPath()
 }
 
+// workshop and backup folders have their own scans
+export function getExtraLibraryRoots(): string[] {
+  const skip = new Set(
+    [getWorkshopPath(), getConfiguredBackupPath()].filter((p): p is string => !!p).map((p) => path.resolve(p))
+  )
+  const roots: string[] = []
+  for (const library of getExtraLibraries()) {
+    const resolved = path.resolve(library.path)
+    if (!skip.has(resolved) && !roots.includes(resolved)) roots.push(resolved)
+  }
+  return roots
+}
+
 export function getDefaultWorkshopPath(): string {
   const home = os.homedir()
   if (process.platform === 'linux') {

+ 17 - 6
src/preload/index.ts

@@ -6,6 +6,7 @@ import type {
   WorkshopItem,
   CreatorWorkshopQueryParams,
   WallpaperMeta,
+  XrayMode,
   WallpaperFolder,
   LibraryFilters,
   WorkshopAuthorInfo,
@@ -26,6 +27,7 @@ import type {
   PlaylistSettings,
   PlaylistPlaybackState,
   SteamIdentity,
+  ExtraLibrary,
   EngineFlags,
   ImageAdjustments,
   EngineFlagPreset,
@@ -35,6 +37,7 @@ import type {
   ScheduleRule,
   CrashEvent
 } from '../shared/types'
+import type { VideoSegment } from '../shared/videoTrim'
 
 const api = {
   workshop: {
@@ -100,13 +103,20 @@ const api = {
     resetFpsOverrides: (): Promise<{ count: number }> =>
       ipcRenderer.invoke(IpcChannels.LIBRARY_RESET_FPS_OVERRIDES),
     checkUnavailable: (): Promise<{ checked: number; unavailable: number; changed: boolean }> =>
-      ipcRenderer.invoke(IpcChannels.LIBRARY_CHECK_UNAVAILABLE)
+      ipcRenderer.invoke(IpcChannels.LIBRARY_CHECK_UNAVAILABLE),
+    transfer: (
+      ids: string[],
+      libraryPath: string,
+      mode: 'copy' | 'move'
+    ): Promise<{ done: number; alreadyThere: number; failed: { id: string; title: string; reason: string }[] }> =>
+      ipcRenderer.invoke(IpcChannels.LIBRARY_TRANSFER, ids, libraryPath, mode)
   },
 
   config: {
     get: (): Promise<{
       workshopPath: string | null
       defaultWorkshopPath: string
+      extraLibraries: ExtraLibrary[]
       isConfigured: boolean
       defaultFps: number | null
       recommendedFpsEnabled: boolean
@@ -144,6 +154,8 @@ const api = {
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_DISPLAY_MODE, mode),
     setWorkshopPath: (p: string): Promise<{ ok: boolean }> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_WORKSHOP_PATH, p),
+    setExtraLibraries: (libraries: ExtraLibrary[]): Promise<{ ok: boolean }> =>
+      ipcRenderer.invoke(IpcChannels.CONFIG_SET_EXTRA_LIBRARIES, libraries),
     setDefaultFps: (fps: number | null): Promise<{ ok: boolean }> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_DEFAULT_FPS, fps),
     setRecommendedFpsEnabled: (enabled: boolean): Promise<{ ok: boolean }> =>
@@ -158,8 +170,8 @@ const api = {
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_BACKUP_PATH, p),
     setAutoUnsubscribeAfterBackup: (enabled: boolean): Promise<{ ok: boolean }> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_SET_AUTO_UNSUBSCRIBE, enabled),
-    pickFolder: (): Promise<string | null> =>
-      ipcRenderer.invoke(IpcChannels.CONFIG_PICK_FOLDER),
+    pickFolder: (title?: string): Promise<string | null> =>
+      ipcRenderer.invoke(IpcChannels.CONFIG_PICK_FOLDER, title),
     pickFile: (): Promise<string | null> =>
       ipcRenderer.invoke(IpcChannels.CONFIG_PICK_FILE),
     importWE: (sourcePath: string): Promise<{ folders: number; playlists: number; configPath: string }> =>
@@ -307,7 +319,7 @@ const api = {
       disabledObjects?: string[]
       enabledObjects?: string[]
       volume?: number
-      xray?: boolean
+      xray?: XrayMode
       scaling?: string
       zoom?: number
       offsetX?: number
@@ -317,8 +329,7 @@ const api = {
       cornerColor?: string
       imageAdjustments?: ImageAdjustments
       speed?: number
-      videoStart?: number | null
-      videoEnd?: number | null
+      videoSegments?: VideoSegment[]
       videoSeek?: number
       propertyOverrides?: Record<string, string>
       audioScreen?: string

+ 49 - 30
src/renderer/src/components/common/ContextMenu.tsx

@@ -82,6 +82,48 @@ export function VoteMenuItems({ onVote }: { onVote: (up: boolean) => void }) {
   )
 }
 
+export function SubMenu({
+  icon: Icon,
+  label,
+  empty,
+  children
+}: {
+  icon: LucideIcon
+  label: ReactNode
+  empty?: string
+  children: ReactNode
+}) {
+  const [open, setOpen] = useState(false)
+  const subRef = useRef<HTMLDivElement>(null)
+  const side = useFlipSide(subRef, open)
+  const isEmpty = Array.isArray(children) ? children.length === 0 : !children
+
+  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"
+      >
+        <Icon size={12} /> {label}
+        <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'
+          )}
+        >
+          {isEmpty && empty && <div className="px-3 py-1.5 text-gray-500">{empty}</div>}
+          {children}
+        </div>
+      )}
+    </div>
+  )
+}
+
 // "Move to folder" submenu plus "Remove from folder" when anything selected is in one
 export function FolderMenuItems({
   moveTargets,
@@ -94,38 +136,15 @@ export function FolderMenuItems({
   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>
+      <SubMenu icon={FolderInput} label="Move to folder" empty="No other folders">
+        {moveTargets.map((f) => (
+          <MenuItem key={f.id} icon={Folder} onClick={() => onMove(f.id)}>
+            {f.title}
+          </MenuItem>
+        ))}
+      </SubMenu>
       {hasFolder && (
         <MenuItem icon={Trash2} danger onClick={onRemove}>
           Remove from folder

+ 36 - 15
src/renderer/src/components/common/DetailSidebar.tsx

@@ -50,6 +50,7 @@ import { getPreviewSrc } from '../../utils/preview'
 import EngineFlagsSection from './sidebar/EngineFlagsSection'
 import ImageAdjustmentsSection from './sidebar/ImageAdjustmentsSection'
 import VideoTrimSection from './sidebar/VideoTrimSection'
+import { videoSegmentsOf, type VideoSegment } from '@shared/videoTrim'
 import CompatSection from './sidebar/CompatSection'
 import ThumbnailSection from './sidebar/ThumbnailSection'
 import { ShortcutRow } from './ShortcutRow'
@@ -571,7 +572,9 @@ export default function DetailSidebar({
             disabledObjects: patch.disabledObjects,
             enabledObjects: patch.enabledObjects,
             volume: patch.volumeOverride,
-            xray: patch.xrayFullReveal,
+            xray: 'xrayFullReveal' in patch || 'xrayDisabled' in patch
+              ? patch.xrayDisabled ? 'disabled' : patch.xrayFullReveal ? 'full' : 'normal'
+              : undefined,
             scaling: patch.scalingMode,
             zoom: patch.zoom,
             offsetX: patch.offsetX,
@@ -581,9 +584,7 @@ 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,
+            videoSegments: 'videoSegments' in patch ? (patch.videoSegments ?? []) : undefined,
             propertyOverrides: patch.propertyOverrides,
             audioSensitivity: patch.audioSensitivity,
             soundVolume: patch.soundVolume
@@ -615,8 +616,7 @@ export default function DetailSidebar({
     offsetY?: number
     speed?: number
     imageAdjustments?: ImageAdjustments
-    videoStart?: number | null
-    videoEnd?: number | null
+    videoSegments?: VideoSegment[]
     videoSeek?: number
   }) {
     if (!isActive) return
@@ -731,13 +731,14 @@ export default function DetailSidebar({
   }
 
   const [isCommittingXray, setIsCommittingXray] = useState(false)
-  const xrayFullReveal = libraryMeta?.xrayFullReveal ?? false
+  const xrayDisabled = libraryMeta?.xrayDisabled ?? false
+  const xrayFullReveal = !xrayDisabled && (libraryMeta?.xrayFullReveal ?? false)
 
-  async function toggleXray() {
+  async function setXray(patch: Pick<WallpaperMeta, 'xrayFullReveal' | 'xrayDisabled'>) {
     if (isCommittingXray) return
     setIsCommittingXray(true)
     try {
-      await persistAndMaybeRelaunch({ xrayFullReveal: !xrayFullReveal })
+      await persistAndMaybeRelaunch(patch)
     } finally {
       setIsCommittingXray(false)
     }
@@ -1269,14 +1270,13 @@ export default function DetailSidebar({
 
         {localPath && lweInstalled && libraryMeta?.type === 'video' && (
           <VideoTrimSection
-            start={libraryMeta.videoStart}
-            end={libraryMeta.videoEnd}
+            segments={videoSegmentsOf(libraryMeta)}
             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 })
+            onCommit={(segments) =>
+              persistAndMaybeRelaunch({ videoSegments: segments, videoStart: undefined, videoEnd: undefined })
             }
+            onPreview={(segments, seek) => previewLive({ videoSegments: segments, videoSeek: seek })}
           />
         )}
 
@@ -1352,7 +1352,7 @@ export default function DetailSidebar({
         {localPath && lweInstalled && libraryMeta?.type === 'scene' && (
           <div className="border-t border-white/5 pt-3">
             <button
-              onClick={toggleXray}
+              onClick={() => setXray({ xrayFullReveal: !xrayFullReveal, xrayDisabled: false })}
               disabled={isCommittingXray}
               title="Force the xray effect's reveal spot to cover the whole scene instead of following the mouse"
               className="flex w-full items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300 disabled:opacity-40"
@@ -1372,6 +1372,27 @@ export default function DetailSidebar({
                 <ToggleLeft size={14} className="text-gray-600" />
               )}
             </button>
+            <button
+              onClick={() => setXray({ xrayDisabled: !xrayDisabled, xrayFullReveal: false })}
+              disabled={isCommittingXray}
+              title="Never reveal what the xray effect hides, the mouse no longer uncovers anything"
+              className="mt-1.5 flex w-full items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-gray-500 hover:text-gray-300 disabled:opacity-40"
+            >
+              <EyeOff size={12} />
+              <span className="flex-1 text-left">Disable x-ray</span>
+              {isActive && (
+                <span className="rounded-full bg-green-600/30 px-1.5 normal-case text-green-300">
+                  live
+                </span>
+              )}
+              {isCommittingXray ? (
+                <Loader2 size={14} className="animate-spin text-gray-500" />
+              ) : xrayDisabled ? (
+                <ToggleRight size={14} className="text-indigo-400" />
+              ) : (
+                <ToggleLeft size={14} className="text-gray-600" />
+              )}
+            </button>
             <button
               onClick={toggleParallax}
               disabled={isCommittingParallax}

+ 69 - 5
src/renderer/src/components/common/WallpaperContextMenu.tsx

@@ -1,13 +1,29 @@
 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 { Archive, Copy, ExternalLink, Eye, FolderOpen, HardDrive, MoveRight, Trash2, User } from 'lucide-react'
+import type { ExtraLibrary, WallpaperMeta } from '@shared/types'
+import {
+  ContextMenu,
+  FolderMenuItems,
+  MenuItem,
+  MenuSelectionCount,
+  MenuSeparator,
+  SubMenu,
+  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'
+import {
+  backupSummary,
+  canBrowseCreator,
+  hasBackup,
+  isPlayable,
+  resolveCreatorSteamId,
+  transferSummary,
+  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.
@@ -28,12 +44,15 @@ export default function WallpaperContextMenu({
 }) {
   const queryClient = useQueryClient()
   const { showToast } = useToast()
-  const isBackupConfigured = useConfig()?.isBackupConfigured ?? false
+  const config = useConfig()
+  const isBackupConfigured = config?.isBackupConfigured ?? false
+  const libraries = config?.extraLibraries ?? []
   const { moveToFolder, removeFromFolders, menuState } = useFolders()
   const batchVote = useBatchVote()
   const unsubscribe = useUnsubscribe()
 
   const backupable = wallpapers.filter((w) => w.source === 'workshop')
+  const transferable = wallpapers.filter(isPlayable)
   const backups = wallpapers.filter(hasBackup)
   const video = wallpapers.map(videoPath).find(Boolean)
   const creatorSource = wallpapers.length === 1 && canBrowseCreator(wallpapers[0]) ? wallpapers[0] : undefined
@@ -78,6 +97,31 @@ export default function WallpaperContextMenu({
     queryClient.invalidateQueries({ queryKey: ['folders'] })
   }
 
+  async function transfer(library: ExtraLibrary, mode: 'copy' | 'move') {
+    if (mode === 'move') {
+      const workshop = transferable.filter((w) => w.source === 'workshop').length
+      const backupOnly = transferable.filter((w) => w.source === 'backup').length
+      const notes = [
+        workshop > 0 &&
+          `${workshop === 1 ? 'The workshop wallpaper' : `${workshop} workshop wallpapers`} will be unsubscribed on Steam, otherwise Steam downloads ${workshop === 1 ? 'it' : 'them'} again.`,
+        backupOnly > 0 &&
+          `${backupOnly === 1 ? 'The backup' : `${backupOnly} backups`} will leave the backup folder.`
+      ].filter(Boolean)
+      if (notes.length > 0 && !confirm(`Move to "${library.name}"?\n\n${notes.join('\n')}`)) return
+    }
+    try {
+      const result = await window.electronAPI.library.transfer(
+        transferable.map((w) => w.id),
+        library.path,
+        mode
+      )
+      showToast(transferSummary(result, mode, library.name))
+    } catch (err) {
+      showToast(`${mode === 'copy' ? 'Copy' : 'Move'} failed: ${(err as Error).message}`)
+    }
+    queryClient.invalidateQueries({ queryKey: ['library'] })
+  }
+
   async function openLocally() {
     const paths = wallpapers.filter((w) => w.localPath).map((w) => w.localPath!)
     if (paths.length > 0) await window.electronAPI.shell.openPaths(paths)
@@ -129,6 +173,26 @@ export default function WallpaperContextMenu({
         </MenuItem>
       )}
 
+      {libraries.length > 0 && transferable.length > 0 && (
+        <>
+          <MenuSeparator />
+          <SubMenu icon={Copy} label="Copy to library">
+            {libraries.map((l) => (
+              <MenuItem key={l.path} icon={HardDrive} onClick={run(() => transfer(l, 'copy'))}>
+                <span title={l.path}>{l.name}</span>
+              </MenuItem>
+            ))}
+          </SubMenu>
+          <SubMenu icon={MoveRight} label="Move to library">
+            {libraries.map((l) => (
+              <MenuItem key={l.path} icon={HardDrive} onClick={run(() => transfer(l, 'move'))}>
+                <span title={l.path}>{l.name}</span>
+              </MenuItem>
+            ))}
+          </SubMenu>
+        </>
+      )}
+
       <MenuSeparator />
       <FolderMenuItems
         moveTargets={moveTargets}

+ 167 - 91
src/renderer/src/components/common/sidebar/VideoTrimSection.tsx

@@ -1,105 +1,134 @@
 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
-}
+import { Loader2, Play, Plus, RotateCcw, Scissors, X } from 'lucide-react'
+import {
+  formatVideoTime,
+  normalizeVideoSegments,
+  parseVideoTime,
+  trimmedVideoLength,
+  type VideoSegment
+} from '@shared/videoTrim'
 
 interface Props {
-  start?: number
-  end?: number
+  segments: VideoSegment[]
   /** 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
+  onCommit: (segments: VideoSegment[]) => Promise<void>
+  /** seek: where playback jumps afterwards */
+  onPreview: (segments: VideoSegment[], 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
+// preview starts this long before a cut
 const SEAM_LEAD = 3
+const NEW_PART_LENGTH = 30
 
 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)
+export default function VideoTrimSection({ segments, duration, live, onCommit, onPreview }: Props) {
+  const [draft, setDraft] = useState<VideoSegment[] | null>(null)
+  const [texts, setTexts] = useState<Record<string, string>>({})
+  const [selected, setSelected] = useState(0)
   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
-    }
+  const rows = draft ?? segments
+  const index = Math.min(selected, rows.length - 1)
+  const part = index >= 0 ? rows[index] : undefined
+  const trimmed = segments.length > 0
+
+  function endOf(segment: VideoSegment): number | null {
+    return segment.end ?? duration
   }
 
-  function seamSeek(trim: VideoTrim): number | undefined {
-    const endOfLoop = trim.end ?? duration
-    return endOfLoop === null ? undefined : Math.max(trim.start ?? 0, endOfLoop - SEAM_LEAD)
+  function seamSeek(segment: VideoSegment): number | undefined {
+    const end = endOf(segment)
+    return end === null ? undefined : Math.max(segment.start, end - SEAM_LEAD)
   }
 
-  async function commit(next: VideoTrim) {
+  function clearText(key: string) {
+    setTexts((t) => {
+      const rest = { ...t }
+      delete rest[key]
+      return rest
+    })
+  }
+
+  function withPart(i: number, changed: VideoSegment): VideoSegment[] {
+    return rows.map((s, j) => (j === i ? changed : s))
+  }
+
+  async function commit(next: VideoSegment[]) {
     setBusy(true)
     try {
-      await onCommit(normalize(next))
+      await onCommit(normalizeVideoSegments(next, duration))
     } finally {
       setDraft(null)
-      setStartText(null)
-      setEndText(null)
+      setTexts({})
       setBusy(false)
     }
   }
 
-  function slideStart(value: number) {
-    const next = { ...current, start: loopEnd === null ? value : Math.min(value, loopEnd - MIN_LENGTH) }
+  function slide(side: 'start' | 'end', value: number) {
+    if (!part) return
+    const end = endOf(part)
+    const changed =
+      side === 'start'
+        ? { ...part, start: end === null ? value : Math.min(value, end - MIN_LENGTH) }
+        : { ...part, end: Math.max(value, part.start + MIN_LENGTH) }
+    const next = withPart(index, changed)
     setDraft(next)
-    onPreview(normalize(next))
+    onPreview(normalizeVideoSegments(next, duration), side === 'end' ? seamSeek(changed) : undefined)
   }
 
-  function slideEnd(value: number) {
-    const next = { ...current, end: Math.max(value, startValue + MIN_LENGTH) }
-    setDraft(next)
-    onPreview(normalize(next), seamSeek(next))
+  function commitText(i: number, side: 'start' | 'end', text: string) {
+    const key = `${i}-${side}`
+    const reset = () => clearText(key)
+    const value = text.trim() === '' ? (side === 'start' ? 0 : undefined) : parseVideoTime(text)
+    if (value === null) return reset()
+    const changed = { ...rows[i], [side]: value }
+    if (changed.start === rows[i].start && changed.end === rows[i].end) return reset()
+    const length = (changed.end ?? duration ?? Infinity) - changed.start
+    if (length < MIN_LENGTH || (duration !== null && changed.start >= duration)) return reset()
+    void commit(withPart(i, changed))
   }
 
-  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 newPart(): VideoSegment | null {
+    const last = rows[rows.length - 1]
+    const start = last ? last.end : 0
+    if (start === undefined) return null
+    if (duration === null) return { start, end: start + NEW_PART_LENGTH }
+    if (start > duration - MIN_LENGTH) return null
+    return { start, end: Math.min(start + NEW_PART_LENGTH, duration) }
+  }
+
+  function addPart() {
+    const added = newPart()
+    if (!added) return
+    setSelected(rows.length)
+    void commit([...rows, added])
   }
 
-  function timeInput(side: 'start' | 'end') {
-    const text = side === 'start' ? startText : endText
-    const setText = side === 'start' ? setStartText : setEndText
-    const value = side === 'start' ? startValue : loopEnd
+  function removePart(i: number) {
+    setSelected(Math.max(0, i - 1))
+    void commit(rows.filter((_, j) => j !== i))
+  }
+
+  function timeInput(i: number, side: 'start' | 'end') {
+    const key = `${i}-${side}`
+    const value = side === 'start' ? rows[i].start : endOf(rows[i])
     return (
       <input
         type="text"
-        value={text ?? (value === null ? '' : formatVideoTime(value))}
+        value={texts[key] ?? (value === null ? '' : formatVideoTime(value))}
         placeholder={side === 'start' ? '0:00' : 'end'}
         disabled={busy}
-        onChange={(e) => setText(e.target.value)}
+        onFocus={() => setSelected(i)}
+        onChange={(e) => setTexts((t) => ({ ...t, [key]: e.target.value }))}
         onKeyDown={(e) => {
           if (e.key === 'Enter') e.currentTarget.blur()
-          if (e.key === 'Escape') setText(null)
+          if (e.key === 'Escape') clearText(key)
         }}
-        onBlur={(e) => text !== null && commitText(side, e.currentTarget.value)}
+        onBlur={(e) => texts[key] !== undefined && commitText(i, side, e.currentTarget.value)}
         title="Seconds, m:ss or h:mm:ss - applies on Enter or clicking away"
         className={timeInputClass}
       />
@@ -107,23 +136,25 @@ export default function VideoTrimSection({ start, end, duration, live, onCommit,
   }
 
   function slider(side: 'start' | 'end') {
-    if (duration === null) return null
-    const value = side === 'start' ? startValue : (loopEnd ?? duration)
+    if (duration === null || !part) return null
     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"
-      />
+      <div className="flex items-center gap-1.5">
+        <span className="w-7 text-gray-500">{side === 'start' ? 'Start' : 'End'}</span>
+        <input
+          type="range"
+          min={0}
+          max={duration}
+          step={0.1}
+          value={side === 'start' ? part.start : (part.end ?? duration)}
+          disabled={busy}
+          onChange={(e) => slide(side, Number(e.target.value))}
+          onMouseUp={() => draft && commit(draft)}
+          onTouchEnd={() => draft && commit(draft)}
+          onKeyUp={() => draft && commit(draft)}
+          title={side === 'start' ? 'Where this part starts' : 'Where this part ends and the next one starts'}
+          className="w-full accent-indigo-500 disabled:opacity-50"
+        />
+      </div>
     )
   }
 
@@ -137,7 +168,7 @@ export default function VideoTrimSection({ start, end, duration, live, onCommit,
         {trimmed && (
           <button
             disabled={busy}
-            onClick={() => commit({})}
+            onClick={() => commit([])}
             title="Play the whole video again"
             className="text-gray-500 hover:text-gray-300 disabled:opacity-50"
           >
@@ -145,34 +176,79 @@ export default function VideoTrimSection({ start, end, duration, live, onCommit,
           </button>
         )}
       </div>
-      <p className="mb-1.5 text-[11px] text-gray-600">Only this part of the video plays, over and over.</p>
+      <p className="mb-1.5 text-[11px] text-gray-600">
+        Only these parts play, one after the other, over and over. Everything between them is skipped.
+      </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>
+        {duration !== null && (
+          <div className="relative h-2.5 overflow-hidden rounded bg-white/5">
+            {(rows.length ? rows : [{ start: 0 }]).map((s, i) => (
+              <button
+                key={i}
+                disabled={!rows.length}
+                onClick={() => setSelected(i)}
+                title={`${formatVideoTime(s.start)} - ${formatVideoTime(endOf(s) ?? duration)}`}
+                className={`absolute inset-y-0 ${rows.length && i === index ? 'bg-indigo-400' : 'bg-indigo-500/50'}`}
+                style={{
+                  left: `${(Math.min(s.start, duration) / duration) * 100}%`,
+                  width: `${((Math.min(endOf(s) ?? duration, duration) - Math.min(s.start, duration)) / duration) * 100}%`
+                }}
+              />
+            ))}
+          </div>
+        )}
+
+        {rows.length === 0 && <p className="text-gray-600">Plays the whole video.</p>}
+        {rows.map((s, i) => (
+          <div key={i} className={`flex items-center gap-1.5 rounded px-1 ${i === index ? 'bg-white/5' : ''}`}>
+            <button
+              onClick={() => setSelected(i)}
+              className={`flex-1 text-left ${i === index ? 'text-gray-200' : 'text-gray-500 hover:text-gray-300'}`}
+            >
+              Part {i + 1}
+            </button>
+            {timeInput(i, 'start')}
+            <span className="text-gray-600">-</span>
+            {timeInput(i, 'end')}
+            <button
+              disabled={busy}
+              onClick={() => removePart(i)}
+              title="Remove this part"
+              className="text-gray-500 hover:text-red-300 disabled:opacity-50"
+            >
+              <X size={11} />
+            </button>
+          </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)}`}
+              trimmed &&
+              `Plays ${formatVideoTime(trimmedVideoLength(duration, rows))} of ${formatVideoTime(duration)}`}
           </span>
-          {live && trimmed && seamSeek({ start, end }) !== undefined && (
+          <button
+            disabled={busy || newPart() === null}
+            onClick={addPart}
+            title="Add another part after the last one"
+            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"
+          >
+            <Plus size={9} />
+            Add part
+          </button>
+          {live && trimmed && part && seamSeek(part) !== 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`}
+              onClick={() => onPreview(segments, seamSeek(part))}
+              title={`Jumps ${SEAM_LEAD} seconds before the end of part ${index + 1}, to see the cut into the next one`}
               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
+              Cut
             </button>
           )}
         </div>

+ 10 - 7
src/renderer/src/components/library/LibraryView.tsx

@@ -32,7 +32,7 @@ import {
 } from '../common/GridControls'
 import { CheckItem, FilterPanel, FilterSection, ResolutionFilterSection, TagFilterSection } from '../common/FilterPanel'
 import { useToast } from '../common/Toast'
-import type { LibraryFilters, WallpaperFolder } from '@shared/types'
+import type { BackupProgressEvent, LibraryFilters, WallpaperFolder } from '@shared/types'
 import clsx from 'clsx'
 import {
   WE_TYPES,
@@ -49,7 +49,7 @@ import { useApplyWallpaper, useSubscribe, useUnsubscribe } from '../../hooks/use
 import { useSelectableGrid } from '../../hooks/useSelectableGrid'
 import { toggle } from '../../utils/array'
 import { isEditingText } from '../../utils/dom'
-import { backupSummary, detailSidebarProps, isBackupOutdated } from '../../utils/wallpaper'
+import { backupSummary, detailSidebarProps, isBackupOutdated, progressVerb } from '../../utils/wallpaper'
 
 interface LibraryFilterState {
   types: string[]
@@ -94,7 +94,8 @@ const RATING_MAP: Record<string, string> = {
 }
 const SOURCE_MAP: Record<string, string> = {
   Workshop: 'workshop',
-  Backup: 'backup'
+  Backup: 'backup',
+  Local: 'local'
 }
 
 interface SortState {
@@ -374,7 +375,7 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
   const [runningTasks, setRunningTasks] = useState<Set<BackgroundTask>>(new Set())
   const [backupStatus, setBackupStatus] = useState<string | null>(null)
   const [backupProgress, setBackupProgress] = useState<
-    Map<string, { percentage: number; status: 'copying' | 'verifying' }>
+    Map<string, { percentage: number; status: 'copying' | 'verifying'; action?: BackupProgressEvent['action'] }>
   >(new Map())
 
   useEffect(() => {
@@ -382,14 +383,15 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
       setBackupProgress((prev) => {
         const next = new Map(prev)
         if (progress.status === 'copying' || progress.status === 'verifying') {
-          next.set(progress.itemId, { percentage: progress.percentage, status: progress.status })
+          next.set(progress.itemId, { percentage: progress.percentage, status: progress.status, action: progress.action })
         } else {
           next.delete(progress.itemId)
         }
         return next
       })
       if (progress.status === 'error') {
-        showToast(`Backup failed: ${progress.message ?? 'verification error'}`)
+        const what = progress.action === 'copy' ? 'Copy' : progress.action === 'move' ? 'Move' : 'Backup'
+        showToast(`${what} failed: ${progress.message ?? 'verification error'}`)
       }
     })
   }, [showToast])
@@ -659,7 +661,8 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
 
       {backupProgress.size > 0 && (
         <div className="border-b border-white/5 px-4 py-2 text-xs text-gray-400">
-          Backing up {backupProgress.size} wallpaper{backupProgress.size === 1 ? '' : 's'}
+          {progressVerb(Array.from(backupProgress.values()))} {backupProgress.size} wallpaper
+          {backupProgress.size === 1 ? '' : 's'}
           {Array.from(backupProgress.values()).some((p) => p.status === 'verifying')
             ? ' (verifying copies)'
             : ''}

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

@@ -1,11 +1,11 @@
 import { useState, useEffect } from '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 type { BackupProgressEvent, WallpaperMeta } from '@shared/types'
 import clsx from 'clsx'
 import CompatBadge from '../common/CompatBadge'
 import { getPreviewSrc } from '../../utils/preview'
-import { hasBackup } from '../../utils/wallpaper'
+import { hasBackup, progressVerb } from '../../utils/wallpaper'
 import { useToast } from '../common/Toast'
 import type { PreviewSize } from '../../hooks/usePreviewSize'
 import {
@@ -31,7 +31,7 @@ interface WallpaperCardProps {
   currentPlaylistId: string | null
   isInCurrentPlaylist: boolean
   previewSize: PreviewSize
-  backupProgress: { percentage: number; status: 'copying' | 'verifying' } | null
+  backupProgress: { percentage: number; status: 'copying' | 'verifying'; action?: BackupProgressEvent['action'] } | null
   onSelect: (e: React.MouseEvent) => void
   onContextMenu: (e: React.MouseEvent) => void
 }
@@ -207,7 +207,7 @@ export default function WallpaperCard({
             <span className="text-xs text-gray-300">
               {backupProgress.status === 'verifying'
                 ? `Verifying... ${backupProgress.percentage}%`
-                : `Backing up... ${backupProgress.percentage}%`}
+                : `${progressVerb([backupProgress])}... ${backupProgress.percentage}%`}
             </span>
             <ProgressBar percentage={backupProgress.percentage} className="h-1 w-full max-w-[140px] rounded-full bg-white/10" />
           </CardOverlay>

+ 110 - 0
src/renderer/src/components/settings/LibraryFoldersSettings.tsx

@@ -0,0 +1,110 @@
+import { useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import { FolderPlus, HardDrive, Loader2, X } from 'lucide-react'
+import type { ExtraLibrary } from '@shared/types'
+import { useConfig } from '../../hooks/queries'
+
+function folderName(p: string): string {
+  return p.split('/').filter(Boolean).pop() ?? p
+}
+
+export default function LibraryFoldersSettings() {
+  const queryClient = useQueryClient()
+  const libraries = useConfig()?.extraLibraries ?? []
+  const [names, setNames] = useState<Record<string, string>>({})
+  const [scanning, setScanning] = useState(false)
+  const [status, setStatus] = useState<string | null>(null)
+
+  async function save(next: ExtraLibrary[]) {
+    await window.electronAPI.config.setExtraLibraries(next)
+    await queryClient.invalidateQueries({ queryKey: ['config'] })
+  }
+
+  async function saveAndScan(next: ExtraLibrary[]) {
+    await save(next)
+    setScanning(true)
+    setStatus(null)
+    try {
+      const result = await window.electronAPI.library.scan()
+      setStatus(`Library rescanned: ${result.imported} imported, ${result.removed} removed.`)
+    } catch (err) {
+      setStatus(`Scan failed: ${(err as Error).message}`)
+    } finally {
+      setScanning(false)
+      queryClient.invalidateQueries({ queryKey: ['library'] })
+      queryClient.invalidateQueries({ queryKey: ['library-tags'] })
+    }
+  }
+
+  async function handleAdd() {
+    const picked = await window.electronAPI.config.pickFolder('Select a folder of wallpapers')
+    if (!picked || libraries.some((l) => l.path === picked)) return
+    await saveAndScan([...libraries, { path: picked, name: folderName(picked) }])
+  }
+
+  async function handleRename(library: ExtraLibrary) {
+    const name = names[library.path]?.trim()
+    setNames((prev) => {
+      const next = { ...prev }
+      delete next[library.path]
+      return next
+    })
+    if (!name || name === library.name) return
+    await save(libraries.map((l) => (l.path === library.path ? { ...l, name } : l)))
+  }
+
+  return (
+    <div>
+      <label className="block text-xs font-medium uppercase tracking-wide text-gray-500">
+        Extra library folders
+      </label>
+      <p className="mt-1 text-xs text-gray-600">
+        Folders on other disks holding wallpaper folders (each with a project.json), like a copied
+        workshop folder. They show up in the library as "Local", and selected wallpapers can be copied
+        or moved into them from the right-click menu. When the same wallpaper is also in the workshop
+        or backup folder, that copy is used. Wallpapers on a drive that is not mounted stay in the
+        library until the folder is removed here.
+      </p>
+      {libraries.length > 0 && (
+        <ul className="mt-2 space-y-1">
+          {libraries.map((l) => (
+            <li key={l.path} className="flex items-center gap-2 rounded-lg bg-white/5 px-3 py-2 text-sm text-gray-200">
+              <HardDrive size={14} className="shrink-0 text-gray-500" />
+              <input
+                type="text"
+                value={names[l.path] ?? l.name}
+                onChange={(e) => setNames((prev) => ({ ...prev, [l.path]: e.target.value }))}
+                onBlur={() => handleRename(l)}
+                onKeyDown={(e) => {
+                  if (e.key === 'Enter') e.currentTarget.blur()
+                }}
+                title="Library name"
+                className="w-32 shrink-0 rounded bg-transparent px-1 text-gray-100 outline-none focus:bg-white/5 focus:ring-1 focus:ring-indigo-500"
+              />
+              <span className="flex-1 truncate text-xs text-gray-500" title={l.path}>
+                {l.path}
+              </span>
+              <button
+                onClick={() => saveAndScan(libraries.filter((x) => x.path !== l.path))}
+                disabled={scanning}
+                title="Remove from the library"
+                className="rounded p-0.5 text-gray-500 hover:bg-white/10 hover:text-gray-200 disabled:opacity-50"
+              >
+                <X size={14} />
+              </button>
+            </li>
+          ))}
+        </ul>
+      )}
+      <button
+        onClick={handleAdd}
+        disabled={scanning}
+        className="mt-3 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"
+      >
+        {scanning ? <Loader2 size={16} className="animate-spin" /> : <FolderPlus size={16} />}
+        {scanning ? 'Scanning...' : 'Add folder'}
+      </button>
+      {status && <p className="mt-2 text-xs text-gray-500">{status}</p>}
+    </div>
+  )
+}

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

@@ -5,6 +5,7 @@ import type { LweStatus, LwePrebuiltTarget, LweInstallProgress, LinuxDistro, Ste
 import PerformanceSettings from './PerformanceSettings'
 import DisplaySettings from './DisplaySettings'
 import VoteBorderSettings from './VoteBorderSettings'
+import LibraryFoldersSettings from './LibraryFoldersSettings'
 import ScheduleSettings from './ScheduleSettings'
 
 const DISTRO_LABELS: Record<LinuxDistro, string> = {
@@ -402,6 +403,8 @@ export default function SettingsView() {
           </button>
         </div>
 
+        <LibraryFoldersSettings />
+
         <div>
           <label className="block text-xs font-medium uppercase tracking-wide text-gray-500">
             Backup folder

+ 20 - 1
src/renderer/src/utils/wallpaper.ts

@@ -20,7 +20,7 @@ export function videoPath(w: WallpaperMeta): string | undefined {
 }
 
 export function canBrowseCreator(w: WallpaperMeta): boolean {
-  return w.source !== 'local' && (!!w.authorSteamId || isWorkshopId(w.id))
+  return isWorkshopId(w.id) || (w.source !== 'local' && !!w.authorSteamId)
 }
 
 // items imported before authorSteamId was stored only have it on the Workshop
@@ -38,6 +38,25 @@ export function backupSummary(result: { backedUp: number; alreadyBackedUp: numbe
   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` : ''}`
 }
 
+export function progressVerb(items: { action?: 'backup' | 'copy' | 'move' }[]): string {
+  const actions = new Set(items.map((p) => p.action ?? 'backup'))
+  if (actions.size > 1) return 'Copying'
+  return actions.has('move') ? 'Moving' : actions.has('copy') ? 'Copying' : 'Backing up'
+}
+
+export function transferSummary(
+  result: { done: number; alreadyThere: number; failed: { title: string; reason: string }[] },
+  mode: 'copy' | 'move',
+  libraryName: string
+): string {
+  const verb = mode === 'copy' ? 'Copied' : 'Moved'
+  const parts = [`${verb} ${result.done} to ${libraryName}`]
+  if (result.alreadyThere > 0) parts.push(`${result.alreadyThere} already there`)
+  if (result.failed.length === 1) parts.push(`"${result.failed[0].title}" failed: ${result.failed[0].reason}`)
+  else if (result.failed.length > 1) parts.push(`${result.failed.length} failed (first: ${result.failed[0].reason})`)
+  return parts.join(', ')
+}
+
 // what DetailSidebar shows for a library item until its own queries have loaded
 export function detailSidebarProps(w: WallpaperMeta) {
   return {

+ 2 - 0
src/shared/ipc-channels.ts

@@ -20,6 +20,7 @@ export const IpcChannels = {
 
   LIBRARY_GET_ALL: 'library:get-all',
   LIBRARY_GET_ONE: 'library:get-one',
+  LIBRARY_TRANSFER: 'library:transfer',
   LIBRARY_UPDATE: 'library:update',
   LIBRARY_DELETE: 'library:delete',
   LIBRARY_ADD_TAG: 'library:add-tag',
@@ -58,6 +59,7 @@ export const IpcChannels = {
 
   CONFIG_GET: 'config:get',
   CONFIG_SET_WORKSHOP_PATH: 'config:set-workshop-path',
+  CONFIG_SET_EXTRA_LIBRARIES: 'config:set-extra-libraries',
   CONFIG_SET_DEFAULT_FPS: 'config:set-default-fps',
   CONFIG_SET_RECOMMENDED_FPS: 'config:set-recommended-fps',
   CONFIG_SET_RECOMMENDED_WEB_FPS: 'config:set-recommended-web-fps',

+ 14 - 4
src/shared/types.ts

@@ -1,9 +1,12 @@
 import type { ImageAdjustments } from './imageAdjustments'
+import type { VideoSegment } from './videoTrim'
 
 export type { ImageAdjustments } from './imageAdjustments'
 
 export type WallpaperType = 'scene' | 'video' | 'web' | 'application'
 
+export type XrayMode = 'normal' | 'full' | 'disabled'
+
 /** Matches linux-wallpaperengine's --scaling choices */
 export type ScalingMode = 'default' | 'stretch' | 'fit' | 'fill' | 'center'
 
@@ -31,6 +34,11 @@ export type ContentRating = 'everyone' | 'questionable' | 'mature' | 'uncategori
 /** How this process identifies itself to Steam - see config.service.ts getSteamIdentity(). */
 export type SteamIdentity = 'wallpaper-engine' | 'standalone'
 
+export interface ExtraLibrary {
+  path: string
+  name: string
+}
+
 export interface WallpaperMeta {
   id: string
   title: string
@@ -60,6 +68,7 @@ export interface WallpaperMeta {
   volumeOverride?: number
   /** Forces the "xray" scene effect's reveal spot to cover the whole masked area instead of following the mouse */
   xrayFullReveal?: boolean
+  xrayDisabled?: boolean
   /** How the wallpaper is scaled to fit the screen, applied via linux-wallpaperengine --scaling */
   scalingMode?: ScalingMode
   /** Manual zoom layered on top of scalingMode via linux-wallpaperengine --zoom (1 = no extra zoom) */
@@ -86,10 +95,9 @@ 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
-   */
+  /** --video-segments parts, empty plays the whole video */
+  videoSegments?: VideoSegment[]
+  /** Old single loop range, read through videoSegmentsOf */
   videoStart?: number
   videoEnd?: number
   backedUp?: boolean
@@ -408,6 +416,8 @@ export interface BackupProgressEvent {
   percentage: number
   status: 'copying' | 'verifying' | 'completed' | 'error'
   message?: string
+  /** Plain backup when unset */
+  action?: 'backup' | 'copy' | 'move'
 }
 
 export interface PlaylistItem {

+ 73 - 6
src/shared/videoTrim.test.ts

@@ -1,5 +1,12 @@
 import { describe, expect, it } from 'vitest'
-import { formatVideoTime, parseVideoTime, trimmedVideoLength } from './videoTrim'
+import {
+  formatVideoSegments,
+  formatVideoTime,
+  normalizeVideoSegments,
+  parseVideoTime,
+  trimmedVideoLength,
+  videoSegmentsOf
+} from './videoTrim'
 
 describe('formatVideoTime', () => {
   it('pads seconds and only shows hours when there are some', () => {
@@ -35,10 +42,70 @@ describe('parseVideoTime', () => {
 })
 
 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)
+  it('adds up the parts, an open end going to the end of the video', () => {
+    expect(trimmedVideoLength(300, [{ start: 180, end: 240 }])).toBe(60)
+    expect(trimmedVideoLength(300, [{ start: 180 }])).toBe(120)
+    expect(trimmedVideoLength(300, [{ start: 120, end: 180 }, { start: 240, end: 300 }])).toBe(120)
+    expect(trimmedVideoLength(300, [{ start: 100, end: 900 }])).toBe(200)
+  })
+
+  it('is the whole video without parts', () => {
+    expect(trimmedVideoLength(300, [])).toBe(300)
+  })
+})
+
+describe('videoSegmentsOf', () => {
+  it('turns the old single start/end into one part', () => {
+    expect(videoSegmentsOf({ videoStart: 180, videoEnd: 240 })).toEqual([{ start: 180, end: 240 }])
+    expect(videoSegmentsOf({ videoEnd: 60 })).toEqual([{ start: 0, end: 60 }])
+    expect(videoSegmentsOf({})).toEqual([])
+  })
+
+  it('prefers the parts list', () => {
+    expect(videoSegmentsOf({ videoSegments: [], videoStart: 180 })).toEqual([])
+  })
+})
+
+describe('normalizeVideoSegments', () => {
+  it('sorts, drops empty parts and merges overlapping ones', () => {
+    expect(
+      normalizeVideoSegments([
+        { start: 240, end: 300 },
+        { start: 120, end: 180 },
+        { start: 150, end: 200 },
+        { start: 50, end: 50 }
+      ])
+    ).toEqual([
+      { start: 120, end: 200 },
+      { start: 240, end: 300 }
+    ])
+  })
+
+  it('keeps touching parts apart', () => {
+    expect(normalizeVideoSegments([{ start: 0, end: 30 }, { start: 30, end: 60 }])).toEqual([
+      { start: 0, end: 30 },
+      { start: 30, end: 60 }
+    ])
+  })
+
+  it('lets an open end swallow the parts after it', () => {
+    expect(normalizeVideoSegments([{ start: 10 }, { start: 60, end: 70 }])).toEqual([{ start: 10 }])
+  })
+
+  it('opens an end at the end of the video and drops parts past it', () => {
+    expect(normalizeVideoSegments([{ start: 120, end: 180 }, { start: 240, end: 300 }, { start: 400 }], 300)).toEqual([
+      { start: 120, end: 180 },
+      { start: 240 }
+    ])
+  })
+
+  it('is no parts for the whole video', () => {
+    expect(normalizeVideoSegments([{ start: 0, end: 300 }], 300)).toEqual([])
+  })
+})
+
+describe('formatVideoSegments', () => {
+  it('writes what --video-segments reads', () => {
+    expect(formatVideoSegments([{ start: 120, end: 180 }, { start: 240.25 }])).toBe('120-180,240.25-')
   })
 })

+ 47 - 3
src/shared/videoTrim.ts

@@ -21,7 +21,51 @@ export function parseVideoTime(text: string): number | null {
   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))
+/** In seconds, no end means up to the end of the video */
+export interface VideoSegment {
+  start: number
+  end?: number
+}
+
+export function videoSegmentsOf(meta: {
+  videoSegments?: VideoSegment[]
+  videoStart?: number
+  videoEnd?: number
+}): VideoSegment[] {
+  if (meta.videoSegments) return meta.videoSegments
+  if (meta.videoStart === undefined && meta.videoEnd === undefined) return []
+  return [{ start: meta.videoStart ?? 0, end: meta.videoEnd }]
+}
+
+/** Sorted and merged like the engine, an end past the video stays open, the whole video gives [] */
+export function normalizeVideoSegments(segments: VideoSegment[], duration?: number | null): VideoSegment[] {
+  const merged: VideoSegment[] = []
+  const sorted = segments
+    .map((s) => ({ start: s.start, end: duration && s.end !== undefined && s.end >= duration ? undefined : s.end }))
+    .filter((s) => (s.end === undefined || s.end > s.start) && !(duration && s.start >= duration))
+    .sort((a, b) => a.start - b.start)
+  for (const segment of sorted) {
+    const last = merged[merged.length - 1]
+    // touching parts stay separate rows
+    if (!last || (last.end !== undefined && segment.start >= last.end)) {
+      merged.push({ ...segment })
+    } else if (last.end !== undefined) {
+      last.end = segment.end === undefined ? undefined : Math.max(last.end, segment.end)
+    }
+  }
+  if (merged.length === 1 && merged[0].start <= 0 && merged[0].end === undefined) return []
+  return merged
+}
+
+function seconds(value: number): string {
+  return String(Math.round(value * 1000) / 1000)
+}
+
+export function formatVideoSegments(segments: VideoSegment[]): string {
+  return segments.map((s) => `${seconds(s.start)}-${s.end === undefined ? '' : seconds(s.end)}`).join(',')
+}
+
+export function trimmedVideoLength(duration: number, segments: VideoSegment[]): number {
+  if (segments.length === 0) return duration
+  return segments.reduce((sum, s) => sum + Math.max(0, Math.min(s.end ?? duration, duration) - s.start), 0)
 }