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

DesktopPreReadyPlatform.ts

213 lines8.7 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 Config from "effect/Config";
6import * as Context from "effect/Context";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10​
11import * as Electron from "electron";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13​
14import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
15import { trimmedString } from "./DesktopConfig.ts";
16import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts";
17import {
18 appImageUrlHandlerPath,
19 renderAppImageUrlHandler,
20 renderUrlHandlerDesktopEntry,
21 replacedVersionedAppImagePath,
22} from "./DesktopLinuxUrlHandler.ts";
23import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
24​
25export interface DesktopPreReadyCommandLineReader {
26 readonly hasSwitch: (switchName: string) => boolean;
27 readonly getSwitchValue: (switchName: string) => string;
29​
30function readCommandLineSwitchValue(
31 commandLine: DesktopPreReadyCommandLineReader,
32 switchName: string,
33): string | null {
34 if (!commandLine.hasSwitch(switchName)) {
35 return null;
36 }
37​
38 const value = commandLine.getSwitchValue(switchName).trim();
39 return value.length > 0 ? value : null;
41​
42export const resolveEarlyLinuxElectronOptionsFromProcess = (
43 homeDirectory: string,
44): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
45 DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
46 env: process.env,
47 homeDirectory,
48 joinPath: NodePath.posix.join,
49 readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
50 });
51​
52export class DesktopPreReadyElectronOptions extends Context.Service<
53 DesktopPreReadyElectronOptions,
54 {
55 readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
56 readonly linuxPasswordStoreCommandLine: string | null;
57 }
58>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
59​
60const LinuxDesktopEntryConfig = Config.all({
61 xdgDataHome: trimmedString("XDG_DATA_HOME"),
62 launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"),
63 appImagePath: trimmedString("APPIMAGE"),
64 // electron-updater sets this on the AppImage it relaunches after installing an update.
65 relaunchedByUpdater: trimmedString("APPIMAGE_SILENT_INSTALL"),
66});
67​
68/** @public */
69export const make = Effect.gen(function* () {
70 const platform = yield* HostProcess.Platform;
71 const homeDirectory = yield* HostProcess.HomeDirectory;
72 const linuxDesktopEntryConfig = yield* LinuxDesktopEntryConfig;
73 return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
74 const linuxPasswordStoreCommandLine =
75 platform === "linux"
76 ? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
77 : null;
78 const linux =
79 platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess(homeDirectory) : null;
80​
81 if (linux !== null) {
82 DesktopEarlyElectronStartup.restoreEarlyLinuxDeviceScaleFactor({
83 env: process.env,
84 homeDirectory,
85 joinPath: NodePath.posix.join,
86 commandLine: Electron.app.commandLine,
87 readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
88 writeFileString: (path, value) => {
89 NodeFS.mkdirSync(NodePath.posix.dirname(path), { recursive: true });
90 NodeFS.writeFileSync(path, value, "utf8");
91 },
92 });
93 // The portal also requires a valid desktop entry. An AppImage update may
94 // have removed the executable referenced by the previous launch's entry.
95 try {
96 const applicationsDir = NodePath.posix.join(
97 Option.getOrElse(linuxDesktopEntryConfig.xdgDataHome, () =>
98 NodePath.posix.join(homeDirectory, ".local", "share"),
99 ),
100 "applications",
101 );
102 NodeFS.mkdirSync(applicationsDir, { recursive: true });
103 const iconPath = Electron.app.isPackaged
104 ? NodePath.posix.join(
105 applicationsDir,
106 "..",
107 "icons",
108 `${linux.linuxDesktopEntryName}.png`,
109 )
110 : undefined;
111 if (iconPath !== undefined) {
112 try {
113 NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true });
114 // Electron's copyFileSync from app.asar extracts to a temp file it never deletes.
115 NodeFS.writeFileSync(
116 iconPath,
117 NodeFS.readFileSync(
118 NodePath.posix.join(
119 Electron.app.getAppPath(),
120 "apps/desktop/prod-resources/icon.png",
121 ),
122 ),
123 );
124 } catch {}
125 }
126 const desktopEntryPath = NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName);
127 const { appImagePath } = linuxDesktopEntryConfig;
128 if (
129 Option.isSome(appImagePath) &&
130 Option.isNone(linuxDesktopEntryConfig.launcherPath) &&
131 Option.contains(linuxDesktopEntryConfig.relaunchedByUpdater, "true")
132 ) {
133 try {
134 const replacedPath = replacedVersionedAppImagePath({
135 previousEntry: NodeFS.readFileSync(desktopEntryPath, "utf8"),
136 appImagePath: appImagePath.value,
137 });
138 // Relative, so the pair survives a moved folder; symlink never overwrites a file.
139 if (replacedPath !== null) {
140 NodeFS.symlinkSync(NodePath.posix.basename(appImagePath.value), replacedPath);
141 }
142 } catch {}
143 }
144 let execTarget =
145 Option.getOrUndefined(linuxDesktopEntryConfig.launcherPath) ?? process.execPath;
146 if (Option.isNone(linuxDesktopEntryConfig.launcherPath) && Option.isSome(appImagePath)) {
147 const handlerPath = appImageUrlHandlerPath(
148 applicationsDir,
149 linux.linuxDesktopEntryName,
150 NodePath.posix.join,
151 );
152 // Only the instance holding the single-instance lock records itself, after startup.
153 if (!NodeFS.existsSync(handlerPath)) {
154 NodeFS.mkdirSync(NodePath.posix.dirname(handlerPath), { recursive: true });
155 NodeFS.writeFileSync(
156 handlerPath,
157 renderAppImageUrlHandler({
158 appImagePath: appImagePath.value,
159 executablePath: process.execPath,
160 pid: process.pid,
161 }),
162 { encoding: "utf8", mode: 0o755 },
163 );
164 }
165 execTarget = handlerPath;
166 }
167 NodeFS.writeFileSync(
168 desktopEntryPath,
169 renderUrlHandlerDesktopEntry({
170 displayName: resolveDesktopAppBranding({
171 isDevelopment: linux.isDevelopment,
172 appVersion: Electron.app.getVersion(),
173 }).displayName,
174 execTarget,
175 scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment),
176 ...(iconPath === undefined ? {} : { iconPath }),
177 }),
178 "utf8",
179 );
180 } catch {}
181 // Chromium caches portal identity; set it before any asynchronous initialization.
182 Electron.app.setDesktopName(linux.linuxDesktopEntryName);
183 if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
184 Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
185 }
186 // Chromium keeps only the last --disable-features value, so pass the merged list.
187 const disableFeatures = DesktopEarlyElectronStartup.resolveLinuxDisableFeaturesSwitch({
188 env: process.env,
189 ozonePlatform: readCommandLineSwitchValue(Electron.app.commandLine, "ozone-platform"),
190 enableFeatures: readCommandLineSwitchValue(Electron.app.commandLine, "enable-features"),
191 disableFeatures: readCommandLineSwitchValue(Electron.app.commandLine, "disable-features"),
192 readHyprctlVersionJson: () =>
193 NodeChildProcess.execFileSync("hyprctl", ["version", "-j"], {
194 encoding: "utf8",
195 stdio: ["ignore", "pipe", "ignore"],
196 timeout: 1000,
197 maxBuffer: 64 * 1024,
198 }),
199 });
200 if (disableFeatures !== null) {
201 Electron.app.commandLine.appendSwitch("disable-features", disableFeatures);
202 }
203 }
204​
205 return { linux, linuxPasswordStoreCommandLine };
206 });
207}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
208​
209// Complete scheme privileges and switches before later layers can observe app readiness.
210export const layer = Layer.mergeAll(
211 ElectronProtocol.layerSchemePrivileges,
212 Layer.effect(DesktopPreReadyElectronOptions, make),
213);