| 1 | import { spawn } from "node:child_process"; |
| 2 | import { existsSync, mkdirSync, renameSync, writeFileSync } from "node:fs"; |
| 3 | import path from "node:path"; |
| 4 | |
| 5 | |
| 6 | export function displayDensity(value) { |
| 7 | return typeof value === "number" && value >= 0.75 && value <= 4 ? Math.round(value * 64) / 64 : null; |
| 8 | } |
| 9 | |
| 10 | export function densitySettings(scale) { |
| 11 | const dpi = Math.round(scale * 96 * 1024); |
| 12 | return `Xft/DPI ${dpi}\nGdk/WindowScalingFactor 1\nGdk/UnscaledDPI ${dpi}\n`; |
| 13 | } |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | export function createDisplaySettings({ |
| 19 | file, initial, available = existsSync("/usr/bin/xsettingsd"), |
| 20 | start = () => spawn("/usr/bin/xsettingsd", ["--config=" + file], { stdio: "ignore" }), restart = 1000, |
| 21 | }) { |
| 22 | let scale = initial, child, timer, closed = false; |
| 23 | const write = () => { |
| 24 | writeFileSync(file + ".new", densitySettings(scale)); |
| 25 | renameSync(file + ".new", file); |
| 26 | }; |
| 27 | const run = () => { |
| 28 | const current = child = start(); |
| 29 | |
| 30 | const ended = () => { |
| 31 | if (child !== current) return; |
| 32 | child = undefined; |
| 33 | if (!closed) timer = setTimeout(run, restart); |
| 34 | }; |
| 35 | current.on("error", ended); |
| 36 | current.on("exit", ended); |
| 37 | }; |
| 38 | if (available) { |
| 39 | mkdirSync(path.dirname(file), { recursive: true }); |
| 40 | write(); |
| 41 | run(); |
| 42 | } |
| 43 | return { |
| 44 | available, |
| 45 | get scale() { return scale; }, |
| 46 | set(value) { |
| 47 | if (!available || value === scale) return scale; |
| 48 | scale = value; |
| 49 | write(); |
| 50 | |
| 51 | child?.kill("SIGHUP"); |
| 52 | return scale; |
| 53 | }, |
| 54 | close() { |
| 55 | closed = true; |
| 56 | clearTimeout(timer); |
| 57 | child?.kill(); |
| 58 | }, |
| 59 | }; |
| 60 | } |