platform.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import fs from 'fs'
  2. import path from 'path'
  3. import { execFileSync, execSync } from 'child_process'
  4. import { parseDesktopEnv, type DesktopEnvironment } from '@shared/desktop'
  5. import { hostCommand } from './flatpak'
  6. /** stdout of a program on the host, stderr dropped; the words are the program and its arguments */
  7. function hostOutput(commandLine: string, timeout: number): string {
  8. const [program, ...args] = commandLine.split(' ')
  9. const [file, fileArgs] = hostCommand(program, args)
  10. return execFileSync(file, fileArgs, { encoding: 'utf8', timeout, stdio: ['ignore', 'pipe', 'ignore'] })
  11. }
  12. export type DisplayServer = 'wayland' | 'x11' | 'unknown'
  13. export type { DesktopEnvironment }
  14. export function detectDisplayServer(): DisplayServer {
  15. if (process.platform === 'win32' || process.platform === 'darwin') return 'unknown'
  16. if (process.env.WAYLAND_DISPLAY) return 'wayland'
  17. if (process.env.DISPLAY) return 'x11'
  18. return 'unknown'
  19. }
  20. export function detectDesktopEnv(): DesktopEnvironment {
  21. if (process.platform === 'win32' || process.platform === 'darwin') return 'other'
  22. return parseDesktopEnv(process.env.XDG_CURRENT_DESKTOP, process.env)
  23. }
  24. /** children of an AppImage inherit APPIMAGE and APPDIR too */
  25. export function runningAppImage(): string | undefined {
  26. const { APPIMAGE, APPDIR } = process.env
  27. return APPIMAGE && APPDIR && process.execPath.startsWith(APPDIR) ? APPIMAGE : undefined
  28. }
  29. /** Electron often runs under XWayland without WAYLAND_DISPLAY, so the session type counts too. */
  30. export function isWaylandSession(): boolean {
  31. return !!process.env.WAYLAND_DISPLAY || process.env.XDG_SESSION_TYPE === 'wayland'
  32. }
  33. /**
  34. * WAYLAND_DISPLAY of the user session. Electron often runs under XWayland
  35. * without it set, so fall back to the session type and loginctl.
  36. */
  37. export function getWaylandDisplay(): string | undefined {
  38. if (process.env.WAYLAND_DISPLAY) return process.env.WAYLAND_DISPLAY
  39. if (process.env.XDG_SESSION_TYPE === 'wayland') return 'wayland-0'
  40. try {
  41. const sessionType = execSync(
  42. 'loginctl show-session $(loginctl 2>/dev/null | grep $USER | head -1 | awk \'{print $1}\') -p Type --value 2>/dev/null',
  43. { encoding: 'utf8', timeout: 3000 }
  44. ).trim()
  45. if (sessionType === 'wayland') return 'wayland-0'
  46. } catch { }
  47. return undefined
  48. }
  49. export function getXdgRuntimeDir(): string {
  50. return process.env.XDG_RUNTIME_DIR || `/run/user/${process.getuid?.() ?? 1000}`
  51. }
  52. function parseJson(output: string): unknown {
  53. try {
  54. return JSON.parse(output)
  55. } catch {
  56. return null
  57. }
  58. }
  59. function isNamed(v: unknown): v is { name: string; [key: string]: unknown } {
  60. return typeof v === 'object' && v !== null && typeof (v as { name?: unknown }).name === 'string' && (v as { name: string }).name !== ''
  61. }
  62. /** `hyprctl monitors -j`: an array of monitors, a disabled one has no output to draw on */
  63. export function parseHyprctlMonitors(output: string): string[] {
  64. const monitors = parseJson(output)
  65. if (!Array.isArray(monitors)) return []
  66. return monitors
  67. .filter(isNamed)
  68. .filter(m => m.disabled !== true)
  69. .map(m => m.name)
  70. }
  71. /** `swaymsg -t get_outputs -r`: an array of outputs, inactive ones are switched off */
  72. export function parseSwayOutputs(output: string): string[] {
  73. const outputs = parseJson(output)
  74. if (!Array.isArray(outputs)) return []
  75. return outputs
  76. .filter(isNamed)
  77. .filter(o => o.active !== false)
  78. .map(o => o.name)
  79. }
  80. /** `niri msg --json outputs`: an object keyed by output name, a disabled one has no current mode */
  81. export function parseNiriOutputs(output: string): string[] {
  82. const outputs = parseJson(output)
  83. if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) return []
  84. return Object.entries(outputs)
  85. .filter(([, o]) => (o as { current_mode?: unknown } | null)?.current_mode !== null)
  86. .map(([name]) => name)
  87. }
  88. const COMPOSITOR_QUERIES: { marker: string; command: string; parse: (output: string) => string[] }[] = [
  89. { marker: 'HYPRLAND_INSTANCE_SIGNATURE', command: 'hyprctl monitors -j', parse: parseHyprctlMonitors },
  90. { marker: 'SWAYSOCK', command: 'swaymsg -t get_outputs -r', parse: parseSwayOutputs },
  91. { marker: 'NIRI_SOCKET', command: 'niri msg --json outputs', parse: parseNiriOutputs }
  92. ]
  93. /** Outputs that show another output's picture; kscreen-doctor -j gives them a nonzero replicationSource (an output id) */
  94. export function parseKscreenMirrors(json: string): string[] {
  95. try {
  96. const outputs = (JSON.parse(json) as { outputs?: { name?: string; replicationSource?: number }[] }).outputs ?? []
  97. return outputs.filter((o) => o.name && o.replicationSource).map((o) => o.name as string)
  98. } catch {
  99. return []
  100. }
  101. }
  102. export function getMirroredScreens(): string[] {
  103. if (process.platform !== 'linux' || !isWaylandSession() || detectDesktopEnv() !== 'kde') return []
  104. try {
  105. return parseKscreenMirrors(hostOutput('kscreen-doctor -j', 5000))
  106. } catch {
  107. return []
  108. }
  109. }
  110. export function getConnectedScreens(): string[] {
  111. if (process.platform !== 'linux') return []
  112. // On Wayland, we MUST use native Wayland output names (not xrandr/XWayland names)
  113. if (isWaylandSession()) {
  114. // the compositor's own IPC knows which outputs are enabled
  115. for (const { marker, command, parse } of COMPOSITOR_QUERIES) {
  116. if (!process.env[marker]) continue
  117. try {
  118. const output = hostOutput(command, 5000)
  119. const screens = parse(output)
  120. if (screens.length > 0) return screens
  121. } catch { }
  122. }
  123. try {
  124. const output = hostOutput('wlr-randr', 5000)
  125. const screens = output
  126. .split('\n')
  127. .filter(line => /^[A-Za-z]/.test(line) && !line.startsWith(' '))
  128. .map(line => line.split(/\s+/)[0])
  129. .filter(Boolean)
  130. if (screens.length > 0) return screens
  131. } catch { }
  132. try {
  133. const output = hostOutput('kscreen-doctor --outputs', 5000)
  134. const clean = output.replace(/\x1b\[[0-9;]*m/g, '')
  135. const screens = clean
  136. .split('\n')
  137. .map(line => {
  138. const m = line.match(/Output:\s+\d+\s+(\S+)/)
  139. return m ? m[1] : null
  140. })
  141. .filter((s): s is string => s !== null)
  142. if (screens.length > 0) return screens
  143. } catch { }
  144. try {
  145. const output = hostOutput(
  146. 'gdbus call --session --dest org.gnome.Mutter.DisplayConfig --object-path /org/gnome/Mutter/DisplayConfig --method org.gnome.Mutter.DisplayConfig.GetCurrentState',
  147. 5000
  148. )
  149. // gdbus prints the monitors as ('connector', 'vendor', 'product', 'serial') tuples
  150. const screens = [...new Set([...output.matchAll(/\(\('([^']+)',\s*'[^']*',\s*'[^']*',\s*'[^']*'\)/g)].map(m => m[1]))]
  151. if (screens.length > 0) return screens
  152. } catch { }
  153. }
  154. try {
  155. const output = hostOutput('xrandr --query', 5000)
  156. const screens = output
  157. .split('\n')
  158. .filter(line => / connected/i.test(line))
  159. .map(line => line.split(/\s+/)[0])
  160. .filter(Boolean)
  161. if (screens.length > 0) return screens
  162. } catch { }
  163. return []
  164. }
  165. /** `NAME connected [primary] WxH+X+Y` lines of xrandr, as the engine's XxYxWxH */
  166. export function parseXrandrGeometries(output: string): Map<string, string> {
  167. const geometries = new Map<string, string>()
  168. for (const line of output.split('\n')) {
  169. const m = line.match(/^(\S+) connected (?:primary )?(\d+)x(\d+)\+(\d+)\+(\d+)/)
  170. if (m) geometries.set(m[1], `${m[4]}x${m[5]}x${m[2]}x${m[3]}`)
  171. }
  172. return geometries
  173. }
  174. /** Geometry of the named screen, else of the first one */
  175. export function getScreenGeometry(screen?: string): string | null {
  176. try {
  177. const output = hostOutput('xrandr --query', 5000)
  178. const geometries = parseXrandrGeometries(output)
  179. return (screen && geometries.get(screen)) || geometries.values().next().value || null
  180. } catch {
  181. return null
  182. }
  183. }
  184. /** Answer of a NameHasOwner call, from busctl (`b true`) or gdbus (`(true,)`), null when it is neither */
  185. export function parseNameHasOwner(output: string): boolean | null {
  186. const m = output.trim().match(/^(?:b\s+|\(\s*)(true|false)\b/)
  187. return m ? m[1] === 'true' : null
  188. }
  189. const NAME_HAS_OWNER_COMMANDS = [
  190. 'busctl --user call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus NameHasOwner s org.kde.StatusNotifierWatcher',
  191. 'gdbus call --session --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.NameHasOwner org.kde.StatusNotifierWatcher'
  192. ]
  193. const TRAY_HOST_CACHE_MS = 15_000
  194. let trayHostCache: { value: boolean; at: number } | null = null
  195. /**
  196. * Whether something on the session bus can show a StatusNotifier icon. Without one a window hidden
  197. * to the tray has no way back. Assumes yes when neither busctl nor gdbus can tell.
  198. */
  199. export function hasStatusNotifierHost(maxAgeMs = TRAY_HOST_CACHE_MS): boolean {
  200. if (process.platform !== 'linux') return true
  201. if (trayHostCache && Date.now() - trayHostCache.at < maxAgeMs) return trayHostCache.value
  202. let value = true
  203. for (const command of NAME_HAS_OWNER_COMMANDS) {
  204. try {
  205. const output = hostOutput(command, 2000)
  206. const owned = parseNameHasOwner(output)
  207. if (owned !== null) {
  208. value = owned
  209. break
  210. }
  211. } catch { }
  212. }
  213. trayHostCache = { value, at: Date.now() }
  214. return value
  215. }
  216. const commandCache = new Map<string, boolean>()
  217. export function isCommandAvailable(cmd: string): boolean {
  218. if (commandCache.has(cmd)) return commandCache.get(cmd)!
  219. let found = false
  220. if (process.platform === 'win32') {
  221. try {
  222. execSync(`where ${cmd}`, { stdio: 'ignore' })
  223. found = true
  224. } catch { }
  225. } else {
  226. // a PATH search of our own: minimal systems (openSUSE) ship without which(1)
  227. const dirs = [...(process.env.PATH ?? '').split(':'), '/usr/local/sbin', '/usr/sbin', '/sbin'].filter(Boolean)
  228. found = dirs.some((dir) => {
  229. try {
  230. fs.accessSync(path.join(dir, cmd), fs.constants.X_OK)
  231. return true
  232. } catch {
  233. return false
  234. }
  235. })
  236. }
  237. commandCache.set(cmd, found)
  238. return found
  239. }
  240. export function invalidateCommandCache(cmd: string): void {
  241. commandCache.delete(cmd)
  242. }
  243. export function whichCommand(cmd: string): string | undefined {
  244. try {
  245. const checker = process.platform === 'win32' ? 'where' : 'which'
  246. return execSync(`${checker} ${cmd}`, { encoding: 'utf8' }).trim()
  247. } catch {
  248. return undefined
  249. }
  250. }