The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,806 lines 65.3 KB
Raw
1 // @effect-diagnostics globalTimers:off -- Capture timeouts and Electron overlay animation timers run at native callback boundaries outside Effect fibers.
2
3 import { pipe } from "effect/Function";
4 import {
5 DEFAULT_CLIENT_SETTINGS,
6 DesktopPendingSnapShot,
7 isModifierPairShortcut,
8 snapShotModifierPairLabel,
9 snapShotShortcutModifierPair,
10 type DesktopSnapShot as DesktopSnapShotValue,
11 type DesktopSnapShotShortcutAvailability,
12 type DesktopSnapShotState,
13 DesktopSnapShotSetupAction,
14 type DesktopCaptureConfigRequest,
15 type DesktopCaptureConfigPreview,
16 type DesktopCaptureConfigApplied,
17 type ClientSettings,
18 type SnapShotModifier,
19 type SnapShotModifierPairShortcut,
20 type SnapShotShortcut,
21 type DesktopSnapShotEvent,
22 type DesktopSnapShotId,
23 } from "@t3tools/contracts";
24 import * as Clock from "effect/Clock";
25 import * as Context from "effect/Context";
26 import * as SecureRandom from "effect/crypto/SecureRandom";
27 import * as DateTime from "effect/DateTime";
28 import * as Effect from "effect/Effect";
29 import * as Base64 from "effect/encoding/Base64";
30 import * as FileSystem from "effect/FileSystem";
31 import * as Layer from "effect/Layer";
32 import * as Option from "effect/Option";
33 import * as Path from "effect/Path";
34 import * as Predicate from "effect/Predicate";
35 import * as Ref from "effect/Ref";
36 import * as Schema from "effect/Schema";
37 import * as Semaphore from "effect/Semaphore";
38
39 import * as Electron from "electron";
40
41 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
42 import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
43 import * as DesktopWindow from "../window/DesktopWindow.ts";
44 import { startGlobalShiftShortcutProcess } from "./GlobalShiftShortcutProcess.ts";
45 import { startMacModifierPairShortcutProcess } from "./MacModifierPairShortcutProcess.ts";
46 import { activeWindow, type ActiveWindow } from "./ActiveWindow.ts";
47 import { captureMacWindowSnapshot, type MacSnapShotSource } from "./MacSnapShot.ts";
48 import type { LinuxCaptureFeedback, LinuxWindowMetadata } from "./LinuxSnapShot.ts";
49 import { niriSocketPath } from "./NiriSnapShot.ts";
50 import { CaptureShortcutConfig, niriCaptureConfigPath } from "./CaptureShortcutConfig.ts";
51 import type { PortalCaptureShortcut } from "./PortalCaptureShortcut.ts";
52 import {
53 CaptureSetupRequiredError,
54 isGnomeCaptureSession,
55 niriCaptureBinding,
56 portalShortcutTrigger,
57 } from "./linuxCaptureSession.ts";
58 import {
59 HyprlandCaptureSetup,
60 HYPRLAND_CAPTURE_EXECUTABLE,
61 isHyprlandCaptureSession,
62 hyprlandCaptureShortcut,
63 type HyprlandCapturePaths,
64 } from "./HyprlandSnapShot.ts";
65 import {
66 KdeCaptureSetup,
67 KDE_CAPTURE_EXECUTABLE,
68 isKdeCaptureSession,
69 type KdeCapturePaths,
70 } from "./KdeSnapShot.ts";
71 import {
72 captureRegionWindowSnapshot,
73 makeRegionSnapShotPool,
74 type RegionSnapShotPool,
75 type RegionSnapShotSource,
76 } from "./RegionSnapShot.ts";
77 import { type SnapShotAnimationDestination, SnapShotTransition } from "./SnapShotTransition.ts";
78 import {
79 type AccessibilityProcessPool,
80 makeSnapShotAccessibilityProcessPool,
81 } from "./SnapShotAccessibilityProcess.ts";
82 import * as MacPermissions from "../permissions/MacPermissions.ts";
83 import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts";
84 import { showWindowsCaptureOverlay } from "./WindowsCaptureFeedback.ts";
85
86 import {
87 boundedSnapShotString,
88 isWaylandSession,
89 sameSnapShotShortcut,
90 toElectronAccelerator,
91 snapShotShortcutRegistrationFailureMessage,
92 snapShotShortcutSystemConflict,
93 } from "./snapShot.ts";
94 import * as HostProcess from "@t3tools/shared/HostProcess";
95 import { readImageDimensions } from "@t3tools/shared/imageDimensions";
96
97 const isCaptureSetupRequiredError = Schema.is(CaptureSetupRequiredError);
98
99 const MAX_CAPTURE_WIDTH = 2_560;
100 const MAX_CAPTURE_HEIGHT = 1_600;
101 const SHORTCUT_COOLDOWN_NS = 200_000_000n;
102 const WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE =
103 "Modifier-pair shortcuts aren't available in this Wayland session. Choose another shortcut or use Take snapshot from the command palette.";
104 const FLASH_ANIMATION_DURATION_MS = 180;
105 const FLASH_STATIC_DURATION_MS = 60;
106 const FLASH_FRAME_INTERVAL_MS = 16;
107 const FLASH_PEAK_OPACITY = 0.08;
108 const MAC_SCREEN_CAPTURE_SETTINGS_URL = MAC_PERMISSION_SETTINGS_URLS["screen-recording"];
109 const MAC_SCREEN_CAPTURE_PERMISSION_MESSAGE =
110 "Allow Screen Recording in System Settings, then restart T3 Code.";
111 const MAC_ACCESSIBILITY_PERMISSION_MESSAGE =
112 "Allow Accessibility in System Settings, then restart T3 Code.";
113 const MAC_BOTH_PERMISSIONS_MESSAGE =
114 "Allow Accessibility and Screen Recording in System Settings, then restart T3 Code.";
115 const MAC_PERMISSION_MESSAGES = new Set([
116 MAC_SCREEN_CAPTURE_PERMISSION_MESSAGE,
117 MAC_ACCESSIBILITY_PERMISSION_MESSAGE,
118 MAC_BOTH_PERMISSIONS_MESSAGE,
119 ]);
120
121 const decodePendingCapture = Schema.decodeUnknownEffect(DesktopPendingSnapShot);
122
123 const PendingCaptureJson = Schema.fromJsonString(DesktopPendingSnapShot);
124 const decodePendingCaptureJson = Schema.decodeEffect(PendingCaptureJson);
125 const encodePendingCaptureJson = Schema.encodeEffect(PendingCaptureJson);
126 const DesktopSnapShotOperation = Schema.Literals([
127 "list-pending",
128 "read",
129 "acknowledge",
130 "unsupported",
131 "disabled",
132 "no-window-selected",
133 "window-unavailable",
134 "setup-required",
135 "capture",
136 ]);
137
138 export class DesktopSnapShotError extends Schema.TaggedError<DesktopSnapShotError>()(
139 "DesktopSnapShotError",
140 {
141 operation: DesktopSnapShotOperation,
142 captureId: Schema.optional(Schema.String),
143 cause: Schema.optional(Schema.Defect()),
144 },
145 ) {
146 override get message(): string {
147 switch (this.operation) {
148 case "list-pending":
149 return "Could not list pending snapshots.";
150 case "read":
151 return "Could not read the snapshot.";
152 case "acknowledge":
153 return "Could not remove the snapshot.";
154 case "unsupported":
155 return "SnapShots are not supported here.";
156 case "disabled":
157 return "Enable SnapShots in Settings first.";
158 case "no-window-selected":
159 return "No window was selected.";
160 case "window-unavailable":
161 return "The active window is not available for capture.";
162 case "setup-required":
163 return "Finish SnapShot setup in Settings → SnapShots.";
164 case "capture":
165 return "Could not capture the active window.";
166 }
167 }
168 }
169
170 const isDesktopSnapShotError = Schema.is(DesktopSnapShotError);
171
172 class SnapShotShortcutError extends Schema.TaggedError<SnapShotShortcutError>()(
173 "SnapShotShortcutError",
174 { cause: Schema.Defect() },
175 ) {
176 override get message(): string {
177 return "Could not register the SnapShot shortcut.";
178 }
179 }
180
181 const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause });
182
183 function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError {
184 if (isDesktopSnapShotError(cause)) return cause;
185 const operation = isCaptureSetupRequiredError(cause) ? "setup-required" : "capture";
186 return new DesktopSnapShotError({ operation, captureId, cause });
187 }
188
189 export class DesktopSnapShot extends Context.Service<
190 DesktopSnapShot,
191 {
192 readonly initialize: Effect.Effect<void>;
193 readonly configure: (settings: ClientSettings) => Effect.Effect<void>;
194 readonly requestPermissions: (includeAccessibility: boolean) => Effect.Effect<void>;
195 readonly state: Effect.Effect<DesktopSnapShotState>;
196 readonly setup: (
197 action: DesktopSnapShotSetupAction,
198 ) => Effect.Effect<void, DesktopSnapShotSetupError>;
199 readonly previewConfig: (
200 request: DesktopCaptureConfigRequest,
201 selectedPath?: string,
202 ) => Effect.Effect<DesktopCaptureConfigPreview, DesktopSnapShotSetupError>;
203 readonly applyConfig: (
204 previewId: string,
205 ) => Effect.Effect<DesktopCaptureConfigApplied, DesktopSnapShotSetupError>;
206 readonly checkShortcut: (
207 shortcut: SnapShotShortcut,
208 ) => Effect.Effect<DesktopSnapShotShortcutAvailability>;
209 readonly setShortcutSuppressed: (suppressed: boolean) => Effect.Effect<void>;
210 readonly capture: Effect.Effect<void, DesktopSnapShotError>;
211 readonly listPending: Effect.Effect<
212 ReadonlyArray<DesktopPendingSnapShot>,
213 DesktopSnapShotError
214 >;
215 readonly read: (id: string) => Effect.Effect<DesktopSnapShotValue, DesktopSnapShotError>;
216 readonly setAnimationDestination: (
217 id: string,
218 destination: SnapShotAnimationDestination,
219 ) => Effect.Effect<void>;
220 readonly dismissAnimation: (id: string) => Effect.Effect<void>;
221 readonly acknowledge: (id: string) => Effect.Effect<void, DesktopSnapShotError>;
222 }
223 >()("@t3tools/desktop/snapShot/DesktopSnapShot") {}
224
225 export class DesktopSnapShotSetupError extends Schema.TaggedError<DesktopSnapShotSetupError>()(
226 "DesktopSnapShotSetupError",
227 {
228 action: Schema.Union([
229 DesktopSnapShotSetupAction,
230 Schema.Literals(["preview-config", "apply-config"]),
231 ]),
232 reason: Schema.Literals(["unsupported-session", "setup-failed", "shortcut-permissions"]),
233 step: Schema.optional(Schema.Literals(["find-window", "capture-window"])),
234 status: Schema.optional(Schema.Literals(["missing", "timed-out", "exited", "failed"])),
235 exitCode: Schema.optional(Schema.Number),
236 /** The running app, as macOS lists it under Privacy & Security. */
237 appName: Schema.optional(Schema.String),
238 cause: Schema.optional(Schema.Defect()),
239 },
240 ) {
241 override get message(): string {
242 if (this.action === "test-mac-capture") {
243 if (this.reason === "unsupported-session") return "Test capture requires macOS.";
244 const summary = "Could not capture a test snapshot.";
245 if (this.step === undefined) return summary;
246 if (this.status === "missing") return `${summary} No window is available to capture.`;
247 const [task, command] =
248 this.step === "find-window"
249 ? ["Finding the front window", "osascript"]
250 : ["Capturing the window", "screencapture"];
251 const failure =
252 this.status === "timed-out"
253 ? `${task} timed out.`
254 : this.status === "exited" && this.exitCode !== undefined
255 ? `${task} failed: ${command} exited with code ${this.exitCode}.`
256 : `${task} failed.`;
257 // macOS can report both permissions as allowed while they belong to another install.
258 return this.appName === undefined
259 ? `${summary} ${failure}`
260 : `${summary} ${failure} macOS grants Screen Recording and Accessibility to each app separately. In System Settings, open Privacy & Security and check that "${this.appName}" is allowed for both.`;
261 }
262 if (this.action === "preview-config" || this.action === "apply-config") {
263 if (this.reason === "unsupported-session")
264 return "Config setup requires a Niri or Hyprland session.";
265 return this.action === "preview-config"
266 ? "Couldn't prepare your capture shortcut changes."
267 : "Couldn't save your capture shortcut.";
268 }
269 const kde = this.action === "install-kde-helper" || this.action === "remove-kde-helper";
270 const hyprland =
271 this.action === "install-hyprland-helper" || this.action === "remove-hyprland-helper";
272 if (this.reason === "unsupported-session")
273 return hyprland
274 ? "Helper setup requires a Hyprland Wayland session outside a sandbox."
275 : kde
276 ? "Helper setup requires a KDE Plasma Wayland session outside a sandbox."
277 : "Extension setup requires a GNOME Wayland session outside a sandbox.";
278 if (this.reason === "shortcut-permissions") return "Could not open shortcut permissions.";
279 return hyprland
280 ? "Could not set up Hyprland capture."
281 : kde
282 ? "Could not set up KDE capture."
283 : "Could not set up the GNOME extension.";
284 }
285 }
286
287 function macCommandFailure(cause: unknown) {
288 const failure = Predicate.isObject(cause) ? cause : {};
289 if ("killed" in failure && failure.killed === true) return { status: "timed-out" } as const;
290 return "code" in failure && typeof failure.code === "number"
291 ? ({ status: "exited", exitCode: failure.code } as const)
292 : ({ status: "failed" } as const);
293 }
294
295 type SnapShotSystemAnimationSettings = Pick<
296 ReturnType<typeof Electron.systemPreferences.getAnimationSettings>,
297 "prefersReducedMotion" | "shouldRenderRichAnimation"
298 >;
299
300 function captureMode(platform: NodeJS.Platform): DesktopSnapShotState["mode"] {
301 if (platform === "linux")
302 return isWaylandSession(platform, process.env) ? "portal" : "unavailable";
303 return platform === "darwin" || platform === "win32" ? "direct" : "unavailable";
304 }
305
306 function shouldAnimateSnapShot(settings: SnapShotSystemAnimationSettings): boolean {
307 return settings.shouldRenderRichAnimation && !settings.prefersReducedMotion;
308 }
309
310 function snapShotThumbnailSize(active: ActiveWindow | undefined): Electron.Size {
311 if (!active) return { width: 2_560, height: 1_600 };
312 return {
313 width: Math.min(Math.max(active.bounds.width, 1), MAX_CAPTURE_WIDTH),
314 height: Math.min(Math.max(active.bounds.height, 1), MAX_CAPTURE_HEIGHT),
315 };
316 }
317
318 function snapShotIconDataUrl(
319 ...icons: ReadonlyArray<Electron.NativeImage | null | undefined>
320 ): string | undefined {
321 const icon = icons.find((candidate): candidate is Electron.NativeImage =>
322 Boolean(candidate && !candidate.isEmpty()),
323 );
324 if (!icon) return undefined;
325 return icon.resize({ width: 64, height: 64, quality: "best" }).toDataURL({ scaleFactor: 2 });
326 }
327
328 async function appFileIcon(
329 path: string,
330 platform: NodeJS.Platform,
331 ): Promise<Electron.NativeImage | undefined> {
332 if (platform === "darwin") {
333 const thumbnail = await Electron.nativeImage
334 .createThumbnailFromPath(path, { width: 64, height: 64 })
335 .catch(() => undefined);
336 if (thumbnail && !thumbnail.isEmpty()) return thumbnail;
337 }
338 return Electron.app.getFileIcon(path, { size: "normal" }).catch(() => undefined);
339 }
340
341 async function iconDataUrl(
342 source: { readonly appIcon?: Electron.NativeImage | null },
343 active: ActiveWindow | undefined,
344 platform: NodeJS.Platform,
345 ): Promise<string | undefined> {
346 try {
347 const fileIcon = active?.owner.path
348 ? await appFileIcon(active.owner.path, platform)
349 : undefined;
350 return snapShotIconDataUrl(fileIcon, source.appIcon);
351 } catch {
352 return undefined;
353 }
354 }
355
356 function snapShotAppName(
357 active: ActiveWindow | undefined,
358 linuxWindow: LinuxWindowMetadata | undefined,
359 sourceName: string,
360 ): string {
361 const appName =
362 active?.owner.name.trim() || linuxWindow?.appName.trim() || sourceName.trim() || "Window";
363 if (active?.platform !== "windows") return appName;
364 return appName.replace(/\.exe$/i, "").trim() || appName;
365 }
366
367 async function requestMacScreenCapturePermission(): Promise<string | null> {
368 let status: ReturnType<typeof Electron.systemPreferences.getMediaAccessStatus>;
369 try {
370 status = Electron.systemPreferences.getMediaAccessStatus("screen");
371 if (status === "granted") return null;
372 if (status === "not-determined") {
373 try {
374 await Electron.desktopCapturer.getSources({
375 types: ["screen"],
376 thumbnailSize: { width: 1, height: 1 },
377 });
378 } catch {}
379 status = Electron.systemPreferences.getMediaAccessStatus("screen");
380 if (status === "granted") return null;
381 }
382 } catch {}
383 await Electron.shell.openExternal(MAC_SCREEN_CAPTURE_SETTINGS_URL).catch(() => undefined);
384 return MAC_SCREEN_CAPTURE_PERMISSION_MESSAGE;
385 }
386
387 function currentMacPermissions(): NonNullable<DesktopSnapShotState["macPermissions"]> {
388 return {
389 screenRecording: Electron.systemPreferences.getMediaAccessStatus("screen") === "granted",
390 accessibility: Electron.systemPreferences.isTrustedAccessibilityClient(false),
391 };
392 }
393
394 function macPermissionMessage(
395 permissions: NonNullable<DesktopSnapShotState["macPermissions"]>,
396 includeAccessibility: boolean,
397 ): string | null {
398 const accessibilityGranted = !includeAccessibility || permissions.accessibility;
399 if (!accessibilityGranted && !permissions.screenRecording) {
400 return MAC_BOTH_PERMISSIONS_MESSAGE;
401 }
402 if (!accessibilityGranted) {
403 return MAC_ACCESSIBILITY_PERMISSION_MESSAGE;
404 }
405 return permissions.screenRecording ? null : MAC_SCREEN_CAPTURE_PERMISSION_MESSAGE;
406 }
407
408 function currentMacSnapShotPermissionMessage(includeAccessibility: boolean): string | null {
409 return macPermissionMessage(
410 {
411 screenRecording: Electron.systemPreferences.getMediaAccessStatus("screen") === "granted",
412 accessibility:
413 !includeAccessibility || Electron.systemPreferences.isTrustedAccessibilityClient(false),
414 },
415 includeAccessibility,
416 );
417 }
418
419 async function requestMacSnapShotPermissions(
420 includeAccessibility: boolean,
421 ): Promise<string | null> {
422 const accessibilityGranted =
423 !includeAccessibility || Electron.systemPreferences.isTrustedAccessibilityClient(true);
424 const screenMessage = await requestMacScreenCapturePermission();
425 if (!accessibilityGranted && screenMessage) {
426 return MAC_BOTH_PERMISSIONS_MESSAGE;
427 }
428 if (!accessibilityGranted) {
429 return MAC_ACCESSIBILITY_PERMISSION_MESSAGE;
430 }
431 return screenMessage;
432 }
433
434 function snapShotImageSize(png: Buffer, fallback: Electron.Rectangle): Electron.Size {
435 // Capture backends already validate or encode the PNG. Reading its header
436 // avoids decoding every pixel again just to size accessibility coordinates.
437 const size = readImageDimensions(png);
438 if (size) return size;
439 return {
440 width: Math.max(1, Math.round(fallback.width)),
441 height: Math.max(1, Math.round(fallback.height)),
442 };
443 }
444
445 async function captureSource({
446 mode,
447 captureId,
448 platform,
449 settings,
450 flash,
451 transition,
452 imageTempPath,
453 linuxAppId,
454 kdeCapturePaths,
455 hyprlandCapturePaths,
456 accessibilityProcessPool,
457 regionSnapShotPool,
458 prepareReveal,
459 onLinuxFeedback,
460 }: {
461 mode: DesktopSnapShotState["mode"];
462 captureId: string;
463 platform: NodeJS.Platform;
464 settings: ClientSettings;
465 flash: SnapShotFlash;
466 transition: SnapShotTransition;
467 imageTempPath: string;
468 linuxAppId: string;
469 kdeCapturePaths: KdeCapturePaths;
470 hyprlandCapturePaths: HyprlandCapturePaths;
471 accessibilityProcessPool: AccessibilityProcessPool;
472 regionSnapShotPool: RegionSnapShotPool;
473 prepareReveal: () => Promise<void>;
474 onLinuxFeedback: (feedback: LinuxCaptureFeedback) => void;
475 }) {
476 let active: ActiveWindow | undefined;
477 let linuxWindow: LinuxWindowMetadata | undefined;
478 let linuxFeedback: LinuxCaptureFeedback | undefined;
479 let linuxActivationFailure: { readonly cause: unknown } | undefined;
480 const destinationWindow =
481 Electron.BrowserWindow.getFocusedWindow() ??
482 Electron.BrowserWindow.getAllWindows().find((window) => !window.isDestroyed());
483 const destinationWindowBounds = destinationWindow?.getBounds();
484 {
485 const revealPreparation =
486 platform === "win32" ? prepareReveal().catch(() => undefined) : Promise.resolve();
487 if (mode === "direct") {
488 active = await activeWindow(platform);
489 }
490
491 let source: MacSnapShotSource | RegionSnapShotSource | Electron.DesktopCapturerSource;
492 let png: Buffer;
493 let imageTempReady = false;
494 if (platform === "darwin") {
495 if (!active) {
496 throw new DesktopSnapShotError({ operation: "window-unavailable", captureId });
497 }
498 ({ source, png } = await captureMacWindowSnapshot(
499 active,
500 imageTempPath,
501 snapShotThumbnailSize(active),
502 ));
503 imageTempReady = true;
504 } else if (mode === "direct") {
505 if (!active) {
506 throw new DesktopSnapShotError({ operation: "window-unavailable", captureId });
507 }
508 ({ source, png } = await captureRegionWindowSnapshot(
509 regionSnapShotPool,
510 active,
511 snapShotThumbnailSize(active),
512 ));
513 } else {
514 const { captureLinuxWindow } = await import("./LinuxSnapShot.ts");
515 const snapshot = await captureLinuxWindow(
516 linuxAppId,
517 {
518 flash: settings.snapShotFlash,
519 animate:
520 settings.snapShotAnimations &&
521 shouldAnimateSnapShot(Electron.systemPreferences.getAnimationSettings()),
522 },
523 kdeCapturePaths,
524 hyprlandCapturePaths,
525 );
526 if (snapshot) {
527 linuxFeedback = snapshot.feedback;
528 if (linuxFeedback) onLinuxFeedback(linuxFeedback);
529 linuxWindow = snapshot.window;
530 source = { name: linuxWindow?.title || "Active window" };
531 png = snapshot.png;
532 } else {
533 const [selected] = await Electron.desktopCapturer.getSources({
534 types: ["window", "screen"],
535 thumbnailSize: snapShotThumbnailSize(active),
536 fetchWindowIcons: true,
537 });
538 if (!selected || selected.thumbnail.isEmpty()) {
539 throw new DesktopSnapShotError({
540 operation: "no-window-selected",
541 captureId,
542 });
543 }
544 source = selected;
545 png = selected.thumbnail.toPNG();
546 }
547 }
548 const accessibleIdentity = active
549 ? active
550 : linuxWindow?.processId
551 ? {
552 title: linuxWindow.title,
553 bounds: linuxWindow.bounds,
554 ...(linuxWindow.clientBounds ? { clientBounds: linuxWindow.clientBounds } : {}),
555 owner: { processId: linuxWindow.processId },
556 ...(linuxWindow.accessibilityBoundsReliable === false
557 ? { accessibilityBoundsReliable: false }
558 : {}),
559 }
560 : undefined;
561 const accessibilityRead =
562 accessibleIdentity && settings.snapShotIncludeAccessibility
563 ? accessibilityProcessPool.read({
564 active: accessibleIdentity,
565 platform,
566 sourceTitle: source.name,
567 imageSize: snapShotImageSize(png, active?.bounds ?? accessibleIdentity.bounds),
568 })
569 : undefined;
570 if (accessibilityRead) {
571 await accessibilityRead.started;
572 }
573 const contextPromise = accessibilityRead?.result ?? Promise.resolve(undefined);
574 await revealPreparation;
575 if (linuxFeedback && destinationWindow && !destinationWindow.isDestroyed()) {
576 if (destinationWindow.isMinimized()) destinationWindow.restore();
577 if (!destinationWindow.isVisible()) destinationWindow.show();
578 await linuxFeedback.activate(destinationWindow.getTitle()).catch((cause: unknown) => {
579 linuxActivationFailure = { cause };
580 });
581 }
582 const animationStarted =
583 linuxFeedback?.animationStarted ??
584 (await showCaptureFeedback(
585 transition,
586 flash,
587 captureId,
588 `data:image/png;base64,${png.toString("base64")}`,
589 settings,
590 active,
591 platform,
592 destinationWindowBounds,
593 ));
594 return {
595 source,
596 active,
597 linuxWindow,
598 linuxActivationFailure,
599 contextPromise,
600 animationStarted,
601 png,
602 imageTempReady,
603 };
604 }
605 }
606
607 function createSnapShotFlashWindow(bounds: Electron.Rectangle): Electron.BaseWindow {
608 const window = new Electron.BaseWindow({
609 ...bounds,
610 alwaysOnTop: true,
611 focusable: false,
612 frame: false,
613 hasShadow: false,
614 resizable: false,
615 show: false,
616 skipTaskbar: true,
617 backgroundColor: "#ffffff",
618 opacity: FLASH_PEAK_OPACITY,
619 transparent: false,
620 });
621 window.setIgnoreMouseEvents(true);
622 return window;
623 }
624
625 class SnapShotFlash {
626 private flashWindow: Electron.BaseWindow | undefined;
627 private animationTimer: ReturnType<typeof setInterval> | undefined;
628 private closeTimer: ReturnType<typeof setTimeout> | undefined;
629 private readonly showWindow: (window: Electron.BaseWindow) => void;
630
631 constructor(
632 showWindow: (window: Electron.BaseWindow) => void = (window) => window.showInactive(),
633 ) {
634 this.showWindow = showWindow;
635 }
636
637 showAnimated(bounds: Electron.Rectangle): Promise<void> {
638 return this.show(bounds, true, FLASH_ANIMATION_DURATION_MS);
639 }
640
641 showStatic(bounds: Electron.Rectangle): Promise<void> {
642 return this.show(bounds, false, FLASH_STATIC_DURATION_MS);
643 }
644
645 dispose(): void {
646 if (this.animationTimer) clearInterval(this.animationTimer);
647 if (this.closeTimer) clearTimeout(this.closeTimer);
648 this.animationTimer = undefined;
649 this.closeTimer = undefined;
650 if (this.flashWindow && !this.flashWindow.isDestroyed()) this.flashWindow.destroy();
651 this.flashWindow = undefined;
652 }
653
654 private async show(
655 bounds: Electron.Rectangle,
656 animated: boolean,
657 durationMs: number,
658 ): Promise<void> {
659 this.dispose();
660 const window = createSnapShotFlashWindow(bounds);
661 this.flashWindow = window;
662 if (window.isDestroyed()) return;
663 this.showWindow(window);
664 if (animated) {
665 let opacity = FLASH_PEAK_OPACITY;
666 this.animationTimer = setInterval(() => {
667 if (window.isDestroyed()) return this.dispose();
668 opacity = Math.max(
669 0,
670 opacity - (FLASH_PEAK_OPACITY * FLASH_FRAME_INTERVAL_MS) / durationMs,
671 );
672 window.setOpacity(opacity);
673 }, FLASH_FRAME_INTERVAL_MS);
674 }
675 this.closeTimer = setTimeout(() => {
676 if (this.flashWindow === window) this.dispose();
677 }, durationMs);
678 }
679 }
680
681 function snapShotFlashBounds(
682 active: ActiveWindow | undefined,
683 platform: NodeJS.Platform,
684 ): Electron.Rectangle {
685 if (!active) return Electron.screen.getPrimaryDisplay().bounds;
686 return platform === "win32"
687 ? Electron.screen.screenToDipRect(null, active.bounds)
688 : active.bounds;
689 }
690
691 async function showCaptureFeedback(
692 transition: SnapShotTransition,
693 flash: SnapShotFlash,
694 captureId: string,
695 snapshotDataUrl: string,
696 settings: ClientSettings,
697 active: ActiveWindow | undefined,
698 platform: NodeJS.Platform,
699 destinationWindowBounds?: Electron.Rectangle,
700 ): Promise<boolean> {
701 // Wayland does not let this client position overlays on another app's window.
702 if (platform === "linux") return false;
703 const bounds = snapShotFlashBounds(active, platform);
704 const animationsEnabled =
705 settings.snapShotAnimations &&
706 shouldAnimateSnapShot(Electron.systemPreferences.getAnimationSettings());
707 if (animationsEnabled) {
708 try {
709 await transition.begin(
710 captureId,
711 bounds,
712 snapshotDataUrl,
713 settings.snapShotFlash,
714 destinationWindowBounds,
715 );
716 return true;
717 } catch {
718 transition.dispose();
719 }
720 }
721 if (!settings.snapShotFlash) return false;
722 const playback = animationsEnabled ? flash.showAnimated(bounds) : flash.showStatic(bounds);
723 await playback.catch(() => undefined);
724 return false;
725 }
726
727 function observedPairMessage(
728 shortcut: SnapShotModifierPairShortcut,
729 platform: NodeJS.Platform,
730 ): string {
731 const modifier = snapShotShortcutModifierPair(shortcut);
732 const label = snapShotModifierPairLabel(modifier, platform === "darwin");
733 const base = `${label} is observed and cannot be reserved exclusively.`;
734 if (modifier === "meta" && platform !== "darwin") {
735 return `${base} This key can also open the system's own menu.`;
736 }
737 if (modifier === "alt" && platform === "win32") {
738 return `${base} This key can also activate app menu bars.`;
739 }
740 return base;
741 }
742
743 function probeGlobalShortcut(accelerator: string): DesktopSnapShotShortcutAvailability {
744 try {
745 if (!Electron.globalShortcut.register(accelerator, () => undefined)) {
746 return {
747 available: false,
748 message: "This shortcut is already used by the system or another app.",
749 };
750 }
751 Electron.globalShortcut.unregister(accelerator);
752 return { available: true, message: null };
753 } catch {
754 return { available: false, message: "The system could not register this shortcut." };
755 }
756 }
757
758 export const make = Effect.gen(function* () {
759 const environment = yield* DesktopEnvironment.DesktopEnvironment;
760 const permissions = yield* MacPermissions.MacPermissions;
761 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
762 const desktopWindow = yield* DesktopWindow.DesktopWindow;
763 const fileSystem = yield* FileSystem.FileSystem;
764 const path = yield* Path.Path;
765 const random = yield* SecureRandom.SecureRandom;
766 const settingsRef = yield* Ref.make(DEFAULT_CLIENT_SETTINGS);
767 const stateRef = yield* Ref.make<DesktopSnapShotState>({
768 mode: captureMode(environment.platform),
769 shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
770 shortcutRegistered: false,
771 shortcutMessage: null,
772 message: null,
773 });
774 const snapshotMutex = yield* Semaphore.make(1);
775 const configurationMutex = yield* Semaphore.make(1);
776 const context = yield* Effect.context<
777 DesktopEnvironment.DesktopEnvironment | DesktopWindow.DesktopWindow
778 >();
779 const runPromise = Effect.runPromiseWith(context);
780 const captureDirectory = path.join(environment.stateDir, "snap-shots");
781 const linuxAppId = environment.linuxDesktopEntryName.replace(/\.desktop$/, "");
782 const home = yield* HostProcess.HomeDirectory;
783 // Shell discovery can replace XDG_CURRENT_DESKTOP after startup, so read the live env per state.
784 const hostEnv = yield* HostProcess.Environment;
785 let shortcutVerified = false;
786 const gnomeSetupPaths = {
787 bundle: environment.isPackaged
788 ? path.join(environment.resourcesPath, "gnome-extension")
789 : path.join(environment.appRoot, "apps/desktop/gnome-extension"),
790 dataHome: path.dirname(environment.linuxApplicationsDir),
791 };
792 const kdeCapturePaths = {
793 bundle: environment.isPackaged
794 ? path.join(environment.resourcesPath, "kde-capture", KDE_CAPTURE_EXECUTABLE)
795 : path.join(
796 environment.appRoot,
797 "native/kde-snap-shot/target/release",
798 KDE_CAPTURE_EXECUTABLE,
799 ),
800 dataHome: path.dirname(environment.linuxApplicationsDir),
801 };
802 const hasGnomeSetup = () =>
803 captureMode(environment.platform) === "portal" && isGnomeCaptureSession(process.env);
804 const hyprlandCapturePaths = {
805 bundle: environment.isPackaged
806 ? path.join(environment.resourcesPath, "hyprland-capture", HYPRLAND_CAPTURE_EXECUTABLE)
807 : path.join(
808 environment.appRoot,
809 "native/hyprland-snap-shot/target/release",
810 HYPRLAND_CAPTURE_EXECUTABLE,
811 ),
812 dataHome: path.dirname(environment.linuxApplicationsDir),
813 };
814 const shiftShortcutWorkerPath = path.join(__dirname, "snapShot", "GlobalShiftShortcutWorker.cjs");
815 const shortcutConfig = new CaptureShortcutConfig(home);
816 const accessibilityWorkerPath = path.join(
817 __dirname,
818 "snapShot",
819 "SnapShotAccessibilityWorker.cjs",
820 );
821 const accessibilityProcessPool = makeSnapShotAccessibilityProcessPool(accessibilityWorkerPath);
822 const regionSnapShotPool = makeRegionSnapShotPool(
823 path.join(__dirname, "snapShot", "RegionSnapShotWorker.cjs"),
824 );
825 let registeredAccelerator: string | undefined;
826 let initialized = false;
827 let portalShortcut: PortalCaptureShortcut | undefined;
828 let shortcutGeneration = 0;
829 let shortcutSuppressed = false;
830 let lastShortcutAt: bigint | undefined;
831 let stopShiftShortcut: (() => void) | undefined;
832 const showCaptureWindow =
833 environment.platform === "win32" ? showWindowsCaptureOverlay : undefined;
834 const flash = new SnapShotFlash(showCaptureWindow);
835 const transition = new SnapShotTransition({
836 showWindow: showCaptureWindow,
837 waitForCompositorFrame: environment.platform === "win32",
838 // Transparent Windows surfaces must not resize while their compositor animation is running.
839 boundOverlayToCaptureDisplays: environment.platform !== "linux",
840 alwaysOnTopLevel: environment.platform === "linux" ? undefined : "pop-up-menu",
841 });
842 let linuxFeedback: { id: string; feedback: LinuxCaptureFeedback } | undefined;
843 const closeLinuxFeedback = (id?: string) => {
844 if (!linuxFeedback || (id !== undefined && linuxFeedback.id !== id)) return;
845 linuxFeedback.feedback.close();
846 linuxFeedback = undefined;
847 };
848 const completeLinuxFeedback = async (id: string) => {
849 if (linuxFeedback?.id !== id) return;
850 const pending = linuxFeedback;
851 await pending.feedback.complete().catch(() => undefined);
852 if (linuxFeedback === pending) linuxFeedback = undefined;
853 };
854
855 const startPairShortcutProcess = (
856 modifier: SnapShotModifier,
857 onTrigger: () => void,
858 onFailure: (error: Error) => void,
859 ) =>
860 environment.platform === "darwin"
861 ? startMacModifierPairShortcutProcess(modifier, onTrigger, onFailure)
862 : startGlobalShiftShortcutProcess(shiftShortcutWorkerPath, modifier, onTrigger, onFailure);
863
864 const releaseShortcut = () => {
865 shortcutGeneration++;
866 portalShortcut?.close();
867 portalShortcut = undefined;
868 if (registeredAccelerator) {
869 Electron.globalShortcut.unregister(registeredAccelerator);
870 registeredAccelerator = undefined;
871 }
872 stopShiftShortcut?.();
873 stopShiftShortcut = undefined;
874 };
875
876 const emit = (event: DesktopSnapShotEvent) =>
877 desktopWindow.dispatchSnapShotEvent(event).pipe(Effect.ignoreCause);
878 const setFailure = (message: string, captureId?: string) =>
879 Ref.update(stateRef, (state) => ({ ...state, message })).pipe(
880 Effect.andThen(
881 emit(
882 captureId ? { type: "failed", id: captureId as DesktopSnapShotId } : { type: "failed" },
883 ),
884 ),
885 );
886 const setShortcutFailure = (shortcutMessage: string) =>
887 Effect.sync(() => {
888 shortcutVerified = false;
889 }).pipe(
890 Effect.andThen(
891 Ref.update(stateRef, (state) => ({
892 ...state,
893 shortcutRegistered: false,
894 shortcutMessage,
895 })),
896 ),
897 Effect.andThen(emit({ type: "failed" })),
898 );
899
900 const discardCapture = Effect.fn("desktop.snapShot.discardCapture")(function* (id: string) {
901 closeLinuxFeedback(id);
902 transition.dismiss(id);
903 yield* Effect.forEach(
904 [`${id}.png`, `${id}.tmp.png`, `${id}.json`, `${id}.json.tmp`],
905 (name) => fileSystem.remove(path.join(captureDirectory, name), { force: true }),
906 { concurrency: "unbounded", discard: true },
907 ).pipe(Effect.ignore);
908 });
909
910 const prepareCapture = Effect.fn("desktop.snapShot.prepareCapture")(function* (
911 settings: ClientSettings,
912 ) {
913 const id = yield* random.uuidV4().pipe(Effect.mapError((cause) => captureFailure(cause)));
914 const mode = captureMode(environment.platform);
915 if (mode === "unavailable") {
916 return yield* new DesktopSnapShotError({ operation: "unsupported", captureId: id });
917 }
918 const imageTempPath = path.join(captureDirectory, `${id}.tmp.png`);
919
920 return yield* Effect.gen(function* () {
921 // Retire feedback before capture so rapid captures cannot photograph the previous overlay.
922 closeLinuxFeedback();
923 flash.dispose();
924 transition.dispose();
925 yield* fileSystem.makeDirectory(captureDirectory, { recursive: true });
926 yield* emit({ type: "requested", id: id as DesktopSnapShotId });
927 const snapshot = yield* Effect.tryPromise({
928 try: () =>
929 captureSource({
930 mode,
931 captureId: id,
932 platform: environment.platform,
933 settings,
934 flash,
935 transition,
936 imageTempPath,
937 linuxAppId,
938 kdeCapturePaths,
939 hyprlandCapturePaths,
940 accessibilityProcessPool,
941 regionSnapShotPool,
942 prepareReveal: () => runPromise(desktopWindow.prepareCaptureReveal),
943 onLinuxFeedback: (feedback) => {
944 linuxFeedback = { id, feedback };
945 },
946 }),
947 catch: (cause) => captureFailure(cause, id),
948 });
949 const capturedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
950 if (snapshot.linuxActivationFailure) {
951 yield* Effect.logWarning(
952 "The compositor could not activate T3 Code after the snapshot",
953 snapshot.linuxActivationFailure.cause,
954 );
955 }
956 if (snapshot.animationStarted) {
957 yield* emit({ type: "started", id: id as DesktopSnapShotId });
958 } else {
959 yield* desktopWindow.activate.pipe(Effect.ignoreCause);
960 }
961 return { id, capturedAt, ...snapshot };
962 }).pipe(Effect.mapError((cause) => captureFailure(cause, id)));
963 });
964
965 const persistCapture = Effect.fn("desktop.snapShot.persistCapture")(function* (
966 capture: Effect.Success<ReturnType<typeof prepareCapture>>,
967 ) {
968 const { id, capturedAt, source, active, linuxWindow, contextPromise, png, imageTempReady } =
969 capture;
970 const imagePath = path.join(captureDirectory, `${id}.png`);
971 const imageTempPath = path.join(captureDirectory, `${id}.tmp.png`);
972 const metadataPath = path.join(captureDirectory, `${id}.json`);
973
974 yield* Effect.gen(function* () {
975 const accessibilityContext = yield* Effect.promise(() => contextPromise);
976 const appIconDataUrl = yield* Effect.promise(() =>
977 iconDataUrl(source, active, environment.platform),
978 );
979 const appIdentifier = boundedSnapShotString(
980 active?.platform === "macos" ? active.owner.bundleId : linuxWindow?.appIdentifier,
981 255,
982 );
983 const pending = yield* decodePendingCapture({
984 id,
985 name: `window-${capturedAt.replaceAll(":", "-")}.png`,
986 mimeType: "image/png",
987 sizeBytes: png.byteLength,
988 source: {
989 kind: "snap-shot",
990 capturedAt,
991 appName:
992 boundedSnapShotString(snapShotAppName(active, linuxWindow, source.name), 255) ??
993 "Window",
994 windowTitle:
995 boundedSnapShotString(
996 active?.title.trim() || linuxWindow?.title.trim() || source.name,
997 1_000,
998 ) ?? "",
999 ...(accessibilityContext?.accessibleText
1000 ? { accessibleText: accessibilityContext.accessibleText }
1001 : {}),
1002 ...(accessibilityContext?.accessibility
1003 ? { accessibility: accessibilityContext.accessibility }
1004 : {}),
1005 ...(appIdentifier ? { appIdentifier } : {}),
1006 ...(appIconDataUrl ? { appIconDataUrl } : {}),
1007 },
1008 });
1009 if (!imageTempReady) yield* fileSystem.writeFile(imageTempPath, png);
1010 yield* fileSystem.rename(imageTempPath, imagePath);
1011 yield* fileSystem.writeFileString(
1012 metadataPath + ".tmp",
1013 yield* encodePendingCaptureJson(pending),
1014 );
1015 yield* fileSystem.rename(metadataPath + ".tmp", metadataPath);
1016 }).pipe(Effect.mapError((cause) => captureFailure(cause, id)));
1017 });
1018
1019 const capture = Effect.gen(function* () {
1020 const settings = yield* Ref.get(settingsRef);
1021 if (!settings.snapShotEnabled) {
1022 return yield* new DesktopSnapShotError({ operation: "disabled" });
1023 }
1024 const prepared = yield* prepareCapture(settings).pipe(
1025 Effect.tapError((error) =>
1026 (error.captureId ? discardCapture(error.captureId) : Effect.void).pipe(
1027 Effect.andThen(setFailure(error.message, error.captureId)),
1028 ),
1029 ),
1030 snapshotMutex.withPermitsIfAvailable(1),
1031 );
1032 if (Option.isNone(prepared)) return;
1033 const capture = prepared.value;
1034 yield* persistCapture(capture).pipe(
1035 Effect.tap(() =>
1036 Ref.update(stateRef, (state) => ({ ...state, message: null })).pipe(
1037 Effect.andThen(emit({ type: "ready", id: capture.id as DesktopSnapShotId })),
1038 ),
1039 ),
1040 Effect.tapError((error) =>
1041 discardCapture(capture.id).pipe(
1042 Effect.andThen(Ref.update(stateRef, (state) => ({ ...state, message: error.message }))),
1043 Effect.andThen(emit({ type: "failed", id: capture.id as DesktopSnapShotId })),
1044 ),
1045 ),
1046 );
1047 }).pipe(Effect.withSpan("desktop.snapShot.capture"));
1048
1049 const captureFromShortcut = Effect.gen(function* () {
1050 // Repeated shortcuts must not replace a capture during its flight.
1051 if (shortcutSuppressed || transition.isAnimating) return;
1052 shortcutVerified = true;
1053 const now = yield* Clock.currentTimeNanos;
1054 if (lastShortcutAt !== undefined && now - lastShortcutAt < SHORTCUT_COOLDOWN_NS) return;
1055 lastShortcutAt = now;
1056 yield* capture;
1057 }).pipe(Effect.withSpan("desktop.snapShot.shortcutActivated"));
1058 const onShortcut = () => runPromise(captureFromShortcut).catch(() => undefined);
1059
1060 const checkShortcut = Effect.fn("desktop.snapShot.checkShortcut")(function* (
1061 shortcut: SnapShotShortcut,
1062 ) {
1063 const mode = captureMode(environment.platform);
1064 if (mode === "unavailable") {
1065 return { available: false, message: "SnapShots are not supported on this platform." };
1066 }
1067 if (mode === "portal" && niriSocketPath()) {
1068 return {
1069 available: false,
1070 message: "Configure the capture shortcut in your Niri config, not in T3 Code.",
1071 };
1072 }
1073 if (mode === "portal" && isHyprlandCaptureSession()) {
1074 return {
1075 available: false,
1076 message: "Change the capture binding in your Hyprland config, then save it.",
1077 };
1078 }
1079 if (isModifierPairShortcut(shortcut)) {
1080 if (mode === "portal") {
1081 return { available: false, message: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE };
1082 }
1083 const available = yield* Effect.tryPromise({
1084 try: () =>
1085 startPairShortcutProcess(
1086 snapShotShortcutModifierPair(shortcut),
1087 () => undefined,
1088 () => undefined,
1089 ),
1090 catch: shortcutFailure,
1091 }).pipe(
1092 Effect.tap((stop) => Effect.sync(stop)),
1093 Effect.as(true),
1094 Effect.orElseSucceed(() => false),
1095 );
1096 return {
1097 available,
1098 message: available
1099 ? observedPairMessage(shortcut, environment.platform)
1100 : snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1101 };
1102 }
1103 const systemConflict = snapShotShortcutSystemConflict(shortcut);
1104 if (systemConflict) return { available: false, message: systemConflict };
1105 if (mode === "portal") {
1106 return yield* Effect.try({
1107 try: () => portalShortcutTrigger(shortcut),
1108 catch: shortcutFailure,
1109 }).pipe(
1110 Effect.match({
1111 onSuccess: () => ({
1112 available: true,
1113 message: "Your desktop will confirm this shortcut when you save it.",
1114 }),
1115 onFailure: (error) => ({
1116 available: false,
1117 message: error.cause instanceof Error ? error.cause.message : "Unsupported shortcut.",
1118 }),
1119 }),
1120 );
1121 }
1122 const accelerator = toElectronAccelerator(shortcut);
1123 const available =
1124 registeredAccelerator === accelerator
1125 ? { available: true, message: null }
1126 : probeGlobalShortcut(accelerator);
1127 return available;
1128 });
1129
1130 const applySettings = Effect.fn("desktop.snapShot.applySettings")(function* (
1131 settings: ClientSettings,
1132 requestedPermissionMessage: string | null,
1133 forceShortcut = false,
1134 ) {
1135 const previousSettings = yield* Ref.get(settingsRef);
1136 yield* Ref.set(settingsRef, settings);
1137
1138 const mode = captureMode(environment.platform);
1139 const shortcut = settings.snapShotShortcut;
1140 if (
1141 settings.snapShotEnabled &&
1142 settings.snapShotIncludeAccessibility &&
1143 mode !== "unavailable"
1144 ) {
1145 accessibilityProcessPool.warm();
1146 } else {
1147 accessibilityProcessPool.cool();
1148 }
1149 if (settings.snapShotEnabled && environment.platform === "win32") {
1150 regionSnapShotPool.warm();
1151 } else {
1152 regionSnapShotPool.cool();
1153 }
1154 if (!settings.snapShotEnabled || !settings.snapShotFlash || mode === "unavailable") {
1155 flash.dispose();
1156 }
1157 if (!settings.snapShotEnabled || !settings.snapShotAnimations || mode === "unavailable") {
1158 transition.dispose();
1159 closeLinuxFeedback();
1160 }
1161 // Unrelated settings saves must not uninstall the keyboard hook or drop an approved portal session.
1162 const shortcutInputsChanged =
1163 settings.snapShotEnabled !== previousSettings.snapShotEnabled ||
1164 settings.snapShotIncludeAccessibility !== previousSettings.snapShotIncludeAccessibility ||
1165 !sameSnapShotShortcut(shortcut, previousSettings.snapShotShortcut);
1166 const portalShortcutUnchanged =
1167 portalShortcut !== undefined &&
1168 settings.snapShotEnabled &&
1169 previousSettings.snapShotEnabled &&
1170 (isHyprlandCaptureSession() ||
1171 (!isModifierPairShortcut(shortcut) &&
1172 !isModifierPairShortcut(previousSettings.snapShotShortcut) &&
1173 toElectronAccelerator(shortcut) ===
1174 toElectronAccelerator(previousSettings.snapShotShortcut)));
1175 if (!forceShortcut && (portalShortcutUnchanged || (initialized && !shortcutInputsChanged))) {
1176 yield* Ref.update(stateRef, (state) => ({ ...state, shortcut }));
1177 return;
1178 }
1179 initialized = true;
1180 releaseShortcut();
1181 shortcutVerified = false;
1182 const generation = shortcutGeneration;
1183 const onCurrentShortcut = () => {
1184 if (generation === shortcutGeneration) return onShortcut();
1185 return Promise.resolve();
1186 };
1187 if (!settings.snapShotEnabled || mode === "unavailable") {
1188 yield* Ref.set(stateRef, {
1189 mode,
1190 shortcut,
1191 shortcutRegistered: false,
1192 shortcutMessage: null,
1193 message:
1194 mode === "unavailable"
1195 ? environment.platform === "linux"
1196 ? "SnapShots require a Wayland session. X11 capture is not supported."
1197 : "SnapShots are not supported on this platform."
1198 : null,
1199 });
1200 return;
1201 }
1202
1203 const permissionMessage =
1204 requestedPermissionMessage ??
1205 (environment.platform === "darwin"
1206 ? currentMacSnapShotPermissionMessage(settings.snapShotIncludeAccessibility)
1207 : null);
1208 if (permissionMessage) {
1209 yield* Ref.set(stateRef, {
1210 mode,
1211 shortcut,
1212 shortcutRegistered: false,
1213 shortcutMessage: null,
1214 message: permissionMessage,
1215 });
1216 return;
1217 }
1218 if (mode === "portal" && niriSocketPath()) {
1219 const registered = yield* Effect.tryPromise({
1220 try: async () => {
1221 const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
1222 return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
1223 void runPromise(
1224 setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
1225 ).catch(() => undefined);
1226 });
1227 },
1228 catch: shortcutFailure,
1229 }).pipe(
1230 Effect.tap((stop) =>
1231 Effect.sync(() => {
1232 stopShiftShortcut = stop;
1233 }),
1234 ),
1235 Effect.as(true),
1236 Effect.orElseSucceed(() => false),
1237 );
1238 yield* Ref.set(stateRef, {
1239 mode,
1240 linuxBackend: "niri",
1241 shortcut,
1242 shortcutRegistered: false,
1243 shortcutBinding: niriCaptureBinding(linuxAppId),
1244 shortcutConfigPath: niriCaptureConfigPath(home),
1245 shortcutActionRegistered: registered,
1246 shortcutMessage: registered
1247 ? "Set up the shortcut to add it to your Niri config."
1248 : "Could not start the Niri capture endpoint. Another T3 Code instance may be using it.",
1249 message: null,
1250 });
1251 return;
1252 }
1253 const hyprland = mode === "portal" && isHyprlandCaptureSession();
1254 if (mode === "portal" && isModifierPairShortcut(shortcut) && !hyprland) {
1255 yield* Ref.set(stateRef, {
1256 mode,
1257 shortcut,
1258 shortcutRegistered: false,
1259 shortcutMessage: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE,
1260 message: null,
1261 });
1262 return;
1263 }
1264 if (mode === "portal" && (!isModifierPairShortcut(shortcut) || hyprland)) {
1265 yield* Ref.set(stateRef, {
1266 mode,
1267 shortcut,
1268 shortcutRegistered: false,
1269 shortcutMessage: null,
1270 message: null,
1271 });
1272 yield* Effect.tryPromise({
1273 try: async () => {
1274 const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
1275 return new PortalCaptureShortcut(
1276 linuxAppId,
1277 isModifierPairShortcut(shortcut)
1278 ? {
1279 key: "2",
1280 ctrlKey: true,
1281 modKey: false,
1282 altKey: false,
1283 shiftKey: true,
1284 metaKey: false,
1285 }
1286 : shortcut,
1287 onCurrentShortcut,
1288 () => {
1289 if (generation !== shortcutGeneration) return;
1290 shortcutVerified = false;
1291 void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
1292 },
1293 undefined,
1294 hyprland,
1295 );
1296 },
1297 catch: shortcutFailure,
1298 }).pipe(
1299 Effect.tap((registration) =>
1300 Effect.sync(() => {
1301 portalShortcut = registration;
1302 }),
1303 ),
1304 Effect.catch((error) =>
1305 Ref.update(stateRef, (state) => ({
1306 ...state,
1307 shortcutMessage:
1308 error.cause instanceof Error
1309 ? error.cause.message
1310 : "Could not connect to your desktop's shortcut service.",
1311 })),
1312 ),
1313 );
1314 return;
1315 }
1316
1317 let registered = false;
1318 if (isModifierPairShortcut(shortcut)) {
1319 registered = yield* Effect.tryPromise({
1320 try: () =>
1321 startPairShortcutProcess(
1322 snapShotShortcutModifierPair(shortcut),
1323 onCurrentShortcut,
1324 () => {
1325 void pipe(
1326 snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1327 setShortcutFailure,
1328 runPromise,
1329 ).catch(() => undefined);
1330 },
1331 ),
1332 catch: shortcutFailure,
1333 }).pipe(
1334 Effect.tap((stop) =>
1335 Effect.sync(() => {
1336 stopShiftShortcut = stop;
1337 }),
1338 ),
1339 Effect.as(true),
1340 Effect.orElseSucceed(() => false),
1341 );
1342 } else {
1343 const accelerator = toElectronAccelerator(shortcut);
1344 registered = Electron.globalShortcut.register(accelerator, onCurrentShortcut);
1345 if (registered) registeredAccelerator = accelerator;
1346 }
1347
1348 yield* Ref.set(stateRef, {
1349 mode,
1350 shortcut,
1351 shortcutRegistered: registered,
1352 message: null,
1353 shortcutMessage: registered
1354 ? isModifierPairShortcut(shortcut)
1355 ? observedPairMessage(shortcut, environment.platform)
1356 : null
1357 : snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1358 });
1359 });
1360
1361 const setShortcutSuppressed = (suppressed: boolean) =>
1362 Effect.sync(() => {
1363 shortcutSuppressed = suppressed;
1364 });
1365
1366 const configure = Effect.fn("desktop.snapShot.configure")(function* (settings: ClientSettings) {
1367 yield* configurationMutex.withPermits(1)(applySettings(settings, null));
1368 });
1369
1370 const requestPermissions = Effect.fn("desktop.snapShot.requestPermissions")(function* (
1371 includeAccessibility: boolean,
1372 ) {
1373 if (environment.platform !== "darwin") return;
1374 const owner = Electron.BrowserWindow.getFocusedWindow();
1375 yield* Effect.promise(() => requestMacSnapShotPermissions(includeAccessibility));
1376 if (Electron.systemPreferences.getMediaAccessStatus("screen") !== "granted") {
1377 yield* permissions.showHelper("screen-recording", owner);
1378 } else if (
1379 includeAccessibility &&
1380 !Electron.systemPreferences.isTrustedAccessibilityClient(false)
1381 ) {
1382 yield* Effect.promise(() =>
1383 Electron.shell
1384 .openExternal(MAC_PERMISSION_SETTINGS_URLS.accessibility)
1385 .catch(() => undefined),
1386 );
1387 yield* permissions.showHelper("accessibility", owner);
1388 }
1389 }, configurationMutex.withPermits(1));
1390
1391 const setup = Effect.fn("desktop.snapShot.setup")(function* (action: DesktopSnapShotSetupAction) {
1392 if (action === "test-mac-capture") {
1393 if (environment.platform !== "darwin")
1394 return yield* new DesktopSnapShotSetupError({ action, reason: "unsupported-session" });
1395 yield* Effect.scoped(
1396 Effect.gen(function* () {
1397 const directory = yield* fileSystem
1398 .makeTempDirectoryScoped({ prefix: "t3-snapshot-test-" })
1399 .pipe(
1400 Effect.mapError(
1401 (cause) => new DesktopSnapShotSetupError({ action, reason: "setup-failed", cause }),
1402 ),
1403 );
1404 const active = yield* Effect.tryPromise({
1405 try: () => activeWindow("darwin"),
1406 catch: (cause) =>
1407 new DesktopSnapShotSetupError({
1408 action,
1409 reason: "setup-failed",
1410 step: "find-window",
1411 ...macCommandFailure(cause),
1412 appName: environment.displayName,
1413 cause,
1414 }),
1415 });
1416 if (!active)
1417 return yield* new DesktopSnapShotSetupError({
1418 action,
1419 reason: "setup-failed",
1420 step: "find-window",
1421 status: "missing",
1422 });
1423 yield* Effect.tryPromise({
1424 try: () =>
1425 captureMacWindowSnapshot(
1426 active,
1427 path.join(directory, "test.png"),
1428 snapShotThumbnailSize(active),
1429 ),
1430 catch: (cause) =>
1431 new DesktopSnapShotSetupError({
1432 action,
1433 reason: "setup-failed",
1434 step: "capture-window",
1435 ...macCommandFailure(cause),
1436 appName: environment.displayName,
1437 cause,
1438 }),
1439 });
1440 }),
1441 );
1442 return;
1443 } else if (action === "install-kde-helper" || action === "remove-kde-helper") {
1444 if (captureMode(environment.platform) !== "portal" || !isKdeCaptureSession())
1445 return yield* new DesktopSnapShotSetupError({
1446 action,
1447 reason: "unsupported-session",
1448 });
1449 yield* Effect.tryPromise({
1450 try: () => new KdeCaptureSetup(kdeCapturePaths).perform(action),
1451 catch: (error) =>
1452 new DesktopSnapShotSetupError({
1453 action,
1454 reason: "setup-failed",
1455 cause: error,
1456 }),
1457 });
1458 } else if (action === "install-hyprland-helper" || action === "remove-hyprland-helper") {
1459 if (captureMode(environment.platform) !== "portal" || !isHyprlandCaptureSession())
1460 return yield* new DesktopSnapShotSetupError({
1461 action,
1462 reason: "unsupported-session",
1463 });
1464 yield* Effect.tryPromise({
1465 try: () => new HyprlandCaptureSetup(hyprlandCapturePaths).perform(action),
1466 catch: (error) =>
1467 new DesktopSnapShotSetupError({
1468 action,
1469 reason: "setup-failed",
1470 cause: error,
1471 }),
1472 });
1473 } else if (action === "allow-screen-recording" || action === "allow-accessibility") {
1474 if (environment.platform !== "darwin")
1475 return yield* new DesktopSnapShotSetupError({
1476 action,
1477 reason: "unsupported-session",
1478 });
1479 const owner = Electron.BrowserWindow.getFocusedWindow();
1480 if (action === "allow-accessibility") {
1481 const granted = Electron.systemPreferences.isTrustedAccessibilityClient(true);
1482 if (!granted && environment.isPackaged) {
1483 yield* Effect.promise(() =>
1484 Electron.shell
1485 .openExternal(MAC_PERMISSION_SETTINGS_URLS.accessibility)
1486 .catch(() => undefined),
1487 );
1488 }
1489 } else yield* Effect.promise(requestMacScreenCapturePermission);
1490 yield* permissions.showHelper(
1491 action === "allow-accessibility" ? "accessibility" : "screen-recording",
1492 owner,
1493 );
1494 } else if (action !== "retry-shortcut") {
1495 if (!hasGnomeSetup())
1496 return yield* new DesktopSnapShotSetupError({
1497 action,
1498 reason: "unsupported-session",
1499 });
1500 yield* Effect.tryPromise({
1501 try: async () => {
1502 const { GnomeCaptureSetup } = await import("./GnomeCaptureSetup.ts");
1503 const setup = new GnomeCaptureSetup(gnomeSetupPaths);
1504 try {
1505 await setup.perform(action);
1506 } finally {
1507 setup.close();
1508 }
1509 },
1510 catch: (error) =>
1511 new DesktopSnapShotSetupError({
1512 action,
1513 reason: "setup-failed",
1514 cause: error,
1515 }),
1516 });
1517 }
1518 if (action === "retry-shortcut") {
1519 const currentPortal = portalShortcut;
1520 if (currentPortal?.hasSession && !currentPortal.state.shortcutPending) {
1521 yield* Effect.tryPromise({
1522 try: () => currentPortal.configure(),
1523 catch: shortcutFailure,
1524 }).pipe(
1525 Effect.mapError(
1526 (error) =>
1527 new DesktopSnapShotSetupError({
1528 action,
1529 reason: "shortcut-permissions",
1530 cause: error.cause,
1531 }),
1532 ),
1533 );
1534 } else yield* applySettings(yield* Ref.get(settingsRef), null, true);
1535 }
1536 }, configurationMutex.withPermits(1));
1537
1538 yield* Effect.addFinalizer(() =>
1539 Effect.sync(() => {
1540 releaseShortcut();
1541 flash.dispose();
1542 transition.dispose();
1543 closeLinuxFeedback();
1544 accessibilityProcessPool.close();
1545 regionSnapShotPool.close();
1546 }),
1547 );
1548
1549 const configDesktop = Effect.fn("desktop.snapShot.configDesktop")(function* (
1550 action: "preview-config" | "apply-config",
1551 ) {
1552 if (captureMode(environment.platform) === "portal") {
1553 if (niriSocketPath()) return "niri" as const;
1554 if (isHyprlandCaptureSession()) return "hyprland" as const;
1555 }
1556 return yield* new DesktopSnapShotSetupError({
1557 action,
1558 reason: "unsupported-session",
1559 });
1560 });
1561 const previewConfig = Effect.fn("desktop.snapShot.previewConfig")(function* (
1562 request: DesktopCaptureConfigRequest,
1563 selectedPath?: string,
1564 ) {
1565 const desktop = yield* configDesktop("preview-config");
1566 return yield* Effect.tryPromise({
1567 try: async () => {
1568 const configPath =
1569 selectedPath ??
1570 (desktop === "niri"
1571 ? niriCaptureConfigPath(home)
1572 : (await hyprlandCaptureShortcut(linuxAppId, home)).shortcutConfigPath);
1573 return shortcutConfig.preview({ desktop, path: configPath, appId: linuxAppId }, request);
1574 },
1575 catch: (cause) =>
1576 new DesktopSnapShotSetupError({
1577 action: "preview-config",
1578 reason: "setup-failed",
1579 cause,
1580 }),
1581 });
1582 });
1583 const applyConfig = Effect.fn("desktop.snapShot.applyConfig")(function* (previewId: string) {
1584 const desktop = yield* configDesktop("apply-config");
1585 const result = yield* Effect.tryPromise({
1586 try: () => shortcutConfig.apply(previewId, desktop),
1587 catch: (cause) =>
1588 new DesktopSnapShotSetupError({
1589 action: "apply-config",
1590 reason: "setup-failed",
1591 cause,
1592 }),
1593 });
1594 if (result.backupPath) shortcutVerified = false;
1595 return result;
1596 });
1597
1598 return DesktopSnapShot.of({
1599 initialize: configurationMutex.withPermits(1)(
1600 clientSettings.get.pipe(
1601 Effect.flatMap((stored) =>
1602 applySettings(
1603 Option.getOrElse(stored, () => DEFAULT_CLIENT_SETTINGS),
1604 null,
1605 ),
1606 ),
1607 Effect.ignore,
1608 ),
1609 ),
1610 configure,
1611 requestPermissions,
1612 setup,
1613 previewConfig,
1614 applyConfig,
1615 state: Ref.get(stateRef).pipe(
1616 Effect.flatMap((state) =>
1617 state.mode === "portal"
1618 ? Effect.tryPromise({
1619 try: async () => {
1620 const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
1621 return getLinuxCaptureSupport(linuxAppId);
1622 },
1623 catch: (cause) => new DesktopSnapShotError({ operation: "unsupported", cause }),
1624 }).pipe(
1625 Effect.map((support) => ({ ...state, ...support })),
1626 Effect.catch((error) =>
1627 Effect.succeed({
1628 ...state,
1629 message:
1630 error.cause instanceof Error
1631 ? error.cause.message
1632 : "Could not check desktop capture support. Check your desktop session and try again.",
1633 }),
1634 ),
1635 )
1636 : environment.platform === "darwin"
1637 ? Effect.gen(function* () {
1638 const settings = yield* Ref.get(settingsRef);
1639 const macPermissions = currentMacPermissions();
1640 const message = settings.snapShotEnabled
1641 ? macPermissionMessage(macPermissions, settings.snapShotIncludeAccessibility)
1642 : null;
1643 const recovered =
1644 message === null &&
1645 state.message !== null &&
1646 MAC_PERMISSION_MESSAGES.has(state.message)
1647 ? yield* configurationMutex
1648 .withPermits(1)(applySettings(settings, null, true))
1649 .pipe(Effect.andThen(Ref.get(stateRef)))
1650 : state;
1651 return { ...recovered, macPermissions, ...(message ? { message } : {}) };
1652 })
1653 : Effect.succeed(
1654 environment.platform === "win32" ? { ...state, windows: true } : state,
1655 ),
1656 ),
1657 Effect.flatMap((state) =>
1658 Effect.gen(function* () {
1659 const linuxDesktop =
1660 state.mode === "portal"
1661 ? (hostEnv.XDG_CURRENT_DESKTOP ?? "")
1662 .toLowerCase()
1663 .split(":")
1664 .find(
1665 (name) =>
1666 name === "gnome" || name === "kde" || name === "niri" || name === "hyprland",
1667 )
1668 : undefined;
1669 const gnomeExtension = hasGnomeSetup()
1670 ? yield* Effect.promise(async () => {
1671 const { GnomeCaptureSetup } = await import("./GnomeCaptureSetup.ts");
1672 const setup = new GnomeCaptureSetup(gnomeSetupPaths);
1673 try {
1674 return await setup.state();
1675 } finally {
1676 setup.close();
1677 }
1678 })
1679 : undefined;
1680 const kdeHelper =
1681 state.linuxBackend === "kde"
1682 ? yield* Effect.promise(() => new KdeCaptureSetup(kdeCapturePaths).state())
1683 : undefined;
1684 const hyprlandHelper =
1685 state.linuxBackend === "hyprland"
1686 ? yield* Effect.promise(() => new HyprlandCaptureSetup(hyprlandCapturePaths).state())
1687 : undefined;
1688 const hyprlandShortcut =
1689 state.linuxBackend === "hyprland"
1690 ? yield* Effect.promise(() => hyprlandCaptureShortcut(linuxAppId, home))
1691 : undefined;
1692 return {
1693 ...state,
1694 ...portalShortcut?.state,
1695 ...(linuxDesktop ? { linuxDesktop } : {}),
1696 ...(gnomeExtension ? { gnomeExtension } : {}),
1697 ...(hyprlandHelper
1698 ? {
1699 hyprlandHelper,
1700 linuxFeedbackAvailable:
1701 hyprlandHelper.status === "ready" && hyprlandHelper.feedbackAvailable === true,
1702 }
1703 : {}),
1704 ...hyprlandShortcut,
1705 ...(state.linuxBackend === "niri"
1706 ? { shortcutConfigPath: niriCaptureConfigPath(home) }
1707 : {}),
1708 ...(kdeHelper
1709 ? {
1710 kdeHelper,
1711 linuxFeedbackAvailable:
1712 kdeHelper.status === "ready" && kdeHelper.feedbackAvailable === true,
1713 }
1714 : {}),
1715 shortcutVerified,
1716 };
1717 }),
1718 ),
1719 ),
1720 checkShortcut,
1721 setShortcutSuppressed,
1722 capture,
1723 listPending: fileSystem.readDirectory(captureDirectory).pipe(
1724 Effect.catchTags({
1725 PlatformError: (cause) =>
1726 cause.reason._tag === "NotFound" ? Effect.succeed([]) : Effect.fail(cause),
1727 }),
1728 Effect.flatMap((names) =>
1729 Effect.forEach(
1730 names.filter((name) => name.endsWith(".json") && !name.endsWith(".json.tmp")),
1731 (name) =>
1732 fileSystem.readFileString(path.join(captureDirectory, name)).pipe(
1733 Effect.flatMap(decodePendingCaptureJson),
1734 Effect.orElseSucceed(() => undefined),
1735 ),
1736 { concurrency: "unbounded" },
1737 ),
1738 ),
1739 Effect.map((captures) =>
1740 captures
1741 .filter((capture) => capture !== undefined)
1742 .sort((left, right) => left.source.capturedAt.localeCompare(right.source.capturedAt)),
1743 ),
1744 Effect.mapError((cause) => new DesktopSnapShotError({ operation: "list-pending", cause })),
1745 ),
1746 read: Effect.fn("DesktopSnapShot.read")(
1747 function* (id) {
1748 const metadata = yield* fileSystem
1749 .readFileString(path.join(captureDirectory, `${id}.json`))
1750 .pipe(Effect.flatMap(decodePendingCaptureJson));
1751 const png = yield* fileSystem.readFile(path.join(captureDirectory, `${id}.png`));
1752 return {
1753 ...metadata,
1754 dataUrl: `data:image/png;base64,${Base64.encode(png)}`,
1755 };
1756 },
1757 (effect, id) =>
1758 effect.pipe(
1759 Effect.mapError(
1760 (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }),
1761 ),
1762 ),
1763 ),
1764 setAnimationDestination: Effect.fn("DesktopSnapShot.setAnimationDestination")(
1765 function (id, destination) {
1766 return Effect.promise(async () => {
1767 if (linuxFeedback?.id === id && destination.relativeFrame) {
1768 await linuxFeedback.feedback
1769 .animateTo(destination.relativeFrame)
1770 .catch(() => closeLinuxFeedback(id));
1771 return;
1772 }
1773 transition.animateTo(id, destination);
1774 await transition.waitForLanding(id);
1775 });
1776 },
1777 ),
1778 dismissAnimation: Effect.fn("DesktopSnapShot.dismissAnimation")(function (id) {
1779 return Effect.sync(() => {
1780 closeLinuxFeedback(id);
1781 transition.dismiss(id);
1782 });
1783 }),
1784 acknowledge: Effect.fn("DesktopSnapShot.acknowledge")(function (id) {
1785 return Effect.promise(async () => {
1786 await completeLinuxFeedback(id);
1787 await transition.complete(id);
1788 }).pipe(
1789 Effect.andThen(
1790 Effect.all(
1791 [
1792 fileSystem.remove(path.join(captureDirectory, `${id}.json`), { force: true }),
1793 fileSystem.remove(path.join(captureDirectory, `${id}.png`), { force: true }),
1794 ],
1795 { concurrency: "unbounded", discard: true },
1796 ),
1797 ),
1798 Effect.mapError(
1799 (cause) => new DesktopSnapShotError({ operation: "acknowledge", captureId: id, cause }),
1800 ),
1801 );
1802 }),
1803 });
1804 });
1805
1806 export const layer = Layer.effect(DesktopSnapShot, make);