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

GnomeCaptureSetup.ts

244 lines9.1 KB

1// @effect-diagnostics nodeBuiltinImport:off -- GNOME's per-user installation is a native adapter boundary.
2// @effect-diagnostics globalTimers:off -- Bound calls into the user's desktop session.
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5import { Message, sessionBus, type MessageBus, type MessageLike } from "dbus-next";
6import * as Schema from "effect/Schema";
7import type { DesktopCaptureExtensionState } from "@t3tools/contracts";
8​
9import { GNOME_CAPTURE_FILES, GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts";
10export { isGnomeCaptureSession } from "./linuxCaptureSession.ts";
11​
12const SHELL = "org.gnome.Shell";
13const SHELL_PATH = "/org/gnome/Shell";
14const EXTENSIONS = "org.gnome.Shell.Extensions";
15const NumberValue = Schema.Struct({ value: Schema.Number });
16const decodeInfo = Schema.decodeUnknownSync(
17 Schema.Struct({
18 state: Schema.optional(NumberValue),
19 version: Schema.optional(NumberValue),
20 error: Schema.optional(Schema.Struct({ value: Schema.String })),
21 }),
22);
23const decodeProperties = Schema.decodeUnknownSync(
24 Schema.Struct({
25 ShellVersion: Schema.Struct({ value: Schema.String }),
26 UserExtensionsEnabled: Schema.Struct({ value: Schema.Boolean }),
27 }),
28);
29const Metadata = Schema.Struct({
30 uuid: Schema.Literal(GNOME_CAPTURE_UUID),
31 version: Schema.Number,
32 "shell-version": Schema.Array(Schema.String),
33});
34const decodeMetadata = Schema.decodeUnknownSync(Schema.fromJsonString(Metadata));
35​
36type SetupPaths = { readonly bundle: string; readonly dataHome: string };
37​
38export async function installGnomeCaptureBundle({ bundle, dataHome }: SetupPaths) {
39 const metadata = decodeMetadata(
40 await NodeFSP.readFile(NodePath.join(bundle, "metadata.json"), "utf8"),
41 );
42 const parent = NodePath.join(dataHome, "gnome-shell", "extensions");
43 const target = NodePath.join(parent, GNOME_CAPTURE_UUID);
44 await NodeFSP.mkdir(parent, { recursive: true });
45 const existing = await NodeFSP.lstat(target).catch((error: NodeJS.ErrnoException) => {
46 if (error.code !== "ENOENT") throw error;
47 return undefined;
48 });
49 if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
50 throw new Error(
51 "The extension installation is not a regular directory. Manage it in GNOME Extensions instead.",
52 );
53 if (existing) {
54 const installed = decodeMetadata(
55 await NodeFSP.readFile(NodePath.join(target, "metadata.json"), "utf8"),
56 );
57 if (installed.version > metadata.version)
58 throw new Error("A newer extension is installed. Update T3 Code instead of replacing it.");
59 }
60 const staged = await NodeFSP.mkdtemp(NodePath.join(parent, ".t3-capture-install-"));
61 let backup: string | undefined;
62 try {
63 for (const name of GNOME_CAPTURE_FILES) {
64 await NodeFSP.copyFile(NodePath.join(bundle, name), NodePath.join(staged, name));
65 await NodeFSP.chmod(NodePath.join(staged, name), 0o644);
66 }
67 await NodeFSP.chmod(staged, 0o755);
68 if (existing) {
69 const backupParent = NodePath.join(dataHome, "t3code", "extension-backups");
70 await NodeFSP.mkdir(backupParent, { recursive: true });
71 backup = NodePath.join(
72 await NodeFSP.mkdtemp(NodePath.join(backupParent, "capture-")),
73 GNOME_CAPTURE_UUID,
74 );
75 await NodeFSP.rename(target, backup);
76 }
77 try {
78 await NodeFSP.rename(staged, target);
79 } catch (error) {
80 if (backup) await NodeFSP.rename(backup, target);
81 throw error;
82 }
83 } finally {
84 await NodeFSP.rm(staged, { recursive: true, force: true });
85 }
87​
88export class GnomeCaptureSetup {
89 private readonly disconnected: Promise<never>;
90 private readonly paths: SetupPaths;
91 private readonly bus: MessageBus;
92 private failure: Error | undefined;
93 constructor(paths: SetupPaths, bus: MessageBus = sessionBus()) {
94 this.paths = paths;
95 this.bus = bus;
96 this.disconnected = new Promise((_, reject) =>
97 bus.on("error", (error: Error) => {
98 this.failure = error;
99 reject(error);
100 }),
101 );
102 void this.disconnected.catch(() => undefined);
103 }
104​
105 close() {
106 this.bus.disconnect();
107 }
108​
109 private async call(message: Omit<MessageLike, "destination" | "path">) {
110 if (this.failure) throw this.failure;
111 let timer: ReturnType<typeof setTimeout> | undefined;
112 try {
113 const reply = await Promise.race([
114 this.bus.call(new Message({ destination: SHELL, path: SHELL_PATH, ...message })),
115 this.disconnected,
116 new Promise<never>((_, reject) => {
117 timer = setTimeout(
118 () =>
119 reject(
120 new Error(
121 "GNOME did not respond. Sign in to a GNOME Wayland session and try again.",
122 ),
123 ),
124 5_000,
125 );
126 }),
127 ]);
128 if (!reply) throw new Error("GNOME returned no setup information.");
129 return reply.body[0] as unknown;
130 } finally {
131 clearTimeout(timer);
132 }
133 }
134​
135 async state(): Promise<DesktopCaptureExtensionState> {
136 try {
137 const [properties, info, bundled, installed] = await Promise.all([
138 this.call({
139 interface: "org.freedesktop.DBus.Properties",
140 member: "GetAll",
141 signature: "s",
142 body: [EXTENSIONS],
143 }).then(decodeProperties),
144 this.call({
145 interface: EXTENSIONS,
146 member: "GetExtensionInfo",
147 signature: "s",
148 body: [GNOME_CAPTURE_UUID],
149 }).then(decodeInfo),
150 NodeFSP.readFile(NodePath.join(this.paths.bundle, "metadata.json"), "utf8").then(
151 decodeMetadata,
152 ),
153 NodeFSP.readFile(
154 NodePath.join(
155 this.paths.dataHome,
156 "gnome-shell",
157 "extensions",
158 GNOME_CAPTURE_UUID,
159 "metadata.json",
160 ),
161 "utf8",
162 )
163 .then(decodeMetadata)
164 .catch((error: NodeJS.ErrnoException) => {
165 if (error.code !== "ENOENT") throw error;
166 return undefined;
167 }),
168 ]);
169 const major = properties.ShellVersion.value.split(".")[0]!;
170 if (!bundled["shell-version"].includes(major))
171 return {
172 status: "unsupported",
173 message: `The bundled extension supports GNOME ${bundled["shell-version"].join(", ")}. This session runs GNOME ${major}.`,
174 };
175 if (!info.state && !installed)
176 return {
177 status: "not-installed",
178 message:
179 "Install the bundled extension to capture the active window without a picker. No download or administrator password is needed.",
180 };
181 if (installed && (!info.state || (info.version && installed.version > info.version.value)))
182 return {
183 status: "restart-required",
184 message:
185 "Installed. Save your work, sign out of GNOME and sign back in, then return here to enable the extension. Restarting T3 Code alone is not enough.",
186 };
187 if ((installed?.version ?? info.version?.value ?? 0) < bundled.version)
188 return {
189 status: "update-required",
190 message:
191 "A newer extension is bundled with this app. Install it, then sign out and back in to load the update.",
192 };
193 if (!properties.UserExtensionsEnabled.value)
194 return {
195 status: "extensions-disabled",
196 message:
197 "GNOME has disabled user extensions. Turn on Extensions in the GNOME Extensions app, then check again. T3 Code will not enable your other extensions for you.",
198 };
199 if (info.state?.value === 1)
200 return {
201 status: "enabled",
202 message: "The T3 Code extension is running. Active-window snapshots are available.",
203 };
204 if (info.state?.value === 3 || info.state?.value === 4)
205 return {
206 status: "error",
207 message:
208 info.error?.value ||
209 "GNOME could not load the extension. Check GNOME Extensions for details, or sign out and back in.",
210 };
211 return {
212 status: "disabled",
213 message:
214 "Enable the T3 Code extension to allow active-window snapshots. You can disable it here at any time.",
215 };
216 } catch (error) {
217 return {
218 status: "error",
219 message: error instanceof Error ? error.message : "Could not check GNOME extension setup.",
220 };
221 }
222 }
223​
224 async perform(action: "install-extension" | "enable-extension" | "disable-extension") {
225 const state = await this.state();
226 if (action === "install-extension") {
227 if (state.status !== "not-installed" && state.status !== "update-required")
228 throw new Error(state.message);
229 await installGnomeCaptureBundle(this.paths);
230 // GNOME discovers a newly installed local extension at the next login.
231 return;
232 }
233 if (action === "enable-extension" && state.status !== "disabled")
234 throw new Error(state.message);
235 const result = await this.call({
236 interface: EXTENSIONS,
237 member: action === "enable-extension" ? "EnableExtension" : "DisableExtension",
238 signature: "s",
239 body: [GNOME_CAPTURE_UUID],
240 });
241 if (result !== true)
242 throw new Error("GNOME has not loaded the extension. Sign out and back in, then try again.");
243 }