Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopPreReadyPlatform.ts

166 lines7.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads settings, prepares the Linux desktop entry, and asks Hyprland for its version synchronously before app services are available.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8​
9import * as Electron from "electron";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11​
12import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
13import { resolveDesktopAppBranding, resolveDesktopSafeStorageName } from "./DesktopEnvironment.ts";
14import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts";
15import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
16​
17export interface DesktopPreReadyCommandLineReader {
18 readonly hasSwitch: (switchName: string) => boolean;
19 readonly getSwitchValue: (switchName: string) => string;
21​
22function readCommandLineSwitchValue(
23 commandLine: DesktopPreReadyCommandLineReader,
24 switchName: string,
25): string | null {
26 if (!commandLine.hasSwitch(switchName)) {
27 return null;
28 }
29​
30 const value = commandLine.getSwitchValue(switchName).trim();
31 return value.length > 0 ? value : null;
33​
34export const resolveEarlyLinuxElectronOptionsFromProcess = (
35 homeDirectory: string,
36): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
37 DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
38 env: process.env,
39 homeDirectory,
40 joinPath: NodePath.posix.join,
41 readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
42 });
43​
44export class DesktopPreReadyElectronOptions extends Context.Service<
45 DesktopPreReadyElectronOptions,
46 {
47 readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
48 readonly linuxPasswordStoreCommandLine: string | null;
49 }
50>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
51​
52/** @public Service construction is part of the canonical Effect module API. */
53export const make = Effect.gen(function* () {
54 const platform = yield* HostProcess.Platform;
55 const homeDirectory = yield* HostProcess.HomeDirectory;
56 return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
57 // Chromium reads the safeStorage key's name before startup first yields.
58 // DesktopAppIdentity's later rename only changes the branded app name.
59 if (platform === "darwin" || platform === "linux") {
60 Electron.app.setName(resolveDesktopSafeStorageName(Electron.app.getVersion()));
61 }
62 const linuxPasswordStoreCommandLine =
63 platform === "linux"
64 ? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
65 : null;
66 const linux =
67 platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess(homeDirectory) : null;
68​
69 if (linux !== null) {
70 DesktopEarlyElectronStartup.restoreEarlyLinuxDeviceScaleFactor({
71 env: process.env,
72 homeDirectory,
73 joinPath: NodePath.posix.join,
74 commandLine: Electron.app.commandLine,
75 readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
76 writeFileString: (path, value) => {
77 NodeFS.mkdirSync(NodePath.posix.dirname(path), { recursive: true });
78 NodeFS.writeFileSync(path, value, "utf8");
79 },
80 });
81 // The portal also requires a valid desktop entry. An AppImage update may
82 // have removed the executable referenced by the previous launch's entry.
83 try {
84 const applicationsDir = NodePath.posix.join(
85 process.env.XDG_DATA_HOME?.trim() ||
86 NodePath.posix.join(homeDirectory, ".local", "share"),
87 "applications",
88 );
89 NodeFS.mkdirSync(applicationsDir, { recursive: true });
90 const iconPath = Electron.app.isPackaged
91 ? NodePath.posix.join(
92 applicationsDir,
93 "..",
94 "icons",
95 `${linux.linuxDesktopEntryName}.png`,
96 )
97 : undefined;
98 if (iconPath !== undefined) {
99 try {
100 // Electron's copyFile extracts ASAR entries to temporary files it never removes.
101 const icon = NodeFS.readFileSync(
102 NodePath.posix.join(
103 Electron.app.getAppPath(),
104 "apps/desktop/prod-resources/icon.png",
105 ),
106 );
107 let current: Buffer | null = null;
108 try {
109 current = NodeFS.readFileSync(iconPath);
110 } catch {}
111 if (current === null || !current.equals(icon)) {
112 NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true });
113 NodeFS.writeFileSync(iconPath, icon, { mode: 0o600 });
114 }
115 } catch {}
116 }
117 NodeFS.writeFileSync(
118 NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName),
119 renderUrlHandlerDesktopEntry({
120 displayName: resolveDesktopAppBranding({
121 isDevelopment: linux.isDevelopment,
122 appVersion: Electron.app.getVersion(),
123 }).displayName,
124 execTarget: process.env.APPIMAGE?.trim() || process.execPath,
125 scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment),
126 ...(iconPath === undefined ? {} : { iconPath }),
127 }),
128 "utf8",
129 );
130 } catch {}
131 // Chromium caches its portal registration during startup. Set the identity
132 // before any asynchronous work can initialize it with Electron's default.
133 Electron.app.setDesktopName(linux.linuxDesktopEntryName);
134 Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
135 if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
136 Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
137 }
138 // Chromium keeps only the last --disable-features value, so pass the merged list.
139 const disableFeatures = DesktopEarlyElectronStartup.resolveLinuxDisableFeaturesSwitch({
140 env: process.env,
141 ozonePlatform: readCommandLineSwitchValue(Electron.app.commandLine, "ozone-platform"),
142 enableFeatures: readCommandLineSwitchValue(Electron.app.commandLine, "enable-features"),
143 disableFeatures: readCommandLineSwitchValue(Electron.app.commandLine, "disable-features"),
144 readHyprctlVersionJson: () =>
145 NodeChildProcess.execFileSync("hyprctl", ["version", "-j"], {
146 encoding: "utf8",
147 stdio: ["ignore", "pipe", "ignore"],
148 timeout: 1000,
149 maxBuffer: 64 * 1024,
150 }),
151 });
152 if (disableFeatures !== null) {
153 Electron.app.commandLine.appendSwitch("disable-features", disableFeatures);
154 }
155 }
156​
157 return { linux, linuxPasswordStoreCommandLine };
158 });
159}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
160​
161// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
162// observe app readiness before scheme privileges and command-line switches exist.
163export const layer = Layer.mergeAll(
164 ElectronProtocol.layerSchemePrivileges,
165 Layer.effect(DesktopPreReadyElectronOptions, make),
166);