static-wallpaper.service.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
  2. import { setTimeout as sleep } from 'timers/promises'
  3. import { promisify } from 'util'
  4. import { hostCommand, isHostCommandAvailable } from '../utils/flatpak'
  5. const execFileAsync = promisify(execFile)
  6. export interface CommandResult {
  7. ok: boolean
  8. output: string
  9. }
  10. export type CommandRunner = (cmd: string, args: string[]) => Promise<CommandResult>
  11. export type DaemonStarter = (cmd: string, args: string[]) => ChildProcess | void
  12. /** never throws */
  13. export const runHostCommand: CommandRunner = async (cmd, args) => {
  14. try {
  15. const { stdout, stderr } = await execFileAsync(...hostCommand(cmd, args), { timeout: 10000 })
  16. return { ok: true, output: `${stdout}${stderr}`.trim() }
  17. } catch (error) {
  18. const failed = error as { stdout?: string; stderr?: string; message: string }
  19. return { ok: false, output: `${failed.stdout ?? ''}${failed.stderr ?? ''}`.trim() || failed.message }
  20. }
  21. }
  22. export const startHostDaemon: DaemonStarter = (cmd, args) => {
  23. const [file, fileArgs] = hostCommand(cmd, args)
  24. const child = spawn(file, fileArgs, { detached: true, stdio: 'ignore' })
  25. child.on('error', () => {})
  26. child.unref()
  27. return child
  28. }
  29. /** swww was renamed to awww, distributions ship either */
  30. export function swwwCommand(has: (cmd: string) => boolean = isHostCommandAvailable): 'awww' | 'swww' | undefined {
  31. if (has('awww')) return 'awww'
  32. if (has('swww')) return 'swww'
  33. return undefined
  34. }
  35. export async function applySwww(
  36. imagePath: string,
  37. command = swwwCommand(),
  38. run: CommandRunner = runHostCommand,
  39. start: DaemonStarter = startHostDaemon
  40. ): Promise<void> {
  41. if (!command) throw new Error('Neither awww nor swww is installed')
  42. // img only talks to the daemon, nothing draws without it
  43. if (!(await run(command, ['query'])).ok) {
  44. start(`${command}-daemon`, [])
  45. for (let i = 0; i < 25 && !(await run(command, ['query'])).ok; i++) await sleep(200)
  46. }
  47. const result = await run(command, ['img', imagePath, '--transition-type', 'fade'])
  48. if (!result.ok) throw new Error(`${command} img failed: ${result.output}`)
  49. }
  50. const HYPRPAPER_NOT_RUNNING = /is it running|failed to connect|couldn't connect|connection refused/i
  51. // hyprctl's hyprwire handshake with a hyprpaper that is still starting
  52. const HYPRPAPER_STARTING = /wire error|doesn't have the spec/i
  53. // 0.8 answers nothing on success, older ones "ok"
  54. const hyprpaperAccepted = (result: CommandResult) => result.ok && (result.output === '' || result.output === 'ok')
  55. /** 0.8: "monitor,path,fit" in one request; 0.7: preload, no fit. Empty monitor = all */
  56. export async function applyHyprpaper(
  57. imagePath: string,
  58. run: CommandRunner = runHostCommand,
  59. start: DaemonStarter = startHostDaemon
  60. ): Promise<void> {
  61. const current = () => run('hyprctl', ['hyprpaper', 'wallpaper', `,${imagePath},cover`])
  62. let result = await current()
  63. if (HYPRPAPER_NOT_RUNNING.test(result.output)) {
  64. start('hyprpaper', [])
  65. for (let i = 0; i < 25 && (HYPRPAPER_NOT_RUNNING.test(result.output) || HYPRPAPER_STARTING.test(result.output)); i++) {
  66. await sleep(200)
  67. result = await current()
  68. }
  69. }
  70. if (hyprpaperAccepted(result)) return
  71. if (HYPRPAPER_NOT_RUNNING.test(result.output)) throw new Error(`hyprpaper did not start: ${result.output}`)
  72. const preload = await run('hyprctl', ['hyprpaper', 'preload', imagePath])
  73. const legacy = await run('hyprctl', ['hyprpaper', 'wallpaper', `,${imagePath}`])
  74. if (!hyprpaperAccepted(legacy)) {
  75. throw new Error(`hyprpaper refused the wallpaper: ${legacy.output || preload.output || result.output}`)
  76. }
  77. await run('hyprctl', ['hyprpaper', 'unload', 'unused'])
  78. }
  79. let swaybgProcess: ChildProcess | undefined
  80. /** swaybg draws while it runs: start the new one, then stop the old */
  81. export async function applySwaybg(imagePath: string, start: DaemonStarter = startHostDaemon): Promise<void> {
  82. const child = start('swaybg', ['-i', imagePath, '-m', 'fill'])
  83. if (!child) return
  84. const exitCode = await new Promise<number | null | undefined>((resolve) => {
  85. const timer = setTimeout(() => resolve(undefined), 700)
  86. child.once('exit', (code) => {
  87. clearTimeout(timer)
  88. resolve(code)
  89. })
  90. child.once('error', () => {
  91. clearTimeout(timer)
  92. resolve(-1)
  93. })
  94. })
  95. if (exitCode !== undefined) throw new Error(`swaybg exited right away (code ${exitCode})`)
  96. const previous = swaybgProcess
  97. swaybgProcess = child
  98. if (previous?.pid && previous.exitCode === null) {
  99. // own process group, so a wrapper script's swaybg is reached too
  100. try {
  101. process.kill(-previous.pid, 'SIGTERM')
  102. } catch {
  103. previous.kill('SIGTERM')
  104. }
  105. }
  106. }
  107. export function hasHyprpaper(has: (cmd: string) => boolean = isHostCommandAvailable): boolean {
  108. return has('hyprpaper') && has('hyprctl')
  109. }
  110. export function isHostProcessRunning(name: string): boolean {
  111. try {
  112. execFileSync(...hostCommand('pgrep', ['-x', name]), { stdio: 'ignore', timeout: 5000 })
  113. return true
  114. } catch {
  115. return false
  116. }
  117. }
  118. /** a running awww/swww daemon wins over hyprpaper, they would fight */
  119. export function prefersHyprpaper(
  120. has: (cmd: string) => boolean = isHostCommandAvailable,
  121. running: (name: string) => boolean = isHostProcessRunning
  122. ): boolean {
  123. if (!hasHyprpaper(has)) return false
  124. if (running('hyprpaper')) return true
  125. return !(swwwCommand(has) && (running('awww-daemon') || running('swww-daemon')))
  126. }