wallpaper.service.ts 7.4 KB

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