wallpaper.service.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { execFile } from 'child_process'
  2. import { promisify } from 'util'
  3. import * as os from 'os'
  4. import * as fs from 'fs'
  5. import * as path from 'path'
  6. import { detectDisplayServer, detectDesktopEnv, isCommandAvailable } from '../utils/platform'
  7. import type { WallpaperBackend, WallpaperEnvironment, WallpaperMeta } from '@shared/types'
  8. import { getLweStatus, launchLweAsync } from './lwe.service'
  9. import { getDefaultFps, getRecommendedFpsEnabled } from './config.service'
  10. import { findWallpaperVideoFile, getVideoFps } from '../utils/video'
  11. const execFileAsync = promisify(execFile)
  12. let envCache: WallpaperEnvironment | null = null
  13. export function invalidateEnvCache(): void {
  14. envCache = null
  15. }
  16. export function detectEnvironment(): WallpaperEnvironment {
  17. if (envCache) return envCache
  18. const platform = os.platform()
  19. const displayServer = detectDisplayServer()
  20. const desktopEnv = detectDesktopEnv()
  21. const available: WallpaperBackend[] = []
  22. if (platform === 'win32') {
  23. available.push('windows')
  24. } else if (platform === 'darwin') {
  25. available.push('macos')
  26. } else {
  27. if (isCommandAvailable('swww')) available.push('swww')
  28. if (isCommandAvailable('swaybg')) available.push('swaybg')
  29. if (isCommandAvailable('feh')) available.push('feh')
  30. if (isCommandAvailable('xwallpaper')) available.push('xwallpaper')
  31. if (desktopEnv === 'gnome') available.push('gsettings')
  32. if (desktopEnv === 'kde' && isCommandAvailable('qdbus')) available.push('qdbus')
  33. }
  34. let recommended: WallpaperBackend = 'auto'
  35. if (platform === 'win32') recommended = 'windows'
  36. else if (platform === 'darwin') recommended = 'macos'
  37. else if (desktopEnv === 'gnome') recommended = 'gsettings'
  38. else if (desktopEnv === 'kde') recommended = 'qdbus'
  39. else if (displayServer === 'wayland' && available.includes('swww')) recommended = 'swww'
  40. else if (available.includes('feh')) recommended = 'feh'
  41. envCache = {
  42. displayServer,
  43. desktopEnv,
  44. availableBackends: available,
  45. recommendedBackend: recommended,
  46. linuxWallpaperEngine: getLweStatus()
  47. }
  48. return envCache
  49. }
  50. export async function applyWallpaper(imagePath: string, backend?: WallpaperBackend): Promise<void> {
  51. const platform = os.platform()
  52. if (platform === 'linux') {
  53. await applyLinux(imagePath, backend)
  54. } else if (platform === 'darwin') {
  55. await applyMacOS(imagePath)
  56. } else if (platform === 'win32') {
  57. await applyWindows(imagePath)
  58. } else {
  59. throw new Error(`Unsupported platform: ${platform}`)
  60. }
  61. }
  62. async function applyLinux(imagePath: string, preferredBackend?: WallpaperBackend): Promise<void> {
  63. if (preferredBackend && preferredBackend !== 'auto') {
  64. await applyWithBackend(preferredBackend, imagePath)
  65. return
  66. }
  67. const backend = pickLinuxBackend()
  68. if (!backend) {
  69. throw new Error(
  70. 'No supported wallpaper backend found. Please install swww (Wayland) or feh (X11).'
  71. )
  72. }
  73. await applyWithBackend(backend, imagePath)
  74. }
  75. function pickLinuxBackend(): WallpaperBackend | null {
  76. const de = detectDesktopEnv()
  77. if (de === 'gnome') return 'gsettings'
  78. if (de === 'kde' && isCommandAvailable('qdbus')) return 'qdbus'
  79. if (detectDisplayServer() === 'wayland') {
  80. if (isCommandAvailable('swww')) return 'swww'
  81. if (isCommandAvailable('swaybg')) return 'swaybg'
  82. }
  83. if (isCommandAvailable('feh')) return 'feh'
  84. if (isCommandAvailable('xwallpaper')) return 'xwallpaper'
  85. return null
  86. }
  87. async function applyWithBackend(backend: WallpaperBackend, imagePath: string): Promise<void> {
  88. switch (backend) {
  89. case 'swww':
  90. await execFileAsync('swww', ['img', imagePath, '--transition-type', 'fade'])
  91. break
  92. case 'swaybg':
  93. await execFileAsync('swaybg', ['-i', imagePath, '-m', 'fill'])
  94. break
  95. case 'feh':
  96. await execFileAsync('feh', ['--bg-fill', imagePath])
  97. break
  98. case 'xwallpaper':
  99. await execFileAsync('xwallpaper', ['--zoom', imagePath])
  100. break
  101. case 'gsettings':
  102. await execFileAsync('gsettings', [
  103. 'set',
  104. 'org.gnome.desktop.background',
  105. 'picture-uri',
  106. `file://${imagePath}`
  107. ])
  108. break
  109. case 'qdbus': {
  110. const script = `
  111. var allDesktops = desktops();
  112. for (var i = 0; i < allDesktops.length; i++) {
  113. var d = allDesktops[i];
  114. d.wallpaperPlugin = 'org.kde.image';
  115. d.currentConfigGroup = ['Wallpaper', 'org.kde.image', 'General'];
  116. d.writeConfig('Image', 'file://${imagePath}');
  117. }
  118. `
  119. await execFileAsync('qdbus', [
  120. 'org.kde.plasmashell',
  121. '/PlasmaShell',
  122. 'org.kde.PlasmaShell.evaluateScript',
  123. script
  124. ])
  125. break
  126. }
  127. case 'windows':
  128. await applyWindows(imagePath)
  129. break
  130. case 'macos':
  131. await applyMacOS(imagePath)
  132. break
  133. default:
  134. throw new Error(`Unknown backend: ${backend}`)
  135. }
  136. }
  137. async function applyMacOS(imagePath: string): Promise<void> {
  138. const script = `tell application "Finder" to set desktop picture to POSIX file "${imagePath}"`
  139. await execFileAsync('osascript', ['-e', script])
  140. }
  141. async function applyWindows(imagePath: string): Promise<void> {
  142. // Pass path via environment variable to avoid injection risk from special characters
  143. const script = `
  144. Add-Type -TypeDefinition @'
  145. using System.Runtime.InteropServices;
  146. public class Wallpaper {
  147. [DllImport("user32.dll", CharSet=CharSet.Auto)]
  148. public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
  149. }
  150. '@
  151. [Wallpaper]::SystemParametersInfo(20, 0, $env:WE_WALLPAPER_PATH, 3)
  152. `
  153. await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
  154. env: { ...process.env, WE_WALLPAPER_PATH: imagePath }
  155. })
  156. }
  157. function findWallpaperImage(dirPath: string): string {
  158. if (!fs.existsSync(dirPath)) {
  159. throw new Error(`Directory not found: ${dirPath}`)
  160. }
  161. if (!fs.statSync(dirPath).isDirectory()) {
  162. return dirPath
  163. }
  164. const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
  165. const files = fs.readdirSync(dirPath)
  166. const preview = files.find((f) => f.toLowerCase().startsWith('preview'))
  167. if (preview && imageExtensions.includes(path.extname(preview).toLowerCase())) {
  168. return path.join(dirPath, preview)
  169. }
  170. const image = files.find((f) => imageExtensions.includes(path.extname(f).toLowerCase()))
  171. if (image) return path.join(dirPath, image)
  172. throw new Error(`No image found in ${dirPath}`)
  173. }
  174. /**
  175. * Apply a library wallpaper: renders animated/scene/web/video wallpapers via
  176. * linux-wallpaperengine when available, otherwise falls back to a static image.
  177. * Shared by the manual "apply" IPC handler and the playlist playback engine.
  178. */
  179. export async function applyWallpaperMeta(
  180. wallpaper: WallpaperMeta,
  181. options: { fps?: number; volume?: number; backend?: WallpaperBackend } = {}
  182. ): Promise<string> {
  183. if (!wallpaper.localPath) throw new Error(`Wallpaper ${wallpaper.id} has no local path`)
  184. const isAnimated = wallpaper.type === 'scene' || wallpaper.type === 'web' || wallpaper.type === 'video'
  185. const lwe = getLweStatus()
  186. if (isAnimated && os.platform() === 'linux' && lwe.installed) {
  187. let fps = options.fps ?? wallpaper.fpsOverride
  188. if (fps === undefined && wallpaper.type === 'video' && getRecommendedFpsEnabled()) {
  189. const videoFile = findWallpaperVideoFile(wallpaper.localPath, wallpaper.file)
  190. if (videoFile) fps = await getVideoFps(videoFile)
  191. }
  192. fps = fps ?? getDefaultFps() ?? undefined
  193. const volume = options.volume ?? wallpaper.volumeOverride
  194. await launchLweAsync(wallpaper.localPath, {
  195. fps,
  196. volume,
  197. disabledObjects: wallpaper.disabledObjects,
  198. enabledObjects: wallpaper.enabledObjects,
  199. propertyOverrides: wallpaper.propertyOverrides,
  200. // Explicit even when off: xray state lives on the running LWE process, not per-wallpaper,
  201. // so a hot-reload into a wallpaper with xray off must actively clear a previous wallpaper's "on".
  202. xrayFullReveal: wallpaper.xrayFullReveal ?? false
  203. })
  204. return wallpaper.localPath
  205. }
  206. // Static fallback: set the preview image as a plain wallpaper
  207. const appliedPath = findWallpaperImage(wallpaper.localPath)
  208. await applyWallpaper(appliedPath, options.backend)
  209. return appliedPath
  210. }