wallpaper.service.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 } from '../utils/platform'
  7. import { hostCommand, isHostCommandAvailable } from '../utils/flatpak'
  8. import type { ScreenTarget, WallpaperBackend, WallpaperEnvironment, WallpaperMeta } from '@shared/types'
  9. import { getLweStatus, launchLweAsync, type LweLaunchOptions } from './lwe.service'
  10. import { ensureDependencyInstalled } from './dependency.service'
  11. import {
  12. getDefaultFps,
  13. getGlobalEngineFlags,
  14. getRecommendedFpsEnabled,
  15. getRecommendedWebFpsEnabled
  16. } from './config.service'
  17. import { findWallpaperVideoFile, getVideoFps } from '../utils/video'
  18. import { RECOMMENDED_WEB_FPS } from '@shared/constants'
  19. import { resolveEngineFlags } from '@shared/engineFlags'
  20. import { needsFreshLaunch } from '@shared/compat'
  21. import { videoSegmentsOf } from '@shared/videoTrim'
  22. const execFileAsync = promisify(execFile)
  23. let envCache: WallpaperEnvironment | null = null
  24. export function invalidateEnvCache(): void {
  25. envCache = null
  26. }
  27. export function detectEnvironment(): WallpaperEnvironment {
  28. if (envCache) return envCache
  29. const platform = os.platform()
  30. const displayServer = detectDisplayServer()
  31. const desktopEnv = detectDesktopEnv()
  32. const available: WallpaperBackend[] = []
  33. if (platform === 'win32') {
  34. available.push('windows')
  35. } else if (platform === 'darwin') {
  36. available.push('macos')
  37. } else {
  38. if (isHostCommandAvailable('swww')) available.push('swww')
  39. if (isHostCommandAvailable('swaybg')) available.push('swaybg')
  40. if (isHostCommandAvailable('feh')) available.push('feh')
  41. if (isHostCommandAvailable('xwallpaper')) available.push('xwallpaper')
  42. if (desktopEnv === 'gnome') available.push('gsettings')
  43. if (desktopEnv === 'kde' && isHostCommandAvailable('qdbus')) available.push('qdbus')
  44. }
  45. let recommended: WallpaperBackend = 'auto'
  46. if (platform === 'win32') recommended = 'windows'
  47. else if (platform === 'darwin') recommended = 'macos'
  48. else if (desktopEnv === 'gnome') recommended = 'gsettings'
  49. else if (desktopEnv === 'kde') recommended = 'qdbus'
  50. else if (displayServer === 'wayland' && available.includes('swww')) recommended = 'swww'
  51. else if (available.includes('feh')) recommended = 'feh'
  52. envCache = {
  53. displayServer,
  54. desktopEnv,
  55. availableBackends: available,
  56. recommendedBackend: recommended,
  57. linuxWallpaperEngine: getLweStatus()
  58. }
  59. return envCache
  60. }
  61. export async function applyWallpaper(imagePath: string, backend?: WallpaperBackend): Promise<void> {
  62. const platform = os.platform()
  63. if (platform === 'linux') {
  64. await applyLinux(imagePath, backend)
  65. } else if (platform === 'darwin') {
  66. await applyMacOS(imagePath)
  67. } else if (platform === 'win32') {
  68. await applyWindows(imagePath)
  69. } else {
  70. throw new Error(`Unsupported platform: ${platform}`)
  71. }
  72. }
  73. async function applyLinux(imagePath: string, preferredBackend?: WallpaperBackend): Promise<void> {
  74. if (preferredBackend && preferredBackend !== 'auto') {
  75. await applyWithBackend(preferredBackend, imagePath)
  76. return
  77. }
  78. const backend = pickLinuxBackend()
  79. if (!backend) {
  80. throw new Error(
  81. 'No supported wallpaper backend found. Please install swww (Wayland) or feh (X11).'
  82. )
  83. }
  84. await applyWithBackend(backend, imagePath)
  85. }
  86. function pickLinuxBackend(): WallpaperBackend | null {
  87. const de = detectDesktopEnv()
  88. if (de === 'gnome') return 'gsettings'
  89. if (de === 'kde' && isHostCommandAvailable('qdbus')) return 'qdbus'
  90. if (detectDisplayServer() === 'wayland') {
  91. if (isHostCommandAvailable('swww')) return 'swww'
  92. if (isHostCommandAvailable('swaybg')) return 'swaybg'
  93. }
  94. if (isHostCommandAvailable('feh')) return 'feh'
  95. if (isHostCommandAvailable('xwallpaper')) return 'xwallpaper'
  96. return null
  97. }
  98. async function applyWithBackend(backend: WallpaperBackend, imagePath: string): Promise<void> {
  99. switch (backend) {
  100. case 'swww':
  101. await execFileAsync(...hostCommand('swww', ['img', imagePath, '--transition-type', 'fade']))
  102. break
  103. case 'swaybg':
  104. await execFileAsync(...hostCommand('swaybg', ['-i', imagePath, '-m', 'fill']))
  105. break
  106. case 'feh':
  107. await execFileAsync(...hostCommand('feh', ['--bg-fill', imagePath]))
  108. break
  109. case 'xwallpaper':
  110. await execFileAsync(...hostCommand('xwallpaper', ['--zoom', imagePath]))
  111. break
  112. case 'gsettings':
  113. await execFileAsync(...hostCommand('gsettings', [
  114. 'set',
  115. 'org.gnome.desktop.background',
  116. 'picture-uri',
  117. `file://${imagePath}`
  118. ]))
  119. break
  120. case 'qdbus': {
  121. const script = `
  122. var allDesktops = desktops();
  123. for (var i = 0; i < allDesktops.length; i++) {
  124. var d = allDesktops[i];
  125. d.wallpaperPlugin = 'org.kde.image';
  126. d.currentConfigGroup = ['Wallpaper', 'org.kde.image', 'General'];
  127. d.writeConfig('Image', 'file://${imagePath}');
  128. }
  129. `
  130. await execFileAsync(...hostCommand('qdbus', [
  131. 'org.kde.plasmashell',
  132. '/PlasmaShell',
  133. 'org.kde.PlasmaShell.evaluateScript',
  134. script
  135. ]))
  136. break
  137. }
  138. case 'windows':
  139. await applyWindows(imagePath)
  140. break
  141. case 'macos':
  142. await applyMacOS(imagePath)
  143. break
  144. default:
  145. throw new Error(`Unknown backend: ${backend}`)
  146. }
  147. }
  148. async function applyMacOS(imagePath: string): Promise<void> {
  149. const script = `tell application "Finder" to set desktop picture to POSIX file "${imagePath}"`
  150. await execFileAsync('osascript', ['-e', script])
  151. }
  152. async function applyWindows(imagePath: string): Promise<void> {
  153. // Pass path via environment variable to avoid injection risk from special characters
  154. const script = `
  155. Add-Type -TypeDefinition @'
  156. using System.Runtime.InteropServices;
  157. public class Wallpaper {
  158. [DllImport("user32.dll", CharSet=CharSet.Auto)]
  159. public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
  160. }
  161. '@
  162. [Wallpaper]::SystemParametersInfo(20, 0, $env:WE_WALLPAPER_PATH, 3)
  163. `
  164. await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
  165. env: { ...process.env, WE_WALLPAPER_PATH: imagePath }
  166. })
  167. }
  168. function findWallpaperImage(dirPath: string): string {
  169. if (!fs.existsSync(dirPath)) {
  170. throw new Error(`Directory not found: ${dirPath}`)
  171. }
  172. if (!fs.statSync(dirPath).isDirectory()) {
  173. return dirPath
  174. }
  175. const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
  176. const files = fs.readdirSync(dirPath)
  177. const preview = files.find((f) => f.toLowerCase().startsWith('preview'))
  178. if (preview && imageExtensions.includes(path.extname(preview).toLowerCase())) {
  179. return path.join(dirPath, preview)
  180. }
  181. const image = files.find((f) => imageExtensions.includes(path.extname(f).toLowerCase()))
  182. if (image) return path.join(dirPath, image)
  183. throw new Error(`No image found in ${dirPath}`)
  184. }
  185. export async function lweOptionsFor(
  186. wallpaper: WallpaperMeta,
  187. options: { fps?: number; volume?: number } = {}
  188. ): Promise<LweLaunchOptions> {
  189. let fps = options.fps ?? wallpaper.fpsOverride
  190. if (fps === undefined && wallpaper.type === 'video' && wallpaper.localPath && getRecommendedFpsEnabled()) {
  191. const videoFile = findWallpaperVideoFile(wallpaper.localPath, wallpaper.file)
  192. if (videoFile) fps = await getVideoFps(videoFile)
  193. }
  194. if (fps === undefined && wallpaper.type === 'web' && getRecommendedWebFpsEnabled()) {
  195. fps = RECOMMENDED_WEB_FPS
  196. }
  197. fps = fps ?? getDefaultFps() ?? undefined
  198. return {
  199. engineFlags: resolveEngineFlags(getGlobalEngineFlags(), wallpaper.engineFlags),
  200. fps,
  201. volume: options.volume ?? wallpaper.volumeOverride,
  202. disabledObjects: wallpaper.disabledObjects,
  203. enabledObjects: wallpaper.enabledObjects,
  204. disabledEffects: wallpaper.disabledEffects,
  205. enabledEffects: wallpaper.enabledEffects,
  206. propertyOverrides: wallpaper.propertyOverrides,
  207. // always sent: xray state lives in the running engine, a hotswap must clear it
  208. xrayMode: wallpaper.xrayDisabled ? 'disabled' : wallpaper.xrayFullReveal ? 'full' : 'normal',
  209. scalingMode: wallpaper.scalingMode,
  210. zoom: wallpaper.zoom,
  211. offsetX: wallpaper.offsetX,
  212. offsetY: wallpaper.offsetY,
  213. disableParallax: wallpaper.disableParallax ?? false,
  214. expandCanvas: wallpaper.expandCanvas ?? false,
  215. cornerColor: wallpaper.cornerColor,
  216. imageAdjustments: wallpaper.imageAdjustments,
  217. speed: wallpaper.playbackSpeed,
  218. videoSegments: wallpaper.type === 'video' ? videoSegmentsOf(wallpaper) : undefined,
  219. audioSensitivity: wallpaper.audioSensitivity,
  220. soundVolume: wallpaper.soundVolume,
  221. customArgs: wallpaper.customArgs
  222. }
  223. }
  224. export function isAnimatedWallpaper(wallpaper: WallpaperMeta): boolean {
  225. return wallpaper.type === 'scene' || wallpaper.type === 'web' || wallpaper.type === 'video'
  226. }
  227. /**
  228. * Apply a library wallpaper: renders animated/scene/web/video wallpapers via
  229. * linux-wallpaperengine when available, otherwise falls back to a static image.
  230. * Shared by the manual "apply" IPC handler and the playlist playback engine.
  231. */
  232. export async function applyWallpaperMeta(
  233. wallpaper: WallpaperMeta,
  234. options: {
  235. fps?: number
  236. volume?: number
  237. backend?: WallpaperBackend
  238. dependencyPrompt?: 'always' | 'once'
  239. screen?: ScreenTarget
  240. forceFresh?: boolean
  241. } = {}
  242. ): Promise<string> {
  243. if (!wallpaper.localPath) throw new Error(`Wallpaper ${wallpaper.id} has no local path`)
  244. await ensureDependencyInstalled(wallpaper, options.dependencyPrompt)
  245. if (isAnimatedWallpaper(wallpaper) && os.platform() === 'linux' && getLweStatus().installed) {
  246. await launchLweAsync(wallpaper.localPath, {
  247. ...(await lweOptionsFor(wallpaper, options)),
  248. screen: options.screen,
  249. forceFresh: options.forceFresh || needsFreshLaunch(wallpaper.compat)
  250. })
  251. return wallpaper.localPath
  252. }
  253. // Static fallback: set the preview image as a plain wallpaper
  254. const appliedPath = findWallpaperImage(wallpaper.localPath)
  255. await applyWallpaper(appliedPath, options.backend)
  256. return appliedPath
  257. }