wallpaper.service.ts 9.9 KB

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