Преглед изворни кода

support for new linux-wallpaperengine-kde, gnome 45-50 support added

UwU пре 1 месец
родитељ
комит
33dd52c334

+ 1 - 0
src/main/ipc/backup.handlers.ts

@@ -45,6 +45,7 @@ async function backupOne(id: string, win: BrowserWindow): Promise<BackupItemResu
       library.updateWallpaper(id, {
         source: 'backup',
         localPath: backupDir!,
+        previewLocal: await backup.previewInBackup(wallpaper, backupDir!),
         subscribed: false,
         downloading: false,
         downloadFailed: false

+ 15 - 0
src/main/ipc/gnome-extension.handlers.ts

@@ -0,0 +1,15 @@
+import { ipcMain } from 'electron'
+import { IpcChannels } from '@shared/ipc-channels'
+import { getGnomeExtensionStatus, installGnomeExtension } from '../services/gnome-extension.service'
+
+export function registerGnomeExtensionHandlers(): void {
+  ipcMain.handle(IpcChannels.GNOME_EXTENSION_STATUS, () => getGnomeExtensionStatus())
+
+  ipcMain.handle(IpcChannels.GNOME_EXTENSION_INSTALL, async () => {
+    try {
+      return await installGnomeExtension()
+    } catch (error) {
+      return { ok: false, message: (error as Error).message, status: await getGnomeExtensionStatus() }
+    }
+  })
+}

+ 2 - 0
src/main/ipc/index.ts

@@ -8,6 +8,7 @@ import { registerFolderHandlers } from './folders.handlers'
 import { registerShellHandlers } from './shell.handlers'
 import { registerLweHandlers } from './lwe.handlers'
 import { registerDesktopIconsHandlers } from './desktop-icons.handlers'
+import { registerGnomeExtensionHandlers } from './gnome-extension.handlers'
 import { registerBackupHandlers } from './backup.handlers'
 import { registerPlaylistHandlers } from './playlist.handlers'
 import { registerScheduleHandlers } from './schedule.handlers'
@@ -22,6 +23,7 @@ export function registerAllHandlers(win: BrowserWindow): void {
   registerShellHandlers()
   registerLweHandlers(win)
   registerDesktopIconsHandlers()
+  registerGnomeExtensionHandlers()
   registerBackupHandlers(win)
   registerPlaylistHandlers()
   registerScheduleHandlers()

+ 1 - 0
src/main/ipc/steam.handlers.ts

@@ -82,6 +82,7 @@ export function registerSteamHandlers(win: BrowserWindow): void {
       library.updateWallpaper(itemId, {
         source: 'backup',
         localPath: backupDir,
+        previewLocal: await backup.previewInBackup(wallpaper, backupDir),
         backupDir,
         subscribed: false,
         downloading: false,

+ 41 - 0
src/main/services/backup.service.test.ts

@@ -158,6 +158,47 @@ describe('scanBackupFolder', () => {
     expect(wallpapers.get('moved')?.localPath).toBe(path.join(backupRoot, 'moved'))
   })
 
+  it('fixes the thumbnail of a backup entry that still points into the deleted workshop folder', async () => {
+    writeFiles(path.join(backupRoot, 'unsubbed'), { 'project.json': '{"preview":"preview.gif"}', 'preview.gif': 'gif' })
+    const gone = path.join(tmp, 'workshop', 'unsubbed', 'preview.gif')
+    wallpapers.set('unsubbed', { ...base, id: 'unsubbed', source: 'backup', localPath: path.join(backupRoot, 'unsubbed'), backedUp: true, fileSize: 1, previewLocal: gone })
+    const result = await backup.scanBackupFolder()
+    expect(result.previewsFixed).toBe(1)
+    expect(wallpapers.get('unsubbed')?.previewLocal).toBe(path.join(backupRoot, 'unsubbed', 'preview.gif'))
+    expect((await backup.scanBackupFolder()).previewsFixed).toBe(0)
+  })
+
+  it('fixes the thumbnail of a workshop entry whose preview file changed name', async () => {
+    writeFiles(source, { 'project.json': '{"preview":"Preview.GIF"}', 'preview.gif': 'gif' })
+    wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, fileSize: 1, previewLocal: path.join(source, 'preview.jpg') })
+    const result = await backup.scanBackupFolder()
+    expect(result.previewsFixed).toBe(1)
+    expect(wallpapers.get('123')?.previewLocal).toBe(path.join(source, 'preview.gif'))
+  })
+
+  it('drops a custom thumbnail whose file is gone', async () => {
+    writeFiles(source, { 'project.json': '{"preview":"preview.jpg"}', 'preview.jpg': 'jpg' })
+    const preview = path.join(source, 'preview.jpg')
+    wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, previewLocal: preview, customPreview: path.join(tmp, 'thumbs', 'gone.png') })
+    expect((await backup.scanBackupFolder()).previewsFixed).toBe(1)
+    expect(wallpapers.get('123')?.customPreview).toBeUndefined()
+    expect(wallpapers.get('123')?.previewLocal).toBe(preview)
+  })
+
+  it('leaves the preview of an entry on an unmounted drive alone', async () => {
+    const gone = path.join(tmp, 'unmounted', '123', 'preview.jpg')
+    wallpapers.set('123', { ...base, id: '123', source: 'local', localPath: path.dirname(gone), previewLocal: gone })
+    expect((await backup.scanBackupFolder()).previewsFixed).toBe(0)
+    expect(wallpapers.get('123')?.previewLocal).toBe(gone)
+  })
+
+  it('moves the preview into the backup folder', async () => {
+    writeFiles(source, { 'project.json': '{"preview":"preview.jpg"}', 'preview.jpg': 'jpg' })
+    const dir = await backup.backupWallpaper('123', source, win)
+    const meta = { ...base, id: '123', source: 'workshop' as const, localPath: source, previewLocal: path.join(source, 'preview.jpg') }
+    expect(await backup.previewInBackup(meta, dir)).toBe(path.join(dir, 'preview.jpg'))
+  })
+
   it('keeps a workshop entry linked when its backup differs from the workshop copy', async () => {
     const dir = await backup.backupWallpaper('123', source, win)
     wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })

+ 93 - 3
src/main/services/backup.service.ts

@@ -50,6 +50,39 @@ async function readProjectJson(dir: string): Promise<ProjectJson | null> {
   }
 }
 
+// project.json names come from Windows, where "Preview.JPG" finds preview.jpg
+async function findFileIgnoringCase(dir: string, rel: string): Promise<string | undefined> {
+  const exact = path.join(dir, rel)
+  if (await exists(exact)) return exact
+  const parent = path.dirname(exact)
+  const name = path.basename(exact).toLowerCase()
+  try {
+    const match = (await fs.promises.readdir(parent)).find((f) => f.toLowerCase() === name)
+    return match ? path.join(parent, match) : undefined
+  } catch {
+    return undefined
+  }
+}
+
+// Current relative preview path if present, else project.json's, else any preview.* image.
+export async function previewInBackup(wallpaper: WallpaperMeta, dir: string): Promise<string | undefined> {
+  if (wallpaper.previewLocal && wallpaper.localPath) {
+    const rel = path.relative(wallpaper.localPath, wallpaper.previewLocal)
+    if (rel && !rel.startsWith('..') && !path.isAbsolute(rel) && (await exists(path.join(dir, rel)))) {
+      return path.join(dir, rel)
+    }
+  }
+  const pj = await readProjectJson(dir)
+  const named = pj?.preview ? await findFileIgnoringCase(dir, pj.preview) : undefined
+  if (named) return named
+  try {
+    const any = (await fs.promises.readdir(dir)).find((f) => /^preview\.(png|jpe?g|gif|webp|bmp)$/i.test(f))
+    return any ? path.join(dir, any) : undefined
+  } catch {
+    return undefined
+  }
+}
+
 export async function hasBackupFiles(dir: string | null): Promise<boolean> {
   return !!dir && (await isDir(dir)) && (await exists(path.join(dir, 'project.json')))
 }
@@ -364,19 +397,70 @@ async function buildBackupMeta(id: string, localPath: string, existing?: Wallpap
 
 const SCAN_CONCURRENCY = 4
 
+// Repoints a missing preview at the file on disk now; folders on unmounted drives are skipped.
+async function previewRepair(w: WallpaperMeta): Promise<Partial<WallpaperMeta> | null> {
+  const patch: Partial<WallpaperMeta> = {}
+  if (w.customPreview && !(await exists(w.customPreview))) {
+    patch.customPreview = undefined
+    patch.useOriginalPreview = false
+  }
+  if (!w.previewLocal || !(await exists(w.previewLocal))) {
+    const dirs = [w.localPath, resolveBackupDir(w)].filter((d): d is string => !!d)
+    let mounted = false
+    for (const dir of [...new Set(dirs.map((d) => path.resolve(d)))]) {
+      if (!(await isDir(dir))) continue
+      mounted = true
+      const found = await previewInBackup(w, dir)
+      if (found) {
+        patch.previewLocal = found
+        break
+      }
+    }
+    if (!patch.previewLocal && mounted && w.previewLocal) patch.previewLocal = undefined
+  }
+  return Object.keys(patch).length > 0 ? patch : null
+}
+
+async function previewRepairs(wallpapers: WallpaperMeta[]): Promise<{ id: string; patch: Partial<WallpaperMeta> }[]> {
+  const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
+  await forEachLimit(
+    wallpapers.filter((w) => !w.downloading),
+    SCAN_CONCURRENCY,
+    async (w) => {
+      const patch = await previewRepair(w)
+      if (patch) patches.push({ id: w.id, patch })
+    }
+  )
+  return patches
+}
+
 export async function scanBackupFolder(): Promise<{
   imported: number
   skipped: number
   linked: number
   removed: number
   unlinked: number
+  previewsFixed: number
   corrupted: string[]
 }> {
-  const result = { imported: 0, skipped: 0, linked: 0, removed: 0, unlinked: 0, corrupted: [] as string[] }
+  const result = {
+    imported: 0,
+    skipped: 0,
+    linked: 0,
+    removed: 0,
+    unlinked: 0,
+    previewsFixed: 0,
+    corrupted: [] as string[]
+  }
   const backupPath = getConfiguredBackupPath()
-  if (!backupPath || !(await isDir(backupPath))) return result
-
   const wallpapers = new Map(library.getAllWallpapers().map((w) => [w.id, w]))
+  if (!backupPath || !(await isDir(backupPath))) {
+    const patches = await previewRepairs([...wallpapers.values()])
+    library.applyWallpaperChanges({ patches })
+    result.previewsFixed = patches.length
+    return result
+  }
+
   const folderIds = (await fs.promises.readdir(backupPath, { withFileTypes: true }))
     // dot folders are staging copies of an in-progress backup
     .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
@@ -445,6 +529,12 @@ export async function scanBackupFolder(): Promise<{
   })
 
   const reimported = new Set(upserts.map((m) => m.id))
+  const previewPatches = await previewRepairs(
+    [...wallpapers.values()].filter((w) => !reimported.has(w.id) && !deletes.includes(w.id))
+  )
+  patches.push(...previewPatches)
+  result.previewsFixed = previewPatches.length
+
   library.applyWallpaperChanges({
     upserts,
     patches,

+ 41 - 0
src/main/services/gnome-extension.service.test.ts

@@ -0,0 +1,41 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('./lwe.service', () => ({ getLweStatus: () => ({ installed: false }) }))
+
+import { flatpakInstallCommands, parseExtensionState, parseStringArray } from './gnome-extension.service'
+
+describe('parseExtensionState', () => {
+  it('reads the state line of gnome-extensions info', () => {
+    const output = [
+      'linux-wallpaperengine@wallpaperenginelover.github.io',
+      '  Name: linux-wallpaperengine',
+      '  Path: /home/user/.local/share/gnome-shell/extensions/linux-wallpaperengine@wallpaperenginelover.github.io',
+      '  Enabled: Yes',
+      '  State: ACTIVE'
+    ].join('\n')
+    expect(parseExtensionState(output)).toBe('ACTIVE')
+  })
+
+  it('keeps states made of two words', () => {
+    expect(parseExtensionState('  State: OUT OF DATE\n')).toBe('OUT OF DATE')
+  })
+
+  it('has nothing for an unknown extension', () => {
+    expect(parseExtensionState('Extension “x” doesn\'t exist')).toBeUndefined()
+  })
+})
+
+describe('parseStringArray', () => {
+  it('reads gsettings string arrays', () => {
+    expect(parseStringArray("['a@b', 'c@d']")).toEqual(['a@b', 'c@d'])
+    expect(parseStringArray('@as []')).toEqual([])
+  })
+})
+
+describe('flatpakInstallCommands', () => {
+  it('copies the Flatpak copy from its host path and enables it', () => {
+    const commands = flatpakInstallCommands("/var/lib/flatpak/app/x/files/bin/gnome-shell-extension/it's")
+    expect(commands[1]).toBe("cp -r '/var/lib/flatpak/app/x/files/bin/gnome-shell-extension/it'\\''s' ~/.local/share/gnome-shell/extensions/")
+    expect(commands[2]).toBe('gnome-extensions enable linux-wallpaperengine@wallpaperenginelover.github.io')
+  })
+})

+ 149 - 0
src/main/services/gnome-extension.service.ts

@@ -0,0 +1,149 @@
+import { execFile } from 'child_process'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { promisify } from 'util'
+import type { GnomeExtensionStatus } from '@shared/types'
+import { detectDesktopEnv, isWaylandSession } from '../utils/platform'
+import { hostCommand, isFlatpak, toHostPath } from '../utils/flatpak'
+import { getLweStatus } from './lwe.service'
+
+const execFileAsync = promisify(execFile)
+
+/**
+ * GNOME Wayland has no layer-shell, the engine's Shell extension makes its windows desktop windows. The Shell only
+ * scans extensions at startup, so a fresh install needs a re-login.
+ */
+export const GNOME_EXTENSION_UUID = 'linux-wallpaperengine@wallpaperenginelover.github.io'
+const GNOME_HELPER = 'linux-wallpaperengine-gnome-helper'
+
+function userExtensionDir(): string {
+  // the Flatpak's XDG_DATA_HOME is under ~/.var/app, the Shell reads the host's
+  const dataHome = (!isFlatpak() && process.env.XDG_DATA_HOME) || path.join(os.homedir(), '.local', 'share')
+  return path.join(dataHome, 'gnome-shell', 'extensions', GNOME_EXTENSION_UUID)
+}
+
+/** The copy next to the real engine binary */
+export function bundledExtensionDir(enginePath = getLweStatus().path): string | undefined {
+  if (!enginePath) return undefined
+  let real = enginePath
+  try { real = fs.realpathSync(enginePath) } catch { /* keep the path */ }
+  const dir = path.join(path.dirname(real), 'gnome-shell-extension', GNOME_EXTENSION_UUID)
+  return fs.existsSync(path.join(dir, 'metadata.json')) ? dir : undefined
+}
+
+function readVersion(dir: string): string | undefined {
+  try {
+    const metadata = JSON.parse(fs.readFileSync(path.join(dir, 'metadata.json'), 'utf8'))
+    return metadata['version-name'] !== undefined ? String(metadata['version-name']) : undefined
+  } catch {
+    return undefined
+  }
+}
+
+/** older gnome-extensions print ENABLED instead of ACTIVE */
+export function parseExtensionState(output: string): string | undefined {
+  return output.match(/^\s*State:\s*(.+?)\s*$/m)?.[1]?.toUpperCase()
+}
+
+async function runHost(cmd: string, args: string[]): Promise<{ ok: boolean; out: string }> {
+  const [file, fileArgs] = hostCommand(cmd, args)
+  try {
+    const { stdout, stderr } = await execFileAsync(file, fileArgs, { timeout: 10000, encoding: 'utf8' })
+    return { ok: true, out: `${stdout}${stderr}` }
+  } catch (error) {
+    const failure = error as { stdout?: string; stderr?: string; message?: string }
+    return { ok: false, out: `${failure.stdout ?? ''}${failure.stderr ?? ''}` || (failure.message ?? '') }
+  }
+}
+
+export function isGnomeWayland(): boolean {
+  return detectDesktopEnv() === 'gnome' && isWaylandSession()
+}
+
+export async function getGnomeExtensionStatus(): Promise<GnomeExtensionStatus> {
+  if (!isGnomeWayland()) return { needed: false, state: 'not-needed' }
+
+  const bundled = bundledExtensionDir()
+  const bundledVersion = bundled ? readVersion(bundled) : undefined
+  const installedDir = userExtensionDir()
+  const installedVersion = fs.existsSync(installedDir) ? readVersion(installedDir) : undefined
+  const base: Partial<GnomeExtensionStatus> & { needed: true } = { needed: true, bundled: !!bundled, ...(bundledVersion ? { bundledVersion } : {}),
+    ...(installedVersion ? { installedVersion } : {}) }
+
+  const info = await runHost('gnome-extensions', ['info', GNOME_EXTENSION_UUID])
+  const state = info.ok ? parseExtensionState(info.out) : undefined
+  if (isFlatpak()) Object.assign(base, await flatpakDetails(bundled))
+
+  if (state === 'ACTIVE' || state === 'ENABLED') {
+    if (bundledVersion && installedVersion && bundledVersion !== installedVersion) {
+      return { ...base, state: 'outdated' }
+    }
+    return { ...base, state: 'active' }
+  }
+  if (state === 'ERROR' || state === 'OUT OF DATE') return { ...base, state: 'error', detail: info.out.trim() }
+  if (state) return { ...base, state: 'disabled' }
+
+  if (installedVersion !== undefined) return { ...base, state: 'needs-relogin' }
+  return { ...base, state: 'not-installed' }
+}
+
+/** Host terminal commands that install the Flatpak's copy */
+export function flatpakInstallCommands(hostDir: string): string[] {
+  const quoted = `'${hostDir.replace(/'/g, "'\\''")}'`
+  return [
+    'mkdir -p ~/.local/share/gnome-shell/extensions',
+    `cp -r ${quoted} ~/.local/share/gnome-shell/extensions/`,
+    `gnome-extensions enable ${GNOME_EXTENSION_UUID}`
+  ]
+}
+
+async function flatpakDetails(bundled: string | undefined): Promise<Partial<GnomeExtensionStatus>> {
+  const hostDir = bundled ? toHostPath(bundled) : undefined
+  return hostDir ? { flatpakCommands: flatpakInstallCommands(hostDir) } : {}
+}
+
+export async function installGnomeExtension(): Promise<{ ok: boolean; message: string; status: GnomeExtensionStatus }> {
+  const bundled = bundledExtensionDir()
+  if (!bundled) {
+    return {
+      ok: false,
+      message: 'The installed engine has no gnome-shell-extension folder, update linux-wallpaperengine first',
+      status: await getGnomeExtensionStatus()
+    }
+  }
+  const target = userExtensionDir()
+  const staging = `${target}.new`
+  await fs.promises.rm(staging, { recursive: true, force: true })
+  await fs.promises.mkdir(path.dirname(target), { recursive: true })
+  // the Flatpak shares the host home, gnome-extensions runs on the host
+  await fs.promises.cp(bundled, staging, { recursive: true })
+  const helper = path.join(staging, GNOME_HELPER)
+  if (fs.existsSync(helper)) await fs.promises.chmod(helper, 0o755)
+  await fs.promises.rm(target, { recursive: true, force: true })
+  await fs.promises.rename(staging, target)
+
+  // recorded even if not loaded yet, starts at next login
+  const enabled = await runHost('gnome-extensions', ['enable', GNOME_EXTENSION_UUID])
+  if (!enabled.ok) await addToEnabledExtensions()
+
+  const status = await getGnomeExtensionStatus()
+  const message = status.state === 'active'
+    ? 'The GNOME Shell extension is active'
+    : 'Installed. Log out and back in once, GNOME Shell only loads new extensions at login'
+  return { ok: true, message, status }
+}
+
+/** Parses gsettings' GVariant string array, e.g. @as [] or ['a@b', 'c@d'] */
+export function parseStringArray(value: string): string[] {
+  return [...value.matchAll(/'([^']*)'/g)].map(match => match[1])
+}
+
+async function addToEnabledExtensions(): Promise<void> {
+  const current = await runHost('gsettings', ['get', 'org.gnome.shell', 'enabled-extensions'])
+  if (!current.ok) return
+  const uuids = parseStringArray(current.out)
+  if (uuids.includes(GNOME_EXTENSION_UUID)) return
+  const list = [...uuids, GNOME_EXTENSION_UUID].map(uuid => `'${uuid}'`).join(', ')
+  await runHost('gsettings', ['set', 'org.gnome.shell', 'enabled-extensions', `[${list}]`])
+}

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

@@ -498,7 +498,7 @@ export async function scanLibrary(): Promise<{ imported: number; skipped: number
     }
 
     const existing = wallpapers[entry.name]
-    if (existing?.localPath === localPath && !existing.downloading && existing.previewLocal !== undefined && existing?.contentRating !== undefined && existing?.fileSize !== undefined) {
+    if (existing?.localPath === localPath && !existing.downloading && existing.previewLocal !== undefined && fs.existsSync(existing.previewLocal) && existing?.contentRating !== undefined && existing?.fileSize !== undefined) {
       cacheHits.push(entry.name)
       skipped++
       continue

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

@@ -1926,7 +1926,7 @@ export async function captureLweScreenshot(
       ...options,
       fps: 60,
       volume: 0,
-      engineFlags: { ...options.engineFlags, silent: true, fullscreenPause: 'off', disableMouse: true }
+      engineFlags: { ...options.engineFlags, silent: true, fullscreenPause: 'off', pauseOnFocus: false, disableMouse: true }
     },
     { window: `0x0x${size.width}x${size.height}`, screenshotPath: outPath, delayFrames: 120 }
   )

+ 10 - 0
src/main/utils/flatpak.test.ts

@@ -29,3 +29,13 @@ describe('hostCommand', () => {
     expect(hostShell('wlr-randr 2>/dev/null')).toBe('flatpak-spawn --host sh -c "wlr-randr 2>/dev/null"')
   })
 })
+
+describe('toHostPath', () => {
+  it('maps /app through app-path from /.flatpak-info', async () => {
+    const { hostAppPath, toHostPath } = await load()
+    const appPath = hostAppPath('[Application]\nname=io.x\n\n[Instance]\napp-path=/var/lib/flatpak/app/io.x/x86_64/stable/abc/files\n')
+    expect(appPath).toBe('/var/lib/flatpak/app/io.x/x86_64/stable/abc/files')
+    expect(toHostPath('/app/bin/gnome-shell-extension', appPath)).toBe('/var/lib/flatpak/app/io.x/x86_64/stable/abc/files/bin/gnome-shell-extension')
+    expect(toHostPath('/usr/bin/x', appPath)).toBeUndefined()
+  })
+})

+ 10 - 0
src/main/utils/flatpak.ts

@@ -36,3 +36,13 @@ export function isHostCommandAvailable(cmd: string): boolean {
   hostCommandCache.set(cmd, found)
   return found
 }
+
+/** The sandbox's /app as the host sees it (app-path in /.flatpak-info) */
+export function hostAppPath(info = (() => { try { return fs.readFileSync('/.flatpak-info', 'utf8') } catch { return '' } })()): string | undefined {
+  return info.match(/^app-path=(.+)$/m)?.[1]?.trim() || undefined
+}
+
+export function toHostPath(sandboxPath: string, appPath = hostAppPath()): string | undefined {
+  if (!appPath || !sandboxPath.startsWith('/app/')) return undefined
+  return appPath + sandboxPath.slice('/app'.length)
+}

+ 8 - 0
src/preload/index.ts

@@ -17,6 +17,7 @@ import type {
   DownloadProgressEvent,
   WallpaperEnvironment,
   LweStatus,
+  GnomeExtensionStatus,
   LwePrebuiltTarget,
   LweInstallProgress,
   LinuxDistro,
@@ -397,6 +398,7 @@ const api = {
       linked: number
       removed: number
       unlinked: number
+      previewsFixed: number
       corrupted: string[]
     }> => ipcRenderer.invoke(IpcChannels.BACKUP_SCAN),
     remove: (itemIds: string[]): Promise<{ removed: number; failed: number; keptDirs: string[] }> =>
@@ -410,6 +412,12 @@ const api = {
       ipcRenderer.invoke(IpcChannels.DESKTOP_ICONS_GET_ENABLED)
   },
 
+  gnomeExtension: {
+    status: (): Promise<GnomeExtensionStatus> => ipcRenderer.invoke(IpcChannels.GNOME_EXTENSION_STATUS),
+    install: (): Promise<{ ok: boolean; message: string; status: GnomeExtensionStatus }> =>
+      ipcRenderer.invoke(IpcChannels.GNOME_EXTENSION_INSTALL)
+  },
+
   shell: {
     openInFileManager: (folderPath: string): Promise<{ ok: boolean; error?: string }> =>
       ipcRenderer.invoke(IpcChannels.SHELL_OPEN_IN_FILE_MANAGER, folderPath),

+ 2 - 0
src/renderer/src/App.tsx

@@ -8,6 +8,7 @@ import PlaylistsView from './components/playlist/PlaylistsView'
 import SettingsView from './components/settings/SettingsView'
 import SetupScreen from './components/setup/SetupScreen'
 import StatusBar from './components/layout/StatusBar'
+import GnomeExtensionNotice from './components/layout/GnomeExtensionNotice'
 import { useToast } from './components/common/Toast'
 import { screenLabel } from './utils/screens'
 import { useConfig } from './hooks/queries'
@@ -148,6 +149,7 @@ export default function App() {
   return (
     <ErrorBoundary>
       <div className="flex h-full flex-col bg-app text-gray-100">
+        <GnomeExtensionNotice />
         <div className="flex flex-1 overflow-hidden">
           <Sidebar activeView={activeView} onNavigate={setActiveView} />
           <main className="flex-1 overflow-hidden">

+ 89 - 0
src/renderer/src/components/layout/GnomeExtensionNotice.tsx

@@ -0,0 +1,89 @@
+import { useState } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { Puzzle } from 'lucide-react'
+import type { GnomeExtensionStatus } from '@shared/types'
+import { useToast } from '../common/Toast'
+import CopyField from '../common/CopyField'
+
+const MESSAGES: Record<GnomeExtensionStatus['state'], string> = {
+  'not-needed': '',
+  active: '',
+  outdated: 'A newer version of the GNOME Shell extension is installed, it loads after you log out and back in.',
+  'needs-relogin': 'The GNOME Shell extension is installed. Log out and back in once so GNOME Shell loads it.',
+  disabled: 'The linux-wallpaperengine GNOME Shell extension is turned off, wallpapers cannot start without it.',
+  'not-installed': 'GNOME on Wayland needs the linux-wallpaperengine GNOME Shell extension to show wallpapers.',
+  error: 'The linux-wallpaperengine GNOME Shell extension failed to load.'
+}
+
+export default function GnomeExtensionNotice() {
+  const queryClient = useQueryClient()
+  const { showToast } = useToast()
+  const [busy, setBusy] = useState(false)
+  const { data: status } = useQuery({
+    queryKey: ['gnome-extension'],
+    queryFn: () => window.electronAPI.gnomeExtension.status()
+  })
+
+  if (!status || !status.needed || status.state === 'active') return null
+
+  const canInstall = status.bundled && (status.state === 'not-installed' || status.state === 'disabled'
+    || status.state === 'error')
+  const commands = canInstall ? status.flatpakCommands : undefined
+
+  const recheck = async (): Promise<void> => {
+    queryClient.setQueryData(['gnome-extension'], await window.electronAPI.gnomeExtension.status())
+  }
+
+  const install = async (): Promise<void> => {
+    setBusy(true)
+    try {
+      const result = await window.electronAPI.gnomeExtension.install()
+      showToast(result.message, result.ok ? {} : { warning: true, durationMs: 8000 })
+      queryClient.setQueryData(['gnome-extension'], result.status)
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  const notice = (
+    <div className="flex items-center gap-3 text-sm text-gray-300">
+      <Puzzle size={16} className="shrink-0 text-accent-400" />
+      <span className="flex-1">
+        {MESSAGES[status.state]}
+        {status.state === 'error' && status.detail && <span className="ml-1 text-gray-500">{status.detail}</span>}
+        {!status.bundled && status.state === 'not-installed' && (
+          <span className="ml-1 text-gray-500">The installed engine does not ship it, update linux-wallpaperengine.</span>
+        )}
+      </span>
+      {canInstall && (
+        <button
+          onClick={install}
+          disabled={busy}
+          className="rounded bg-accent-600 px-3 py-1 text-xs font-medium text-white hover:bg-accent-500 disabled:opacity-50"
+        >
+          {busy ? 'Installing...' : status.state === 'not-installed' ? 'Install extension' : 'Reinstall and enable'}
+        </button>
+      )}
+      {commands && (
+        <button onClick={recheck} className="rounded bg-fg/10 px-3 py-1 text-xs hover:bg-fg/20">
+          Check again
+        </button>
+      )}
+    </div>
+  )
+
+  return (
+    <div className="flex flex-col gap-2 border-b border-fg/10 bg-pane px-4 py-2">
+      {notice}
+      {commands && (
+        <div className="flex flex-col gap-1 pl-7 text-xs text-gray-400">
+          <span>
+            Or by hand in a terminal, then log out and back in once so GNOME Shell loads it:
+          </span>
+          {commands.map((command) => <CopyField key={command} text={command} />)}
+          <CopyField text={commands.join(' && ')} label="All at once" />
+        </div>
+      )}
+    </div>
+  )
+}

+ 50 - 28
src/renderer/src/components/library/LibraryView.tsx

@@ -1,4 +1,4 @@
-import { useState, useEffect, useMemo } from 'react'
+import { useState, useEffect, useMemo, useRef } from 'react'
 import { useQuery, useQueryClient } from '@tanstack/react-query'
 import {
   Loader2,
@@ -41,7 +41,7 @@ import {
   migrateResolutionSelection
 } from '../../constants/weFilters'
 import { usePreviewSize, previewGridStyle } from '../../hooks/usePreviewSize'
-import { usePersistentState } from '../../hooks/usePersistentState'
+import { loadPageSize, usePersistentState, useSessionState } from '../../hooks/usePersistentState'
 import { useCardBorders, useCardSteamState } from '../../hooks/useCardBorders'
 import { useDislikedIds, useVotedIds } from '../../hooks/useVotes'
 import { useFavoriteIds } from '../../hooks/useFavorites'
@@ -172,7 +172,7 @@ interface LibraryViewProps {
 export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
   const queryClient = useQueryClient()
   const { showToast } = useToast()
-  const [search, setSearch] = useState('')
+  const [search, setSearch] = useSessionState('we-library-search', '')
   const [sort, setSort] = usePersistentState('we-library-sort', DEFAULT_SORT)
   const [filterState, setFilterState] = usePersistentState('we-library-filters', DEFAULT_STATE, loadFilters)
   const [showFilters, setShowFilters] = usePersistentState('we-library-show-filters', true, (v) => v !== false)
@@ -181,11 +181,13 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
   const [scanning, setScanning] = useState(false)
   const [scanResult, setScanResult] = useState<{ imported: number; skipped: number; removed: number } | null>(null)
 
-  const [page, setPage] = useState(1)
-  const [pageSize, setPageSize] = useState(50)
+  const [page, setPage] = useSessionState('we-library-page', 1)
+  const [pageSize, setPageSize] = usePersistentState('we-library-page-size', 50, loadPageSize)
   const [previewSize, setPreviewSize] = usePreviewSize()
 
-  const [activeFolder, setActiveFolder] = useState<string | null>(null) // null = "All"
+  const [activeFolder, setActiveFolder] = usePersistentState<string | null>('we-library-folder', null, (v) =>
+    typeof v === 'string' ? v : null
+  ) // null = "All"
   const [folderMenu, setFolderMenu] = useState<{ folder: WallpaperFolder; x: number; y: number } | null>(null)
   const [renamingId, setRenamingId] = useState<string | null>(null)
   const [renameValue, setRenameValue] = useState('')
@@ -198,7 +200,11 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
   const cardBorders = useCardBorders()
   const lweInstalled = useLweInstalled()
   const isBackupConfigured = useConfig()?.isBackupConfigured ?? false
-  const { folders, refetchFolders, moveToFolder } = useFolders()
+  const { folders, foldersLoaded, refetchFolders, moveToFolder } = useFolders()
+
+  useEffect(() => {
+    if (foldersLoaded && activeFolder && !folders.some((f) => f.id === activeFolder)) setActiveFolder(null)
+  }, [foldersLoaded, folders, activeFolder, setActiveFolder])
   const applyWallpaper = useApplyWallpaper()
   const subscribe = useSubscribe()
   const unsubscribe = useUnsubscribe()
@@ -339,7 +345,14 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     [allWallpapersForView, safePage, pageSize]
   )
 
-  useEffect(() => { setPage(1) }, [filterState, activeFolder, search, sort, pageSize])
+  // only a real change resets to page 1, not remounting
+  const pageResetKey = JSON.stringify([filterState, activeFolder, search, sort, pageSize])
+  const lastPageResetKey = useRef(pageResetKey)
+  useEffect(() => {
+    if (lastPageResetKey.current === pageResetKey) return
+    lastPageResetKey.current = pageResetKey
+    setPage(1)
+  }, [pageResetKey, setPage])
 
   const wallpaperIds = useMemo(() => wallpapers.map((w) => w.id), [wallpapers])
   const {
@@ -410,6 +423,31 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     })
   }, [showToast])
 
+  // keep the last text between items so the progress line doesn't flicker
+  const backupTaskRunning = runningTasks.has('backup-selection') || runningTasks.has('backup-unavailable')
+  const progressItems = Array.from(backupProgress.values())
+  const liveProgress =
+    progressItems.length > 0
+      ? `${progressVerb(progressItems)} ${progressItems.length} wallpaper${progressItems.length === 1 ? '' : 's'}` +
+        `${progressItems.some((p) => p.status === 'verifying') ? ' (verifying copies)' : ''}... ` +
+        `${Math.round(progressItems.reduce((sum, p) => sum + p.percentage, 0) / progressItems.length)}% avg`
+      : null
+  const [lingeringProgress, setLingeringProgress] = useState<string | null>(null)
+
+  useEffect(() => {
+    if (liveProgress) {
+      setLingeringProgress(liveProgress)
+      return
+    }
+    if (backupTaskRunning) return
+    const timer = setTimeout(() => setLingeringProgress(null), 1500)
+    return () => clearTimeout(timer)
+  }, [liveProgress, backupTaskRunning])
+
+  const statusLine =
+    liveProgress ??
+    (backupTaskRunning ? (lingeringProgress ?? 'Backing up...') : (backupStatus ?? lingeringProgress))
+
   // backup and availability checks report into the status line and can change any wallpaper's flags
   async function runTask(task: BackgroundTask, work: () => Promise<string>) {
     setRunningTasks((prev) => new Set(prev).add(task))
@@ -442,7 +480,7 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
     void runTask('scan-backups', async () => {
       const result = await window.electronAPI.backup.scan()
       const dropped = result.removed + result.unlinked
-      return `Backup scan: ${result.imported} imported, ${result.linked} linked${dropped > 0 ? `, ${dropped} broken removed` : ''}${result.corrupted.length > 0 ? `, ${result.corrupted.length} corrupted folder${result.corrupted.length === 1 ? '' : 's'} skipped (${result.corrupted.join(', ')})` : ''}.`
+      return `Backup scan: ${result.imported} imported, ${result.linked} linked${dropped > 0 ? `, ${dropped} broken removed` : ''}${result.previewsFixed > 0 ? `, ${result.previewsFixed} thumbnail${result.previewsFixed === 1 ? '' : 's'} fixed` : ''}${result.corrupted.length > 0 ? `, ${result.corrupted.length} corrupted folder${result.corrupted.length === 1 ? '' : 's'} skipped (${result.corrupted.join(', ')})` : ''}.`
     })
   }
 
@@ -673,25 +711,9 @@ export default function LibraryView({ onBrowseCreator }: LibraryViewProps) {
         </div>
       )}
 
-      {backupProgress.size > 0 && (
-        <div className="border-b border-fg/5 px-4 py-2 text-xs text-gray-400">
-          {progressVerb(Array.from(backupProgress.values()))} {backupProgress.size} wallpaper
-          {backupProgress.size === 1 ? '' : 's'}
-          {Array.from(backupProgress.values()).some((p) => p.status === 'verifying')
-            ? ' (verifying copies)'
-            : ''}
-          ...{' '}
-          {Math.round(
-            Array.from(backupProgress.values()).reduce((sum, p) => sum + p.percentage, 0) /
-              backupProgress.size
-          )}
-          % avg
-        </div>
-      )}
-
-      {backupStatus && (
-        <div className="border-b border-fg/5 px-4 py-2 text-xs text-gray-400">
-          {backupStatus}
+      {statusLine && (
+        <div className="truncate border-b border-fg/5 px-4 py-2 text-xs text-gray-400" title={statusLine}>
+          {statusLine}
         </div>
       )}
 

+ 24 - 8
src/renderer/src/components/workshop/WorkshopBrowser.tsx

@@ -1,4 +1,4 @@
-import { useState, useEffect, useMemo } from 'react'
+import { useState, useEffect, useMemo, useRef } from 'react'
 import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
 import { X, Loader2, User, ExternalLink, Play, Download, EyeOff, Eye } from 'lucide-react'
 import WorkshopCard from './WorkshopCard'
@@ -34,7 +34,7 @@ import {
   migrateResolutionSelection
 } from '../../constants/weFilters'
 import { usePreviewSize, previewGridStyle } from '../../hooks/usePreviewSize'
-import { usePersistentState } from '../../hooks/usePersistentState'
+import { loadPageSize, usePersistentState, useSessionState } from '../../hooks/usePersistentState'
 import { useCardBorders, useCardSteamState } from '../../hooks/useCardBorders'
 import { useBatchVote, useDislikedIds, useVotedIds } from '../../hooks/useVotes'
 import { useBatchFavorite, useFavoriteIds } from '../../hooks/useFavorites'
@@ -48,6 +48,13 @@ import { matchesSearchTerms, parseSearchQuery } from '../../utils/searchQuery'
 import { formatFileSize } from '../../utils/format'
 
 const STORAGE_KEY = 'we-workshop-filters'
+const QUERY_TYPES: WorkshopQueryType[] = [
+  'RankedByVote',
+  'RankedByPublicationDate',
+  'RankedByTrend',
+  'RankedByTotalUniqueSubscriptions',
+  'RankedByLastUpdatedDate'
+]
 const STORAGE_VERSION = 2
 
 const ALL_TAGS = {
@@ -133,18 +140,22 @@ export default function WorkshopBrowser({
   const queryClient = useQueryClient()
   const { entries: subscribeEntries, enqueue: enqueueSubscribe, clear: clearSubscribeEntries } =
     useSubscriptionQueue(() => queryClient.invalidateQueries({ queryKey: ['library'] }))
-  const [searchText, setSearchText] = useState('')
+  const [searchText, setSearchText] = useSessionState(`we-workshop-search:${creatorFilter ?? ''}`, '')
   const searchQuery = useMemo(() => parseSearchQuery(searchText), [searchText])
   const steamSearchText = searchQuery.steamText
-  const [queryType, setQueryType] = useState<WorkshopQueryType>('RankedByPublicationDate')
+  const [queryType, setQueryType] = usePersistentState<WorkshopQueryType>(
+    'we-workshop-sort',
+    'RankedByPublicationDate',
+    (v) => (typeof v === 'string' && QUERY_TYPES.includes(v as WorkshopQueryType) ? (v as WorkshopQueryType) : 'RankedByPublicationDate')
+  )
   const [showFilters, setShowFilters] = usePersistentState('we-workshop-show-filters', true, (v) => v !== false)
   const [filters, setFilters] = usePersistentState(STORAGE_KEY, DEFAULT_STATE, loadFilters)
   const [ctxMenu, setCtxMenu] = useState<CtxMenu | null>(null)
-  const [page, setPage] = useState(1)
-  const [pageSize, setPageSize] = useState(50)
+  const [page, setPage] = useSessionState(`we-workshop-page:${creatorFilter ?? ''}`, 1)
+  const [pageSize, setPageSize] = usePersistentState('we-workshop-page-size', 50, loadPageSize)
   const [previewSize, setPreviewSize] = usePreviewSize()
   const [detailId, setDetailId] = useState<string | null>(null)
-  const [showIgnored, setShowIgnored] = useState(false)
+  const [showIgnored, setShowIgnored] = usePersistentState('we-workshop-show-ignored', false, (v) => v === true)
 
   const votedSet = useVotedIds()
   const dislikedSet = useDislikedIds()
@@ -158,9 +169,14 @@ export default function WorkshopBrowser({
   const unsubscribe = useUnsubscribe()
   const { moveToFolder, removeFromFolders, menuState } = useFolders()
 
+  // only a real change resets to page 1, not remounting
+  const pageResetKey = JSON.stringify([searchText, queryType, filters, pageSize, creatorFilter])
+  const lastPageResetKey = useRef(pageResetKey)
   useEffect(() => {
+    if (lastPageResetKey.current === pageResetKey) return
+    lastPageResetKey.current = pageResetKey
     setPage(1)
-  }, [searchText, queryType, filters, pageSize, creatorFilter])
+  }, [pageResetKey, setPage])
 
   function setFilter<K extends keyof WorkshopFilterState>(key: K, value: WorkshopFilterState[K]) {
     setFilters((prev) => ({ ...prev, [key]: value }))

+ 5 - 0
src/renderer/src/constants/engineFlags.ts

@@ -8,6 +8,11 @@ export const BOOLEAN_FLAGS: { key: BooleanFlag; label: string; hint: string }[]
   { key: 'disableParticles', label: 'Disable particles', hint: 'Skips particle systems (fog, sparks, rain), usually the biggest GPU cost' },
   { key: 'disableAnimations', label: 'Freeze animations', hint: 'Stops scene time: scripts, particles, effects and puppets' },
   { key: 'disableMouse', label: 'Ignore the mouse', hint: 'No parallax or cursor effects' },
+  {
+    key: 'pauseOnFocus',
+    label: 'Pause while another app is focused',
+    hint: 'Like Wallpaper Engine\'s "Other application focused: Pause". On GNOME and KDE only the screen with the focused app pauses, elsewhere every screen'
+  },
   { key: 'noAudioProcessing', label: 'No audio visualizer', hint: 'Stops capturing system audio for audio-reactive wallpapers' },
   { key: 'automute', label: 'Mute when other apps play sound', hint: '' },
   { key: 'silent', label: 'Always muted', hint: '' },

+ 2 - 2
src/renderer/src/hooks/queries.ts

@@ -58,7 +58,7 @@ export interface FolderMenuState {
 
 export function useFolders() {
   const queryClient = useQueryClient()
-  const { data: folders = [] } = useQuery({
+  const { data: folders = [], isSuccess: foldersLoaded } = useQuery({
     queryKey: ['folders'],
     queryFn: () => window.electronAPI.folders.getAll()
   })
@@ -97,5 +97,5 @@ export function useFolders() {
     }
   }
 
-  return { folders, folderOfItem, refetchFolders, moveToFolder, removeFromFolders, menuState }
+  return { folders, foldersLoaded, folderOfItem, refetchFolders, moveToFolder, removeFromFolders, menuState }
 }

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

@@ -1,5 +1,7 @@
 import { useEffect, useState, type Dispatch, type SetStateAction } from 'react'
 
+const sessionValues = new Map<string, unknown>()
+
 // useState backed by localStorage. load turns the stored JSON back into a value, returning the
 // fallback for anything it doesn't accept (wrong version, old shape).
 export function usePersistentState<T>(
@@ -26,3 +28,20 @@ export function usePersistentState<T>(
 
   return [value, setValue]
 }
+
+// useState that survives the view unmounting (switching tabs) but not an app restart
+export function useSessionState<T>(key: string, initial: T): [T, Dispatch<SetStateAction<T>>] {
+  const [value, setValue] = useState<T>(() => (sessionValues.has(key) ? (sessionValues.get(key) as T) : initial))
+
+  useEffect(() => {
+    sessionValues.set(key, value)
+  }, [key, value])
+
+  return [value, setValue]
+}
+
+const PAGE_SIZES = [50, 100, 200]
+
+export function loadPageSize(stored: unknown): number {
+  return typeof stored === 'number' && PAGE_SIZES.includes(stored) ? stored : 50
+}

+ 2 - 0
src/shared/engineFlags.test.ts

@@ -36,6 +36,8 @@ describe('engineFlagArgs', () => {
     expect(engineFlagArgs({ hwdec: 'auto' })).toEqual([])
     expect(engineFlagArgs({ kdeBackgroundLayer: true })).toEqual(['--layer', 'background'])
     expect(engineFlagArgs({ kdeBackgroundLayer: false })).toEqual([])
+    expect(engineFlagArgs({ pauseOnFocus: true, fullscreenPause: 'off' })).toEqual(['--no-fullscreen-pause', '--pause-on-focus'])
+    expect(engineFlagArgs({ pauseOnFocus: false })).toEqual([])
   })
 
   it('leaves disableAnimations to the caller, it needs its own capability probe', () => {

+ 1 - 0
src/shared/engineFlags.ts

@@ -58,6 +58,7 @@ export function engineFlagArgs(flags: EngineFlags): string[] {
   if (flags.noAudioProcessing) args.push('--no-audio-processing')
   if (flags.fullscreenPause === 'off') args.push('--no-fullscreen-pause')
   if (flags.fullscreenPause === 'active-only') args.push('--fullscreen-pause-only-active')
+  if (flags.pauseOnFocus) args.push('--pause-on-focus')
   if (flags.automute) args.push('--automute')
   if (flags.silent) args.push('--silent')
   if (flags.hdr) args.push('--hdr')

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

@@ -147,6 +147,8 @@ export const IpcChannels = {
 
   DESKTOP_ICONS_SET_ENABLED: 'desktop-icons:set-enabled',
   DESKTOP_ICONS_GET_ENABLED: 'desktop-icons:get-enabled',
+  GNOME_EXTENSION_STATUS: 'gnome-extension:status',
+  GNOME_EXTENSION_INSTALL: 'gnome-extension:install',
 
   // Events pushed from main to renderer
   EVENT_DOWNLOAD_PROGRESS: 'event:download-progress',

+ 14 - 0
src/shared/types.ts

@@ -171,6 +171,8 @@ export interface EngineFlags {
   disableAnimations?: boolean
   noAudioProcessing?: boolean
   fullscreenPause?: FullscreenPauseMode
+  /** --pause-on-focus, WE's "Other application focused: Pause" */
+  pauseOnFocus?: boolean
   automute?: boolean
   silent?: boolean
   hdr?: boolean
@@ -405,6 +407,18 @@ export interface WallpaperEnvironment {
   linuxWallpaperEngine: LweStatus
 }
 
+/** The engine's GNOME Shell extension (GNOME Wayland only) */
+export interface GnomeExtensionStatus {
+  needed: boolean
+  state: 'not-needed' | 'active' | 'outdated' | 'needs-relogin' | 'disabled' | 'not-installed' | 'error'
+  bundled?: boolean
+  bundledVersion?: string
+  installedVersion?: string
+  detail?: string
+  /** Flatpak: manual host commands if the button fails */
+  flatpakCommands?: string[]
+}
+
 export interface LweStatus {
   installed: boolean
   path?: string