desktop-icons.service.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
  2. import * as path from 'path'
  3. import * as fs from 'fs'
  4. import { openStore } from '../utils/safeStore'
  5. import { app } from 'electron'
  6. import { detectDesktopEnv, getConnectedScreens, getWaylandDisplay, getXdgRuntimeDir, isCommandAvailable, isWaylandSession } from '../utils/platform'
  7. import { hostCommand, isFlatpak, isHostCommandAvailable } from '../utils/flatpak'
  8. import { detectDistro, distroFromIds, isOstreeSystem, parseOsReleaseIds, onLweLaunched } from './lwe.service'
  9. import type { DesktopIconsStatus, LinuxDistro } from '@shared/types'
  10. interface DesktopIconsStoreSchema {
  11. desktopIconsEnabled: boolean
  12. }
  13. const store = openStore<DesktopIconsStoreSchema>({
  14. defaults: { desktopIconsEnabled: false }
  15. })
  16. let overlayProcesses: ChildProcess[] = []
  17. function getOverlayScriptPath(): string {
  18. // In dev: __dirname is out/main, project root is two levels up
  19. // In prod: script is copied to resources/
  20. const candidates = [
  21. path.join(__dirname, '..', '..', 'src', 'main', 'services', 'desktop-icons-overlay.py'),
  22. path.join(process.resourcesPath ?? '', 'desktop-icons-overlay.py'),
  23. path.join(__dirname, 'desktop-icons-overlay.py')
  24. ]
  25. for (const c of candidates) {
  26. if (fs.existsSync(c)) return c
  27. }
  28. return candidates[0]
  29. }
  30. const LAYER_SHELL_DIRS = [
  31. '/usr/lib64',
  32. '/usr/lib',
  33. '/usr/lib/x86_64-linux-gnu',
  34. '/usr/lib/aarch64-linux-gnu',
  35. '/usr/local/lib64',
  36. '/usr/local/lib',
  37. '/lib64',
  38. '/lib'
  39. ]
  40. const LAYER_SHELL_NAMES = ['libgtk4-layer-shell.so.0', 'libgtk4-layer-shell.so']
  41. const LAYER_SHELL_LIBS = LAYER_SHELL_DIRS.flatMap((dir) => LAYER_SHELL_NAMES.map((name) => `${dir}/${name}`))
  42. const PACKAGES: Record<string, string> = {
  43. fedora: 'sudo dnf install gtk4-layer-shell python3-gobject python3-cairo',
  44. arch: 'sudo pacman -S gtk4-layer-shell python-gobject python-cairo',
  45. debian: 'sudo apt install gir1.2-gtk4layershell-1.0 libgtk4-layer-shell0 python3-gi python3-gi-cairo gir1.2-gtk-4.0',
  46. suse: 'sudo zypper install libgtk4-layer-shell0 typelib-1_0-Gtk4LayerShell-1_0 python3-gobject python3-cairo typelib-1_0-Gtk-4_0'
  47. }
  48. /** In a Flatpak /etc/os-release is the runtime's, the packages go onto the host */
  49. let cachedHostDistro: LinuxDistro | undefined
  50. function hostDistro(): LinuxDistro {
  51. if (!isFlatpak()) return detectDistro()
  52. if (cachedHostDistro) return cachedHostDistro
  53. try {
  54. const [file, args] = hostCommand('cat', ['/etc/os-release'])
  55. cachedHostDistro = distroFromIds(parseOsReleaseIds(execFileSync(file, args, { encoding: 'utf8', timeout: 5000 })))
  56. } catch {
  57. cachedHostDistro = 'unknown'
  58. }
  59. return cachedHostDistro
  60. }
  61. function hostIsImmutable(): boolean {
  62. if (!isFlatpak()) return isOstreeSystem()
  63. try {
  64. const [file, args] = hostCommand('test', ['-e', '/run/ostree-booted'])
  65. execFileSync(file, args, { stdio: 'ignore', timeout: 5000 })
  66. return true
  67. } catch {
  68. return false
  69. }
  70. }
  71. const INSTALL_ARGS: Record<string, string[]> = {
  72. fedora: ['dnf', 'install', '-y', 'gtk4-layer-shell', 'python3-gobject', 'python3-cairo'],
  73. arch: ['pacman', '-S', '--needed', '--noconfirm', 'gtk4-layer-shell', 'python-gobject', 'python-cairo'],
  74. debian: ['apt-get', 'install', '-y', 'gir1.2-gtk4layershell-1.0', 'libgtk4-layer-shell0', 'python3-gi', 'python3-gi-cairo', 'gir1.2-gtk-4.0'],
  75. suse: ['zypper', '--non-interactive', 'install', 'libgtk4-layer-shell0', 'typelib-1_0-Gtk4LayerShell-1_0', 'python3-gobject', 'python3-cairo', 'typelib-1_0-Gtk-4_0']
  76. }
  77. export function installDesktopIconsDependencies(): Promise<{ ok: boolean; error?: string }> {
  78. const install = INSTALL_ARGS[hostDistro()]
  79. if (!install) return Promise.resolve({ ok: false, error: 'unknown-distro' })
  80. if (hostIsImmutable()) return Promise.resolve({ ok: false, error: 'immutable' })
  81. const hasPkexec = isFlatpak() ? isHostCommandAvailable('pkexec') : isCommandAvailable('pkexec')
  82. if (!hasPkexec) return Promise.resolve({ ok: false, error: 'no-pkexec' })
  83. const [file, args] = hostCommand('pkexec', install)
  84. return new Promise((resolve) => {
  85. execFile(file, args, { timeout: 10 * 60 * 1000, encoding: 'utf8' }, (err, _stdout, stderr) => {
  86. if (err) {
  87. // 126 and 127 are pkexec's dismissed and not-authorized codes
  88. const code = (err as { code?: number }).code
  89. if (code === 126 || code === 127) return resolve({ ok: false, error: 'cancelled' })
  90. return resolve({ ok: false, error: stderr.trim().split('\n').slice(-4).join('\n') || err.message })
  91. }
  92. startFailure = null
  93. if (getDesktopIconsEnabled()) startDesktopIconsOverlay()
  94. resolve({ ok: true })
  95. })
  96. })
  97. }
  98. /** The runtime library is libgtk4-layer-shell.so.0, the plain .so name only comes with the -devel package */
  99. function findLayerShellLib(): string | undefined {
  100. const found = LAYER_SHELL_LIBS.find((p) => fs.existsSync(p))
  101. if (found) return found
  102. for (const ldconfig of ['ldconfig', '/sbin/ldconfig', '/usr/sbin/ldconfig']) {
  103. try {
  104. const out = execFileSync(ldconfig, ['-p'], { encoding: 'utf8', timeout: 3000 })
  105. const line = out.split('\n').find((l) => l.includes('libgtk4-layer-shell.so'))
  106. const target = line?.split('=>')[1]?.trim()
  107. if (target && fs.existsSync(target)) return target
  108. } catch {
  109. }
  110. }
  111. return undefined
  112. }
  113. /** The overlay needs the host's Python, GTK4 and gtk4-layer-shell, so it runs on the host from a copy of the script */
  114. function flatpakOverlayCommand(scriptPath: string, envVars: string[], screen?: string): [string, string[]] {
  115. const hostScript = path.join(app.getPath('userData'), 'desktop-icons-overlay.py')
  116. fs.copyFileSync(scriptPath, hostScript)
  117. const findLib = `for lib in ${LAYER_SHELL_LIBS.join(' ')} $(ldconfig -p 2>/dev/null | sed -n 's/.*libgtk4-layer-shell.so.* => //p'); do [ -e "$lib" ] && export LD_PRELOAD="$lib" && break; done`
  118. const args = ['--host', ...envVars.filter((v) => !v.startsWith('LD_PRELOAD=')).map((v) => `--env=${v}`),
  119. 'sh', '-c', `${findLib}; exec python3 "$@"`, 'sh', hostScript]
  120. if (screen) args.push(screen)
  121. return ['flatpak-spawn', args]
  122. }
  123. /** Env vars for the overlay; Electron runs under XWayland so the Wayland env must be passed explicitly. */
  124. function buildOverlayEnvVars(layerShellLib: string | undefined): string[] {
  125. const vars: string[] = []
  126. if (layerShellLib) vars.push(`LD_PRELOAD=${layerShellLib}`)
  127. // Force GTK4 onto the Wayland backend (layer-shell does not work under X11)
  128. vars.push('GDK_BACKEND=wayland')
  129. const waylandDisplay = getWaylandDisplay()
  130. if (waylandDisplay) vars.push(`WAYLAND_DISPLAY=${waylandDisplay}`)
  131. vars.push(`XDG_RUNTIME_DIR=${getXdgRuntimeDir()}`)
  132. if (process.env.DISPLAY) vars.push(`DISPLAY=${process.env.DISPLAY}`)
  133. return vars
  134. }
  135. const EXIT_MISSING_MODULES = 2
  136. const EXIT_NO_LAYER_SHELL = 3
  137. const STDERR_LINES = 8
  138. let startFailure: { problem: 'missing-modules' | 'failed'; detail: string } | null = null
  139. /** Only Plasma's Folder View sits below the engine's surface; other desktops draw their icons above it themselves */
  140. function unsupportedReason(): 'not-kde' | 'not-wayland' | null {
  141. if (detectDesktopEnv() !== 'kde') return 'not-kde'
  142. if (!isWaylandSession()) return 'not-wayland'
  143. return null
  144. }
  145. export function getDesktopIconsStatus(): DesktopIconsStatus {
  146. const enabled = getDesktopIconsEnabled()
  147. const unsupported = unsupportedReason()
  148. if (unsupported) return { enabled, problem: unsupported }
  149. const command = PACKAGES[hostDistro()]
  150. if (!isFlatpak() && !findLayerShellLib()) return { enabled, problem: 'missing-lib', command }
  151. if (startFailure) return { enabled, problem: startFailure.problem, detail: startFailure.detail, command }
  152. return { enabled }
  153. }
  154. export function startDesktopIconsOverlay(): void {
  155. stopDesktopIconsOverlay()
  156. startFailure = null
  157. if (unsupportedReason()) return
  158. const scriptPath = getOverlayScriptPath()
  159. if (!fs.existsSync(scriptPath)) {
  160. console.error('[DesktopIcons] Overlay script not found:', scriptPath)
  161. startFailure = { problem: 'failed', detail: 'script not found' }
  162. return
  163. }
  164. const layerShellLib = isFlatpak() ? undefined : findLayerShellLib()
  165. if (!isFlatpak() && !layerShellLib) {
  166. console.error('[DesktopIcons] libgtk4-layer-shell not found')
  167. return
  168. }
  169. const envVars = buildOverlayEnvVars(layerShellLib)
  170. const screens = getConnectedScreens()
  171. const targets = screens.length > 0 ? screens : [undefined]
  172. for (const screen of targets) {
  173. const args = ['python3', scriptPath]
  174. if (screen) args.push(screen)
  175. const [command, commandArgs] = isFlatpak()
  176. ? flatpakOverlayCommand(scriptPath, envVars, screen)
  177. : ['env', [...envVars, ...args]]
  178. const child = spawn(command, commandArgs, {
  179. stdio: ['ignore', 'ignore', 'pipe'],
  180. detached: true
  181. })
  182. const errors: string[] = []
  183. child.stderr?.on('data', (chunk: Buffer) => {
  184. errors.push(...chunk.toString('utf8').split('\n').filter(Boolean))
  185. if (errors.length > STDERR_LINES) errors.splice(0, errors.length - STDERR_LINES)
  186. })
  187. child.on('exit', (code, signal) => {
  188. const mine = overlayProcesses.includes(child)
  189. overlayProcesses = overlayProcesses.filter((p) => p !== child)
  190. if (!mine || signal || code === 0 || code === null) return
  191. const detail = errors.join('\n')
  192. console.error(`[DesktopIcons] Overlay for ${screen ?? 'default screen'} exited with ${code}: ${detail}`)
  193. startFailure = { problem: code === EXIT_MISSING_MODULES ? 'missing-modules' : 'failed', detail }
  194. if (code === EXIT_NO_LAYER_SHELL) startFailure.detail = detail || 'the compositor has no layer-shell'
  195. })
  196. child.unref()
  197. overlayProcesses.push(child)
  198. }
  199. console.log(`[DesktopIcons] Started ${targets.length} overlay(s)`)
  200. }
  201. export function stopDesktopIconsOverlay(): void {
  202. for (const child of overlayProcesses) {
  203. try {
  204. child.kill('SIGTERM')
  205. } catch {
  206. }
  207. }
  208. overlayProcesses = []
  209. }
  210. export function setDesktopIconsEnabled(enabled: boolean): void {
  211. store.set('desktopIconsEnabled', enabled)
  212. if (enabled) {
  213. startDesktopIconsOverlay()
  214. } else {
  215. startFailure = null
  216. stopDesktopIconsOverlay()
  217. }
  218. }
  219. /** The engine and the overlay share the bottom layer and the later surface is drawn on top, so the overlay has to map after the wallpaper */
  220. export function raiseDesktopIconsOverlay(): void {
  221. if (getDesktopIconsEnabled()) startDesktopIconsOverlay()
  222. }
  223. export function getDesktopIconsEnabled(): boolean {
  224. return store.get('desktopIconsEnabled', false)
  225. }
  226. export function initDesktopIcons(): void {
  227. onLweLaunched(raiseDesktopIconsOverlay)
  228. if (getDesktopIconsEnabled()) {
  229. startDesktopIconsOverlay()
  230. }
  231. }
  232. export function cleanupDesktopIcons(): void {
  233. stopDesktopIconsOverlay()
  234. }