lwe.service.ts 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  1. import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
  2. import { promisify } from 'util'
  3. import * as fs from 'fs'
  4. import * as path from 'path'
  5. import * as os from 'os'
  6. import type { BrowserWindow } from 'electron'
  7. import { IpcChannels } from '@shared/ipc-channels'
  8. import { parseLweFontList } from './lwe-fonts'
  9. import type {
  10. LweStatus,
  11. LweInstallProgress,
  12. LinuxDistro,
  13. LweSceneObject,
  14. LweProperty,
  15. LweAudioObject,
  16. LweSceneEffect,
  17. LweFontNeed,
  18. CrashPhase,
  19. EngineFlags,
  20. ScreenTarget,
  21. HwdecBackend,
  22. HrtfMode,
  23. TransitionDuration,
  24. TransitionMode,
  25. BatteryFps,
  26. IdlePause,
  27. SplitLayout,
  28. XrayMode
  29. } from '@shared/types'
  30. import {
  31. isCommandAvailable,
  32. invalidateCommandCache,
  33. whichCommand,
  34. getConnectedScreens,
  35. getMirroredScreens,
  36. getScreenGeometry,
  37. getWaylandDisplay,
  38. getXdgRuntimeDir,
  39. isWaylandSession
  40. } from '../utils/platform'
  41. import { getWorkshopPath, getLweManifestPath, getLwePrebuiltDir, getSteamRoots } from '../utils/paths'
  42. import {
  43. flatpakInstanceId,
  44. hostCommand,
  45. hostPidOf,
  46. hostProcessCommandLine,
  47. hostProcessCommandLineAsync,
  48. isFlatpak,
  49. killHostProcess
  50. } from '../utils/flatpak'
  51. import { owningPackage } from '../utils/packages'
  52. import { isOwnDirectory, lweBuildDir } from '../utils/buildDir'
  53. import { LWE_PROCESS_PATTERN, isLweCommandLine } from '../utils/engineProcess'
  54. import {
  55. getLweRepoUrl,
  56. getLweRepoBranch,
  57. getLweCmakeArgs,
  58. getAudioScreen,
  59. getAmbientVolume,
  60. getLeds,
  61. getDefaultAudioSensitivity,
  62. getDisablePuppetAnimation,
  63. getScriptLimits,
  64. getDisabledScreens
  65. } from './config.service'
  66. import { DEFAULT_LWE_FPS, DEFAULT_LWE_REPO } from '@shared/constants'
  67. import { engineFlagArgs, filterSupportedArgs } from '@shared/engineFlags'
  68. import { imageAdjustmentArgs, imageAdjustmentLines, type ImageAdjustments } from '@shared/imageAdjustments'
  69. import { formatVideoSegments, type VideoSegment } from '@shared/videoTrim'
  70. import { t } from '../i18n'
  71. export const ALL_SCREENS: ScreenTarget = '*'
  72. const execFileAsync = promisify(execFile)
  73. // AppRun points LD_LIBRARY_PATH etc. into /tmp/.mount_*, which CMake would cache
  74. const APPIMAGE_MOUNT = /^\/tmp\/\.mount_[^/]+(\/|$)/
  75. const DEFAULT_LED_SERVER = '127.0.0.1:6742'
  76. function validLedServer(value: string): string {
  77. const server = value.trim()
  78. const match = /^([^\s:]+)(?::(\d{1,5}))?$/.exec(server)
  79. if (!match) return DEFAULT_LED_SERVER
  80. if (match[2] !== undefined && (Number(match[2]) < 1 || Number(match[2]) > 65535)) return DEFAULT_LED_SERVER
  81. return server
  82. }
  83. function isAppImagePath(entry: string, appDir: string | undefined): boolean {
  84. if (appDir && (entry === appDir || entry.startsWith(`${appDir}/`))) return true
  85. return APPIMAGE_MOUNT.test(entry)
  86. }
  87. export function buildCleanBuildEnv(): NodeJS.ProcessEnv {
  88. const env = { ...process.env }
  89. const appDir = env.APPDIR
  90. for (const key of ['LD_LIBRARY_PATH', 'LD_PRELOAD', 'APPDIR', 'APPIMAGE', 'OWD', 'ARGV0']) {
  91. delete env[key]
  92. }
  93. // find_library also searches PATH, which picked up Electron's bundled libEGL.so
  94. for (const [key, value] of Object.entries(env)) {
  95. if (!value || !value.includes('/')) continue
  96. const entries = value.split(':')
  97. if (!entries.some((entry) => isAppImagePath(entry, appDir))) continue
  98. const kept = entries.filter((entry) => !isAppImagePath(entry, appDir))
  99. if (kept.length > 0) env[key] = kept.join(':')
  100. else delete env[key]
  101. }
  102. return env
  103. }
  104. /** A cache pointing into an AppImage mount needs a fresh configure */
  105. function dropPoisonedCmakeCache(cmakeBuild: string): boolean {
  106. const cachePath = path.join(cmakeBuild, 'CMakeCache.txt')
  107. let cache: string
  108. try { cache = fs.readFileSync(cachePath, 'utf8') } catch { return false }
  109. if (!/\/tmp\/\.mount_[^/\s]+/.test(cache)) return false
  110. fs.rmSync(cachePath, { force: true })
  111. return true
  112. }
  113. const LWE_BINARY = 'linux-wallpaperengine'
  114. const BUILD_DIR = lweBuildDir()
  115. const LWE_SEARCH_PATHS = [
  116. path.join(os.homedir(), 'projects', 'private', 'linux-wallpaperengine', 'build', 'output', 'linux-wallpaperengine'),
  117. path.join(os.homedir(), 'projects', 'linux-wallpaperengine', 'build', 'output', 'linux-wallpaperengine'),
  118. // a downloaded release wins over a source install
  119. path.join(getLwePrebuiltDir(), 'linux-wallpaperengine'),
  120. '/usr/local/bin/linux-wallpaperengine',
  121. '/usr/local/linux-wallpaperengine',
  122. '/usr/bin/linux-wallpaperengine',
  123. path.join(os.homedir(), '.local', 'bin', 'linux-wallpaperengine'),
  124. path.join(os.homedir(), 'bin', 'linux-wallpaperengine'),
  125. '/opt/linux-wallpaperengine/linux-wallpaperengine'
  126. ]
  127. async function removeBuildDir(dir: string): Promise<void> {
  128. if (!fs.existsSync(dir)) return
  129. try {
  130. fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 60 })
  131. return
  132. } catch (err) {
  133. const code = (err as NodeJS.ErrnoException).code
  134. if (code !== 'EACCES' && code !== 'ENOTEMPTY' && code !== 'EPERM') throw err
  135. }
  136. // root only deletes what is ours: files a make install left root-owned inside our folder, not somebody else's
  137. // folder or a link
  138. if (!isOwnDirectory(dir)) throw new Error(`${dir} is not a folder of yours, not removing it as root.`)
  139. const elevate = isCommandAvailable('pkexec') ? 'pkexec' : 'sudo'
  140. await execFileAsync(elevate, ['rm', '-rf', dir], { timeout: 30_000, encoding: 'utf8' })
  141. }
  142. interface LweInstallManifest {
  143. files: string[]
  144. symlink: string
  145. }
  146. function readLweManifest(): LweInstallManifest | undefined {
  147. try {
  148. const parsed = JSON.parse(fs.readFileSync(getLweManifestPath(), 'utf8')) as LweInstallManifest
  149. if (Array.isArray(parsed.files) && typeof parsed.symlink === 'string') return parsed
  150. } catch { /* falls back to heuristic cleanup in uninstallLwe */ }
  151. return undefined
  152. }
  153. function writeLweManifest(manifest: LweInstallManifest): void {
  154. try {
  155. fs.writeFileSync(getLweManifestPath(), JSON.stringify(manifest, null, 2), 'utf8')
  156. } catch { }
  157. }
  158. const FLATPAK_LWE_BINARY = '/app/bin/linux-wallpaperengine'
  159. function findLweBinary(): string | undefined {
  160. if (isFlatpak()) return fs.existsSync(FLATPAK_LWE_BINARY) ? FLATPAK_LWE_BINARY : undefined
  161. for (const p of LWE_SEARCH_PATHS) {
  162. try {
  163. fs.accessSync(p, fs.constants.X_OK)
  164. return p
  165. } catch { }
  166. }
  167. return whichCommand(LWE_BINARY)
  168. }
  169. export function readPrebuiltRelease(): { tag: string; asset: string } | undefined {
  170. try {
  171. return JSON.parse(fs.readFileSync(path.join(getLwePrebuiltDir(), '.release'), 'utf8'))
  172. } catch {
  173. return undefined
  174. }
  175. }
  176. function isPrebuiltPath(p: string): boolean {
  177. return p.startsWith(getLwePrebuiltDir() + path.sep)
  178. }
  179. let ownerCache: { path: string; owner: string | undefined } | undefined
  180. /** Flatpak, Nix profile or distribution package that owns the binary */
  181. export function lwePackageOwner(binary: string): string | undefined {
  182. let real = binary
  183. try { real = fs.realpathSync(binary) } catch { }
  184. if (ownerCache?.path === real) return ownerCache.owner
  185. let owner: string | undefined
  186. if (isFlatpak() && real.startsWith('/app/')) {
  187. owner = 'the Flatpak'
  188. } else if (real.startsWith('/nix/store/')) {
  189. owner = 'Nix'
  190. } else {
  191. const pkg = owningPackage(real)
  192. if (pkg) owner = `${pkg.manager} (${pkg.name})`
  193. }
  194. ownerCache = { path: real, owner }
  195. return owner
  196. }
  197. export function getLweStatus(): LweStatus {
  198. const found = findLweBinary()
  199. if (!found) return { installed: false }
  200. const version = isPrebuiltPath(found) ? readPrebuiltRelease()?.tag : undefined
  201. const managedBy = isPrebuiltPath(found) ? undefined : lwePackageOwner(found)
  202. return {
  203. installed: true,
  204. path: found,
  205. ...(version ? { version } : {}),
  206. ...(managedBy ? { managedBy } : {})
  207. }
  208. }
  209. export function resetLweDetection(): void {
  210. ownerCache = undefined
  211. invalidateCommandCache(LWE_BINARY)
  212. invalidateHelpText()
  213. }
  214. export function parseOsReleaseIds(release: string): string[] {
  215. const ids: string[] = []
  216. for (const line of release.split('\n')) {
  217. const match = /^(ID|ID_LIKE)=(.*)$/.exec(line.trim())
  218. if (match) ids.push(...match[2].replace(/^["']|["']$/g, '').toLowerCase().split(/\s+/).filter(Boolean))
  219. }
  220. return ids
  221. }
  222. export function detectDistro(): LinuxDistro {
  223. let ids: string[]
  224. try {
  225. ids = parseOsReleaseIds(fs.readFileSync('/etc/os-release', 'utf8'))
  226. } catch {
  227. return 'unknown'
  228. }
  229. return distroFromIds(ids)
  230. }
  231. export function distroFromIds(ids: string[]): LinuxDistro {
  232. for (const id of ids) {
  233. if (['fedora', 'nobara', 'rhel', 'centos'].includes(id)) return 'fedora'
  234. if (['arch', 'manjaro', 'endeavouros'].includes(id)) return 'arch'
  235. if (['debian', 'ubuntu', 'linuxmint', 'pop'].includes(id)) return 'debian'
  236. if (['suse', 'opensuse', 'opensuse-tumbleweed', 'opensuse-leap', 'opensuse-slowroll', 'sles'].includes(id)) return 'suse'
  237. }
  238. return 'unknown'
  239. }
  240. export function isOstreeSystem(): boolean {
  241. return fs.existsSync('/run/ostree-booted')
  242. }
  243. const DEPS_DEBIAN = [
  244. 'git', 'build-essential', 'cmake', 'pkg-config',
  245. 'libxrandr-dev', 'libxinerama-dev', 'libxcomposite-dev', 'libxdamage-dev', 'libxcursor-dev', 'libxi-dev',
  246. 'libgl-dev', 'libglew-dev', 'freeglut3-dev', 'libsdl2-dev',
  247. 'liblz4-dev', 'libavcodec-dev', 'libavformat-dev', 'libavutil-dev', 'libswscale-dev',
  248. 'libxxf86vm-dev', 'libglm-dev', 'libglfw3-dev',
  249. 'libmpv-dev', 'mpv', 'libpulse-dev', 'libpulse0', 'libfftw3-dev', 'libfreetype-dev', 'libharfbuzz-dev', 'libdbus-1-dev',
  250. 'libwayland-dev', 'wayland-protocols', 'libegl1-mesa-dev',
  251. 'libgmp-dev', 'patchelf',
  252. // V8 for scene scripts
  253. 'libnode-dev'
  254. ]
  255. // 'ffmpeg' conflicts with ffmpeg-free on Fedora
  256. const DEPS_FEDORA = [
  257. 'git', 'gcc', 'g++', 'cmake', 'pkg-config',
  258. 'libXrandr-devel', 'libXinerama-devel', 'libXcomposite-devel', 'libXdamage-devel', 'libXcursor-devel', 'libXi-devel',
  259. 'mesa-libGL-devel', 'glew-devel', 'freeglut-devel', 'SDL2-devel',
  260. 'lz4-devel', 'ffmpeg-free-devel',
  261. 'libXxf86vm-devel', 'glm-devel', 'glfw-devel',
  262. 'mpv-devel', 'pulseaudio-libs-devel', 'fftw-devel', 'freetype-devel', 'harfbuzz-devel', 'dbus-devel',
  263. 'wayland-devel', 'wayland-protocols-devel', 'mesa-libEGL-devel',
  264. 'gmp-devel', 'patchelf'
  265. ]
  266. /** Versioned nodejsNN-devel packages conflict: keep an installed one, else match the newest libnode */
  267. export function nodeDevelPackage(installed: string[]): string | null {
  268. const names = installed.map((name) => name.trim())
  269. if (names.some((name) => /^nodejs\d*-devel$/.test(name))) return null
  270. let best: { name: string; version: number } | undefined
  271. for (const name of names) {
  272. const match = /^nodejs(\d*)-libs$/.exec(name)
  273. if (!match) continue
  274. const version = match[1] ? Number(match[1]) : 0
  275. if (!best || version > best.version) best = { name: `nodejs${match[1]}-devel`, version }
  276. }
  277. return best?.name ?? 'nodejs-devel'
  278. }
  279. function quotedPaths(paths: string[]): string {
  280. return paths.map((p) => JSON.stringify(p)).join(' ')
  281. }
  282. function installedNodePackages(): string[] {
  283. try {
  284. return execFileSync('rpm', ['-qa', '--qf', '%{NAME}\n', 'nodejs*-libs', 'nodejs*-devel'], {
  285. encoding: 'utf8',
  286. timeout: 10_000
  287. }).split('\n')
  288. } catch {
  289. return []
  290. }
  291. }
  292. // SDL2 comes from sdl2-compat, GLFW is libglfw-devel on Leap and glfw-devel on Tumbleweed and nodejs-devel is whichever
  293. // Node.js is the default (V8 for scene scripts), all capabilities. FFmpeg's devel packages are ffmpeg-<N>-lib*-devel, see suseFfmpegDevel
  294. const DEPS_SUSE = [
  295. 'git', 'gcc', 'gcc-c++', 'cmake', 'pkgconf-pkg-config', 'make',
  296. 'libXrandr-devel', 'libXinerama-devel', 'libXcomposite-devel', 'libXdamage-devel', 'libXcursor-devel', 'libXi-devel',
  297. 'Mesa-libGL-devel', 'glew-devel', 'freeglut-devel', 'pkgconfig(sdl2)',
  298. 'liblz4-devel',
  299. 'libXxf86vm-devel', 'glm-devel', 'pkgconfig(glfw3)',
  300. 'mpv-devel', 'libpulse-devel', 'fftw3-devel', 'freetype2-devel', 'harfbuzz-devel', 'dbus-1-devel',
  301. 'wayland-devel', 'wayland-protocols-devel', 'Mesa-libEGL-devel',
  302. 'gmp-devel', 'patchelf', 'nodejs-devel'
  303. ]
  304. /**
  305. * Tumbleweed carries several FFmpeg versions side by side. The engine has to link the one libmpv uses, two FFmpeg
  306. * ABIs in one process resolve each other's symbols. Needs mpv-devel installed (it pulls libmpv2); null if unreadable.
  307. */
  308. export function suseFfmpegDevel(): string[] | null {
  309. try {
  310. const requires = execFileSync('rpm', ['-q', '--requires', 'libmpv2'], { encoding: 'utf8', timeout: 10_000 })
  311. const soname = /libavcodec\.so\.\d+/.exec(requires)?.[0]
  312. if (!soname) return null
  313. const version = execFileSync('rpm', ['-q', '--qf', '%{VERSION}\n', '--whatprovides', `${soname}()(64bit)`], {
  314. encoding: 'utf8',
  315. timeout: 10_000
  316. }).split('\n')[0]
  317. const major = /^(\d+)\./.exec(version)?.[1]
  318. if (!major) return null
  319. return ['avcodec', 'avformat', 'avutil', 'swscale', 'swresample'].map((lib) => `ffmpeg-${major}-lib${lib}-devel`)
  320. } catch {
  321. return null
  322. }
  323. }
  324. const DEPS_ARCH = [
  325. 'git', 'base-devel', 'cmake', 'pkg-config',
  326. 'glew', 'freeglut', 'sdl2', 'lz4', 'ffmpeg',
  327. 'glm', 'glfw', 'mpv', 'libpulse', 'fftw', 'freetype2', 'harfbuzz', 'dbus',
  328. 'libxrandr', 'libxinerama', 'libxcomposite', 'libxdamage', 'libxcursor', 'libxi', 'libxxf86vm',
  329. 'wayland', 'wayland-protocols', 'mesa',
  330. 'gmp', 'patchelf'
  331. ]
  332. export async function installLweDeps(win: BrowserWindow): Promise<boolean> {
  333. const send = (progress: LweInstallProgress) => {
  334. win.webContents.send(IpcChannels.EVENT_LWE_INSTALL_PROGRESS, progress)
  335. }
  336. if (isFlatpak()) {
  337. send({ stage: 'error', message: t('lwe.flatpakManaged'), percentage: 0 })
  338. return false
  339. }
  340. const distro = detectDistro()
  341. if (distro === 'unknown') {
  342. send({
  343. stage: 'error',
  344. message: t('lwe.noDistroDeps'),
  345. percentage: 0
  346. })
  347. return false
  348. }
  349. if (isOstreeSystem()) {
  350. send({
  351. stage: 'error',
  352. message: t('lwe.imageBasedSystem'),
  353. percentage: 0
  354. })
  355. return false
  356. }
  357. let pkgManager: string
  358. let installArgs: string[]
  359. let packages: string[]
  360. switch (distro) {
  361. case 'debian':
  362. pkgManager = 'apt-get'
  363. installArgs = ['install', '-y']
  364. packages = DEPS_DEBIAN
  365. break
  366. case 'fedora':
  367. pkgManager = 'dnf'
  368. // don't fail on broken repos or renamed packages
  369. installArgs = ['install', '-y', '--skip-unavailable']
  370. const nodeDevel = nodeDevelPackage(installedNodePackages())
  371. packages = nodeDevel ? [...DEPS_FEDORA, nodeDevel] : DEPS_FEDORA
  372. break
  373. case 'suse':
  374. pkgManager = 'zypper'
  375. // --force-resolution: the minimal images ship busybox-diffutils, which conflicts with what -devel packages pull in
  376. installArgs = ['--non-interactive', 'install', '--no-recommends', '--force-resolution']
  377. packages = DEPS_SUSE
  378. break
  379. case 'arch':
  380. pkgManager = 'pacman'
  381. // a fresh install has no sync databases and every package would be "target not found"
  382. installArgs = pacmanHasSyncDatabases() ? ['-S', '--noconfirm', '--needed'] : ['-Sy', '--noconfirm', '--needed']
  383. packages = DEPS_ARCH
  384. break
  385. }
  386. const elevate = isCommandAvailable('pkexec') ? 'pkexec' : 'sudo'
  387. if (distro === 'suse') {
  388. try {
  389. await execFileAsync(elevate, [pkgManager, ...installArgs, 'mpv-devel'], { timeout: 600_000 })
  390. } catch (err) {
  391. send({ stage: 'error', message: t('lwe.depsFailed', { error: (err as Error).message }), percentage: 0 })
  392. return false
  393. }
  394. packages = [...packages, ...(suseFfmpegDevel() ?? ['pkgconfig(libavcodec)', 'pkgconfig(libavformat)', 'pkgconfig(libavutil)', 'pkgconfig(libswscale)', 'pkgconfig(libswresample)'])]
  395. }
  396. send({
  397. stage: 'installing-deps',
  398. message: t('lwe.installingPackages', { count: packages.length, manager: pkgManager }),
  399. percentage: 10
  400. })
  401. try {
  402. await execFileAsync(elevate, [pkgManager, ...installArgs, ...packages], {
  403. timeout: 600_000
  404. })
  405. // libnode is AUR only on Arch, the settings page has a button for the CI's prebuilt package; openSUSE Leap's Node.js packages have no shared library at all
  406. const libnodeMissing = distro === 'arch' && !fs.existsSync('/usr/lib/libnode.so')
  407. const suseNoV8 = distro === 'suse' && !fs.readdirSync('/usr/lib64').some((name) => name.startsWith('libnode.so'))
  408. send({
  409. stage: 'done',
  410. message: libnodeMissing
  411. ? t('lwe.depsInstalledNoV8')
  412. : suseNoV8
  413. ? t('lwe.depsInstalledNoV8Suse')
  414. : t('lwe.depsInstalled'),
  415. percentage: 100
  416. })
  417. return true
  418. } catch (err) {
  419. send({
  420. stage: 'error',
  421. message: t('lwe.depsFailed', { error: (err as Error).message }),
  422. percentage: 0
  423. })
  424. return false
  425. }
  426. }
  427. /** the repositories of pacman.conf's [sections] (no [options]), Include lines are not followed */
  428. export function parsePacmanRepos(conf: string): string[] {
  429. return conf.split('\n')
  430. .map(line => /^\[([^\]]+)\]\s*$/.exec(line.trim())?.[1])
  431. .filter((name): name is string => name !== undefined && name !== 'options')
  432. }
  433. /** true when every configured repository has its database, one missing (Garuda ships a stale chaotic-aur one) breaks `-S` */
  434. export function pacmanHasSyncDatabases(): boolean {
  435. try {
  436. const present = new Set(fs.readdirSync('/var/lib/pacman/sync'))
  437. let repos: string[] = []
  438. try {
  439. repos = execFileSync('pacman-conf', ['--repo-list'], { encoding: 'utf8' }).split('\n').map(name => name.trim()).filter(Boolean)
  440. } catch {
  441. repos = parsePacmanRepos(fs.readFileSync('/etc/pacman.conf', 'utf8'))
  442. }
  443. if (repos.length === 0) return [...present].some((name) => name.endsWith('.db'))
  444. return repos.every((repo) => present.has(`${repo}.db`))
  445. } catch {
  446. return false
  447. }
  448. }
  449. export async function installLwe(win: BrowserWindow): Promise<void> {
  450. const send = (progress: LweInstallProgress) => {
  451. win.webContents.send(IpcChannels.EVENT_LWE_INSTALL_PROGRESS, progress)
  452. }
  453. if (isFlatpak()) {
  454. send({ stage: 'error', message: t('lwe.flatpakManaged'), percentage: 0 })
  455. return
  456. }
  457. let isLocalDir = false
  458. try {
  459. send({ stage: 'cloning', message: t('lwe.checkingDeps'), percentage: 0 })
  460. const missingDeps: string[] = []
  461. for (const dep of ['git', 'cmake', 'make', 'pkg-config']) {
  462. if (!isCommandAvailable(dep)) missingDeps.push(dep)
  463. }
  464. if (missingDeps.length > 0) {
  465. send({
  466. stage: 'error',
  467. message: t('lwe.missingDeps', { deps: missingDeps.join(', ') }),
  468. percentage: 0
  469. })
  470. return
  471. }
  472. let repo = getLweRepoUrl() ?? DEFAULT_LWE_REPO
  473. if (repo.startsWith('~/')) repo = path.join(os.homedir(), repo.slice(2))
  474. const branch = getLweRepoBranch()
  475. isLocalDir = (() => {
  476. try { return fs.statSync(repo).isDirectory() } catch { return false }
  477. })()
  478. // keep CEF's ~2GB download and objects for the same local source
  479. const sourceMarker = path.join(BUILD_DIR, '.lwe-source-path')
  480. const canReuseBuildCache = isLocalDir && (() => {
  481. try { return fs.readFileSync(sourceMarker, 'utf8').trim() === repo } catch { return false }
  482. })()
  483. if (!canReuseBuildCache) {
  484. await removeBuildDir(BUILD_DIR)
  485. }
  486. // private, the install runs this tree's make as root
  487. fs.mkdirSync(BUILD_DIR, { recursive: true, mode: 0o700 })
  488. if (isLocalDir) {
  489. // copy the working tree so uncommitted edits are built
  490. send({ stage: 'cloning', message: t('lwe.copyingSource', { repo }), percentage: 5 })
  491. if (isCommandAvailable('rsync')) {
  492. // --no-times: old source mtimes could make make skip a changed file in a reused dir
  493. await execFileAsync('rsync', [
  494. '-a', '--no-times', '--delete', '--exclude=/.git', '--exclude=/build',
  495. `${repo}/`, `${BUILD_DIR}/`
  496. ], { timeout: 120_000, maxBuffer: 10 * 1024 * 1024 })
  497. } else {
  498. // -m, same reason as --no-times
  499. await execFileAsync('bash', [
  500. '-c',
  501. `tar -C ${JSON.stringify(repo)} --exclude=.git --exclude=build -cf - . | tar -C ${JSON.stringify(BUILD_DIR)} -xmf -`
  502. ], { timeout: 120_000, maxBuffer: 10 * 1024 * 1024 })
  503. }
  504. fs.writeFileSync(sourceMarker, repo, 'utf8')
  505. } else {
  506. const cloneArgs = ['clone', '--depth', '1', '--recursive']
  507. if (branch) cloneArgs.push('--branch', branch)
  508. cloneArgs.push(repo, BUILD_DIR)
  509. send({
  510. stage: 'cloning',
  511. message: branch ? t('lwe.cloningBranch', { repo, branch }) : t('lwe.cloning', { repo }),
  512. percentage: 5
  513. })
  514. await execFileAsync('git', cloneArgs, {
  515. timeout: 120_000,
  516. maxBuffer: 10 * 1024 * 1024
  517. })
  518. }
  519. // rsync -a gave it the source folder's mode
  520. fs.chmodSync(BUILD_DIR, 0o700)
  521. const cmakeBuild = path.join(BUILD_DIR, 'build')
  522. fs.mkdirSync(cmakeBuild, { recursive: true })
  523. if (dropPoisonedCmakeCache(cmakeBuild)) {
  524. send({ stage: 'building', message: t('lwe.discardingCache'), percentage: 20 })
  525. }
  526. const buildEnv = buildCleanBuildEnv()
  527. send({ stage: 'building', message: t('lwe.runningCmake'), percentage: 25 })
  528. await execFileAsync('cmake', [
  529. '..',
  530. '-DCMAKE_BUILD_TYPE=Release',
  531. '-DCMAKE_INSTALL_PREFIX=/usr/local',
  532. '-DCMAKE_C_FLAGS=-Wno-error',
  533. '-DCMAKE_CXX_FLAGS=-Wno-error',
  534. ...parseCustomArgs(getLweCmakeArgs() ?? '')
  535. ], {
  536. cwd: cmakeBuild,
  537. env: buildEnv,
  538. timeout: 600_000,
  539. maxBuffer: 10 * 1024 * 1024,
  540. encoding: 'utf8'
  541. })
  542. // make's mtime check shipped a stale binary once; keeps the CEF SDK
  543. if (canReuseBuildCache) {
  544. await execFileAsync('make', ['clean'], {
  545. cwd: cmakeBuild,
  546. env: buildEnv,
  547. timeout: 60_000,
  548. maxBuffer: 10 * 1024 * 1024,
  549. encoding: 'utf8'
  550. }).catch(() => { })
  551. }
  552. send({ stage: 'building', message: t('lwe.compiling'), percentage: 40 })
  553. const cores = Math.max(1, os.cpus().length - 1)
  554. await execFileAsync('make', ['-j', String(cores)], {
  555. cwd: cmakeBuild,
  556. env: buildEnv,
  557. timeout: 600_000,
  558. maxBuffer: 10 * 1024 * 1024,
  559. encoding: 'utf8'
  560. })
  561. send({ stage: 'building', message: t('lwe.buildComplete'), percentage: 80 })
  562. send({ stage: 'installing', message: t('lwe.installingSudo'), percentage: 85 })
  563. const installTool = isCommandAvailable('pkexec') ? 'pkexec' : 'sudo'
  564. // pkexec changes cwd and PATH
  565. const pathEnv = process.env.PATH ?? '/usr/local/bin:/usr/bin:/bin'
  566. // install_manifest.txt lets uninstall remove exactly what was installed
  567. const manifestMarker = '###LWE_INSTALL_MANIFEST###'
  568. const reclaim = isLocalDir
  569. ? `chown -R ${process.getuid!()}:${process.getgid!()} ${JSON.stringify(BUILD_DIR)}`
  570. : `rm -rf ${JSON.stringify(BUILD_DIR)}`
  571. const binaryPath = '/usr/local/linux-wallpaperengine'
  572. const linkPath = '/usr/local/bin/linux-wallpaperengine'
  573. // one elevated script, one password prompt
  574. const installScript = `cd ${JSON.stringify(cmakeBuild)} && export PATH=${JSON.stringify(pathEnv)} && make install && patchelf --set-rpath /usr/local/lib64:/usr/local/lib /usr/local/linux-wallpaperengine 2>/dev/null; ldconfig; ln -sf ${JSON.stringify(binaryPath)} ${JSON.stringify(linkPath)} || true; echo ${manifestMarker}; cat install_manifest.txt 2>/dev/null; ${reclaim}`
  575. const { stdout: installOutput } = await execFileAsync(installTool, ['bash', '-c', installScript], {
  576. timeout: 120_000,
  577. maxBuffer: 5 * 1024 * 1024,
  578. encoding: 'utf8'
  579. })
  580. const manifestIdx = installOutput.indexOf(manifestMarker)
  581. if (manifestIdx !== -1) {
  582. const installedFiles = installOutput.slice(manifestIdx + manifestMarker.length)
  583. .split('\n').map(l => l.trim()).filter(Boolean)
  584. if (installedFiles.length > 0) {
  585. writeLweManifest({ files: installedFiles, symlink: linkPath })
  586. }
  587. }
  588. // a downloaded release would shadow the new build
  589. fs.rmSync(getLwePrebuiltDir(), { recursive: true, force: true })
  590. resetLweDetection()
  591. const status = getLweStatus()
  592. if (status.installed) {
  593. send({ stage: 'done', message: t('lwe.installed'), percentage: 100 })
  594. } else {
  595. send({
  596. stage: 'error',
  597. message: t('lwe.notInPath'),
  598. percentage: 100
  599. })
  600. }
  601. } catch (err) {
  602. // a local repo keeps its build dir so a retry stays incremental
  603. if (!isLocalDir) {
  604. try {
  605. await removeBuildDir(BUILD_DIR)
  606. } catch { }
  607. }
  608. const e = err as Error & { stdout?: string; stderr?: string }
  609. const fullMsg = e.message ?? String(err)
  610. const combined = [e.stdout, e.stderr].filter(Boolean).join('\n')
  611. const lines = (combined || fullMsg).split('\n')
  612. const compilerErrors = lines.filter(
  613. (l: string) => /:\d+:\d+: (?:fatal )?error:/i.test(l) || /^\/.*error:/i.test(l) ||
  614. /undefined reference/i.test(l) || /ld returned/i.test(l) ||
  615. /collect2: error/i.test(l)
  616. )
  617. const otherErrors = lines.filter(
  618. (l: string) => /CMake Error/i.test(l) || /No such file or directory/i.test(l) ||
  619. /Permission denied/i.test(l) || /cannot create/i.test(l) ||
  620. /fatal:/i.test(l) || /failed to/i.test(l)
  621. )
  622. let excerpt: string
  623. if (compilerErrors.length > 0) {
  624. excerpt = compilerErrors.slice(0, 10).join('\n')
  625. } else if (otherErrors.length > 0) {
  626. excerpt = otherErrors.slice(0, 8).join('\n')
  627. } else {
  628. excerpt = lines.filter((l: string) => l.trim() && !/^make\[\d+\]: (Entering|Leaving)/i.test(l))
  629. .slice(-30).join('\n')
  630. }
  631. send({
  632. stage: 'error',
  633. message: `${t('lwe.buildFailed')}\n${excerpt.trim() || fullMsg}`,
  634. percentage: 0
  635. })
  636. }
  637. }
  638. export async function uninstallLwe(): Promise<{ ok: boolean; message: string }> {
  639. if (isFlatpak()) return { ok: false, message: t('lwe.flatpakManaged') }
  640. const status = getLweStatus()
  641. if (!status.installed || !status.path) {
  642. return { ok: false, message: t('lwe.notInstalled') }
  643. }
  644. if (status.managedBy) {
  645. return { ok: false, message: t('lwe.managedBy', { owner: status.managedBy }) }
  646. }
  647. await stopLwe()
  648. if (isPrebuiltPath(status.path)) {
  649. try {
  650. fs.rmSync(getLwePrebuiltDir(), { recursive: true, force: true })
  651. } catch (err) {
  652. return { ok: false, message: t('lwe.uninstallFailed', { error: (err as Error).message }) }
  653. }
  654. resetLweDetection()
  655. return { ok: true, message: t('lwe.uninstalled') }
  656. }
  657. const elevate = isCommandAvailable('pkexec') ? 'pkexec' : 'sudo'
  658. const manifest = readLweManifest()
  659. let filesToRemove: string[]
  660. let dirsToPrune: string[] = []
  661. if (manifest) {
  662. filesToRemove = [...manifest.files, manifest.symlink]
  663. // deepest first, so a dir only prunes once its own contents are gone
  664. dirsToPrune = [...new Set(manifest.files.map(f => path.dirname(f)))].sort((a, b) => b.length - a.length)
  665. } else {
  666. const binaryPath = status.path
  667. let realPath: string
  668. try {
  669. realPath = fs.realpathSync(binaryPath)
  670. } catch {
  671. realPath = binaryPath
  672. }
  673. filesToRemove = [realPath]
  674. if (realPath !== binaryPath) filesToRemove.push(binaryPath)
  675. const binDir = path.dirname(realPath)
  676. const libDir = path.join(binDir, 'lib')
  677. if (fs.existsSync(libDir)) {
  678. try {
  679. const entries = fs.readdirSync(libDir)
  680. if (entries.some(e => e.includes('cef') || e.includes('wallpaper'))) {
  681. filesToRemove.push(libDir)
  682. }
  683. } catch { }
  684. }
  685. }
  686. try {
  687. const script = dirsToPrune.length > 0
  688. ? `rm -f ${quotedPaths(filesToRemove)}; rmdir --ignore-fail-on-non-empty -p ${quotedPaths(dirsToPrune)} 2>/dev/null; ldconfig`
  689. : `rm -f ${quotedPaths(filesToRemove)}; ldconfig`
  690. await execFileAsync(elevate, ['bash', '-c', script], {
  691. timeout: 60_000,
  692. encoding: 'utf8'
  693. })
  694. try { fs.rmSync(getLweManifestPath(), { force: true }) } catch { }
  695. resetLweDetection()
  696. return { ok: true, message: t('lwe.uninstalled') }
  697. } catch (err) {
  698. return { ok: false, message: t('lwe.uninstallFailed', { error: (err as Error).message }) }
  699. }
  700. }
  701. function findWeAssetsDir(): string | undefined {
  702. const workshopPath = getWorkshopPath()
  703. // .../steamapps/workshop/content/431960 -> .../steamapps/common/wallpaper_engine/assets
  704. const steamappsIdx = workshopPath.lastIndexOf(path.join('steamapps', 'workshop'))
  705. if (steamappsIdx !== -1) {
  706. const steamappsRoot = workshopPath.substring(0, steamappsIdx + 'steamapps'.length)
  707. const assetsDir = path.join(steamappsRoot, 'common', 'wallpaper_engine', 'assets')
  708. if (fs.existsSync(assetsDir)) return assetsDir
  709. }
  710. return getSteamRoots()
  711. .map(root => path.join(root, 'steamapps', 'common', 'wallpaper_engine', 'assets'))
  712. .find(p => fs.existsSync(p))
  713. }
  714. function getLweLibDir(): string {
  715. const p = findLweBinary()
  716. if (!p) return '/usr/local'
  717. try {
  718. const resolved = fs.realpathSync(p)
  719. return path.dirname(resolved)
  720. } catch {
  721. return path.dirname(p)
  722. }
  723. }
  724. function getLweLdLibraryPath(): string {
  725. const binDir = getLweLibDir()
  726. const candidates = [
  727. // local builds keep their .so files next to the binary
  728. binDir,
  729. path.join(binDir, 'lib64'),
  730. path.join(binDir, 'lib'),
  731. '/usr/local/lib64',
  732. '/usr/local/lib'
  733. ]
  734. const paths = candidates.filter(p => {
  735. try { return fs.statSync(p).isDirectory() } catch { return false }
  736. })
  737. const existing = process.env.LD_LIBRARY_PATH
  738. if (existing) paths.push(existing)
  739. return paths.join(':')
  740. }
  741. function getLweBinaryPath(): string {
  742. const p = findLweBinary()
  743. if (!p) return LWE_BINARY
  744. try {
  745. return fs.realpathSync(p)
  746. } catch {
  747. return p
  748. }
  749. }
  750. function buildLweEnvVars(): string[] {
  751. const vars: string[] = []
  752. // a Nix build brings its own libraries
  753. const fromNix = getLweBinaryPath().startsWith('/nix/store/')
  754. if (fromNix) vars.push('-u', 'LD_LIBRARY_PATH', '-u', 'LD_PRELOAD')
  755. else vars.push(`LD_LIBRARY_PATH=${getLweLdLibraryPath()}`)
  756. // CEF's bundled libEGL.so next to the binary would shadow Mesa's and break Wayland
  757. const systemEgl = ['/lib64/libEGL.so.1', '/usr/lib64/libEGL.so.1', '/usr/lib/x86_64-linux-gnu/libEGL.so.1',
  758. '/usr/lib/libEGL.so.1']
  759. .find(p => fs.existsSync(p))
  760. if (systemEgl && !fromNix) vars.push(`LD_PRELOAD=${systemEgl}`)
  761. const waylandDisplay = getWaylandDisplay()
  762. if (waylandDisplay) vars.push(`WAYLAND_DISPLAY=${waylandDisplay}`)
  763. // picks X11/Wayland by this, often unset without a login manager
  764. const sessionType = process.env.XDG_SESSION_TYPE || (waylandDisplay ? 'wayland' : undefined)
  765. if (sessionType) vars.push(`XDG_SESSION_TYPE=${sessionType}`)
  766. for (const name of ['XDG_CURRENT_DESKTOP', 'HYPRLAND_INSTANCE_SIGNATURE', 'SWAYSOCK', 'NIRI_SOCKET']) {
  767. const value = process.env[name]
  768. if (value) vars.push(`${name}=${value}`)
  769. }
  770. if (process.env.DISPLAY) vars.push(`DISPLAY=${process.env.DISPLAY}`)
  771. vars.push(`XDG_RUNTIME_DIR=${getXdgRuntimeDir()}`)
  772. if (diagnosticStats) vars.push('LWE_FRAME_STATS=1')
  773. if (getScriptLimits()) vars.push('LWE_SCRIPT_TIMEOUT_MS=5000', 'LWE_SCRIPT_HEAP_MB=512', 'LWE_SCRIPT_BUFFER_MB=512')
  774. return vars
  775. }
  776. function supportsObjectFlags(): boolean {
  777. return supportsFlag('--list-objects')
  778. }
  779. function supportsAudioSensitivity(): boolean {
  780. return supportsFlag('--list-audio-objects')
  781. }
  782. function supportsSoundVolume(): boolean {
  783. return supportsFlag('--sound-volume')
  784. }
  785. function supportsEffectFlags(): boolean {
  786. return supportsFlag('--list-effects')
  787. }
  788. function supportsDisableAnimations(): boolean {
  789. return supportsFlag('--disable-animations')
  790. }
  791. function supportsExpandCanvas(): boolean {
  792. return supportsFlag('--expand-canvas')
  793. }
  794. // shell-like: quotes anywhere in a token group whitespace and are dropped
  795. export function parseCustomArgs(raw: string): string[] {
  796. const tokens: string[] = []
  797. let current = ''
  798. let inToken = false
  799. let quote: string | null = null
  800. for (const ch of raw) {
  801. if (quote) {
  802. if (ch === quote) quote = null
  803. else current += ch
  804. } else if (ch === '"' || ch === "'") {
  805. quote = ch
  806. inToken = true
  807. } else if (/\s/.test(ch)) {
  808. if (inToken) tokens.push(current)
  809. current = ''
  810. inToken = false
  811. } else {
  812. current += ch
  813. inToken = true
  814. }
  815. }
  816. if (inToken) tokens.push(current)
  817. return tokens
  818. }
  819. let helpText: string | null = null
  820. let helpTextStamp = ''
  821. function invalidateHelpText(): void {
  822. helpText = null
  823. }
  824. // cached --help is tied to the file, the binary can be replaced
  825. function binaryStamp(binaryPath: string): string {
  826. try {
  827. const stat = fs.statSync(binaryPath)
  828. return `${binaryPath}:${stat.ino}:${stat.size}:${stat.mtimeMs}`
  829. } catch {
  830. return binaryPath
  831. }
  832. }
  833. // older builds ignore unknown flags, so unlisted ones are left out
  834. function supportsFlag(flag: string): boolean {
  835. const binaryPath = getLweBinaryPath()
  836. const stamp = binaryStamp(binaryPath)
  837. if (helpText === null || stamp !== helpTextStamp) {
  838. helpTextStamp = stamp
  839. try {
  840. helpText = execFileSync('env', [...buildLweEnvVars(), binaryPath, '--help'], {
  841. timeout: 5_000,
  842. encoding: 'utf8',
  843. maxBuffer: 2 * 1024 * 1024
  844. })
  845. } catch {
  846. helpText = ''
  847. }
  848. }
  849. return helpText.includes(flag)
  850. }
  851. export function supportsSplitScreens(): boolean {
  852. return supportsFlag('--screen-slot')
  853. }
  854. /** One wallpaper of a split screen with its own display settings */
  855. export interface LweSplitSlot {
  856. path: string
  857. scalingMode?: string
  858. zoom?: number
  859. offsetX?: number
  860. offsetY?: number
  861. cornerColor?: string
  862. imageAdjustments?: ImageAdjustments
  863. }
  864. export interface LweLaunchOptions {
  865. /** '*' = one engine for every screen */
  866. screen?: ScreenTarget
  867. /** --screen-slot on options.screen, display options become per slot */
  868. split?: { layout: SplitLayout; slots: LweSplitSlot[] }
  869. fps?: number
  870. volume?: number
  871. disabledObjects?: string[]
  872. enabledObjects?: string[]
  873. disabledEffects?: string[]
  874. enabledEffects?: string[]
  875. propertyOverrides?: Record<string, string>
  876. xrayMode?: XrayMode
  877. scalingMode?: string
  878. zoom?: number
  879. offsetX?: number
  880. offsetY?: number
  881. disableParallax?: boolean
  882. expandCanvas?: boolean
  883. repairAssets?: boolean
  884. cornerColor?: string
  885. imageAdjustments?: ImageAdjustments
  886. speed?: number
  887. videoSegments?: VideoSegment[]
  888. audioSensitivity?: Record<string, number>
  889. soundVolume?: Record<string, number>
  890. customArgs?: string
  891. engineFlags?: EngineFlags
  892. forceFresh?: boolean
  893. }
  894. const FALLBACK_WINDOW = '0x0x1920x1080'
  895. function windowedGeometry(screen?: ScreenTarget): string {
  896. return getScreenGeometry(screen && screen !== ALL_SCREENS ? screen : undefined) ?? FALLBACK_WINDOW
  897. }
  898. export function getActiveScreens(): string[] {
  899. const all = getConnectedScreens()
  900. const off = new Set([...getDisabledScreens(), ...getMirroredScreens()])
  901. const active = all.filter((s) => !off.has(s))
  902. return active.length > 0 ? active : all
  903. }
  904. export function buildLweArgs(
  905. wallpaperPath: string,
  906. options: LweLaunchOptions,
  907. capture?: { window: string; screenshotPath: string; delayFrames: number }
  908. ): string[] {
  909. const args: string[] = []
  910. const assetsDir = findWeAssetsDir()
  911. if (assetsDir) args.push('--assets-dir', assetsDir)
  912. // before any --screen-root, so they apply to every screen
  913. if (supportsFlag('--image-filter')) args.push(...imageAdjustmentArgs(options.imageAdjustments))
  914. const wantsWindow = !!(options.engineFlags?.windowed || options.engineFlags?.windowBackground)
  915. const windowGeometry = capture ? capture.window : wantsWindow ? windowedGeometry(options.screen) : null
  916. if (windowGeometry) {
  917. args.push('--window', windowGeometry)
  918. // without it the engine's window is a normal one on top of everything
  919. if (!capture && options.engineFlags?.windowBackground && supportsFlag('--window-background')) {
  920. args.push('--window-background')
  921. } else if (!capture && supportsFlag('--window-normal')) {
  922. // otherwise the window has no frame and stays above every other window
  923. args.push('--window-normal')
  924. }
  925. } else if (options.split && options.screen && options.screen !== ALL_SCREENS) {
  926. // every option after a --screen-slot belongs to that slot
  927. for (const slot of options.split.slots) {
  928. args.push('--screen-slot', options.screen, '--bg', slot.path)
  929. if (slot.scalingMode) args.push('--scaling', slot.scalingMode)
  930. if (slot.zoom !== undefined) args.push('--zoom', String(slot.zoom))
  931. if (slot.offsetX !== undefined || slot.offsetY !== undefined) {
  932. args.push('--offset', `${slot.offsetX ?? 0},${slot.offsetY ?? 0}`)
  933. }
  934. if (slot.cornerColor) args.push('--corner-color', slot.cornerColor)
  935. if (supportsFlag('--image-filter')) args.push(...imageAdjustmentArgs(slot.imageAdjustments))
  936. }
  937. args.push('--split-layout', options.split.layout)
  938. } else if (options.screen && options.screen !== ALL_SCREENS) {
  939. args.push('--screen-root', options.screen)
  940. } else {
  941. for (const s of getActiveScreens()) args.push('--screen-root', s)
  942. }
  943. if (options.fps) args.push('--fps', String(options.fps))
  944. if (options.volume !== undefined) args.push('--volume', String(options.volume))
  945. const audioScreen = getAudioScreen()
  946. if (audioScreen) args.push('--audio-screen', audioScreen)
  947. const ambientVolume = getAmbientVolume()
  948. if (ambientVolume !== null) args.push('--ambient-volume', String(ambientVolume))
  949. const leds = getLeds()
  950. if (leds.enabled && supportsFlag('--leds-server')) {
  951. args.push('--leds-server', validLedServer(leds.server), '--leds-brightness', String(leds.brightness))
  952. if (!leds.boost) args.push('--leds-no-boost')
  953. if (leds.reduceFps) args.push('--leds-reduce-fps')
  954. }
  955. if (getDisablePuppetAnimation()) args.push('--render-debug', 'no-puppet-animation')
  956. const flags = options.engineFlags ?? {}
  957. if (flags.disableAnimations && supportsDisableAnimations()) args.push('--disable-animations')
  958. args.push(...filterSupportedArgs(engineFlagArgs(flags), supportsFlag))
  959. if (options.scalingMode) args.push('--scaling', options.scalingMode)
  960. if (options.zoom !== undefined) args.push('--zoom', String(options.zoom))
  961. if (options.offsetX !== undefined || options.offsetY !== undefined) {
  962. args.push('--offset', `${options.offsetX ?? 0},${options.offsetY ?? 0}`)
  963. }
  964. if (options.disableParallax) args.push('--disable-parallax')
  965. if (options.expandCanvas && supportsExpandCanvas()) args.push('--expand-canvas')
  966. if (options.repairAssets && supportsFlag('--repair-assets')) args.push('--repair-assets')
  967. if (options.cornerColor) args.push('--corner-color', options.cornerColor)
  968. if (options.speed !== undefined) args.push('--speed', String(options.speed))
  969. const segments = options.videoSegments ?? []
  970. if (segments.length > 0 && supportsFlag('--video-segments')) {
  971. args.push('--video-segments', formatVideoSegments(segments))
  972. } else if (segments.length === 1 && supportsFlag('--video-start')) {
  973. // fallback for engines without --video-segments
  974. args.push('--video-start', String(segments[0].start))
  975. if (segments[0].end !== undefined) args.push('--video-end', String(segments[0].end))
  976. }
  977. if ((options.disabledObjects?.length || options.enabledObjects?.length) && supportsObjectFlags()) {
  978. for (const id of options.disabledObjects ?? []) args.push('--disable-object', id)
  979. for (const id of options.enabledObjects ?? []) args.push('--enable-object', id)
  980. }
  981. if ((options.disabledEffects?.length || options.enabledEffects?.length) && supportsEffectFlags()) {
  982. for (const id of options.disabledEffects ?? []) args.push('--disable-effect', id)
  983. for (const id of options.enabledEffects ?? []) args.push('--enable-effect', id)
  984. }
  985. for (const [name, value] of Object.entries(options.propertyOverrides ?? {})) {
  986. args.push('--set-property', `${name}=${value}`)
  987. }
  988. if (supportsAudioSensitivity()) {
  989. // the engine prefers a specific id over "*", so both are always sent
  990. const defaultSensitivity = getDefaultAudioSensitivity()
  991. if (defaultSensitivity !== 1) args.push('--audio-sensitivity', `*=${defaultSensitivity}`)
  992. for (const [id, multiplier] of Object.entries(options.audioSensitivity ?? {})) {
  993. args.push('--audio-sensitivity', `${id}=${multiplier}`)
  994. }
  995. }
  996. if (supportsSoundVolume()) {
  997. for (const [id, volume] of Object.entries(options.soundVolume ?? {})) {
  998. args.push('--sound-volume', `${id}=${volume}`)
  999. }
  1000. }
  1001. if (options.customArgs?.trim()) {
  1002. args.push(...parseCustomArgs(options.customArgs))
  1003. }
  1004. if (capture) {
  1005. args.push('--screenshot', capture.screenshotPath, '--screenshot-delay', String(capture.delayFrames))
  1006. }
  1007. args.push(wallpaperPath)
  1008. return args
  1009. }
  1010. function getControlFilePath(): string {
  1011. return path.join(getXdgRuntimeDir(), 'lwe-control')
  1012. }
  1013. function screenFileSuffix(screen: ScreenTarget): string {
  1014. return screen === ALL_SCREENS ? 'all' : screen.replace(/[^A-Za-z0-9._-]/g, '_')
  1015. }
  1016. /** One hotswap file per engine so engines can't read each other's */
  1017. function controlFileFor(screen: ScreenTarget): string {
  1018. return path.join(getXdgRuntimeDir(), `lwe-control-${screenFileSuffix(screen)}`)
  1019. }
  1020. /** Mouse button state written by a desktop shell (--input-file) */
  1021. function inputFileFor(screen: ScreenTarget): string {
  1022. return path.join(getXdgRuntimeDir(), `lwe-input-${screenFileSuffix(screen)}`)
  1023. }
  1024. function supportsInputFile(): boolean {
  1025. return isWaylandSession() && supportsFlag('--input-file')
  1026. }
  1027. export function listInputFiles(screens: string[]): { screen: ScreenTarget; path: string }[] {
  1028. if (!supportsInputFile()) return []
  1029. return [ALL_SCREENS, ...screens].map((screen) => ({ screen, path: inputFileFor(screen) }))
  1030. }
  1031. /** Engines outlive the app, so they are recorded here and adopted after a restart */
  1032. function getInstancesFilePath(): string {
  1033. return path.join(getXdgRuntimeDir(), 'lwe-instances.json')
  1034. }
  1035. function getLegacyPidFilePath(): string {
  1036. return path.join(getXdgRuntimeDir(), 'lwe-pid')
  1037. }
  1038. interface LweInstance {
  1039. screen: ScreenTarget
  1040. pid: number
  1041. /** null for a process adopted from a previous run */
  1042. child: ChildProcess | null
  1043. wallpaperPath: string
  1044. launchKey: string
  1045. /** wallpaperPath is only the first slot's */
  1046. split: boolean
  1047. startedAt: number
  1048. swappedAt: number | null
  1049. stopping: boolean
  1050. log: string[]
  1051. /** everything the engine printed since the launch, up to HISTORY_LINES_KEPT */
  1052. history: string[]
  1053. /** null: the engine reads the shared control file */
  1054. controlFile: string | null
  1055. /** Flatpak: the run whose sandbox the engine lives in, and its host pid */
  1056. sandbox: string | null
  1057. hostPid: number | null
  1058. }
  1059. export interface LweExitInfo {
  1060. screen: ScreenTarget
  1061. wallpaperPath: string
  1062. split: boolean
  1063. crashed: boolean
  1064. phase: CrashPhase
  1065. description: string
  1066. log: string[]
  1067. }
  1068. const instances = new Map<ScreenTarget, LweInstance>()
  1069. let instancesLoaded = false
  1070. let adoptedPoll: ReturnType<typeof setInterval> | null = null
  1071. const exitListeners = new Set<(info: LweExitInfo) => void>()
  1072. const LOG_LINES_KEPT = 60
  1073. const HISTORY_LINES_KEPT = 5000
  1074. let diagnosticStats = false
  1075. let engineRenderer: string | undefined
  1076. // a crash this soon after a launch or hotswap is blamed on it
  1077. const CRASH_WINDOW_MS = 20_000
  1078. const CRASH_SIGNALS = new Set(['SIGSEGV', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGILL', 'SIGTRAP'])
  1079. const launchListeners = new Set<() => void>()
  1080. export function onLweLaunched(cb: () => void): () => void {
  1081. launchListeners.add(cb)
  1082. return () => launchListeners.delete(cb)
  1083. }
  1084. export function onLweExit(cb: (info: LweExitInfo) => void): () => void {
  1085. exitListeners.add(cb)
  1086. return () => exitListeners.delete(cb)
  1087. }
  1088. function persistInstances(): void {
  1089. const entries = [...instances.values()].map((i) => ({
  1090. screen: i.screen,
  1091. pid: i.pid,
  1092. wallpaperPath: i.wallpaperPath,
  1093. launchKey: i.launchKey,
  1094. split: i.split,
  1095. startedAt: i.startedAt,
  1096. controlFile: i.controlFile,
  1097. sandbox: i.sandbox,
  1098. hostPid: i.hostPid
  1099. }))
  1100. try {
  1101. if (entries.length === 0) fs.rmSync(getInstancesFilePath(), { force: true })
  1102. else fs.writeFileSync(getInstancesFilePath(), JSON.stringify(entries))
  1103. fs.rmSync(getLegacyPidFilePath(), { force: true })
  1104. } catch (err) {
  1105. console.error('[LWE] Failed to write instances file:', err)
  1106. }
  1107. }
  1108. /** Alive and still a linux-wallpaperengine process, not a recycled pid */
  1109. function isLweProcess(pid: number): boolean {
  1110. try {
  1111. process.kill(pid, 0)
  1112. } catch {
  1113. return false
  1114. }
  1115. try {
  1116. const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8')
  1117. return isLweCommandLine(cmdline)
  1118. } catch {
  1119. // /proc unreadable, it is alive at least
  1120. return true
  1121. }
  1122. }
  1123. /** Engines of an earlier Flatpak run live in another pid namespace, only reachable through the host */
  1124. function inOtherSandbox(inst: Pick<LweInstance, 'sandbox'>): boolean {
  1125. return isFlatpak() && inst.sandbox !== (flatpakInstanceId() ?? null)
  1126. }
  1127. const hostAliveCache = new Map<number, { alive: boolean; at: number }>()
  1128. // kept fresh by the adopted-engine poll so status queries rarely wait on flatpak-spawn
  1129. const HOST_ALIVE_TTL_MS = 5000
  1130. function rememberHostAlive(hostPid: number, cmdline: string | null | undefined): boolean {
  1131. // undefined: the host couldn't be asked
  1132. const alive = cmdline === undefined ? (hostAliveCache.get(hostPid)?.alive ?? true) : !!cmdline && isLweCommandLine(cmdline)
  1133. hostAliveCache.set(hostPid, { alive, at: Date.now() })
  1134. return alive
  1135. }
  1136. function isEngineAlive(inst: Pick<LweInstance, 'pid' | 'sandbox' | 'hostPid'>): boolean {
  1137. if (!inOtherSandbox(inst)) return isLweProcess(inst.pid)
  1138. if (inst.hostPid === null) return false
  1139. const cached = hostAliveCache.get(inst.hostPid)
  1140. if (cached) {
  1141. // a stale answer is refreshed in the background instead of blocking the main process
  1142. if (Date.now() - cached.at >= HOST_ALIVE_TTL_MS) void isEngineAliveAsync(inst)
  1143. return cached.alive
  1144. }
  1145. return rememberHostAlive(inst.hostPid, hostProcessCommandLine(inst.hostPid))
  1146. }
  1147. async function isEngineAliveAsync(inst: Pick<LweInstance, 'pid' | 'sandbox' | 'hostPid'>): Promise<boolean> {
  1148. if (!inOtherSandbox(inst)) return isLweProcess(inst.pid)
  1149. if (inst.hostPid === null) return false
  1150. return rememberHostAlive(inst.hostPid, await hostProcessCommandLineAsync(inst.hostPid))
  1151. }
  1152. function signalEngine(inst: Pick<LweInstance, 'pid' | 'sandbox' | 'hostPid'>, signal: NodeJS.Signals): void {
  1153. if (!inOtherSandbox(inst)) {
  1154. process.kill(inst.pid, signal)
  1155. return
  1156. }
  1157. if (inst.hostPid === null) throw new Error('engine of an earlier Flatpak run without a known host pid')
  1158. hostAliveCache.delete(inst.hostPid)
  1159. killHostProcess(inst.hostPid, signal)
  1160. }
  1161. function adopt(
  1162. screen: ScreenTarget,
  1163. pid: number,
  1164. wallpaperPath: string,
  1165. key: string,
  1166. split: boolean,
  1167. startedAt: number,
  1168. controlFile: string | null,
  1169. sandbox: string | null,
  1170. hostPid: number | null
  1171. ): void {
  1172. if (!Number.isInteger(pid) || !isEngineAlive({ pid, sandbox, hostPid })) return
  1173. instances.set(screen, {
  1174. screen,
  1175. pid,
  1176. child: null,
  1177. wallpaperPath,
  1178. launchKey: key,
  1179. split,
  1180. startedAt,
  1181. swappedAt: null,
  1182. stopping: false,
  1183. log: [],
  1184. history: [],
  1185. controlFile,
  1186. sandbox,
  1187. hostPid
  1188. })
  1189. }
  1190. interface InstanceEntry {
  1191. screen: string
  1192. pid: number
  1193. wallpaperPath: string
  1194. launchKey: string
  1195. split?: boolean
  1196. startedAt: number
  1197. controlFile?: string | null
  1198. sandbox?: string | null
  1199. hostPid?: number | null
  1200. }
  1201. function readInstanceEntries(): InstanceEntry[] {
  1202. try {
  1203. return JSON.parse(fs.readFileSync(getInstancesFilePath(), 'utf8')) as InstanceEntry[]
  1204. } catch {
  1205. return []
  1206. }
  1207. }
  1208. /** Asks the host about engines of an earlier Flatpak run before they are loaded, so loading doesn't block */
  1209. export async function checkEarlierRunEngines(): Promise<void> {
  1210. if (instancesLoaded || !isFlatpak()) return
  1211. await Promise.all(
  1212. readInstanceEntries()
  1213. .map((e) => ({ pid: e.pid, sandbox: e.sandbox ?? null, hostPid: e.hostPid ?? null }))
  1214. .filter((e) => inOtherSandbox(e) && e.hostPid !== null)
  1215. .map((e) => isEngineAliveAsync(e))
  1216. )
  1217. }
  1218. function loadInstances(): void {
  1219. if (instancesLoaded) return
  1220. instancesLoaded = true
  1221. try {
  1222. for (const e of readInstanceEntries()) {
  1223. adopt(e.screen, e.pid, e.wallpaperPath, e.launchKey, !!e.split, e.startedAt, e.controlFile ?? null, e.sandbox ?? null,
  1224. e.hostPid ?? null)
  1225. }
  1226. } catch { /* written by an older version */ }
  1227. try {
  1228. const legacyPid = parseInt(fs.readFileSync(getLegacyPidFilePath(), 'utf8').trim(), 10)
  1229. if (!instances.has(ALL_SCREENS)) adopt(ALL_SCREENS, legacyPid, '', '', false, Date.now(), null, null, null)
  1230. } catch { /* no legacy pid file */ }
  1231. persistInstances()
  1232. watchAdoptedInstances()
  1233. }
  1234. // Node only reports exits of its own children, adopted ones are polled
  1235. function watchAdoptedInstances(): void {
  1236. if (adoptedPoll) return
  1237. let polling = false
  1238. adoptedPoll = setInterval(async () => {
  1239. if (polling) return
  1240. polling = true
  1241. let adopted = 0
  1242. try {
  1243. for (const inst of instances.values()) {
  1244. if (inst.child) continue
  1245. adopted++
  1246. if (await isEngineAliveAsync(inst)) continue
  1247. // replaced or stopped while the host was asked
  1248. if (instances.get(inst.screen) !== inst) continue
  1249. instances.delete(inst.screen)
  1250. persistInstances()
  1251. if (!inst.stopping) {
  1252. // no exit status, a crash can't be told from a kill
  1253. emitExit(inst, false, 'exited while the app was not watching it')
  1254. }
  1255. }
  1256. } finally {
  1257. polling = false
  1258. }
  1259. if (adopted === 0 && adoptedPoll) {
  1260. clearInterval(adoptedPoll)
  1261. adoptedPoll = null
  1262. }
  1263. }, 3000)
  1264. }
  1265. function crashPhase(inst: LweInstance): CrashPhase {
  1266. const now = Date.now()
  1267. if (inst.swappedAt !== null && now - inst.swappedAt < CRASH_WINDOW_MS) return 'hotswap'
  1268. if (now - inst.startedAt < CRASH_WINDOW_MS) return 'launch'
  1269. return 'runtime'
  1270. }
  1271. function emitExit(inst: LweInstance, crashed: boolean, description: string): void {
  1272. const info: LweExitInfo = {
  1273. screen: inst.screen,
  1274. wallpaperPath: inst.wallpaperPath,
  1275. split: inst.split,
  1276. crashed,
  1277. phase: crashPhase(inst),
  1278. description,
  1279. log: [...inst.log]
  1280. }
  1281. for (const cb of exitListeners) cb(info)
  1282. }
  1283. function liveInstance(screen: ScreenTarget): LweInstance | undefined {
  1284. loadInstances()
  1285. const inst = instances.get(screen)
  1286. if (!inst) return undefined
  1287. if (inst.child ? inst.child.exitCode === null && inst.child.signalCode === null : isEngineAlive(inst)) return inst
  1288. instances.delete(screen)
  1289. persistInstances()
  1290. return undefined
  1291. }
  1292. function liveInstances(): LweInstance[] {
  1293. loadInstances()
  1294. return [...instances.keys()].map(liveInstance).filter((i): i is LweInstance => !!i)
  1295. }
  1296. export interface RunningInstance {
  1297. screen: ScreenTarget
  1298. wallpaperPath: string
  1299. split: boolean
  1300. pid: number
  1301. startedAt: number
  1302. swappedAt: number | null
  1303. }
  1304. export function getRunningInstances(): RunningInstance[] {
  1305. return liveInstances().map(({ screen, wallpaperPath, split, pid, startedAt, swappedAt }) => ({
  1306. screen,
  1307. wallpaperPath,
  1308. split,
  1309. pid,
  1310. startedAt,
  1311. swappedAt
  1312. }))
  1313. }
  1314. /** Engines started while this is on print per-frame timings (LWE_FRAME_STATS), which costs some speed */
  1315. export function setDiagnosticStats(on: boolean): void {
  1316. diagnosticStats = on
  1317. }
  1318. /** The GL renderer the last engine reported, undefined before one did or for engines that don't say */
  1319. export function getEngineRenderer(): string | undefined {
  1320. return engineRenderer
  1321. }
  1322. export interface EngineHistory {
  1323. screen: ScreenTarget
  1324. wallpaperPath: string
  1325. pid: number
  1326. startedAt: number
  1327. lines: string[]
  1328. }
  1329. /** What the live engines printed since they started, adopted ones have no output */
  1330. export function getEngineHistory(): EngineHistory[] {
  1331. return liveInstances().map(({ screen, wallpaperPath, pid, startedAt, history }) => ({
  1332. screen,
  1333. wallpaperPath,
  1334. pid,
  1335. startedAt,
  1336. lines: [...history]
  1337. }))
  1338. }
  1339. function supportsEffectHotswap(): boolean {
  1340. return supportsFlag('effects=1')
  1341. }
  1342. function supportsAnimationHotswap(): boolean {
  1343. return supportsFlag('disable-animations=on')
  1344. }
  1345. function supportsHwdecHotswap(): boolean {
  1346. return supportsFlag('hwdec=<backend>')
  1347. }
  1348. function supportsHrtfHotswap(): boolean {
  1349. return supportsFlag('hrtf=<mode>')
  1350. }
  1351. function supportsTransitionHotswap(): boolean {
  1352. return supportsFlag('transition=<kind>')
  1353. }
  1354. function supportsPowerHotswap(): boolean {
  1355. return supportsFlag('fps-battery=<fps|off>') && supportsFlag('idle-pause=<minutes>')
  1356. }
  1357. // what a hotswap can't change, a differing engine is restarted
  1358. function launchKey(options: LweLaunchOptions): string {
  1359. const flags = options.engineFlags ?? {}
  1360. return JSON.stringify({
  1361. // a hotswap would put its wallpaper into every slot
  1362. split: options.split ?? null,
  1363. customArgs: options.customArgs?.trim() ?? '',
  1364. disabledEffects: supportsEffectHotswap() ? [] : (options.disabledEffects ?? []),
  1365. enabledEffects: supportsEffectHotswap() ? [] : (options.enabledEffects ?? []),
  1366. disableAnimations: supportsAnimationHotswap() ? false : !!flags.disableAnimations,
  1367. flags: engineFlagArgs({
  1368. ...flags,
  1369. ...(supportsHwdecHotswap() ? { hwdec: undefined } : {}),
  1370. ...(supportsHrtfHotswap() ? { hrtf: undefined } : {}),
  1371. ...(supportsTransitionHotswap() ? { transition: undefined, transitionDuration: undefined } : {}),
  1372. ...(supportsPowerHotswap() ? { batteryFps: undefined, idlePause: undefined } : {})
  1373. })
  1374. })
  1375. }
  1376. export interface HotswapOptions {
  1377. path?: string
  1378. disabledObjects?: string[]
  1379. enabledObjects?: string[]
  1380. volume?: number
  1381. fps?: number
  1382. xray?: XrayMode
  1383. scaling?: string
  1384. zoom?: number
  1385. offsetX?: number
  1386. offsetY?: number
  1387. disableParallax?: boolean
  1388. expandCanvas?: boolean
  1389. repairAssets?: boolean
  1390. cornerColor?: string
  1391. imageAdjustments?: ImageAdjustments
  1392. speed?: number
  1393. videoSegments?: VideoSegment[]
  1394. /** Video seek in seconds */
  1395. videoSeek?: number
  1396. propertyOverrides?: Record<string, string>
  1397. /** Empty string = every screen can produce audio */
  1398. audioScreen?: string
  1399. ambientVolume?: number
  1400. /** Object id or "*" -> multiplier */
  1401. audioSensitivity?: Record<string, number>
  1402. /** Sound object id -> volume (0-1) */
  1403. soundVolume?: Record<string, number>
  1404. /** Either being present replaces the engine's effect lists */
  1405. disabledEffects?: string[]
  1406. enabledEffects?: string[]
  1407. disableAnimations?: boolean
  1408. hwdec?: HwdecBackend
  1409. hrtf?: HrtfMode
  1410. transition?: TransitionMode
  1411. transitionDuration?: TransitionDuration
  1412. batteryFps?: BatteryFps
  1413. idlePause?: IdlePause
  1414. }
  1415. /** Object lists replace the engine's when present (even empty). Every property key is sent */
  1416. export function buildHotswapLines(options: HotswapOptions): string[] {
  1417. const lines: string[] = []
  1418. if (options.path !== undefined) lines.push(`path=${options.path}`)
  1419. if (options.disabledObjects !== undefined || options.enabledObjects !== undefined) {
  1420. lines.push('layers=1')
  1421. for (const id of options.disabledObjects ?? []) lines.push(`disable-object=${id}`)
  1422. for (const id of options.enabledObjects ?? []) lines.push(`enable-object=${id}`)
  1423. }
  1424. if (options.disabledEffects !== undefined || options.enabledEffects !== undefined) {
  1425. lines.push('effects=1')
  1426. for (const id of options.disabledEffects ?? []) lines.push(`disable-effect=${id}`)
  1427. for (const id of options.enabledEffects ?? []) lines.push(`enable-effect=${id}`)
  1428. }
  1429. if (options.disableAnimations !== undefined) lines.push(`disable-animations=${options.disableAnimations ? 'on' : 'off'}`)
  1430. if (options.hwdec !== undefined) lines.push(`hwdec=${options.hwdec}`)
  1431. if (options.hrtf !== undefined) lines.push(`hrtf=${options.hrtf}`)
  1432. if (options.transition !== undefined) lines.push(`transition=${options.transition}`)
  1433. if (options.transitionDuration !== undefined) lines.push(`transition-duration=${options.transitionDuration}`)
  1434. if (options.batteryFps !== undefined) lines.push(`fps-battery=${options.batteryFps}`)
  1435. if (options.idlePause !== undefined) lines.push(`idle-pause=${options.idlePause}`)
  1436. if (options.volume !== undefined) lines.push(`volume=${options.volume}`)
  1437. if (options.fps !== undefined) lines.push(`fps=${options.fps}`)
  1438. // on/off keeps engines without the disabled mode working
  1439. if (options.xray !== undefined) {
  1440. lines.push(`xray=${options.xray === 'full' ? 'on' : options.xray === 'normal' ? 'off' : options.xray}`)
  1441. }
  1442. if (options.scaling !== undefined) lines.push(`scaling=${options.scaling}`)
  1443. if (options.zoom !== undefined) lines.push(`zoom=${options.zoom}`)
  1444. if (options.offsetX !== undefined || options.offsetY !== undefined) {
  1445. lines.push(`offset=${options.offsetX ?? 0},${options.offsetY ?? 0}`)
  1446. }
  1447. if (options.disableParallax !== undefined) lines.push(`disable-parallax=${options.disableParallax ? 'on' : 'off'}`)
  1448. if (options.expandCanvas !== undefined) lines.push(`expand-canvas=${options.expandCanvas ? 'on' : 'off'}`)
  1449. if (options.repairAssets !== undefined && supportsFlag('--repair-assets')) {
  1450. lines.push(`repair-assets=${options.repairAssets ? 'on' : 'off'}`)
  1451. }
  1452. if (options.cornerColor !== undefined) lines.push(`corner-color=${options.cornerColor}`)
  1453. lines.push(...imageAdjustmentLines(options.imageAdjustments))
  1454. if (options.speed !== undefined) lines.push(`speed=${options.speed}`)
  1455. if (options.videoSegments !== undefined) {
  1456. lines.push(`video-segments=${options.videoSegments.length ? formatVideoSegments(options.videoSegments) : 'none'}`)
  1457. }
  1458. if (options.videoSeek !== undefined) lines.push(`video-seek=${options.videoSeek}`)
  1459. if (options.audioScreen !== undefined) lines.push(`audio-screen=${options.audioScreen}`)
  1460. if (options.ambientVolume !== undefined) lines.push(`ambient-volume=${options.ambientVolume}`)
  1461. for (const [name, value] of Object.entries(options.propertyOverrides ?? {})) {
  1462. lines.push(`property=${name}=${value}`)
  1463. }
  1464. for (const [id, multiplier] of Object.entries(options.audioSensitivity ?? {})) {
  1465. lines.push(`audio-sensitivity=${id}=${multiplier}`)
  1466. }
  1467. for (const [id, volume] of Object.entries(options.soundVolume ?? {})) {
  1468. lines.push(`sound-volume=${id}=${volume}`)
  1469. }
  1470. const whole = lines.filter((line) => !/[\r\n]/.test(line))
  1471. if (whole.length !== lines.length) console.warn('[LWE] Left out control lines holding a line break')
  1472. return whole
  1473. }
  1474. // engines sharing the control file must read a request before the next overwrites it
  1475. const HOTSWAP_SETTLE_MS = 1000
  1476. let lastSignal: { pid: number; at: number; file: string } | null = null
  1477. let signalQueue: Promise<unknown> = Promise.resolve()
  1478. function signalInstance(inst: LweInstance, lines: string[]): Promise<boolean> {
  1479. const file = inst.controlFile ?? getControlFilePath()
  1480. const send = async (): Promise<boolean> => {
  1481. if (lastSignal && lastSignal.pid !== inst.pid && lastSignal.file === file) {
  1482. const wait = lastSignal.at + HOTSWAP_SETTLE_MS - Date.now()
  1483. if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait))
  1484. }
  1485. try {
  1486. fs.writeFileSync(file, lines.join('\n') + '\n')
  1487. signalEngine(inst, 'SIGUSR1')
  1488. lastSignal = { pid: inst.pid, at: Date.now(), file }
  1489. console.log(`[LWE] Hotswap sent to ${inst.screen}:`, lines.join(' '))
  1490. return true
  1491. } catch (err) {
  1492. console.error('[LWE] Hotswap failed:', err)
  1493. return false
  1494. }
  1495. }
  1496. const result = signalQueue.then(send, send)
  1497. signalQueue = result
  1498. return result
  1499. }
  1500. /**
  1501. * One change per call, engines hold a single pending request. Targets the screens, else engines showing
  1502. * `wallpaperPath`, else all. xray has no launch flag, so it always goes here.
  1503. */
  1504. export async function hotswapLweSettings(
  1505. options: HotswapOptions,
  1506. target: { screens?: ScreenTarget[]; wallpaperPath?: string } = {}
  1507. ): Promise<boolean> {
  1508. const lines = buildHotswapLines(options)
  1509. if (lines.length === 0) return false
  1510. let targets = liveInstances()
  1511. if (target.screens) targets = targets.filter((i) => target.screens!.includes(i.screen))
  1512. else if (target.wallpaperPath) targets = targets.filter((i) => i.wallpaperPath === target.wallpaperPath)
  1513. if (targets.length === 0) return false
  1514. let sent = false
  1515. for (const inst of targets) {
  1516. // a split screen's engine runs its first slot's wallpaper, settings for it go only there
  1517. if (!(await signalInstance(inst, inst.split ? [`screen=${inst.screen}#1`, ...lines] : lines))) continue
  1518. sent = true
  1519. if (options.path !== undefined) {
  1520. inst.wallpaperPath = options.path
  1521. inst.swappedAt = Date.now()
  1522. }
  1523. }
  1524. if (sent && options.path !== undefined) persistInstances()
  1525. return sent
  1526. }
  1527. export function liveEngineFlagOptions(
  1528. flags: EngineFlags
  1529. ): Pick<HotswapOptions, 'hwdec' | 'hrtf' | 'transition' | 'transitionDuration' | 'batteryFps' | 'idlePause'> {
  1530. return {
  1531. ...(supportsHwdecHotswap() ? { hwdec: flags.hwdec ?? 'auto' } : {}),
  1532. ...(supportsHrtfHotswap() ? { hrtf: flags.hrtf ?? 'auto' } : {}),
  1533. ...(supportsTransitionHotswap()
  1534. ? { transition: flags.transition ?? 'none', transitionDuration: flags.transitionDuration ?? '600' }
  1535. : {}),
  1536. ...(supportsPowerHotswap() ? { batteryFps: flags.batteryFps ?? 'off', idlePause: flags.idlePause ?? 'off' } : {})
  1537. }
  1538. }
  1539. function hotswapOptionsFor(wallpaperPath: string, options: LweLaunchOptions): HotswapOptions {
  1540. const defaultSensitivity = getDefaultAudioSensitivity()
  1541. return {
  1542. path: wallpaperPath,
  1543. // a path swap drops the previous wallpaper's overrides
  1544. disabledObjects: options.disabledObjects ?? [],
  1545. enabledObjects: options.enabledObjects ?? [],
  1546. fps: options.fps ?? DEFAULT_LWE_FPS,
  1547. xray: options.xrayMode,
  1548. scaling: options.scalingMode ?? 'default',
  1549. zoom: options.zoom ?? 1,
  1550. offsetX: options.offsetX ?? 0,
  1551. offsetY: options.offsetY ?? 0,
  1552. disableParallax: options.disableParallax ?? false,
  1553. expandCanvas: options.expandCanvas ?? false,
  1554. repairAssets: options.repairAssets ?? false,
  1555. cornerColor: options.cornerColor ?? '000000',
  1556. imageAdjustments: options.imageAdjustments,
  1557. speed: options.speed ?? 1,
  1558. // a path swap drops the trim
  1559. videoSegments: options.videoSegments?.length ? options.videoSegments : undefined,
  1560. propertyOverrides: options.propertyOverrides ?? {},
  1561. audioSensitivity: {
  1562. ...(defaultSensitivity !== 1 ? { '*': defaultSensitivity } : {}),
  1563. ...options.audioSensitivity
  1564. },
  1565. soundVolume: options.soundVolume ?? {},
  1566. ...(supportsEffectHotswap()
  1567. ? { disabledEffects: options.disabledEffects ?? [], enabledEffects: options.enabledEffects ?? [] }
  1568. : {}),
  1569. ...(supportsAnimationHotswap() ? { disableAnimations: !!options.engineFlags?.disableAnimations } : {}),
  1570. ...liveEngineFlagOptions(options.engineFlags ?? {})
  1571. }
  1572. }
  1573. /** Hotswaps the engine on the screen when possible, else restarts it. Resolves once it survived 2s */
  1574. export async function launchLweAsync(wallpaperPath: string, options: LweLaunchOptions = {}): Promise<void> {
  1575. const screen = options.screen ?? ALL_SCREENS
  1576. const key = launchKey(options)
  1577. // an all-screens engine and per-screen ones would overlap
  1578. for (const inst of liveInstances()) {
  1579. if ((screen === ALL_SCREENS) !== (inst.screen === ALL_SCREENS)) await stopLwe(inst.screen)
  1580. }
  1581. const existing = liveInstance(screen)
  1582. const canHotswap =
  1583. existing &&
  1584. !options.forceFresh &&
  1585. !options.customArgs?.trim() &&
  1586. existing.launchKey === key &&
  1587. (existing.controlFile !== null || liveInstances().length === 1)
  1588. if (canHotswap && (await hotswapLweSettings(hotswapOptionsFor(wallpaperPath, options), { screens: [screen] }))) {
  1589. return
  1590. }
  1591. await stopLwe(screen)
  1592. const binaryPath = getLweBinaryPath()
  1593. const controlFile = supportsFlag('--control-file') ? controlFileFor(screen) : null
  1594. const inputFile = supportsInputFile() ? inputFileFor(screen) : null
  1595. const lweArgs = [
  1596. ...(controlFile ? ['--control-file', controlFile] : []),
  1597. ...(inputFile ? ['--input-file', inputFile] : []),
  1598. ...buildLweArgs(wallpaperPath, options)
  1599. ]
  1600. const envVars = buildLweEnvVars()
  1601. // spawn's env option can lose vars with detached
  1602. const spawnArgs = [...envVars, binaryPath, ...lweArgs]
  1603. console.log('[LWE] Binary:', binaryPath)
  1604. console.log('[LWE] Args:', lweArgs.join(' '))
  1605. console.log('[LWE] Env:', envVars.join(' '))
  1606. return new Promise((resolve, reject) => {
  1607. const child = spawn('env', spawnArgs, {
  1608. stdio: ['ignore', 'pipe', 'pipe'],
  1609. detached: true
  1610. })
  1611. const inst: LweInstance = {
  1612. screen,
  1613. pid: child.pid ?? -1,
  1614. child,
  1615. wallpaperPath,
  1616. launchKey: key,
  1617. split: !!options.split,
  1618. startedAt: Date.now(),
  1619. swappedAt: null,
  1620. stopping: false,
  1621. log: [],
  1622. history: [],
  1623. controlFile,
  1624. sandbox: flatpakInstanceId() ?? null,
  1625. hostPid: null
  1626. }
  1627. if (child.pid !== undefined) {
  1628. instances.set(screen, inst)
  1629. persistInstances()
  1630. if (isFlatpak()) {
  1631. void hostPidOf(child.pid).then((hostPid) => {
  1632. if (hostPid === undefined || instances.get(screen) !== inst) return
  1633. inst.hostPid = hostPid
  1634. persistInstances()
  1635. })
  1636. }
  1637. }
  1638. const collect = (stream: 'stdout' | 'stderr') => (chunk: Buffer) => {
  1639. const msg = chunk.toString('utf8').trim()
  1640. if (!msg) return
  1641. console.log(`[LWE ${stream}]`, msg)
  1642. inst.log.push(...msg.split('\n'))
  1643. if (inst.log.length > LOG_LINES_KEPT) inst.log.splice(0, inst.log.length - LOG_LINES_KEPT)
  1644. const renderer = /OpenGL renderer: (.+)/.exec(msg)
  1645. if (renderer) engineRenderer = renderer[1]
  1646. inst.history.push(...msg.split('\n'))
  1647. if (inst.history.length > HISTORY_LINES_KEPT) inst.history.splice(0, inst.history.length - HISTORY_LINES_KEPT)
  1648. }
  1649. child.stdout?.on('data', collect('stdout'))
  1650. child.stderr?.on('data', collect('stderr'))
  1651. let settled = false
  1652. child.on('exit', (code, signal) => {
  1653. // the old process's exit can arrive after its replacement registered
  1654. const current = instances.get(screen) === inst
  1655. if (current) {
  1656. instances.delete(screen)
  1657. persistInstances()
  1658. }
  1659. const crashed = (signal !== null && CRASH_SIGNALS.has(signal)) || (code !== null && code !== 0)
  1660. const description = signal ? `killed by ${signal}` : `exit code ${code}`
  1661. if (!settled) {
  1662. settled = true
  1663. if (crashed) {
  1664. const msg = inst.log.length ? inst.log.slice(-3).join('\n') : description
  1665. reject(new Error(`linux-wallpaperengine failed: ${msg}`))
  1666. } else {
  1667. resolve()
  1668. }
  1669. }
  1670. if (current && !inst.stopping) emitExit(inst, crashed, description)
  1671. })
  1672. child.on('error', (err) => {
  1673. if (instances.get(screen) === inst) {
  1674. instances.delete(screen)
  1675. persistInstances()
  1676. }
  1677. if (!settled) {
  1678. settled = true
  1679. reject(err)
  1680. }
  1681. })
  1682. child.unref()
  1683. setTimeout(() => {
  1684. if (!settled && instances.get(screen) === inst && child.exitCode === null) {
  1685. settled = true
  1686. for (const cb of launchListeners) cb()
  1687. if (options.xrayMode && options.xrayMode !== 'normal') {
  1688. void hotswapLweSettings({ xray: options.xrayMode }, { screens: [screen] })
  1689. }
  1690. resolve()
  1691. }
  1692. }, 2000)
  1693. })
  1694. }
  1695. // " 123 - Layer Name (image)"
  1696. const OBJECT_LINE_RE = /^\s*(\S+)\s-\s(.*)\s\((image|particle|text|sound|unknown)\)\s*$/
  1697. function parseLweObjectList(output: string): LweSceneObject[] {
  1698. const objects: LweSceneObject[] = []
  1699. for (const line of output.split('\n')) {
  1700. const m = line.match(OBJECT_LINE_RE)
  1701. if (m) objects.push({ id: m[1], name: m[2], type: m[3] as LweSceneObject['type'] })
  1702. }
  1703. return objects
  1704. }
  1705. export async function listLweObjects(wallpaperPath: string): Promise<LweSceneObject[]> {
  1706. const status = getLweStatus()
  1707. if (!status.installed) throw new Error('linux-wallpaperengine is not installed.')
  1708. // older builds ignore unknown flags and render instead of exiting
  1709. if (!supportsObjectFlags()) return []
  1710. const binaryPath = getLweBinaryPath()
  1711. const args = ['--list-objects']
  1712. const assetsDir = findWeAssetsDir()
  1713. if (assetsDir) args.push('--assets-dir', assetsDir)
  1714. args.push(wallpaperPath)
  1715. const envVars = buildLweEnvVars()
  1716. try {
  1717. const { stdout } = await execFileAsync('env', [...envVars, binaryPath, ...args], {
  1718. timeout: 15_000,
  1719. maxBuffer: 5 * 1024 * 1024,
  1720. encoding: 'utf8'
  1721. })
  1722. return parseLweObjectList(stdout)
  1723. } catch (err) {
  1724. const e = err as Error & { stdout?: string; stderr?: string }
  1725. const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
  1726. throw new Error(`Failed to list wallpaper objects: ${msg}`, { cause: err })
  1727. }
  1728. }
  1729. export async function listLweFonts(wallpaperPath: string): Promise<LweFontNeed[]> {
  1730. const status = getLweStatus()
  1731. if (!status.installed) return []
  1732. // older builds ignore unknown flags and render the wallpaper instead of exiting
  1733. if (!supportsFlag('--list-fonts')) return []
  1734. const args = ['--list-fonts']
  1735. const assetsDir = findWeAssetsDir()
  1736. if (assetsDir) args.push('--assets-dir', assetsDir)
  1737. args.push(wallpaperPath)
  1738. const { stdout } = await execFileAsync('env', [...buildLweEnvVars(), getLweBinaryPath(), ...args], {
  1739. timeout: 15_000,
  1740. maxBuffer: 5 * 1024 * 1024,
  1741. encoding: 'utf8'
  1742. })
  1743. return parseLweFontList(stdout)
  1744. }
  1745. // ` 42 - Bloom (object=17 objectName="body" group="Lighting")`
  1746. const EFFECT_LINE_RE = /^\s*(\S+)\s-\s(.*)\s\(object=(\S+)\sobjectName="(.*)"\sgroup="(.*)"\)\s*$/
  1747. function parseLweEffectList(output: string): LweSceneEffect[] {
  1748. const effects: LweSceneEffect[] = []
  1749. for (const line of output.split('\n')) {
  1750. const m = line.match(EFFECT_LINE_RE)
  1751. if (m) effects.push({ id: m[1], name: m[2], objectId: m[3], objectName: m[4], group: m[5] })
  1752. }
  1753. return effects
  1754. }
  1755. export async function listLweEffects(wallpaperPath: string): Promise<LweSceneEffect[]> {
  1756. const status = getLweStatus()
  1757. if (!status.installed) throw new Error('linux-wallpaperengine is not installed.')
  1758. // older builds ignore unknown flags and render the wallpaper instead of exiting
  1759. if (!supportsEffectFlags()) return []
  1760. const binaryPath = getLweBinaryPath()
  1761. const args = ['--list-effects']
  1762. const assetsDir = findWeAssetsDir()
  1763. if (assetsDir) args.push('--assets-dir', assetsDir)
  1764. args.push(wallpaperPath)
  1765. const envVars = buildLweEnvVars()
  1766. try {
  1767. const { stdout } = await execFileAsync('env', [...envVars, binaryPath, ...args], {
  1768. timeout: 15_000,
  1769. maxBuffer: 5 * 1024 * 1024,
  1770. encoding: 'utf8'
  1771. })
  1772. return parseLweEffectList(stdout)
  1773. } catch (err) {
  1774. const e = err as Error & { stdout?: string; stderr?: string }
  1775. const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
  1776. throw new Error(`Failed to list wallpaper effects: ${msg}`, { cause: err })
  1777. }
  1778. }
  1779. // " 24 - transbig (scale): minvalue=0.9 maxvalue=1.1 frequency=0 smoothing=10"
  1780. const AUDIO_OBJECT_LINE_RE =
  1781. /^\s*(\S+)\s-\s(.*)\s\((.+)\):\sminvalue=(\S+)\smaxvalue=(\S+)\sfrequency=(\S+)\ssmoothing=(\S+)\s*$/
  1782. function parseLweAudioObjectList(output: string): LweAudioObject[] {
  1783. const objects: LweAudioObject[] = []
  1784. for (const line of output.split('\n')) {
  1785. const m = line.match(AUDIO_OBJECT_LINE_RE)
  1786. if (m) {
  1787. objects.push({
  1788. objectId: m[1],
  1789. objectName: m[2],
  1790. property: m[3],
  1791. minvalue: parseFloat(m[4]),
  1792. maxvalue: parseFloat(m[5]),
  1793. frequency: parseFloat(m[6]),
  1794. smoothing: parseFloat(m[7])
  1795. })
  1796. }
  1797. }
  1798. return objects
  1799. }
  1800. export async function listLweAudioObjects(wallpaperPath: string): Promise<LweAudioObject[]> {
  1801. const status = getLweStatus()
  1802. if (!status.installed) throw new Error('linux-wallpaperengine is not installed.')
  1803. // older builds ignore unknown flags and render instead of exiting
  1804. if (!supportsAudioSensitivity()) return []
  1805. const binaryPath = getLweBinaryPath()
  1806. const args = ['--list-audio-objects']
  1807. const assetsDir = findWeAssetsDir()
  1808. if (assetsDir) args.push('--assets-dir', assetsDir)
  1809. args.push(wallpaperPath)
  1810. const envVars = buildLweEnvVars()
  1811. try {
  1812. const { stdout } = await execFileAsync('env', [...envVars, binaryPath, ...args], {
  1813. timeout: 15_000,
  1814. maxBuffer: 5 * 1024 * 1024,
  1815. encoding: 'utf8'
  1816. })
  1817. return parseLweAudioObjectList(stdout)
  1818. } catch (err) {
  1819. const e = err as Error & { stdout?: string; stderr?: string }
  1820. const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
  1821. throw new Error(`Failed to list audio-reactive objects: ${msg}`, { cause: err })
  1822. }
  1823. }
  1824. // --list-properties output:
  1825. // clock_font - combo
  1826. // Text: ui_clock_font
  1827. // Value: impact
  1828. // Values:
  1829. // segoe ui = ui_clock_font_4
  1830. // combo values can contain spaces, split only on " = "
  1831. const PROPERTY_HEADER_RE =
  1832. /^(\S+) - (slider|boolean|color|combo|text|scene texture|file|textinput|usershortcut)$/
  1833. const PROPERTY_DETAIL_RE = /^\t(Text|Value|Min|Max|Step): (.*)$/
  1834. const PROPERTY_COMBO_OPTION_RE = /^\t\t(.+?) = (.*)$/
  1835. function parseLweProperties(output: string): LweProperty[] {
  1836. const properties: LweProperty[] = []
  1837. let current: LweProperty | null = null
  1838. for (const line of output.split('\n')) {
  1839. const header = line.match(PROPERTY_HEADER_RE)
  1840. if (header) {
  1841. if (current) properties.push(current)
  1842. const type = header[2] === 'scene texture' ? 'scene-texture' : (header[2] as LweProperty['type'])
  1843. current = { name: header[1], type, value: '' }
  1844. continue
  1845. }
  1846. if (!current) continue
  1847. const comboOption = line.match(PROPERTY_COMBO_OPTION_RE)
  1848. if (comboOption) {
  1849. current.options ??= []
  1850. current.options.push({ value: comboOption[1], label: comboOption[2] })
  1851. continue
  1852. }
  1853. const detail = line.match(PROPERTY_DETAIL_RE)
  1854. if (detail) {
  1855. const [, key, value] = detail
  1856. if (key === 'Text') current.text = value
  1857. else if (key === 'Value') current.value = value
  1858. else if (key === 'Min') current.min = parseFloat(value)
  1859. else if (key === 'Max') current.max = parseFloat(value)
  1860. else if (key === 'Step') current.step = parseFloat(value)
  1861. }
  1862. }
  1863. if (current) properties.push(current)
  1864. return properties
  1865. }
  1866. export async function listLweProperties(wallpaperPath: string): Promise<LweProperty[]> {
  1867. const status = getLweStatus()
  1868. if (!status.installed) throw new Error('linux-wallpaperengine is not installed.')
  1869. const binaryPath = getLweBinaryPath()
  1870. const args = ['--list-properties']
  1871. const assetsDir = findWeAssetsDir()
  1872. if (assetsDir) args.push('--assets-dir', assetsDir)
  1873. args.push(wallpaperPath)
  1874. const envVars = buildLweEnvVars()
  1875. try {
  1876. const { stdout } = await execFileAsync('env', [...envVars, binaryPath, ...args], {
  1877. timeout: 15_000,
  1878. maxBuffer: 5 * 1024 * 1024,
  1879. encoding: 'utf8'
  1880. })
  1881. return parseLweProperties(stdout)
  1882. } catch (err) {
  1883. const e = err as Error & { stdout?: string; stderr?: string }
  1884. const msg = (e.stderr || e.stdout || e.message || String(err)).trim().split('\n').slice(0, 3).join('\n')
  1885. throw new Error(`Failed to list wallpaper properties: ${msg}`, { cause: err })
  1886. }
  1887. }
  1888. type EngineProcess = Pick<LweInstance, 'pid' | 'sandbox' | 'hostPid'>
  1889. /** Node has no waitpid() for a process it didn't spawn */
  1890. async function pollUntilGone(target: EngineProcess, timeoutMs: number): Promise<boolean> {
  1891. const other = inOtherSandbox(target)
  1892. const deadline = Date.now() + timeoutMs
  1893. while (Date.now() < deadline) {
  1894. if (other) {
  1895. if (!(await isEngineAliveAsync(target))) return true
  1896. } else {
  1897. try {
  1898. process.kill(target.pid, 0)
  1899. } catch {
  1900. return true
  1901. }
  1902. }
  1903. // every check of another sandbox's engine is a flatpak-spawn round trip
  1904. await new Promise((resolve) => setTimeout(resolve, other ? 100 : 25))
  1905. }
  1906. return false
  1907. }
  1908. /** SIGKILL after the grace period; a replacement would race it for the audio device */
  1909. async function waitForExit(target: EngineProcess, timeoutMs = 2000): Promise<void> {
  1910. if (await pollUntilGone(target, timeoutMs)) return
  1911. try {
  1912. signalEngine(target, 'SIGKILL')
  1913. } catch { }
  1914. await pollUntilGone(target, 500)
  1915. }
  1916. /** One screen's engine, or every engine this app started */
  1917. export async function stopLwe(screen?: ScreenTarget): Promise<void> {
  1918. loadInstances()
  1919. const targets = screen === undefined ? [...instances.values()] : [instances.get(screen)].filter((i) => !!i)
  1920. await Promise.all(
  1921. targets.map(async (inst) => {
  1922. inst.stopping = true
  1923. try {
  1924. signalEngine(inst, 'SIGTERM')
  1925. } catch { }
  1926. await waitForExit(inst)
  1927. if (inst.controlFile) fs.rmSync(inst.controlFile, { force: true })
  1928. fs.rmSync(inputFileFor(inst.screen), { force: true })
  1929. if (instances.get(inst.screen) === inst) instances.delete(inst.screen)
  1930. })
  1931. )
  1932. persistInstances()
  1933. }
  1934. export function isLweRunning(screen?: ScreenTarget): boolean {
  1935. return screen === undefined ? liveInstances().length > 0 : !!liveInstance(screen)
  1936. }
  1937. /** Including engines this app isn't tracking */
  1938. export async function killAllLweProcesses(): Promise<{ ok: boolean; message: string }> {
  1939. loadInstances()
  1940. for (const inst of instances.values()) inst.stopping = true
  1941. instances.clear()
  1942. persistInstances()
  1943. // by the program's own name, not by the name showing up anywhere in a command line (an editor on the repo folder,
  1944. // git, make): the pattern is anchored, so flatpak-spawn's own command line doesn't match either
  1945. const [file, args] = hostCommand('pkill', ['-9', '-f', '-c', LWE_PROCESS_PATTERN])
  1946. try {
  1947. const { stdout } = await execFileAsync(file, args)
  1948. const count = parseInt(stdout.trim(), 10) || 0
  1949. return { ok: true, message: t('lwe.killed', { count }) }
  1950. } catch (err) {
  1951. const code = (err as { code?: number }).code
  1952. // exit 1 = nothing matched
  1953. if (code === 1) {
  1954. return { ok: true, message: t('lwe.noProcesses') }
  1955. }
  1956. return { ok: false, message: t('lwe.killFailed', { error: (err as Error).message }) }
  1957. }
  1958. }
  1959. const SCREENSHOT_TIMEOUT_MS = 45_000
  1960. export async function captureLweScreenshot(
  1961. wallpaperPath: string,
  1962. options: LweLaunchOptions,
  1963. outPath: string,
  1964. size = { width: 1280, height: 720 }
  1965. ): Promise<void> {
  1966. if (!getLweStatus().installed) throw new Error('linux-wallpaperengine is not installed.')
  1967. fs.rmSync(outPath, { force: true })
  1968. const args = buildLweArgs(
  1969. wallpaperPath,
  1970. {
  1971. ...options,
  1972. fps: 60,
  1973. volume: 0,
  1974. engineFlags: { ...options.engineFlags, silent: true, fullscreenPause: 'off', pauseOnFocus: false, pauseOnMaximized: false, disableMouse: true }
  1975. },
  1976. { window: `0x0x${size.width}x${size.height}`, screenshotPath: outPath, delayFrames: 120 }
  1977. )
  1978. // the window is X11, without an X server render offscreen
  1979. const headless = process.env.DISPLAY ? [] : ['XDG_SESSION_TYPE=headless']
  1980. const child = spawn('env', [...buildLweEnvVars(), ...headless, getLweBinaryPath(), ...args], {
  1981. stdio: ['ignore', 'ignore', 'pipe']
  1982. })
  1983. const stderr: string[] = []
  1984. child.stderr?.on('data', (chunk: Buffer) => {
  1985. stderr.push(chunk.toString('utf8'))
  1986. })
  1987. try {
  1988. const deadline = Date.now() + SCREENSHOT_TIMEOUT_MS
  1989. let lastSize = -1
  1990. while (Date.now() < deadline) {
  1991. await new Promise((resolve) => setTimeout(resolve, 250))
  1992. if (child.exitCode !== null || child.signalCode !== null) {
  1993. const msg = stderr.join('').trim().split('\n').slice(-3).join('\n')
  1994. throw new Error(`linux-wallpaperengine exited before taking the screenshot${msg ? `: ${msg}` : ''}`)
  1995. }
  1996. // done once the size held still for a poll
  1997. const current = fs.existsSync(outPath) ? fs.statSync(outPath).size : -1
  1998. if (current > 0 && current === lastSize) return
  1999. lastSize = current
  2000. }
  2001. throw new Error('Timed out waiting for the screenshot')
  2002. } finally {
  2003. child.kill('SIGTERM')
  2004. if (child.pid !== undefined) await waitForExit({ pid: child.pid, sandbox: flatpakInstanceId() ?? null, hostPid: null }, 3000)
  2005. }
  2006. }