feat(desktop): add cross-platform window capture (#8103)

Co-authored-by: Dara Adedeji <[email protected]>
Co-authored-by: Dara Adedeji <[email protected]>
Co-authored-by: Wout Stiens <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-07 18:21:53 -07:00
1 parent 892de47f06
commit 299404a754
207 files changed
+31651 -362

No files matched your search

+10 -4
View File
@@ -198,11 +198,17 @@ jobs:
with:
components: rustfmt
- name: Check resource monitor formatting
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
- name: Check Rust formatting
run: |
for crate in resource-monitor kde-snap-shot hyprland-snap-shot; do
cargo fmt --manifest-path "native/$crate/Cargo.toml" -- --check
done
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
- name: Test Rust crates
run: |
for crate in resource-monitor kde-snap-shot hyprland-snap-shot; do
cargo test --locked --manifest-path "native/$crate/Cargo.toml"
done
# The static analysis below needs a macOS runner, which bills ~6.7x a Linux
# minute, so gate it on the native sources it actually lints instead of paying
+12 -1
View File
@@ -487,8 +487,18 @@ jobs:
path: native/resource-monitor/target/${{ matrix.rust_target }}/release/t3-resource-monitor${{ matrix.platform == 'win' && '.exe' || '' }}
key: resource-monitor-${{ matrix.rust_target }}-${{ hashFiles('native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }}
- name: Cache Linux capture helpers
if: matrix.platform == 'linux'
id: capture_helper_cache
uses: actions/cache@v6
with:
path: |
native/kde-snap-shot/target/${{ matrix.rust_target }}/release/t3-kde-snap-shot
native/hyprland-snap-shot/target/${{ matrix.rust_target }}/release/t3-hyprland-snap-shot
key: linux-capture-helpers-${{ matrix.rust_target }}-${{ hashFiles('native/kde-snap-shot/Cargo.lock', 'native/kde-snap-shot/Cargo.toml', 'native/kde-snap-shot/src/**', 'native/hyprland-snap-shot/Cargo.lock', 'native/hyprland-snap-shot/Cargo.toml', 'native/hyprland-snap-shot/src/**', 'native/hyprland-snap-shot/protocols/**') }}
- name: Setup Rust
if: steps.resource_monitor_cache.outputs.cache-hit != 'true'
if: steps.resource_monitor_cache.outputs.cache-hit != 'true' || (matrix.platform == 'linux' && steps.capture_helper_cache.outputs.cache-hit != 'true')
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_target }}
@@ -620,6 +630,7 @@ jobs:
env:
pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata
T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: ${{ steps.resource_monitor_cache.outputs.cache-hit == 'true' }}
T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS: ${{ steps.capture_helper_cache.outputs.cache-hit == 'true' }}
CSC_LINK: ${{ secrets.CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
+10
View File
@@ -0,0 +1,10 @@
{
"uuid": "[email protected]",
"files": [
"metadata.json",
"extension.js",
"captureService.js",
"captureFeedback.js",
"feedbackGeometry.js"
]
}
@@ -0,0 +1,168 @@
import Clutter from "gi://Clutter";
import Gio from "gi://Gio";
import GLib from "gi://GLib";
import Meta from "gi://Meta";
import St from "gi://St";
import * as Main from "resource:///org/gnome/shell/ui/main.js";
import { captureDestinationFrame, findCaptureDestination } from "./feedbackGeometry.js";
/** A single, bounded, sender-owned flight. No live window clone or per-frame JS work. */
export class CaptureFeedback {
begin(sender, pid, snapshot, options) {
this.dispose();
const session = { sender, pid };
this._session = session;
this._watch = Gio.bus_watch_name_on_connection(
Gio.DBus.session,
sender,
Gio.BusNameWatcherFlags.NONE,
null,
() => {
if (this._session === session) this.dispose();
},
);
this._timeout = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 6000, () => {
this._timeout = 0;
this.dispose();
return GLib.SOURCE_REMOVE;
});
try {
if (options.animate && snapshot.content && St.Settings.get().enable_animations) {
this._actor = new Clutter.Actor({
...snapshot.bufferBounds,
content: snapshot.content,
reactive: false,
});
Main.uiGroup.add_child(this._actor);
}
if (options.flash) {
this._flash = new St.Widget({
...snapshot.bounds,
reactive: false,
style: "background-color: white;",
opacity: 24,
});
Main.uiGroup.add_child(this._flash);
this._flash.ease({
opacity: 0,
duration: 180,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
onComplete: () => {
this._flash?.destroy();
this._flash = null;
},
});
}
} catch (error) {
// Optional decoration must not prevent attaching a successfully captured image.
this._clearActors();
console.warn(`T3 capture effects unavailable: ${error.message}`);
}
return Boolean(this._actor);
}
_owned(sender) {
if (
!this._session ||
this._session.sender !== sender ||
Main.sessionMode.isLocked ||
Main.sessionMode.isGreeter
) {
throw new Error("No active capture belongs to this caller.");
}
return this._session;
}
async activate(sender, title) {
const session = this._owned(sender);
if (session.target) return;
const find = () =>
findCaptureDestination(
global
.get_window_actors()
.map((actor) => actor.meta_window)
.filter((window) => window.get_window_type() === Meta.WindowType.NORMAL),
session.pid,
title,
);
// A command-palette capture temporarily unmaps T3. Wait for its new surface, not a sleep.
const target =
find() ??
(await new Promise((resolve) => {
const check = () => {
const window = find();
if (window) finish(window);
};
let timeout;
const mapped = global.window_manager.connect("map", check);
const finish = (window) => {
global.window_manager.disconnect(mapped);
if (timeout) GLib.source_remove(timeout);
this._cancelActivation = null;
resolve(window);
};
this._cancelActivation = () => finish(undefined);
timeout = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 1500, () => {
timeout = 0;
finish(undefined);
return GLib.SOURCE_REMOVE;
});
check();
}));
if (this._owned(sender) !== session || !target)
throw new Error("T3 Code's window is not available for activation.");
session.target = target;
Main.activateWindow(target, global.get_current_time());
}
async animate(sender, relative) {
const session = this._owned(sender);
if (this._flight) return this._flight;
const actor = this._actor;
if (!actor || !session.target || !St.Settings.get().enable_animations) {
this._clearActors();
return;
}
const window = session.target;
const bounds = window.frame_rect_to_client_rect(window.get_frame_rect());
const frame = captureDestinationFrame(relative, bounds);
const distance = Math.hypot(frame.x - actor.x, frame.y - actor.y);
this._flight = new Promise((resolve) => {
this._land = resolve;
actor.ease({
x: frame.x,
y: frame.y,
scale_x: frame.width / actor.width,
scale_y: frame.height / actor.height,
duration: Math.round(680 - 400 * Math.exp(-distance / 2000)),
mode: Clutter.AnimationMode.EASE_OUT_CUBIC,
onStopped: () => {
this._land?.();
this._land = null;
},
});
});
await this._flight;
// Keep the landed image until the renderer acknowledges the attachment (connection closes).
}
_clearActors() {
this._actor?.destroy();
this._flash?.destroy();
this._actor = null;
this._flash = null;
this._land?.();
this._land = null;
}
dispose() {
this._session = null;
this._cancelActivation?.();
this._clearActors();
this._flight = null;
if (this._watch) Gio.bus_unwatch_name(this._watch);
if (this._timeout) GLib.source_remove(this._timeout);
this._watch = 0;
this._timeout = 0;
}
}
@@ -0,0 +1,186 @@
import { beforeEach, expect, it, vi } from "vite-plus/test";
const shell = vi.hoisted(() => ({
windows: [],
actors: [],
timers: new Map(),
watchers: new Map(),
mapped: new Map(),
next: 1,
animations: true,
locked: false,
activate: vi.fn(),
}));
vi.mock("gi://Clutter", () => ({
default: {
Actor: class {
constructor(props) {
Object.assign(this, props);
shell.actors.push(this);
}
ease(props) {
this.transition = props;
}
destroy() {
this.destroyed = true;
this.transition?.onStopped?.();
}
},
AnimationMode: { EASE_OUT_QUAD: 1, EASE_OUT_CUBIC: 2 },
},
}));
vi.mock("gi://Gio", () => ({
default: {
DBus: { session: {} },
BusNameWatcherFlags: { NONE: 0 },
bus_watch_name_on_connection: (_bus, name, _flags, _appeared, vanished) => {
const id = shell.next++;
shell.watchers.set(id, { name, vanished });
return id;
},
bus_unwatch_name: (id) => shell.watchers.delete(id),
},
}));
vi.mock("gi://GLib", () => ({
default: {
PRIORITY_DEFAULT: 0,
SOURCE_REMOVE: false,
timeout_add: (_priority, _ms, callback) => {
const id = shell.next++;
shell.timers.set(id, callback);
return id;
},
source_remove: (id) => shell.timers.delete(id),
},
}));
vi.mock("gi://Meta", () => ({ default: { WindowType: { NORMAL: 0 } } }));
vi.mock("gi://St", () => ({
default: { Settings: { get: () => ({ enable_animations: shell.animations }) } },
}));
vi.mock("resource:///org/gnome/shell/ui/main.js", () => ({
sessionMode: {
get isLocked() {
return shell.locked;
},
isGreeter: false,
},
uiGroup: { add_child: () => {} },
activateWindow: shell.activate,
}));
import { CaptureFeedback } from "./captureFeedback.js";
beforeEach(() => {
shell.windows = [];
shell.actors = [];
shell.timers.clear();
shell.watchers.clear();
shell.mapped.clear();
shell.activate.mockClear();
shell.animations = true;
shell.locked = false;
Object.assign(globalThis, {
get_window_actors: () => shell.windows.map((meta_window) => ({ meta_window })),
get_current_time: () => 123,
window_manager: {
connect: (_signal, callback) => {
const id = shell.next++;
shell.mapped.set(id, callback);
return id;
},
disconnect: (id) => shell.mapped.delete(id),
},
});
});
const bounds = { x: -1200, y: 20, width: 1000, height: 800 };
function begin(animate = true) {
const feedback = new CaptureFeedback();
const started = feedback.begin(
":1.23",
42,
{ content: "frozen pixels", bounds, bufferBounds: bounds },
{ flash: false, animate },
);
return { feedback, started };
}
function target(pid = 42) {
return {
get_pid: () => pid,
get_title: () => "T3",
get_window_type: () => 0,
get_frame_rect: () => bounds,
frame_rect_to_client_rect: (rect) => rect,
};
}
it("activates the caller, flies its frozen capture, and retains the landed image until disconnect", async () => {
const window = target();
shell.windows = [target(99), window];
const { feedback, started } = begin();
expect(started).toBe(true);
await feedback.activate(":1.23", "T3");
expect(shell.activate).toHaveBeenCalledWith(window, 123);
const flight = feedback.animate(":1.23", { x: 0.1, y: 0.8, width: 0.2, height: 0.1 });
const actor = shell.actors[0];
expect(actor.content).toBe("frozen pixels");
expect(actor.transition).toMatchObject({ x: -1100, y: 660, scale_x: 0.2, scale_y: 0.1 });
actor.transition.onStopped();
await flight;
expect(actor.destroyed).not.toBe(true);
for (const { vanished } of shell.watchers.values()) vanished();
expect(actor.destroyed).toBe(true);
expect(shell.watchers.size).toBe(0);
expect(shell.timers.size).toBe(0);
});
it("waits for T3 to remap and cancels that wait when disabled", async () => {
const { feedback } = begin();
const activation = feedback.activate(":1.23", "T3");
expect(shell.activate).not.toHaveBeenCalled();
shell.windows = [target()];
for (const mapped of shell.mapped.values()) mapped();
await activation;
expect(shell.activate).toHaveBeenCalledOnce();
feedback.dispose();
shell.windows = [];
const next = begin().feedback;
const cancelled = next.activate(":1.23", "T3");
next.dispose();
await expect(cancelled).rejects.toThrow("No active capture");
expect(shell.mapped.size).toBe(0);
});
it("does not animate under reduced motion but still activates T3", async () => {
shell.animations = false;
shell.windows = [target()];
const { feedback, started } = begin();
expect(started).toBe(false);
expect(shell.actors).toHaveLength(0);
await feedback.activate(":1.23", "T3");
expect(shell.activate).toHaveBeenCalledOnce();
feedback.dispose();
});
it("rejects another sender and locked-session activation", async () => {
shell.windows = [target()];
const { feedback } = begin();
await expect(feedback.activate(":1.99", "T3")).rejects.toThrow("No active capture");
shell.locked = true;
await expect(feedback.activate(":1.23", "T3")).rejects.toThrow("No active capture");
expect(shell.activate).not.toHaveBeenCalled();
feedback.dispose();
});
it("disposes an abandoned flight and resolves its pending response", async () => {
shell.windows = [target()];
const { feedback } = begin();
await feedback.activate(":1.23", "T3");
const flight = feedback.animate(":1.23", { x: 0.1, y: 0.8, width: 0.2, height: 0.1 });
const callbacks = [...shell.timers.values()];
shell.timers.clear();
for (const timeout of callbacks) timeout();
await flight;
expect(shell.actors.every((actor) => actor.destroyed)).toBe(true);
expect(shell.watchers.size).toBe(0);
});
@@ -0,0 +1,63 @@
// This policy is independent of Shell so lifecycle and authorization can be tested without a desktop.
export const CLIENT_NAMES = [
"com.t3tools.T3Code.SnapShot",
"com.t3tools.T3Code.Development.SnapShot",
];
export function isWaylandSession(meta) {
// GNOME 50 removed the X11 compositor and this API. GNOME 45–49 still need the check.
return typeof meta.is_wayland_compositor !== "function" || meta.is_wayland_compositor();
}
export class CaptureService {
constructor({ getNameOwner, isAvailable, takeSnapshot, getProcessId, beginFeedback }) {
this._getNameOwner = getNameOwner;
this._isAvailable = isAvailable;
this._takeSnapshot = takeSnapshot;
this._getProcessId = getProcessId;
this._beginFeedback = beginFeedback;
this._enabled = true;
this._busy = false;
}
disable() {
this._enabled = false;
}
_checkSession() {
if (!this._enabled || !this._isAvailable()) {
throw new Error("SnapShots are unavailable in this session.");
}
}
async capture(sender, options) {
this._checkSession();
if (this._busy) throw new Error("A snapshot is already in progress.");
this._busy = true;
try {
let allowed = false;
for (const name of CLIENT_NAMES) {
const owner = await this._getNameOwner(name);
if (owner === sender) {
allowed = true;
break;
}
}
if (!allowed) throw new Error("Only T3 Code may request a snapshot.");
const pid = options ? await this._getProcessId(sender) : undefined;
this._checkSession();
const snapshot = await this._takeSnapshot(options?.animate ?? false);
// Never deliver pixels after locking the session or disabling the extension.
this._checkSession();
if (options) {
return {
...snapshot,
animationStarted: this._beginFeedback(sender, pid, snapshot, options),
};
}
return snapshot;
} finally {
this._busy = false;
}
}
}
@@ -0,0 +1,148 @@
import { expect, it } from "vite-plus/test";
import { CaptureService, CLIENT_NAMES, isWaylandSession } from "./captureService.js";
it("supports GNOME 50 without the removed X11 API, rejecting older X11 sessions", () => {
expect(isWaylandSession({})).toBe(true);
expect(isWaylandSession({ is_wayland_compositor: () => true })).toBe(true);
expect(isWaylandSession({ is_wayland_compositor: () => false })).toBe(false);
});
function fixture(overrides = {}) {
let snapshots = 0;
const options = {
getNameOwner: async (name) => (name === CLIENT_NAMES[0] ? ":1.23" : null),
isAvailable: () => true,
takeSnapshot: async () => {
snapshots++;
return "pixels";
},
...overrides,
};
return { service: new CaptureService(options), snapshots: () => snapshots };
}
it("rejects other clients before looking at the active window", async () => {
const { service, snapshots } = fixture();
await expect(service.capture(":1.99")).rejects.toThrow("Only T3 Code");
expect(snapshots()).toBe(0);
expect(await service.capture(":1.23")).toBe("pixels");
});
it.each(CLIENT_NAMES)("accepts the current owner of %s", async (client) => {
const { service } = fixture({ getNameOwner: async (name) => (name === client ? ":1.23" : null) });
expect(await service.capture(":1.23")).toBe("pixels");
});
it("rechecks the name owner on each capture", async () => {
let owner = ":1.23";
const { service } = fixture({ getNameOwner: async () => owner });
expect(await service.capture(owner)).toBe("pixels");
owner = ":1.24";
await expect(service.capture(":1.23")).rejects.toThrow("Only T3 Code");
});
it("rejects locked and non-Wayland sessions without taking a screenshot", async () => {
const { service, snapshots } = fixture({ isAvailable: () => false });
await expect(service.capture(":1.23")).rejects.toThrow("unavailable");
expect(snapshots()).toBe(0);
});
it("does not start a screenshot if disabled during authorization", async () => {
let authorize;
const { service, snapshots } = fixture({
getNameOwner: () =>
new Promise((resolve) => {
authorize = resolve;
}),
});
const result = service.capture(":1.23");
service.disable();
authorize(":1.23");
await expect(result).rejects.toThrow("unavailable");
expect(snapshots()).toBe(0);
});
it.each(["lock", "disable"])(
"does not return pixels after %s during capture",
async (operation) => {
let available = true;
const { service } = fixture({
isAvailable: () => available,
takeSnapshot: async () => {
if (operation === "disable") service.disable();
else available = false;
return "private pixels";
},
});
await expect(service.capture(":1.23")).rejects.toThrow("unavailable");
},
);
it("rejects concurrent requests and clears busy after a failed capture", async () => {
let finish;
const started = Promise.withResolvers();
const { service } = fixture({
takeSnapshot: () => {
started.resolve();
return new Promise((_, reject) => {
finish = reject;
});
},
});
const first = service.capture(":1.23");
await started.promise;
await expect(service.capture(":1.23")).rejects.toThrow("already in progress");
finish(new Error("gone"));
await expect(first).rejects.toThrow("gone");
await expect(service.capture(":1.99")).rejects.toThrow("Only T3 Code");
});
it("prepares focus/effects only after pixels and identity have been captured", async () => {
const events = [];
const snapshot = { png: "pixels", metadata: "captured-window" };
const { service } = fixture({
getProcessId: async () => {
events.push("caller-pid");
return 42;
},
takeSnapshot: async () => {
events.push("snapshot");
return snapshot;
},
beginFeedback: (sender, pid, captured, options) => {
expect([sender, pid, captured, options]).toEqual([
":1.23",
42,
snapshot,
{ flash: true, animate: true },
]);
events.push("feedback");
return true;
},
});
expect(await service.capture(":1.23", { flash: true, animate: true })).toEqual({
...snapshot,
animationStarted: true,
});
expect(events).toEqual(["caller-pid", "snapshot", "feedback"]);
});
it("does not create overlays or activate after the session locks during capture", async () => {
let available = true;
let feedback = 0;
const { service } = fixture({
getProcessId: async () => 42,
isAvailable: () => available,
takeSnapshot: async () => {
available = false;
return {};
},
beginFeedback: () => {
feedback++;
},
});
await expect(service.capture(":1.23", { flash: true, animate: true })).rejects.toThrow(
"unavailable",
);
expect(feedback).toBe(0);
});
+192
View File
@@ -0,0 +1,192 @@
import Gio from "gi://Gio";
import GLib from "gi://GLib";
import Meta from "gi://Meta";
import Shell from "gi://Shell";
import St from "gi://St";
import { Extension } from "resource:///org/gnome/shell/extensions/extension.js";
import * as Main from "resource:///org/gnome/shell/ui/main.js";
import { CaptureService, isWaylandSession } from "./captureService.js";
import { CaptureFeedback } from "./captureFeedback.js";
const NAME = "org.gnome.Shell.Extensions.T3SnapShot";
const PATH = "/org/gnome/Shell/Extensions/T3SnapShot";
const XML = `<node><interface name="${NAME}">
<property name="Version" type="u" access="read"/>
<method name="Capture">
<arg name="png" type="ay" direction="out"/>
<arg name="metadata" type="s" direction="out"/>
</method>
<method name="CaptureWithFeedback">
<arg name="flash" type="b" direction="in"/>
<arg name="animate" type="b" direction="in"/>
<arg name="png" type="ay" direction="out"/>
<arg name="metadata" type="s" direction="out"/>
<arg name="animationStarted" type="b" direction="out"/>
</method>
<method name="Activate"><arg name="title" type="s" direction="in"/></method>
<method name="Animate">
<arg name="x" type="d" direction="in"/>
<arg name="y" type="d" direction="in"/>
<arg name="width" type="d" direction="in"/>
<arg name="height" type="d" direction="in"/>
</method>
</interface></node>`;
function busIdentity(method, name, resultType) {
return new Promise((resolve, reject) => {
Gio.DBus.session.call(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
method,
new GLib.Variant("(s)", [name]),
new GLib.VariantType(resultType),
Gio.DBusCallFlags.NONE,
5_000,
null,
(connection, result) => {
try {
resolve(connection.call_finish(result).deepUnpack()[0]);
} catch (error) {
if (error.matches(Gio.DBusError, Gio.DBusError.NAME_HAS_NO_OWNER)) resolve(null);
else reject(error);
}
},
);
});
}
const getNameOwner = (name) => busIdentity("GetNameOwner", name, "(s)");
const getProcessId = (sender) => busIdentity("GetConnectionUnixProcessID", sender, "(u)");
function takeSnapshot(animate) {
// No await between reading identity and Shell taking its snapshot of the focused actor.
const window = global.display.focus_window;
if (!window || window.minimized || !window.get_compositor_private()) {
throw new Error("No active window is available for capture.");
}
const app = Shell.WindowTracker.get_default().get_window_app(window);
const bounds = window.get_frame_rect();
const bufferBounds = window.get_buffer_rect();
let content;
if (animate && St.Settings.get().enable_animations) {
try {
content = window.get_compositor_private().paint_to_content(null);
} catch (error) {
console.warn(`T3 capture preview unavailable: ${error.message}`);
}
}
const metadata = JSON.stringify({
title: window.get_title() ?? "",
appName: app?.get_name() ?? "",
appIdentifier: app?.get_id() ?? "",
processId: Math.max(0, window.get_pid()),
bounds: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height },
});
const stream = Gio.MemoryOutputStream.new_resizable();
const screenshot = new Shell.Screenshot();
return new Promise((resolve, reject) => {
screenshot.screenshot_window(true, false, stream, (source, result) => {
try {
const [success] = source.screenshot_window_finish(result);
if (!success) throw new Error("GNOME could not capture the active window.");
stream.close(null);
if (stream.get_data_size() > 32 * 1024 * 1024)
throw new Error("The screenshot is too large.");
resolve({
png: stream.steal_as_bytes().get_data(),
metadata,
content,
bounds: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height },
bufferBounds: {
x: bufferBounds.x,
y: bufferBounds.y,
width: bufferBounds.width,
height: bufferBounds.height,
},
});
} catch (error) {
reject(error);
} finally {
if (!stream.is_closed()) stream.close(null);
}
});
});
}
export default class T3SnapShotExtension extends Extension {
enable() {
this._feedback = new CaptureFeedback();
this._sessionChanged = Main.sessionMode.connect("updated", () => this._feedback.dispose());
this._monitorsChanged = Main.layoutManager.connect("monitors-changed", () =>
this._feedback.dispose(),
);
this._service = new CaptureService({
getNameOwner,
getProcessId,
beginFeedback: (...args) => this._feedback.begin(...args),
isAvailable: () =>
isWaylandSession(Meta) && !Main.sessionMode.isLocked && !Main.sessionMode.isGreeter,
takeSnapshot,
});
this._object = Gio.DBusExportedObject.wrapJSObject(XML, this);
this._object.export(Gio.DBus.session, PATH);
this._owner = Gio.bus_own_name_on_connection(
Gio.DBus.session,
NAME,
Gio.BusNameOwnerFlags.NONE,
null,
null,
);
}
get Version() {
return 2;
}
CaptureAsync(_params, invocation) {
void this._service
.capture(invocation.get_sender())
.then(({ png, metadata }) =>
invocation.return_value(new GLib.Variant("(ays)", [png, metadata])),
)
.catch((error) => invocation.return_dbus_error(`${NAME}.Failed`, error.message));
}
CaptureWithFeedbackAsync([flash, animate], invocation) {
void this._service
.capture(invocation.get_sender(), { flash, animate })
.then(({ png, metadata, animationStarted }) =>
invocation.return_value(new GLib.Variant("(aysb)", [png, metadata, animationStarted])),
)
.catch((error) => invocation.return_dbus_error(`${NAME}.Failed`, error.message));
}
ActivateAsync([title], invocation) {
void this._feedback
.activate(invocation.get_sender(), title)
.then(() => invocation.return_value(null))
.catch((error) => invocation.return_dbus_error(`${NAME}.Failed`, error.message));
}
AnimateAsync([x, y, width, height], invocation) {
void this._feedback
.animate(invocation.get_sender(), { x, y, width, height })
.then(() => invocation.return_value(null))
.catch((error) => invocation.return_dbus_error(`${NAME}.Failed`, error.message));
}
disable() {
this._service?.disable();
this._feedback?.dispose();
if (this._sessionChanged) Main.sessionMode.disconnect(this._sessionChanged);
if (this._monitorsChanged) Main.layoutManager.disconnect(this._monitorsChanged);
this._sessionChanged = 0;
this._monitorsChanged = 0;
this._object?.unexport();
if (this._owner) Gio.bus_unown_name(this._owner);
this._service = null;
this._object = null;
this._owner = null;
}
}
@@ -0,0 +1,28 @@
// PID comes from the bus daemon, not from the caller. Never focus a different T3 process.
export function findCaptureDestination(windows, pid, title) {
const owned = windows.filter((window) => window.get_pid() === pid);
const matching = owned.filter((window) => window.get_title() === title);
if (matching.length === 1) return matching[0];
return owned.length === 1 ? owned[0] : undefined;
}
export function captureDestinationFrame(relative, bounds) {
const { x, y, width, height } = relative;
if (
![x, y, width, height].every(Number.isFinite) ||
x < 0 ||
y < 0 ||
width <= 0 ||
height <= 0 ||
x + width > 1.01 ||
y + height > 1.01
) {
throw new Error("Invalid capture animation destination.");
}
return {
x: bounds.x + x * bounds.width,
y: bounds.y + y * bounds.height,
width: width * bounds.width,
height: height * bounds.height,
};
}
@@ -0,0 +1,34 @@
import { expect, it } from "vite-plus/test";
import { captureDestinationFrame, findCaptureDestination } from "./feedbackGeometry.js";
const window = (pid, title) => ({ get_pid: () => pid, get_title: () => title });
it("activates only a window of the process authenticated by D-Bus", () => {
const target = window(42, "T3 Code");
expect(findCaptureDestination([window(99, "T3 Code"), target], 42, "T3 Code")).toBe(target);
expect(findCaptureDestination([window(99, "T3 Code")], 42, "T3 Code")).toBeUndefined();
expect(findCaptureDestination([target], 42, "Title before navigation")).toBe(target);
});
it("does not guess between ambiguous windows from the same process", () => {
expect(findCaptureDestination([window(42, "T3"), window(42, "T3")], 42, "T3")).toBeUndefined();
expect(findCaptureDestination([window(42, "A"), window(42, "B")], 42, "C")).toBeUndefined();
});
it("maps the composer onto GNOME's current window position and logical scale", () => {
expect(
captureDestinationFrame(
{ x: 0.1, y: 0.8, width: 0.2, height: 0.1 },
{ x: -1920, y: 30, width: 1200, height: 900 },
),
).toEqual({ x: -1800, y: 750, width: 240, height: 90 });
});
it.each([NaN, Infinity, -1, 2])("rejects invalid/off-window animation geometry %s", (x) => {
expect(() =>
captureDestinationFrame(
{ x, y: 0, width: 0.2, height: 0.1 },
{ x: 0, y: 0, width: 1200, height: 900 },
),
).toThrow("Invalid");
});
@@ -0,0 +1,8 @@
{
"uuid": "[email protected]",
"name": "T3 Code SnapShots",
"description": "Allows T3 Code to capture the focused window, identify it for optional accessibility text, and animate it into T3 Code. Disable this extension to revoke access.",
"shell-version": ["45", "46", "47", "48", "49", "50"],
"version": 2,
"url": "https://github.com/pingdotgg/t3code"
}
+4 -1
View File
@@ -14,6 +14,7 @@
"dependencies": {
"@clerk/electron": "catalog:",
"@clerk/electron-passkeys": "catalog:",
"@crowecawcaw/xa11y": "0.13.0",
"@effect/platform-node": "catalog:",
"@napi-rs/keyring": "^1.3.0",
"@t3tools/client-runtime": "workspace:*",
@@ -21,10 +22,12 @@
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"dbus-next": "0.10.2",
"effect": "catalog:",
"electron": "43.4.1",
"electron": "44.1.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"ffi-rs": "1.3.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
},
+16
View File
@@ -23,11 +23,27 @@ if (!Number.isInteger(port) || port <= 0) {
const requiredFiles = [
"dist-electron/main.cjs",
"dist-electron/electron/WindowsForegroundFocusWorker.cjs",
"dist-electron/preload.cjs",
"dist-electron/snapShot/GlobalShiftShortcutWorker.cjs",
"dist-electron/snapShot/RegionSnapShotWorker.cjs",
"dist-electron/snapShot/SnapShotAccessibilityWorker.cjs",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
{
directory: "dist-electron/electron",
files: new Set(["WindowsForegroundFocusWorker.cjs"]),
},
{
directory: "dist-electron/snapShot",
files: new Set([
"GlobalShiftShortcutWorker.cjs",
"RegionSnapShotWorker.cjs",
"SnapShotAccessibilityWorker.cjs",
]),
},
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
+73 -22
View File
@@ -20,7 +20,7 @@ const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 15;
const LAUNCHER_VERSION = 19;
const developmentMacIconPngPath = NodePath.join(
repoRoot,
"assets",
@@ -96,16 +96,19 @@ function runChecked(command, args) {
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
}
export function resolveMacCodeSignArguments(appBundlePath) {
return ["--force", "--deep", "--sign", "-", "--timestamp=none", appBundlePath];
}
function signMacLauncherBundle(appBundlePath) {
runChecked("codesign", resolveMacCodeSignArguments(appBundlePath));
}
function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
export function makeDevelopmentEnvironmentScript(environment) {
const envEntries = [
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
@@ -116,27 +119,59 @@ export function makeDevelopmentLauncherScript({
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
"",
].join("\n");
}
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environmentFilePath,
}) {
return [
"#!/bin/sh",
`if [ -f ${shellSingleQuote(environmentFilePath)} ]; then . ${shellSingleQuote(environmentFilePath)}; fi`,
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const developmentEnvironmentFilePath = NodePath.join(
desktopDir,
".electron-runtime",
"dev-environment.sh",
);
function writeDevelopmentEnvironmentScript() {
NodeFS.mkdirSync(NodePath.dirname(developmentEnvironmentFilePath), { recursive: true });
NodeFS.writeFileSync(
targetBinaryPath,
makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environment: process.env,
}),
developmentEnvironmentFilePath,
makeDevelopmentEnvironmentScript(process.env),
);
}
export function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const script = makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environmentFilePath: developmentEnvironmentFilePath,
});
if (
NodeFS.existsSync(targetBinaryPath) &&
NodeFS.readFileSync(targetBinaryPath, "utf8") === script
) {
NodeFS.chmodSync(targetBinaryPath, 0o755);
return false;
}
NodeFS.writeFileSync(targetBinaryPath, script);
NodeFS.chmodSync(targetBinaryPath, 0o755);
return true;
}
function registerMacLauncherBundle(appBundlePath) {
@@ -225,13 +260,24 @@ function ensureMacIconIcns(runtimeDir) {
}
}
export function resolveMacBundleInfoPlistStrings(executableName) {
return {
CFBundleDisplayName: APP_DISPLAY_NAME,
CFBundleName: APP_DISPLAY_NAME,
CFBundleIdentifier: APP_BUNDLE_ID,
CFBundleExecutable: executableName,
CFBundleIconFile: "icon.icns",
NSScreenCaptureUsageDescription:
"T3 Code captures the active window when you use the snapshot shortcut.",
NSDocumentsFolderUsageDescription: "T3 Code reads project files you open in the desktop app.",
};
}
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
for (const [key, value] of Object.entries(resolveMacBundleInfoPlistStrings(executableName))) {
setPlistString(infoPlistPath, key, value);
}
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
{
CFBundleURLName: APP_BUNDLE_ID,
@@ -327,7 +373,10 @@ function buildMacLauncher(electronBinaryPath) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
writeDevelopmentEnvironmentScript();
if (writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath)) {
signMacLauncherBundle(targetAppBundlePath);
}
}
registerMacLauncherBundle(targetAppBundlePath);
return launcherBinaryPath;
@@ -354,8 +403,10 @@ function buildMacLauncher(electronBinaryPath) {
// Electron.app even though this bundle's Info.plist has the T3 Code name.
// Its conventional executable name also keeps Electron's default-app runtime
// in development mode instead of making app.isPackaged report true.
writeDevelopmentEnvironmentScript();
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
signMacLauncherBundle(targetAppBundlePath);
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
@@ -1,30 +1,48 @@
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { assert, describe, it } from "vite-plus/test";
import {
makeDevelopmentEnvironmentScript,
makeDevelopmentLauncherScript,
resolveElectronBinaryPath,
resolveMacBundleInfoPlistStrings,
resolveMacCodeSignArguments,
resolveMacLauncherIconPaths,
resolveMacLauncherPaths,
writeDevelopmentLauncherScript,
} from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const environmentScript = makeDevelopmentEnvironmentScript({
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
});
assert.include(
environmentScript,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(environmentScript, "\nexport VITE_DEV_SERVER_URL=");
});
it("keeps the launcher script free of volatile environment values", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
environmentFilePath: "/repo/apps/desktop/.electron-runtime/dev-environment.sh",
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
"if [ -f '/repo/apps/desktop/.electron-runtime/dev-environment.sh' ]; then . '/repo/apps/desktop/.electron-runtime/dev-environment.sh'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.notInclude(script, "VITE_DEV_SERVER_URL");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
@@ -71,7 +89,7 @@ describe("electron development launcher", () => {
electronBinaryPath: paths.runtimeElectronBinaryPath,
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {},
environmentFilePath: "/repo/apps/desktop/.electron-runtime/dev-environment.sh",
});
assert.include(
script,
@@ -80,6 +98,44 @@ describe("electron development launcher", () => {
assert.notInclude(script, "node_modules/electron");
});
it("declares why the macOS app needs protected access", () => {
const values = resolveMacBundleInfoPlistStrings("T3 Code (Dev) Launcher");
assert.equal(
values.NSScreenCaptureUsageDescription,
"T3 Code captures the active window when you use the snapshot shortcut.",
);
assert.equal(
values.NSDocumentsFolderUsageDescription,
"T3 Code reads project files you open in the desktop app.",
);
});
it("ad-hoc signs the complete development app bundle", () => {
assert.deepEqual(resolveMacCodeSignArguments("/runtime/T3 Code (Dev).app"), [
"--force",
"--deep",
"--sign",
"-",
"--timestamp=none",
"/runtime/T3 Code (Dev).app",
]);
});
it("restores execute permissions on an unchanged launcher", () => {
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-launcher-"));
const launcherPath = NodePath.join(directory, "launcher");
try {
writeDevelopmentLauncherScript(launcherPath, "/runtime/Electron");
NodeFS.chmodSync(launcherPath, 0o644);
assert.isFalse(writeDevelopmentLauncherScript(launcherPath, "/runtime/Electron"));
assert.equal(NodeFS.statSync(launcherPath).mode & 0o777, 0o755);
} finally {
NodeFS.rmSync(directory, { recursive: true, force: true });
}
});
it("derives launcher icons from canonical development and production assets", () => {
const development = resolveMacLauncherIconPaths("/runtime", true);
const production = resolveMacLauncherIconPaths("/runtime", false);
+3
View File
@@ -29,6 +29,7 @@ import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
@@ -150,6 +151,7 @@ const bootstrap = Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
yield* logBootstrapInfo("bootstrap start");
@@ -202,6 +204,7 @@ const bootstrap = Effect.gen(function* () {
"bootstrap fell back to local-only because no advertised network host was available",
);
}
yield* snapShot.initialize;
yield* installDesktopIpcHandlers();
yield* logBootstrapInfo("bootstrap ipc handlers registered");
@@ -131,10 +131,6 @@ export const make = Effect.gen(function* () {
yield* electronApp.setAppUserModelId(environment.appUserModelId);
}
if (environment.platform === "linux") {
yield* electronApp.setDesktopName(environment.linuxDesktopEntryName);
}
// Unpackaged runs only. A packaged bundle already carries its icon in
// Info.plist, so setting the dock tile again changes nothing except to
// overwrite a custom icon the user attached to the app themselves.
@@ -81,7 +81,9 @@ describe("DesktopEarlyElectronStartup", () => {
});
assert.deepEqual(options, {
isDevelopment: true,
linuxWmClass: "t3code-dev",
linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
passwordStore: "gnome-libsecret",
});
});
@@ -25,10 +25,15 @@ interface EarlyDesktopSettingsInput {
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
export interface EarlyLinuxElectronOptions {
readonly isDevelopment: boolean;
readonly linuxWmClass: string;
readonly linuxDesktopEntryName: string;
readonly passwordStore: LinuxPasswordStoreSwitch | null;
}
export const resolveLinuxDesktopEntryName = (isDevelopment: boolean): string =>
isDevelopment ? "com.t3tools.T3Code.Development.desktop" : "com.t3tools.T3Code.desktop";
const trimNonEmpty = (value: string | undefined): string | null => {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
@@ -80,8 +85,11 @@ export function resolveEarlyLinuxElectronOptions(
input: EarlyLinuxElectronOptionsInput,
): EarlyLinuxElectronOptions {
const preference = resolveEarlyLinuxPasswordStorePreference(input);
const isDevelopment = isDevelopmentEnvironment(input.env);
return {
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
isDevelopment,
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
linuxDesktopEntryName: resolveLinuxDesktopEntryName(isDevelopment),
passwordStore: resolveLinuxPasswordStoreSwitch({
preference,
env: input.env,
@@ -75,6 +75,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.backendCwd, "/repo");
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev");
assert.equal(environment.linuxWmClass, "t3code-dev");
assert.equal(environment.linuxDesktopEntryName, "com.t3tools.T3Code.Development.desktop");
assert.deepEqual(
Option.map(environment.devServerUrl, (url) => url.href),
Option.some("http://localhost:5173/"),
@@ -122,6 +123,19 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("uses the stable desktop entry as the packaged Linux portal identity", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment({
platform: "linux",
isPackaged: true,
appPath: "/tmp/.mount_t3code/resources/app.asar",
resourcesPath: "/tmp/.mount_t3code/resources",
});
assert.equal(environment.linuxDesktopEntryName, "com.t3tools.T3Code.desktop");
}),
);
it.effect("keeps implicit development state separate from production state", () =>
Effect.gen(function* () {
const development = yield* makeEnvironment(
+3 -2
View File
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { resolveLinuxDesktopEntryName } from "./DesktopEarlyElectronStartup.ts";
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
@@ -98,7 +99,7 @@ function resolveDesktopAppStageLabel(input: {
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
}
function resolveDesktopAppBranding(input: {
export function resolveDesktopAppBranding(input: {
readonly isDevelopment: boolean;
readonly appVersion: string;
}): DesktopAppBranding {
@@ -226,7 +227,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () =>
isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code",
),
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxDesktopEntryName: resolveLinuxDesktopEntryName(isDevelopment),
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
linuxApplicationsDir,
appImagePath: config.appImagePath,
@@ -69,6 +69,7 @@ function makeElectronWindowLayer(destroyAll: Effect.Effect<void> = Effect.void)
focusedMainOrFirst: Effect.die("unexpected focused window read"),
setMain: () => Effect.void,
clearMain: () => Effect.void,
prepareReveal: () => Effect.succeed(false),
reveal: () => Effect.void,
sendAll: () => Effect.void,
destroyAll,
@@ -92,7 +93,9 @@ function makeDesktopWindowLayer(
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: input.flushMainWindowBounds ?? Effect.void,
prepareCaptureReveal: Effect.void,
dispatchMenuAction: () => Effect.void,
dispatchSnapShotEvent: () => Effect.void,
zoomMain: () => Effect.void,
syncAppearance: Effect.void,
});
@@ -23,6 +23,7 @@ const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
isPackaged: true,
isDevelopment: false,
displayName: "T3 Code (Alpha)",
linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
linuxWmClass: "t3code",
linuxApplicationsDir: "/home/alice/.local/share/applications",
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
@@ -51,6 +52,7 @@ const makeHandlerLayer = (
readonly environment?: Record<string, unknown>;
readonly xdgMimeExitCode?: number;
readonly writeError?: PlatformError.PlatformError;
readonly existingEntry?: string;
} = {},
) =>
DesktopLinuxUrlHandler.layer.pipe(
@@ -58,6 +60,7 @@ const makeHandlerLayer = (
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
FileSystem.layerNoop({
readFileString: () => Effect.succeed(input.existingEntry ?? ""),
makeDirectory: (path) =>
Effect.sync(() => {
recorded.directories.push(path);
@@ -128,7 +131,7 @@ describe("DesktopLinuxUrlHandler", () => {
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme: "t3code",
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
desktopEntryPath: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
cause: new Error("boom"),
});
assert.equal(
@@ -137,7 +140,7 @@ describe("DesktopLinuxUrlHandler", () => {
);
assert.equal(
writeError.desktopEntryPath,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
"/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
);
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
@@ -161,7 +164,7 @@ describe("DesktopLinuxUrlHandler", () => {
assert.equal(recorded.files.length, 1);
assert.equal(
recorded.files[0]?.path,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
"/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
);
assert.include(
recorded.files[0]?.content,
@@ -171,7 +174,7 @@ describe("DesktopLinuxUrlHandler", () => {
assert.deepEqual(recorded.commands, [
{
command: "xdg-mime",
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
},
]);
});
@@ -190,19 +193,43 @@ describe("DesktopLinuxUrlHandler", () => {
});
});
it.effect("does nothing on other platforms or unpackaged builds", () => {
it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded, {
existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
displayName: "T3 Code (Alpha)",
execTarget: "/home/alice/Applications/T3-Code.AppImage",
scheme: "t3code",
}),
});
assert.deepEqual(recorded.files, []);
assert.deepEqual(recorded.directories, []);
assert.equal(recorded.commands.length, 1);
});
});
it.effect("writes the portal identity without claiming the URL scheme in development", () => {
const nonLinux = emptyRecording();
const unpackaged = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
yield* runRegister(unpackaged, {
environment: {
isPackaged: false,
linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
},
});
for (const recorded of [nonLinux, unpackaged]) {
assert.deepEqual(recorded.directories, []);
assert.deepEqual(recorded.files, []);
assert.deepEqual(recorded.commands, []);
}
assert.deepEqual(nonLinux.files, []);
assert.equal(
unpackaged.files[0]?.path,
"/home/alice/.local/share/applications/com.t3tools.T3Code.Development.desktop",
);
assert.deepEqual(unpackaged.commands, []);
});
});
@@ -218,7 +245,7 @@ describe("DesktopLinuxUrlHandler", () => {
module: "FileSystem",
method: "writeFileString",
description: "read-only filesystem",
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
pathOrDescriptor: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
}),
});
+16 -13
View File
@@ -20,8 +20,6 @@ import { makeComponentLogger } from "./DesktopObservability.ts";
// our own handler entry pointing at the current AppImage and claim the
// scheme default via xdg-mime, exactly what the file manager's "set as
// default" checkbox would record in mimeapps.list.
const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
@@ -101,22 +99,26 @@ export const make = Effect.gen(function* () {
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
const desktopEntryPath = environment.path.join(
environment.linuxApplicationsDir,
URL_HANDLER_DESKTOP_ENTRY_NAME,
environment.linuxDesktopEntryName,
);
const writeDesktopEntry = Effect.gen(function* () {
// Inside the mounted AppImage, process.execPath points at a transient
// /tmp/.mount_* path — the handler must launch the AppImage itself.
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
const content = renderUrlHandlerDesktopEntry({
displayName: environment.displayName,
execTarget,
scheme,
});
// Pre-ready setup normally wrote this already. Avoid truncating a valid
// entry while the portal may be reading it during startup.
const existing = yield* fileSystem
.readFileString(desktopEntryPath)
.pipe(Effect.orElseSucceed(() => null));
if (existing === content) return;
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
yield* fileSystem.writeFileString(
desktopEntryPath,
renderUrlHandlerDesktopEntry({
displayName: environment.displayName,
execTarget,
scheme,
}),
);
yield* fileSystem.writeFileString(desktopEntryPath, content);
}).pipe(
Effect.mapError(
(cause) =>
@@ -133,7 +135,7 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
const command = ChildProcess.make(
"xdg-mime",
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
{
stdin: "ignore",
stdout: "ignore",
@@ -163,10 +165,11 @@ export const make = Effect.gen(function* () {
);
const register = Effect.gen(function* () {
if (environment.platform !== "linux" || !environment.isPackaged) {
if (environment.platform !== "linux") {
return;
}
yield* writeDesktopEntry;
if (!environment.isPackaged) return;
yield* setDefaultHandler;
yield* logInfo("registered URL scheme handler", { scheme });
}).pipe(
@@ -5,17 +5,28 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
}),
);
const {
appendSwitchMock,
getSwitchValueMock,
hasSwitchMock,
registerSchemesMock,
setDesktopNameMock,
mkdirSyncMock,
writeFileSyncMock,
} = vi.hoisted(() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
setDesktopNameMock: vi.fn(),
mkdirSyncMock: vi.fn(),
writeFileSyncMock: vi.fn(),
}));
vi.mock("electron", () => ({
app: {
setDesktopName: setDesktopNameMock,
getVersion: () => "0.0.37",
commandLine: {
appendSwitch: appendSwitchMock,
getSwitchValue: getSwitchValueMock,
@@ -27,6 +38,12 @@ vi.mock("electron", () => ({
},
}));
vi.mock("node:fs", () => ({
readFileSync: () => "{}",
mkdirSync: mkdirSyncMock,
writeFileSync: writeFileSyncMock,
}));
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
describe("DesktopPreReadyPlatform", () => {
@@ -35,6 +52,9 @@ describe("DesktopPreReadyPlatform", () => {
getSwitchValueMock.mockReset();
hasSwitchMock.mockReset();
registerSchemesMock.mockReset();
setDesktopNameMock.mockReset();
mkdirSyncMock.mockReset();
writeFileSyncMock.mockReset();
});
it.effect("preserves an explicit Linux password-store switch", () => {
@@ -55,6 +75,54 @@ describe("DesktopPreReadyPlatform", () => {
);
});
for (const previousEntry of [undefined, 'Exec="/Applications/deleted-previous.AppImage" %U']) {
it.effect(
`prepares a ${previousEntry ? "stale" : "missing"} Linux desktop entry before startup yields`,
() => {
vi.stubEnv("VITE_DEV_SERVER_URL", "");
vi.stubEnv("XDG_DATA_HOME", "/xdg");
vi.stubEnv("APPIMAGE", "/Applications/current.AppImage");
getSwitchValueMock.mockReturnValue("");
let desktopName = "t3code.desktop";
let desktopEntry = previousEntry;
setDesktopNameMock.mockImplementation((name: string) => {
desktopName = name;
});
writeFileSyncMock.mockImplementation((path: string, contents: string) => {
if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents;
});
return Effect.scoped(
Effect.gen(function* () {
const portalIdentity = Promise.resolve().then(() => ({ desktopName, desktopEntry }));
yield* Layer.build(
DesktopPreReadyPlatform.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
),
);
const identity = yield* Effect.promise(() => portalIdentity);
assert.equal(identity.desktopName, "com.t3tools.T3Code.desktop");
assert.include(identity.desktopEntry ?? "", 'Exec="/Applications/current.AppImage" %U');
assert.include(identity.desktopEntry ?? "", "Name=T3 Code (Alpha)");
assert.include(identity.desktopEntry ?? "", "MimeType=x-scheme-handler/t3code;");
}),
).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
},
);
}
it.effect("keeps startup available when the early desktop entry cannot be written", () => {
getSwitchValueMock.mockReturnValue("");
mkdirSyncMock.mockImplementation(() => {
throw new Error("read-only filesystem");
});
return DesktopPreReadyPlatform.make.pipe(
Effect.provideService(HostProcessPlatform, "linux"),
Effect.asVoid,
);
});
it.effect(
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
() =>
@@ -102,6 +170,7 @@ describe("DesktopPreReadyPlatform", () => {
assert.deepEqual(events, ["pre-ready", "clerk"]);
assert.equal(registerSchemesMock.mock.calls.length, 1);
assert.equal(appendSwitchMock.mock.calls.length, 0);
assert.equal(setDesktopNameMock.mock.calls.length, 0);
}),
);
});
@@ -1,4 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads settings and prepares the Linux desktop entry synchronously before app services are available.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
@@ -10,6 +10,8 @@ import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts";
import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
export interface DesktopPreReadyCommandLineReader {
@@ -57,6 +59,33 @@ export const make = Effect.gen(function* () {
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
if (linux !== null) {
// The portal also requires a valid desktop entry. An AppImage update may
// have removed the executable referenced by the previous launch's entry.
try {
const applicationsDir = NodePath.posix.join(
process.env.XDG_DATA_HOME?.trim() ||
NodePath.posix.join(NodeOS.homedir(), ".local", "share"),
"applications",
);
NodeFS.mkdirSync(applicationsDir, { recursive: true });
NodeFS.writeFileSync(
NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName),
renderUrlHandlerDesktopEntry({
displayName: resolveDesktopAppBranding({
isDevelopment: linux.isDevelopment,
appVersion: Electron.app.getVersion(),
}).displayName,
execTarget: process.env.APPIMAGE?.trim() || process.execPath,
scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment),
}),
"utf8",
);
} catch {
// The URL handler retries with the full environment and logs failures.
}
// Chromium caches its portal registration during startup. Set the identity
// before any asynchronous work can initialize it with Electron's default.
Electron.app.setDesktopName(linux.linuxDesktopEntryName);
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
@@ -96,7 +96,9 @@ function makePoolLayer(
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
prepareCaptureReveal: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
dispatchSnapShotEvent: () => Effect.void,
zoomMain: () => Effect.die("unexpected zoom"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
@@ -36,6 +36,28 @@ describe("ElectronShell", () => {
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("copies text to the system clipboard", () =>
Effect.gen(function* () {
writeTextMock.mockResolvedValue(undefined);
const electronShell = yield* ElectronShell.ElectronShell;
yield* electronShell.copyText("https://example.com/path");
assert.deepEqual(writeTextMock.mock.calls, [["https://example.com/path"]]);
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("does not fail when the clipboard write rejects", () =>
Effect.gen(function* () {
writeTextMock.mockRejectedValue(new Error("write failed"));
const electronShell = yield* ElectronShell.ElectronShell;
yield* electronShell.copyText("https://example.com/path");
assert.deepEqual(writeTextMock.mock.calls, [["https://example.com/path"]]);
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("opens the Full Disk Access settings anchor", () =>
Effect.gen(function* () {
openExternalMock.mockResolvedValue(undefined);
+1 -3
View File
@@ -88,9 +88,7 @@ export const make = ElectronShell.of({
),
),
copyText: (text) =>
Effect.sync(() => {
Electron.clipboard.writeText(text);
}),
Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined)),
});
export const layer = Layer.succeed(ElectronShell, make);
@@ -0,0 +1,9 @@
import { expect, it, vi } from "vite-plus/test";
vi.mock("@crowecawcaw/xa11y", () => {
throw new Error("Cannot find native binding");
});
it("loads without an accessibility native binding", async () => {
await expect(import("./ElectronWindow.ts")).resolves.toBeDefined();
});
+353 -11
View File
@@ -2,18 +2,48 @@ import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
() => ({
appFocusMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
}),
);
const {
activateWindowsForegroundMock,
appFocusMock,
browserWindowMock,
foregroundWindowMock,
getAllWindowsMock,
getFocusedWindowMock,
loadWindowsForegroundApiMock,
shellHostedForegroundMock,
startWindowsForegroundFocusThreadMock,
windowsForegroundFocusMock,
windowsForegroundPrepareMock,
windowsForegroundCloseMock,
} = vi.hoisted(() => ({
activateWindowsForegroundMock: vi.fn(),
appFocusMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
foregroundWindowMock: vi.fn<() => bigint>(),
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
loadWindowsForegroundApiMock: vi.fn<() => Promise<{ getForegroundWindow: () => bigint }>>(),
shellHostedForegroundMock: vi.fn(),
startWindowsForegroundFocusThreadMock: vi.fn(),
windowsForegroundFocusMock: vi.fn(),
windowsForegroundPrepareMock: vi.fn(),
windowsForegroundCloseMock: vi.fn(),
}));
vi.mock("./WindowsForeground.ts", () => ({
activateWindowsForeground: activateWindowsForegroundMock,
isWindowsShellHostedForeground: shellHostedForegroundMock,
loadWindowsForegroundApi: loadWindowsForegroundApiMock,
}));
vi.mock("./WindowsForegroundFocusThread.ts", () => ({
startWindowsForegroundFocusThread: startWindowsForegroundFocusThreadMock,
}));
vi.mock("electron", () => ({
app: {
@@ -27,9 +57,10 @@ vi.mock("electron", () => ({
import * as ElectronWindow from "./ElectronWindow.ts";
const TestLayer = ElectronWindow.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
const testLayer = (platform: NodeJS.Platform) =>
ElectronWindow.layer.pipe(Layer.provide(Layer.succeed(HostProcessPlatform, platform)));
const TestLayer = testLayer("linux");
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
return {
@@ -38,12 +69,44 @@ function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boo
} as unknown as Electron.BrowserWindow;
}
function makeWindowsRevealWindow() {
return {
id: 41,
isDestroyed: vi.fn(() => false),
isFocused: vi.fn(() => false),
isMinimized: vi.fn(() => false),
isVisible: vi.fn(() => true),
show: vi.fn(),
moveTop: vi.fn(),
focus: vi.fn(),
getTitle: vi.fn(() => "T3 Code (Dev)"),
getBounds: vi.fn(() => ({ x: 100, y: 50, width: 1_200, height: 800 })),
getContentBounds: vi.fn(() => ({ x: 108, y: 50, width: 1_184, height: 792 })),
getNativeWindowHandle: vi.fn(() => Buffer.from([41, 0, 0, 0])),
restore: vi.fn(),
};
}
describe("ElectronWindow", () => {
beforeEach(() => {
activateWindowsForegroundMock.mockReset().mockResolvedValue(undefined);
appFocusMock.mockReset();
browserWindowMock.mockReset();
foregroundWindowMock.mockReset().mockReturnValue(0n);
getAllWindowsMock.mockReset();
getFocusedWindowMock.mockReset();
loadWindowsForegroundApiMock
.mockReset()
.mockImplementation(() => Promise.resolve({ getForegroundWindow: foregroundWindowMock }));
shellHostedForegroundMock.mockReset().mockResolvedValue(false);
startWindowsForegroundFocusThreadMock.mockReset().mockReturnValue({
prepare: windowsForegroundPrepareMock,
focus: windowsForegroundFocusMock,
close: windowsForegroundCloseMock,
});
windowsForegroundFocusMock.mockReset().mockResolvedValue(false);
windowsForegroundPrepareMock.mockReset().mockResolvedValue(false);
windowsForegroundCloseMock.mockReset();
});
it.effect("preserves schema-safe creation context and the Electron cause", () =>
@@ -178,6 +241,239 @@ describe("ElectronWindow", () => {
}).pipe(Effect.provide(TestLayer)),
);
it.effect("uses native Windows activation without querying the foreground window", () =>
Effect.gen(function* () {
const operations: Array<string> = [];
appFocusMock.mockImplementation(() => operations.push("app-focus"));
activateWindowsForegroundMock.mockImplementation(async () => {
operations.push("native-activation");
});
const window = {
...makeWindowsRevealWindow(),
show: vi.fn(() => operations.push("show")),
moveTop: vi.fn(() => operations.push("move-top")),
focus: vi.fn(() => operations.push("focus")),
} as unknown as Electron.BrowserWindow;
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window);
yield* electronWindow.reveal(window);
assert.deepEqual(operations, ["app-focus", "show", "move-top", "focus", "native-activation"]);
assert.lengthOf(loadWindowsForegroundApiMock.mock.calls, 0);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("focuses the exact T3 window before activating from a shell-hosted app", () =>
Effect.gen(function* () {
const operations: Array<string> = [];
shellHostedForegroundMock.mockResolvedValue(true);
windowsForegroundFocusMock.mockImplementation(async () => {
operations.push("native-focus");
return true;
});
activateWindowsForegroundMock.mockImplementation(async () => {
operations.push("native-activation");
});
const window = {
...makeWindowsRevealWindow(),
show: vi.fn(() => operations.push("show")),
moveTop: vi.fn(() => operations.push("move-top")),
focus: vi.fn(() => operations.push("focus")),
} as unknown as Electron.BrowserWindow;
appFocusMock.mockImplementation(() => operations.push("app-focus"));
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window);
yield* electronWindow.reveal(window);
assert.deepEqual(operations, [
"app-focus",
"show",
"move-top",
"focus",
"native-focus",
"native-activation",
]);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 1);
assert.deepEqual(windowsForegroundFocusMock.mock.calls, [
[
{
windowId: 41,
processId: process.pid,
title: "T3 Code (Dev)",
bounds: { x: 100, y: 50, width: 1_200, height: 800 },
contentBounds: { x: 108, y: 50, width: 1_184, height: 792 },
},
],
]);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("prepares the exact T3 window before a capture overlay", () =>
Effect.gen(function* () {
windowsForegroundPrepareMock.mockResolvedValue(true);
const window = makeWindowsRevealWindow();
const electronWindow = yield* ElectronWindow.ElectronWindow;
const prepared = yield* electronWindow.prepareReveal(
window as unknown as Electron.BrowserWindow,
);
assert.isTrue(prepared);
assert.deepEqual(windowsForegroundPrepareMock.mock.calls, [
[
{
windowId: 41,
processId: process.pid,
title: "T3 Code (Dev)",
bounds: { x: 100, y: 50, width: 1_200, height: 800 },
contentBounds: { x: 108, y: 50, width: 1_184, height: 792 },
},
],
]);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 0);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect.each([4, 8])(
"skips the focus worker only when the foreground matches the %i-byte HWND",
(handleBytes) =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
activateWindowsForegroundMock.mockRejectedValueOnce(
new Error("Windows initially refused foreground activation"),
);
const hwnd = handleBytes === 4 ? 0xf123_4567n : 0x1_f123_4567n;
const handle = Buffer.alloc(handleBytes);
if (handleBytes === 4) handle.writeUInt32LE(Number(hwnd));
else handle.writeBigUInt64LE(hwnd);
window.getNativeWindowHandle.mockReturnValue(handle);
foregroundWindowMock.mockReturnValue(hwnd);
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
window.getTitle.mockClear();
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
assert.lengthOf(foregroundWindowMock.mock.calls, 1);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0);
assert.lengthOf(window.getTitle.mock.calls, 0);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect.each([42n, 0n])(
"focuses through the worker when the foreground HWND is %s instead of the target",
(foreground) =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
activateWindowsForegroundMock.mockRejectedValueOnce(
new Error("Windows initially refused foreground activation"),
);
foregroundWindowMock.mockReturnValue(foreground);
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 1);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("continues native focus when the foreground query fails", () =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
activateWindowsForegroundMock.mockRejectedValueOnce(
new Error("Windows initially refused foreground activation"),
);
loadWindowsForegroundApiMock.mockRejectedValue(new Error("Foreground query unavailable"));
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 1);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("does not fail reveal when native focus rejects", () =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
activateWindowsForegroundMock.mockRejectedValueOnce(
new Error("Windows initially refused foreground activation"),
);
windowsForegroundFocusMock.mockRejectedValue(new Error("Focus rejected"));
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 1);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("fails reveal when Windows refuses foreground activation", () =>
Effect.gen(function* () {
const cause = new Error("Windows refused foreground activation");
const window = makeWindowsRevealWindow();
activateWindowsForegroundMock.mockRejectedValue(cause);
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
const exit = yield* Effect.exit(
electronWindow.reveal(window as unknown as Electron.BrowserWindow),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "reveal-window");
assert.strictEqual(error.cause, cause);
}
assert.deepEqual(activateWindowsForegroundMock.mock.calls, [
[window.getNativeWindowHandle.mock.results[0]?.value],
[window.getNativeWindowHandle.mock.results[1]?.value],
]);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("cancels native focus when destroyed during the foreground query", () =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
activateWindowsForegroundMock.mockRejectedValueOnce(
new Error("Windows initially refused foreground activation"),
);
const queryStarted = Promise.withResolvers<void>();
const foreground = Promise.withResolvers<{ getForegroundWindow: () => bigint }>();
loadWindowsForegroundApiMock.mockImplementation(() => {
queryStarted.resolve();
return foreground.promise;
});
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
window.getTitle.mockClear();
const revealFiber = yield* electronWindow
.reveal(window as unknown as Electron.BrowserWindow)
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Effect.promise(() => queryStarted.promise);
window.isDestroyed.mockReturnValue(true);
foreground.resolve({ getForegroundWindow: foregroundWindowMock });
yield* Fiber.join(revealFiber);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0);
assert.lengthOf(window.getNativeWindowHandle.mock.calls, 1);
assert.lengthOf(window.getTitle.mock.calls, 0);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("preserves message delivery failures with window and channel context", () =>
Effect.gen(function* () {
const cause = new Error("renderer send failed");
@@ -237,4 +533,50 @@ describe("ElectronWindow", () => {
assert.equal(vi.mocked(laterWindow.destroy).mock.calls.length, 1);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("an ordinary reveal on Windows does not touch the Win32 foreground helpers", () =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 0);
assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0);
assert.lengthOf(shellHostedForegroundMock.mock.calls, 0);
assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 0);
assert.lengthOf(window.focus.mock.calls, 1);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("a capture reveal on Windows uses the Win32 path only once", () =>
Effect.gen(function* () {
const window = makeWindowsRevealWindow();
const electronWindow = yield* ElectronWindow.ElectronWindow;
yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow);
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow);
assert.lengthOf(activateWindowsForegroundMock.mock.calls, 1);
assert.lengthOf(window.focus.mock.calls, 2);
}).pipe(Effect.provide(testLayer("win32"))),
);
it.effect("starts the Windows focus worker lazily and closes it with the layer", () =>
Effect.gen(function* () {
yield* ElectronWindow.ElectronWindow.pipe(Effect.provide(testLayer("win32")));
assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 0);
assert.lengthOf(windowsForegroundCloseMock.mock.calls, 0);
yield* Effect.gen(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const window = makeWindowsRevealWindow() as unknown as Electron.BrowserWindow;
yield* electronWindow.prepareReveal(window);
yield* electronWindow.prepareReveal(window);
assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 1);
assert.lengthOf(windowsForegroundCloseMock.mock.calls, 0);
}).pipe(Effect.provide(testLayer("win32")));
assert.lengthOf(windowsForegroundCloseMock.mock.calls, 1);
}),
);
});
+92 -3
View File
@@ -1,3 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only service resolves its bundled helper beside the Electron entrypoint.
import * as NodePath from "node:path";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import type * as Cause from "effect/Cause";
import * as Context from "effect/Context";
@@ -10,6 +14,33 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
import {
activateWindowsForeground,
isWindowsShellHostedForeground,
loadWindowsForegroundApi,
} from "./WindowsForeground.ts";
import { startWindowsForegroundFocusThread } from "./WindowsForegroundFocusThread.ts";
function windowsForegroundFocusTarget(window: Electron.BrowserWindow) {
return {
windowId: window.id,
processId: process.pid,
title: window.getTitle(),
bounds: window.getBounds(),
contentBounds: window.getContentBounds(),
};
}
async function isWindowsBrowserWindowForeground(window: Electron.BrowserWindow): Promise<boolean> {
const foreground = await loadWindowsForegroundApi()
.then((api) => api.getForegroundWindow())
.catch(() => undefined);
if (window.isDestroyed() || foreground === undefined || foreground === 0n) return false;
const handle = window.getNativeWindowHandle();
const hwnd = handle.length === 8 ? handle.readBigUInt64LE() : BigInt(handle.readUInt32LE());
return foreground === hwnd;
}
const ElectronWindowCreateOptions = Schema.Struct({
title: Schema.NullOr(Schema.String),
width: Schema.NullOr(Schema.Number),
@@ -86,6 +117,7 @@ export class ElectronWindow extends Context.Service<
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect<boolean>;
readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
readonly destroyAll: Effect.Effect<void>;
@@ -98,6 +130,18 @@ export class ElectronWindow extends Context.Service<
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
// The focus worker loads a native accessibility module. Start it on the first
// capture reveal so users who never capture pay nothing at launch.
let windowsForegroundFocus: ReturnType<typeof startWindowsForegroundFocusThread> | undefined;
const ensureWindowsForegroundFocus = () => {
windowsForegroundFocus ??= startWindowsForegroundFocusThread(
NodePath.join(__dirname, "electron", "WindowsForegroundFocusWorker.cjs"),
);
return windowsForegroundFocus;
};
// Tracks a capture reveal in flight. Ordinary reveals keep Electron's native path.
const captureRevealWindows = new Set<number>();
yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const listWindows = Effect.try({
@@ -208,26 +252,71 @@ export const make = Effect.gen(function* () {
}
return Option.none();
}),
prepareReveal: (window) =>
Effect.promise(async () => {
if (platform !== "win32" || window.isDestroyed()) {
return false;
}
captureRevealWindows.add(window.id);
return ensureWindowsForegroundFocus()
.prepare(windowsForegroundFocusTarget(window))
.catch(() => false);
}),
reveal: (window) =>
Effect.try({
try: () => {
Effect.tryPromise({
try: async () => {
if (window.isDestroyed()) {
return;
}
// Only a capture reveal fights another process for the foreground, which
// needs Win32 calls that load native modules. Everything else stays native.
const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id);
const shellHostedForeground =
captureReveal && (await isWindowsShellHostedForeground().catch(() => false));
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
if (captureReveal) {
Electron.app.focus();
}
if (captureReveal || !window.isVisible()) {
window.show();
}
if (captureReveal) {
window.moveTop();
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
if (captureReveal) {
if (shellHostedForeground) {
await windowsForegroundFocus
?.focus(windowsForegroundFocusTarget(window))
.catch(() => false);
}
try {
await activateWindowsForeground(window.getNativeWindowHandle());
} catch {
const needsFocus = !(await isWindowsBrowserWindowForeground(window));
if (needsFocus && !window.isDestroyed()) {
await windowsForegroundFocus
?.focus(windowsForegroundFocusTarget(window))
.catch(() => false);
}
if (!window.isDestroyed()) {
await activateWindowsForeground(window.getNativeWindowHandle());
}
}
}
},
catch: (cause) =>
new ElectronWindowOperationError({
@@ -0,0 +1,120 @@
import { assert, describe, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import {
activateWindowsForegroundWithApi,
isWindowsShellHostedForegroundWithApi,
type WindowsForegroundApi,
} from "./WindowsForeground.ts";
function nativeHandle(value: bigint, bytes = 8): Buffer {
const handle = Buffer.alloc(bytes);
if (bytes === 8) handle.writeBigUInt64LE(value);
else handle.writeUInt32LE(Number(value));
return handle;
}
function makeApi(input: {
readonly foregroundWindow?: bigint;
readonly currentThreadId?: number;
readonly foregroundThreadId?: number;
readonly attached?: boolean;
readonly activated?: boolean;
}) {
return {
getCurrentThreadId: vi.fn(() => input.currentThreadId ?? 10),
getForegroundWindow: vi.fn(() => input.foregroundWindow ?? 99n),
getWindowClassName: vi.fn(() => "Chrome_WidgetWin_1"),
getWindowThreadId: vi.fn(() => input.foregroundThreadId ?? 20),
getWindowThreadAndProcessId: vi.fn(() => ({
threadId: input.foregroundThreadId ?? 20,
processId: 500,
})),
getWindowText: vi.fn(() => ""),
getWindowRect: vi.fn(() => undefined),
getProcessImagePath: vi.fn(() => ""),
isKeyDown: vi.fn(() => false),
attachThreadInput: vi.fn((_source, _target, attach) =>
attach ? (input.attached ?? true) : true,
),
setForegroundWindow: vi.fn(() => input.activated ?? true),
} satisfies WindowsForegroundApi;
}
describe("Windows foreground activation", () => {
it.each([4, 8])("activates a %i-byte native window handle", (bytes) => {
const api = makeApi({});
const handle = nativeHandle(41n, bytes);
assert.isTrue(activateWindowsForegroundWithApi(handle, api));
assert.deepEqual(api.attachThreadInput.mock.calls, [
[10, 20, true],
[10, 20, false],
]);
assert.deepEqual(api.setForegroundWindow.mock.calls, [[41n]]);
});
it("does not disturb input queues when T3 is already foreground", () => {
const api = makeApi({ foregroundWindow: 41n });
assert.isTrue(activateWindowsForegroundWithApi(nativeHandle(41n), api));
assert.lengthOf(api.getCurrentThreadId.mock.calls, 0);
assert.lengthOf(api.attachThreadInput.mock.calls, 0);
assert.lengthOf(api.setForegroundWindow.mock.calls, 0);
});
it("does not attach a thread to itself", () => {
const api = makeApi({ currentThreadId: 20, foregroundThreadId: 20 });
assert.isTrue(activateWindowsForegroundWithApi(nativeHandle(41n), api));
assert.lengthOf(api.attachThreadInput.mock.calls, 0);
assert.deepEqual(api.setForegroundWindow.mock.calls, [[41n]]);
});
it("uses SetForegroundWindow's result as the activation receipt", () => {
const api = makeApi({ activated: false });
assert.isFalse(activateWindowsForegroundWithApi(nativeHandle(41n), api));
assert.deepEqual(api.attachThreadInput.mock.calls, [
[10, 20, true],
[10, 20, false],
]);
});
it("still asks Windows directly when the input queues cannot be attached", () => {
const api = makeApi({ attached: false });
assert.isTrue(activateWindowsForegroundWithApi(nativeHandle(41n), api));
assert.deepEqual(api.attachThreadInput.mock.calls, [[10, 20, true]]);
assert.deepEqual(api.setForegroundWindow.mock.calls, [[41n]]);
});
it("rejects malformed native handles", () => {
const api = makeApi({});
assert.throws(() => activateWindowsForegroundWithApi(Buffer.alloc(6), api));
assert.lengthOf(api.getForegroundWindow.mock.calls, 0);
});
it("recognizes a shell-hosted foreground window", () => {
const api = makeApi({});
api.getWindowClassName.mockReturnValue("ApplicationFrameWindow");
assert.isTrue(isWindowsShellHostedForegroundWithApi(api));
assert.deepEqual(api.getWindowClassName.mock.calls, [[99n]]);
});
it("does not classify ordinary or missing foreground windows as shell-hosted", () => {
const ordinary = makeApi({});
const missing = makeApi({ foregroundWindow: 0n });
assert.isFalse(isWindowsShellHostedForegroundWithApi(ordinary));
assert.isFalse(isWindowsShellHostedForegroundWithApi(missing));
assert.lengthOf(missing.getWindowClassName.mock.calls, 0);
});
});
@@ -0,0 +1,224 @@
export interface WindowsForegroundApi {
readonly getCurrentThreadId: () => number;
readonly getForegroundWindow: () => bigint;
readonly getWindowClassName: (windowHandle: bigint) => string;
readonly getWindowThreadId: (windowHandle: bigint) => number;
readonly getWindowThreadAndProcessId: (windowHandle: bigint) => {
readonly threadId: number;
readonly processId: number;
};
readonly getWindowText: (windowHandle: bigint) => string;
readonly getWindowRect: (
windowHandle: bigint,
) =>
| { readonly x: number; readonly y: number; readonly width: number; readonly height: number }
| undefined;
readonly getProcessImagePath: (processId: number) => string;
/** High bit of `GetAsyncKeyState`: whether the virtual key is currently down. */
readonly isKeyDown: (virtualKey: number) => boolean;
readonly attachThreadInput: (
sourceThreadId: number,
targetThreadId: number,
attach: boolean,
) => boolean;
readonly setForegroundWindow: (windowHandle: bigint) => boolean;
}
const WINDOWS_SHELL_HOSTED_WINDOW_CLASSES = new Set(["ApplicationFrameWindow"]);
function nativeWindowHandle(buffer: Buffer): bigint {
if (buffer.length === 8) return buffer.readBigUInt64LE();
if (buffer.length === 4) return BigInt(buffer.readUInt32LE());
throw new Error(`Unsupported Windows window handle size: ${String(buffer.length)} bytes.`);
}
export function activateWindowsForegroundWithApi(
handleBuffer: Buffer,
api: WindowsForegroundApi,
): boolean {
const targetWindow = nativeWindowHandle(handleBuffer);
const foregroundWindow = api.getForegroundWindow();
if (targetWindow === foregroundWindow) return true;
const currentThreadId = api.getCurrentThreadId();
const foregroundThreadId = foregroundWindow === 0n ? 0 : api.getWindowThreadId(foregroundWindow);
const shouldAttach =
currentThreadId !== 0 && foregroundThreadId !== 0 && currentThreadId !== foregroundThreadId;
const attached = shouldAttach && api.attachThreadInput(currentThreadId, foregroundThreadId, true);
try {
return api.setForegroundWindow(targetWindow);
} finally {
if (attached) {
api.attachThreadInput(currentThreadId, foregroundThreadId, false);
}
}
}
export function isWindowsShellHostedForegroundWithApi(api: WindowsForegroundApi): boolean {
const foregroundWindow = api.getForegroundWindow();
return (
foregroundWindow !== 0n &&
WINDOWS_SHELL_HOSTED_WINDOW_CLASSES.has(api.getWindowClassName(foregroundWindow))
);
}
let windowsForegroundApiPromise: Promise<WindowsForegroundApi> | undefined;
const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
export function loadWindowsForegroundApi(): Promise<WindowsForegroundApi> {
windowsForegroundApiPromise ??= import("ffi-rs").then(({ DataType, load, open }) => {
const kernel32 = "t3-kernel32";
const user32 = "t3-user32";
open({ library: kernel32, path: "kernel32.dll" });
open({ library: user32, path: "user32.dll" });
return {
getCurrentThreadId: () =>
load({
library: kernel32,
funcName: "GetCurrentThreadId",
retType: DataType.U32,
paramsType: [],
paramsValue: [],
}),
getForegroundWindow: () =>
load({
library: user32,
funcName: "GetForegroundWindow",
retType: DataType.BigInt,
paramsType: [],
paramsValue: [],
}) as bigint,
getWindowClassName: (windowHandle) => {
const buffer = Buffer.alloc(512);
const length = load({
library: user32,
funcName: "GetClassNameW",
retType: DataType.I32,
paramsType: [DataType.BigInt, DataType.U8Array, DataType.I32],
paramsValue: [windowHandle, buffer, buffer.byteLength / 2],
});
return length > 0 ? buffer.subarray(0, length * 2).toString("utf16le") : "";
},
getWindowThreadId: (windowHandle) =>
load({
library: user32,
funcName: "GetWindowThreadProcessId",
retType: DataType.U32,
paramsType: [DataType.BigInt, DataType.BigInt],
paramsValue: [windowHandle, 0n],
}),
getWindowThreadAndProcessId: (windowHandle) => {
const out = Buffer.alloc(4);
const threadId = load({
library: user32,
funcName: "GetWindowThreadProcessId",
retType: DataType.U32,
paramsType: [DataType.BigInt, DataType.U8Array],
paramsValue: [windowHandle, out],
});
return { threadId, processId: out.readUInt32LE(0) };
},
getWindowText: (windowHandle) => {
const buffer = Buffer.alloc(2 * 1024);
const length = load({
library: user32,
funcName: "GetWindowTextW",
retType: DataType.I32,
paramsType: [DataType.BigInt, DataType.U8Array, DataType.I32],
paramsValue: [windowHandle, buffer, buffer.byteLength / 2],
});
return length > 0 ? buffer.subarray(0, length * 2).toString("utf16le") : "";
},
getWindowRect: (windowHandle) => {
const rect = Buffer.alloc(16);
const ok = load({
library: user32,
funcName: "GetWindowRect",
retType: DataType.Boolean,
paramsType: [DataType.BigInt, DataType.U8Array],
paramsValue: [windowHandle, rect],
});
if (!ok) return undefined;
const left = rect.readInt32LE(0);
const top = rect.readInt32LE(4);
return {
x: left,
y: top,
width: Math.max(0, rect.readInt32LE(8) - left),
height: Math.max(0, rect.readInt32LE(12) - top),
};
},
getProcessImagePath: (processId) => {
const handle = load({
library: kernel32,
funcName: "OpenProcess",
retType: DataType.BigInt,
paramsType: [DataType.U32, DataType.Boolean, DataType.U32],
paramsValue: [PROCESS_QUERY_LIMITED_INFORMATION, false, processId],
}) as bigint;
if (handle === 0n) return "";
try {
const buffer = Buffer.alloc(2 * 32_768);
const size = Buffer.alloc(4);
size.writeUInt32LE(buffer.byteLength / 2, 0);
const ok = load({
library: kernel32,
funcName: "QueryFullProcessImageNameW",
retType: DataType.Boolean,
paramsType: [DataType.BigInt, DataType.U32, DataType.U8Array, DataType.U8Array],
paramsValue: [handle, 0, buffer, size],
});
return ok ? buffer.subarray(0, size.readUInt32LE(0) * 2).toString("utf16le") : "";
} finally {
load({
library: kernel32,
funcName: "CloseHandle",
retType: DataType.Boolean,
paramsType: [DataType.BigInt],
paramsValue: [handle],
});
}
},
isKeyDown: (virtualKey) =>
(load({
library: user32,
funcName: "GetAsyncKeyState",
retType: DataType.I16,
paramsType: [DataType.I32],
paramsValue: [virtualKey],
}) &
0x8000) !==
0,
attachThreadInput: (sourceThreadId, targetThreadId, attach) =>
load({
library: user32,
funcName: "AttachThreadInput",
retType: DataType.Boolean,
paramsType: [DataType.U32, DataType.U32, DataType.Boolean],
paramsValue: [sourceThreadId, targetThreadId, attach],
}),
setForegroundWindow: (windowHandle) =>
load({
library: user32,
funcName: "SetForegroundWindow",
retType: DataType.Boolean,
paramsType: [DataType.BigInt],
paramsValue: [windowHandle],
}),
} satisfies WindowsForegroundApi;
});
return windowsForegroundApiPromise;
}
export async function activateWindowsForeground(handleBuffer: Buffer): Promise<void> {
const api = await loadWindowsForegroundApi();
if (activateWindowsForegroundWithApi(handleBuffer, api)) return;
throw new Error("Windows refused to activate the T3 Code window.");
}
export async function isWindowsShellHostedForeground(): Promise<boolean> {
return isWindowsShellHostedForegroundWithApi(await loadWindowsForegroundApi());
}
@@ -0,0 +1,100 @@
import { assert, beforeEach, it } from "@effect/vitest";
import * as NodeEvents from "node:events";
import { vi } from "vite-plus/test";
const workerConstructorMock = vi.hoisted(() => vi.fn());
vi.mock("node:worker_threads", () => ({
Worker: function Worker(...args: ReadonlyArray<unknown>) {
return workerConstructorMock(...args);
},
}));
import { startWindowsForegroundFocusThread } from "./WindowsForegroundFocusThread.ts";
const makeWorker = () =>
Object.assign(new NodeEvents.EventEmitter(), {
postMessage: vi.fn(),
terminate: vi.fn(async () => 0),
unref: vi.fn(),
});
let worker = makeWorker();
const target = {
windowId: 7,
processId: 42,
title: "T3 Code (Dev)",
bounds: { x: 100, y: 50, width: 1_200, height: 800 },
contentBounds: { x: 108, y: 50, width: 1_184, height: 792 },
};
beforeEach(() => {
worker = makeWorker();
workerConstructorMock.mockReset().mockReturnValue(worker);
});
it("queues focus until the helper is ready", async () => {
const thread = startWindowsForegroundFocusThread("focus.cjs");
const focused = thread.focus(target);
assert.lengthOf(worker.postMessage.mock.calls, 0);
worker.emit("message", "ready");
assert.deepEqual(worker.postMessage.mock.calls[0]?.[0], {
type: "focus",
requestId: 1,
target,
});
worker.emit("message", { type: "result", requestId: 1, focused: true });
assert.isTrue(await focused);
assert.deepEqual(workerConstructorMock.mock.calls, [["focus.cjs"]]);
thread.close();
});
it("fails pending focus when the helper exits", async () => {
const replacement = makeWorker();
workerConstructorMock.mockReturnValueOnce(worker).mockReturnValueOnce(replacement);
const thread = startWindowsForegroundFocusThread("focus.cjs");
const focused = thread.focus(target);
worker.emit("exit", 1);
assert.isFalse(await focused);
assert.lengthOf(workerConstructorMock.mock.calls, 1);
const prepared = thread.prepare(target);
replacement.emit("message", "ready");
replacement.emit("message", { type: "result", requestId: 2, focused: true });
assert.isTrue(await prepared);
assert.lengthOf(workerConstructorMock.mock.calls, 2);
thread.close();
});
it("replaces a timed-out helper before accepting more work", async () => {
vi.useFakeTimers();
const replacement = makeWorker();
workerConstructorMock.mockReturnValueOnce(worker).mockReturnValueOnce(replacement);
const thread = startWindowsForegroundFocusThread("focus.cjs");
try {
worker.emit("message", "ready");
const focused = thread.focus(target);
await vi.advanceTimersByTimeAsync(1_000);
assert.isFalse(await focused);
assert.lengthOf(worker.terminate.mock.calls, 1);
assert.lengthOf(workerConstructorMock.mock.calls, 2);
replacement.emit("message", "ready");
const prepared = thread.prepare(target);
assert.deepEqual(replacement.postMessage.mock.calls[0]?.[0], {
type: "prepare",
requestId: 2,
target,
});
replacement.emit("message", { type: "result", requestId: 2, focused: true });
assert.isTrue(await prepared);
} finally {
thread.close();
vi.useRealTimers();
}
});
@@ -0,0 +1,148 @@
// @effect-diagnostics globalTimers:off -- The helper timeout runs at a worker callback boundary outside any Effect fiber.
// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node worker.
import * as NodeWorkerThreads from "node:worker_threads";
import type * as Electron from "electron";
const FOCUS_TIMEOUT_MS = 1_000;
export type WindowsForegroundFocusTarget = {
readonly windowId: number;
readonly processId: number;
readonly title: string;
readonly bounds: Electron.Rectangle;
readonly contentBounds: Electron.Rectangle;
};
export type WindowsForegroundFocusThread = {
readonly prepare: (target: WindowsForegroundFocusTarget) => Promise<boolean>;
readonly focus: (target: WindowsForegroundFocusTarget) => Promise<boolean>;
readonly close: () => void;
};
type FocusRequest = {
readonly type: "prepare" | "focus";
readonly requestId: number;
readonly target: WindowsForegroundFocusTarget;
};
type FocusResult = {
readonly type: "result";
readonly requestId: number;
readonly focused: boolean;
};
const unavailableThread = (): WindowsForegroundFocusThread => ({
prepare: async () => false,
focus: async () => false,
close: () => undefined,
});
export function startWindowsForegroundFocusThread(
workerPath: string,
): WindowsForegroundFocusThread {
let worker: NodeWorkerThreads.Worker | undefined;
let ready = false;
let closed = false;
let nextRequestId = 1;
const pending = new Map<
number,
{
readonly request: FocusRequest;
readonly resolve: (focused: boolean) => void;
readonly timeout: ReturnType<typeof setTimeout>;
}
>();
const finish = (requestId: number, focused: boolean) => {
const request = pending.get(requestId);
if (!request) return;
pending.delete(requestId);
clearTimeout(request.timeout);
request.resolve(focused);
};
const send = (request: FocusRequest, targetWorker: NodeWorkerThreads.Worker) => {
if (!ready || closed || worker !== targetWorker) return;
try {
// oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
targetWorker.postMessage(request);
} catch {
finish(request.requestId, false);
}
};
const start = (): boolean => {
if (closed) return false;
let nextWorker: NodeWorkerThreads.Worker;
try {
nextWorker = new NodeWorkerThreads.Worker(workerPath);
nextWorker.unref();
} catch {
return false;
}
worker = nextWorker;
ready = false;
const reset = () => {
if (worker !== nextWorker) return;
worker = undefined;
ready = false;
for (const requestId of pending.keys()) finish(requestId, false);
};
nextWorker.on("message", (rawMessage) => {
if (worker !== nextWorker) return;
if (rawMessage === "ready") {
ready = true;
for (const request of pending.values()) send(request.request, nextWorker);
return;
}
const message = rawMessage as FocusResult;
if (message.type === "result") finish(message.requestId, message.focused);
});
nextWorker.once("error", reset);
nextWorker.once("exit", reset);
return true;
};
if (!start()) return unavailableThread();
const restart = (timedOutWorker: NodeWorkerThreads.Worker | undefined) => {
if (!timedOutWorker || worker !== timedOutWorker) return;
worker = undefined;
ready = false;
for (const requestId of pending.keys()) finish(requestId, false);
void timedOutWorker.terminate();
start();
};
const request = (type: FocusRequest["type"], target: WindowsForegroundFocusTarget) =>
new Promise<boolean>((resolve) => {
if (closed || (!worker && !start())) {
resolve(false);
return;
}
const requestId = nextRequestId++;
const focusRequest = { type, requestId, target } satisfies FocusRequest;
const requestWorker = worker!;
const timeout = setTimeout(() => {
finish(requestId, false);
restart(requestWorker);
}, FOCUS_TIMEOUT_MS);
timeout.unref();
pending.set(requestId, { request: focusRequest, resolve, timeout });
send(focusRequest, requestWorker);
});
return {
prepare: (target) => request("prepare", target),
focus: (target) => request("focus", target),
close: () => {
if (closed) return;
closed = true;
const activeWorker = worker;
worker = undefined;
ready = false;
for (const requestId of pending.keys()) finish(requestId, false);
if (activeWorker) void activeWorker.terminate();
},
};
}
@@ -0,0 +1,36 @@
import { assert, beforeEach, it, vi } from "vite-plus/test";
const { byPid, list, on, postMessage } = vi.hoisted(() => ({
byPid: vi.fn(),
list: vi.fn(),
on: vi.fn(),
postMessage: vi.fn(),
}));
vi.mock("node:worker_threads", () => ({ parentPort: { on, postMessage } }));
vi.mock("@crowecawcaw/xa11y", () => ({ App: { byPid, list } }));
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
});
it.each(["lookup", "children"])("falls back to enumeration after a failed %s", async (failure) => {
const error = new Error("Unavailable");
if (failure === "lookup") byPid.mockRejectedValue(error);
else byPid.mockResolvedValue({ children: () => Promise.reject(error) });
const bounds = { x: 0, y: 0, width: 800, height: 600 };
const focus = vi.fn().mockResolvedValue(undefined);
list.mockResolvedValue([{ pid: 42, asElement: () => ({ name: "T3", bounds, focus }) }]);
await import("./WindowsForegroundFocusWorker.ts");
await vi.dynamicImportSettled();
const result = Promise.withResolvers<unknown>();
postMessage.mockImplementation(result.resolve);
on.mock.calls[0]![1]({
type: "focus",
requestId: 1,
target: { windowId: 1, processId: 42, title: "T3", bounds, contentBounds: bounds },
});
assert.deepEqual(await result.promise, { type: "result", requestId: 1, focused: true });
assert.lengthOf(focus.mock.calls, 1);
});
@@ -0,0 +1,99 @@
import * as NodeWorkerThreads from "node:worker_threads";
import type { WindowsForegroundFocusTarget } from "./WindowsForegroundFocusThread.ts";
import type { Element } from "@crowecawcaw/xa11y";
type FocusRequest = {
readonly type: "prepare" | "focus";
readonly requestId: number;
readonly target: WindowsForegroundFocusTarget;
};
function matchesTarget(
element: {
readonly name?: string | null;
readonly bounds: WindowsForegroundFocusTarget["bounds"] | null;
},
target: WindowsForegroundFocusTarget,
): boolean {
if ((element.name ?? "").trim() !== target.title.trim()) return false;
if (!element.bounds) return false;
return [target.bounds, target.contentBounds].some((bounds) =>
(["x", "y", "width", "height"] as const).every(
(key) => Math.abs(element.bounds![key] - bounds[key]) <= 2,
),
);
}
async function findTarget(
App: (typeof import("@crowecawcaw/xa11y"))["App"],
target: WindowsForegroundFocusTarget,
): Promise<Element | undefined> {
const children = await App.byPid(target.processId, { timeout: 0 })
.then((app) => app.children())
.catch(() => []);
return (
children.find((candidate) => matchesTarget(candidate, target)) ??
(await App.list())
.filter((candidate) => candidate.pid === target.processId)
.map((candidate) => candidate.asElement())
.find((candidate) => matchesTarget(candidate, target))
);
}
const cachedElements = new Map<number, Element>();
async function prepareTarget(
App: (typeof import("@crowecawcaw/xa11y"))["App"],
target: WindowsForegroundFocusTarget,
): Promise<boolean> {
const element = await findTarget(App, target);
if (!element) {
cachedElements.delete(target.windowId);
return false;
}
cachedElements.set(target.windowId, element);
return true;
}
async function focusTarget(
App: (typeof import("@crowecawcaw/xa11y"))["App"],
target: WindowsForegroundFocusTarget,
): Promise<boolean> {
let element = cachedElements.get(target.windowId);
if (!element) {
element = await findTarget(App, target);
if (!element) return false;
cachedElements.set(target.windowId, element);
}
try {
await element.focus();
return true;
} catch {
cachedElements.delete(target.windowId);
return false;
}
}
async function start() {
const { App } = await import("@crowecawcaw/xa11y");
const parentPort = NodeWorkerThreads.parentPort;
if (!parentPort) return;
let work = Promise.resolve();
parentPort.on("message", (message: FocusRequest) => {
if (message.type !== "prepare" && message.type !== "focus") return;
work = work.then(async () => {
const focused = await (
message.type === "prepare"
? prepareTarget(App, message.target)
: focusTarget(App, message.target)
).catch(() => false);
// oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
parentPort.postMessage({ type: "result", requestId: message.requestId, focused });
});
});
// oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
parentPort.postMessage("ready");
}
void start();
+30
View File
@@ -50,6 +50,36 @@ describe("DesktopIpc", () => {
}),
);
it.effect("forwards the invoke sender to the method", () =>
Effect.gen(function* () {
let listener: DesktopIpc.DesktopIpcHandleListener | undefined;
const ipc = DesktopIpc.make(
makeIpcMain({
handle: (_channel, registered) => {
listener = registered;
},
}),
);
const sender = { sender: { id: 7 } };
let received: DesktopIpc.DesktopIpcInvokeEvent | undefined;
yield* Effect.scoped(
Effect.gen(function* () {
yield* ipc.handle({
channel: "desktop.test.sender",
handler: (_raw, event) =>
Effect.sync(() => {
received = event;
}),
});
yield* Effect.promise(async () => listener!(sender, undefined));
}),
);
assert.strictEqual(received, sender);
}),
);
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
Effect.gen(function* () {
const cause = new Error("sync unregistration failed");
+9 -7
View File
@@ -4,7 +4,9 @@ import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
export interface DesktopIpcInvokeEvent {}
export interface DesktopIpcInvokeEvent {
readonly sender: { readonly id: number };
}
export interface DesktopIpcSyncEvent {
returnValue: unknown;
@@ -58,7 +60,7 @@ export type DesktopIpcError = typeof DesktopIpcError.Type;
export interface DesktopIpcMethod<E, R> {
readonly channel: string;
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
readonly handler: (raw: unknown, event?: DesktopIpcInvokeEvent) => Effect.Effect<unknown, E, R>;
}
export interface DesktopSyncIpcMethod<E, R> {
@@ -92,11 +94,11 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
Effect.try({
try: () => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
ipcMain.handle(channel, (event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
return yield* handler(raw, event);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
@@ -181,7 +183,7 @@ export interface DesktopIpcMethodRegistration<
ResultDecodingServices,
ResultEncodingServices
>;
readonly handler: (input: Payload) => Effect.Effect<Result, E, R>;
readonly handler: (input: Payload, event?: DesktopIpcInvokeEvent) => Effect.Effect<Result, E, R>;
}
export const makeIpcMethod = <
@@ -217,9 +219,9 @@ export const makeIpcMethod = <
return {
channel: method.channel,
handler: (raw) =>
handler: (raw, event) =>
decode(raw).pipe(
Effect.flatMap(method.handler),
Effect.flatMap((input) => method.handler(input, event)),
Effect.flatMap(encode),
Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
),
@@ -46,6 +46,20 @@ import {
setTheme,
showContextMenu,
} from "./methods/window.ts";
import {
acknowledgeSnapShot,
checkSnapShotShortcut,
dismissSnapShotAnimation,
getSnapShotState,
setupSnapShot,
previewSnapShotConfig,
applySnapShotConfig,
listPendingSnapShots,
readSnapShot,
requestSnapShotPermissions,
setSnapShotAnimationDestination,
setSnapShotShortcutSuppressed,
} from "./methods/snapShot.ts";
import * as PreviewIpc from "./methods/preview.ts";
import * as AppActivationIpc from "./methods/appActivation.ts";
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
@@ -66,6 +80,18 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(getSnapShotState);
yield* ipc.handle(setupSnapShot);
yield* ipc.handle(previewSnapShotConfig);
yield* ipc.handle(applySnapShotConfig);
yield* ipc.handle(requestSnapShotPermissions);
yield* ipc.handle(checkSnapShotShortcut);
yield* ipc.handle(setSnapShotShortcutSuppressed);
yield* ipc.handle(listPendingSnapShots);
yield* ipc.handle(readSnapShot);
yield* ipc.handle(setSnapShotAnimationDestination);
yield* ipc.handle(dismissSnapShotAnimation);
yield* ipc.handle(acknowledgeSnapShot);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
+15
View File
@@ -7,6 +7,7 @@ export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const OPEN_SYSTEM_SETTINGS_CHANNEL = "desktop:open-system-settings";
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event";
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
@@ -26,6 +27,20 @@ export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const SETUP_SNAP_SHOT_CHANNEL = "desktop:setup-snap-shot";
export const PREVIEW_SNAP_SHOT_CONFIG_CHANNEL = "desktop:preview-snap-shot-config";
export const APPLY_SNAP_SHOT_CONFIG_CHANNEL = "desktop:apply-snap-shot-config";
export const REQUEST_SNAP_SHOT_PERMISSIONS_CHANNEL = "desktop:request-snap-shot-permissions";
export const GET_SNAP_SHOT_STATE_CHANNEL = "desktop:get-snap-shot-state";
export const CHECK_SNAP_SHOT_SHORTCUT_CHANNEL = "desktop:check-snap-shot-shortcut";
export const SET_SNAP_SHOT_SHORTCUT_SUPPRESSED_CHANNEL =
"desktop:set-snap-shot-shortcut-suppressed";
export const LIST_PENDING_SNAP_SHOTS_CHANNEL = "desktop:list-pending-snap-shots";
export const READ_SNAP_SHOT_CHANNEL = "desktop:read-snap-shot";
export const SET_SNAP_SHOT_ANIMATION_DESTINATION_CHANNEL =
"desktop:set-snap-shot-animation-destination";
export const DISMISS_SNAP_SHOT_ANIMATION_CHANNEL = "desktop:dismiss-snap-shot-animation";
export const ACKNOWLEDGE_SNAP_SHOT_CHANNEL = "desktop:acknowledge-snap-shot";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
@@ -4,6 +4,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
@@ -23,6 +24,8 @@ export const setClientSettings = DesktopIpc.makeIpcMethod({
result: Schema.Void,
handler: Effect.fn("desktop.ipc.clientSettings.set")(function* (settings) {
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
yield* clientSettings.set(settings);
yield* snapShot.configure(settings);
}),
});
@@ -0,0 +1,358 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts";
import {
checkSnapShotShortcut,
requestSnapShotPermissions,
setupSnapShot,
previewSnapShotConfig,
applySnapShotConfig,
setSnapShotAnimationDestination,
setSnapShotShortcutSuppressed,
snapShotScreenFrame,
snapShotRelativeFrame,
} from "./snapShot.ts";
describe("window capture IPC", () => {
const configPreview = {
id: "12345678-1234-1234-1234-123456789abc",
path: "/config/niri/config.kdl",
resolvedPath: "/config/niri/config.kdl",
before: "binds {}\n",
after: "binds {\n}\n",
shortcut: "Ctrl+Shift+2",
operation: "install" as const,
};
it.effect("requires a trusted renderer for both config read and write approval", () => {
const calls: string[] = [];
return Effect.gen(function* () {
const request = { operation: "install" as const, chooseFile: false };
const untrustedRead = yield* Effect.exit(
previewSnapShotConfig.handler(request, { sender: { id: 8 } }),
);
const untrustedWrite = yield* Effect.exit(
applySnapShotConfig.handler(configPreview.id, { sender: { id: 8 } }),
);
assert(Exit.isFailure(untrustedRead));
assert(Exit.isFailure(untrustedWrite));
assert.deepEqual(calls, []);
yield* previewSnapShotConfig.handler(request, { sender: { id: 7 } });
assert.deepEqual(calls, ["read"]);
yield* applySnapShotConfig.handler(configPreview.id, { sender: { id: 7 } });
assert.deepEqual(calls, ["read", configPreview.id]);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.succeed(ElectronWindow.ElectronWindow, {
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
Layer.succeed(DesktopSnapShot.DesktopSnapShot, {
previewConfig: () =>
Effect.sync(() => {
calls.push("read");
return configPreview;
}),
applyConfig: (id: string) =>
Effect.sync(() => {
calls.push(id);
return { backupPath: null, warning: null };
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
Layer.succeed(
ElectronDialog.ElectronDialog,
{} as ElectronDialog.ElectronDialog["Service"],
),
),
),
);
});
it.effect("cancelling custom file selection reads and writes nothing", () => {
let read = false;
return Effect.gen(function* () {
const preview = yield* previewSnapShotConfig.handler(
{ operation: "install", chooseFile: true },
{ sender: { id: 7 } },
);
assert.isNull(preview);
assert.isFalse(read);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.succeed(ElectronWindow.ElectronWindow, {
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
Layer.succeed(DesktopSnapShot.DesktopSnapShot, {
state: Effect.succeed({
linuxBackend: "niri",
shortcutConfigPath: "/config/niri/config.kdl",
}),
previewConfig: () =>
Effect.sync(() => {
read = true;
return configPreview;
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
Layer.succeed(ElectronDialog.ElectronDialog, {
pickFiles: () => Effect.succeed([]),
} as unknown as ElectronDialog.ElectronDialog["Service"]),
),
),
);
});
it.effect("uses only the file returned by the native custom config picker", () => {
let path: string | undefined;
return Effect.gen(function* () {
yield* previewSnapShotConfig.handler(
{ operation: "install", chooseFile: true },
{ sender: { id: 7 } },
);
assert.equal(path, "/chosen/config.kdl");
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.succeed(ElectronWindow.ElectronWindow, {
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
Layer.succeed(DesktopSnapShot.DesktopSnapShot, {
state: Effect.succeed({ linuxBackend: "niri" }),
previewConfig: (_: unknown, selected: string) =>
Effect.sync(() => {
path = selected;
return configPreview;
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
Layer.succeed(ElectronDialog.ElectronDialog, {
pickFiles: () => Effect.succeed(["/chosen/config.kdl"]),
} as unknown as ElectronDialog.ElectronDialog["Service"]),
),
),
);
});
it("converts renderer viewport coordinates from the content origin using the window zoom", () => {
assert.deepEqual(
snapShotScreenFrame(
{ x: 12, y: 20, width: 208, height: 112 },
{ x: 100, y: 80, width: 1_000, height: 700 },
1.25,
),
{ x: 115, y: 105, width: 260, height: 140 },
);
});
it.effect("forwards a trusted renderer animation destination in screen coordinates", () => {
let received: unknown;
const webContents = { id: 7, getZoomFactor: () => 1.25 };
const layer = Layer.mergeAll(
Layer.succeed(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({
main: Effect.succeed(
Option.some({
getBounds: () => ({ x: 100, y: 80, width: 1_000, height: 700 }),
getContentBounds: () => ({ x: 100, y: 118, width: 1_000, height: 662 }),
webContents,
}),
),
} as ElectronWindow.ElectronWindow["Service"]),
),
Layer.succeed(
DesktopSnapShot.DesktopSnapShot,
DesktopSnapShot.DesktopSnapShot.of({
setAnimationDestination: (id: string, destination: unknown) =>
Effect.sync(() => {
received = { id, destination };
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
),
);
return Effect.gen(function* () {
yield* setSnapShotAnimationDestination.handler(
{
id: "12345678-1234-1234-1234-123456789abc",
viewportFrame: { x: 12, y: 20, width: 208, height: 112 },
backgroundColor: "rgb(20, 20, 20)",
borderColor: "rgba(80, 80, 80, 0.8)",
borderWidth: 1,
cornerRadius: 8,
details: {
appName: "T3 Code",
windowTitle: "Capture animation",
appIconDataUrl: "data:image/png;base64,aWNvbg==",
},
},
{ sender: webContents },
);
assert.deepEqual(received, {
id: "12345678-1234-1234-1234-123456789abc",
destination: {
relativeFrame: { x: 15 / 1000, y: 25 / 662, width: 260 / 1000, height: 140 / 662 },
frame: { x: 115, y: 143, width: 260, height: 140 },
backgroundColor: "rgb(20, 20, 20)",
borderColor: "rgba(80, 80, 80, 0.8)",
borderWidth: 1.25,
cornerRadius: 10,
scaleFactor: 1.25,
details: {
appName: "T3 Code",
windowTitle: "Capture animation",
appIconDataUrl: "data:image/png;base64,aWNvbg==",
},
},
});
}).pipe(Effect.provide(layer));
});
it.effect("forwards the accessibility permission preference from a trusted renderer", () => {
let includeAccessibility: boolean | undefined;
const webContents = { id: 7 };
const layer = Layer.mergeAll(
Layer.succeed(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({
main: Effect.succeed(Option.some({ webContents })),
} as ElectronWindow.ElectronWindow["Service"]),
),
Layer.succeed(
DesktopSnapShot.DesktopSnapShot,
DesktopSnapShot.DesktopSnapShot.of({
requestPermissions: (include: boolean) =>
Effect.sync(() => {
includeAccessibility = include;
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
),
);
return Effect.gen(function* () {
yield* requestSnapShotPermissions.handler(false, { sender: webContents });
assert.isFalse(includeAccessibility);
}).pipe(Effect.provide(layer));
});
it.effect("rejects an untrusted renderer at the IPC boundary", () =>
Effect.gen(function* () {
const exit = yield* Effect.exit(
requestSnapShotPermissions.handler(false, { sender: { id: 8 } }),
);
assert(Exit.isFailure(exit));
const failure = Cause.findErrorOption(exit.cause);
assert(Option.isSome(failure));
const error = failure.value;
assert.equal((error as { readonly _tag: string })._tag, "SnapShotIpcUnauthorizedSenderError");
assert.equal((error as Error).message, "Snapshot request was rejected.");
}).pipe(
Effect.provideService(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
),
Effect.provideService(DesktopSnapShot.DesktopSnapShot, null as never),
),
);
it.effect("allows capture setup only from the trusted main renderer", () => {
const actions: string[] = [];
return Effect.gen(function* () {
yield* setupSnapShot.handler("install-extension", { sender: { id: 7 } });
assert.deepEqual(actions, ["install-extension"]);
const rejected = yield* Effect.exit(
setupSnapShot.handler("enable-extension", { sender: { id: 8 } }),
);
assert(Exit.isFailure(rejected));
assert.deepEqual(actions, ["install-extension"]);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.succeed(ElectronWindow.ElectronWindow, {
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
Layer.succeed(DesktopSnapShot.DesktopSnapShot, {
setup: (action: string) =>
Effect.sync(() => {
actions.push(action);
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
),
),
);
});
it.effect("checks shortcut availability for a trusted renderer", () => {
const layer = Layer.mergeAll(
Layer.succeed(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
),
Layer.succeed(
DesktopSnapShot.DesktopSnapShot,
DesktopSnapShot.DesktopSnapShot.of({
checkShortcut: () => Effect.succeed({ available: true, message: null }),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
),
);
return Effect.gen(function* () {
const result = yield* checkSnapShotShortcut.handler(
{ kind: "both-shift-keys" },
{ sender: { id: 7 } },
);
assert.deepEqual(result, { available: true, message: null });
}).pipe(Effect.provide(layer));
});
it.effect("suppresses the active shortcut for a trusted renderer", () => {
let suppressed = false;
const layer = Layer.mergeAll(
Layer.succeed(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({
main: Effect.succeed(Option.some({ webContents: { id: 7 } })),
} as ElectronWindow.ElectronWindow["Service"]),
),
Layer.succeed(
DesktopSnapShot.DesktopSnapShot,
DesktopSnapShot.DesktopSnapShot.of({
setShortcutSuppressed: (next: boolean) =>
Effect.sync(() => {
suppressed = next;
}),
} as unknown as DesktopSnapShot.DesktopSnapShot["Service"]),
),
);
return Effect.gen(function* () {
yield* setSnapShotShortcutSuppressed.handler(true, { sender: { id: 7 } });
assert.isTrue(suppressed);
}).pipe(Effect.provide(layer));
});
});
it("normalizes Wayland attachment coordinates without trusting Electron's screen origin", () => {
const frame = { x: 100, y: 300, width: 200, height: 100 };
const bounds = { x: 0, y: 0, width: 1000, height: 600 };
assert.deepEqual(snapShotRelativeFrame(frame, bounds, 1.25), {
x: 0.125,
y: 0.625,
width: 0.25,
height: 125 / 600,
});
assert.deepEqual(
snapShotRelativeFrame(frame, { ...bounds, x: -3840, y: 900 }, 1.25),
snapShotRelativeFrame(frame, bounds, 1.25),
);
assert.isUndefined(snapShotRelativeFrame(frame, { ...bounds, width: 0 }, 1));
});
+239
View File
@@ -0,0 +1,239 @@
import {
DesktopPendingSnapShot,
DesktopSnapShot as DesktopSnapShotSchema,
DesktopSnapShotAnimationDestination,
DesktopSnapShotId,
DesktopSnapShotShortcutAvailability,
DesktopSnapShotState,
DesktopSnapShotSetupAction,
SnapShotShortcut,
DesktopCaptureConfigRequest,
DesktopCaptureConfigPreview,
DesktopCaptureConfigApplied,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as Electron from "electron";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
class SnapShotIpcUnauthorizedSenderError extends Schema.TaggedErrorClass<SnapShotIpcUnauthorizedSenderError>()(
"SnapShotIpcUnauthorizedSenderError",
{},
) {
override get message(): string {
return "Snapshot request was rejected.";
}
}
const ensureTrustedSnapShotSender = Effect.fn("desktop.ipc.snapShot.ensureTrustedSender")(
function* (event: DesktopIpc.DesktopIpcInvokeEvent | undefined) {
const main = yield* (yield* ElectronWindow.ElectronWindow).main;
if (
event === undefined ||
Option.isNone(main) ||
main.value.webContents.id !== event.sender.id
) {
return yield* new SnapShotIpcUnauthorizedSenderError();
}
return main.value;
},
);
export function snapShotScreenFrame(
viewportFrame: DesktopSnapShotAnimationDestination["viewportFrame"],
contentBounds: Electron.Rectangle,
zoomFactor: number,
): Electron.Rectangle {
return {
x: contentBounds.x + viewportFrame.x * zoomFactor,
y: contentBounds.y + viewportFrame.y * zoomFactor,
width: viewportFrame.width * zoomFactor,
height: viewportFrame.height * zoomFactor,
};
}
export function snapShotRelativeFrame(
frame: DesktopSnapShotAnimationDestination["viewportFrame"],
bounds: Electron.Rectangle,
zoom: number,
): Electron.Rectangle | undefined {
if (bounds.width <= 0 || bounds.height <= 0) return undefined;
return {
x: (frame.x * zoom) / bounds.width,
y: (frame.y * zoom) / bounds.height,
width: (frame.width * zoom) / bounds.width,
height: (frame.height * zoom) / bounds.height,
};
}
export const getSnapShotState = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_SNAP_SHOT_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopSnapShotState,
handler: Effect.fn("desktop.ipc.snapShot.getState")(function* () {
return yield* (yield* DesktopSnapShot.DesktopSnapShot).state;
}),
});
export const requestSnapShotPermissions = DesktopIpc.makeIpcMethod({
channel: IpcChannels.REQUEST_SNAP_SHOT_PERMISSIONS_CHANNEL,
payload: Schema.Boolean,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.snapShot.requestPermissions")(
function* (includeAccessibility, event) {
yield* ensureTrustedSnapShotSender(event);
yield* (yield* DesktopSnapShot.DesktopSnapShot).requestPermissions(includeAccessibility);
},
),
});
export const setupSnapShot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SETUP_SNAP_SHOT_CHANNEL,
payload: DesktopSnapShotSetupAction,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.snapShot.setup")(function* (action, event) {
yield* ensureTrustedSnapShotSender(event);
yield* (yield* DesktopSnapShot.DesktopSnapShot).setup(action);
}),
});
export const previewSnapShotConfig = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_SNAP_SHOT_CONFIG_CHANNEL,
payload: DesktopCaptureConfigRequest,
result: Schema.NullOr(DesktopCaptureConfigPreview),
handler: Effect.fn("desktop.ipc.snapShot.previewConfig")(function* (request, event) {
const window = yield* ensureTrustedSnapShotSender(event);
const capture = yield* DesktopSnapShot.DesktopSnapShot;
let selectedPath: string | undefined;
if (request.chooseFile) {
const state = yield* capture.state;
const paths = yield* (yield* ElectronDialog.ElectronDialog).pickFiles({
owner: Option.some(window),
defaultPath: Option.fromUndefinedOr(state.shortcutConfigPath),
filters: [
{
name: "Desktop config",
extensions: state.linuxBackend === "niri" ? ["kdl"] : ["conf", "lua"],
},
],
multiple: false,
});
selectedPath = paths[0];
if (!selectedPath) return null;
}
return yield* capture.previewConfig(request, selectedPath);
}),
});
export const applySnapShotConfig = DesktopIpc.makeIpcMethod({
channel: IpcChannels.APPLY_SNAP_SHOT_CONFIG_CHANNEL,
payload: DesktopSnapShotId,
result: DesktopCaptureConfigApplied,
handler: Effect.fn("desktop.ipc.snapShot.applyConfig")(function* (id, event) {
yield* ensureTrustedSnapShotSender(event);
return yield* (yield* DesktopSnapShot.DesktopSnapShot).applyConfig(id);
}),
});
export const checkSnapShotShortcut = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CHECK_SNAP_SHOT_SHORTCUT_CHANNEL,
payload: SnapShotShortcut,
result: DesktopSnapShotShortcutAvailability,
handler: Effect.fn("desktop.ipc.snapShot.checkShortcut")(function* (shortcut, event) {
yield* ensureTrustedSnapShotSender(event);
return yield* (yield* DesktopSnapShot.DesktopSnapShot).checkShortcut(shortcut);
}),
});
export const setSnapShotShortcutSuppressed = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_SNAP_SHOT_SHORTCUT_SUPPRESSED_CHANNEL,
payload: Schema.Boolean,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.snapShot.setShortcutSuppressed")(function* (suppressed, event) {
yield* ensureTrustedSnapShotSender(event);
yield* (yield* DesktopSnapShot.DesktopSnapShot).setShortcutSuppressed(suppressed);
}),
});
export const listPendingSnapShots = DesktopIpc.makeIpcMethod({
channel: IpcChannels.LIST_PENDING_SNAP_SHOTS_CHANNEL,
payload: Schema.Void,
result: Schema.Array(DesktopPendingSnapShot),
handler: Effect.fn("desktop.ipc.snapShot.listPending")(function* (_, event) {
yield* ensureTrustedSnapShotSender(event);
return yield* (yield* DesktopSnapShot.DesktopSnapShot).listPending;
}),
});
export const readSnapShot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.READ_SNAP_SHOT_CHANNEL,
payload: DesktopSnapShotId,
result: DesktopSnapShotSchema,
handler: Effect.fn("desktop.ipc.snapShot.read")(function* (id, event) {
yield* ensureTrustedSnapShotSender(event);
return yield* (yield* DesktopSnapShot.DesktopSnapShot).read(id);
}),
});
export const setSnapShotAnimationDestination = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_SNAP_SHOT_ANIMATION_DESTINATION_CHANNEL,
payload: DesktopSnapShotAnimationDestination,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.snapShot.setAnimationDestination")(
function* (destination, event) {
const window = yield* ensureTrustedSnapShotSender(event);
if (
destination.viewportFrame.width <= 0 ||
destination.viewportFrame.height <= 0 ||
destination.borderWidth < 0 ||
destination.cornerRadius < 0
) {
return;
}
yield* (yield* DesktopSnapShot.DesktopSnapShot).setAnimationDestination(destination.id, {
relativeFrame: snapShotRelativeFrame(
destination.viewportFrame,
window.getContentBounds(),
window.webContents.getZoomFactor(),
),
frame: snapShotScreenFrame(
destination.viewportFrame,
window.getContentBounds(),
window.webContents.getZoomFactor(),
),
backgroundColor: destination.backgroundColor,
borderColor: destination.borderColor,
borderWidth: destination.borderWidth * window.webContents.getZoomFactor(),
cornerRadius: destination.cornerRadius * window.webContents.getZoomFactor(),
scaleFactor: window.webContents.getZoomFactor(),
details: destination.details,
});
},
),
});
export const dismissSnapShotAnimation = DesktopIpc.makeIpcMethod({
channel: IpcChannels.DISMISS_SNAP_SHOT_ANIMATION_CHANNEL,
payload: DesktopSnapShotId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.snapShot.dismissAnimation")(function* (id, event) {
yield* ensureTrustedSnapShotSender(event);
yield* (yield* DesktopSnapShot.DesktopSnapShot).dismissAnimation(id);
}),
});
export const acknowledgeSnapShot = DesktopIpc.makeIpcMethod({
channel: IpcChannels.ACKNOWLEDGE_SNAP_SHOT_CHANNEL,
payload: DesktopSnapShotId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.snapShot.acknowledge")(function* (id, event) {
yield* ensureTrustedSnapShotSender(event);
yield* (yield* DesktopSnapShot.DesktopSnapShot).acknowledge(id);
}),
});
+6
View File
@@ -50,6 +50,7 @@ import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
import * as DesktopSnapShot from "./snapShot/DesktopSnapShot.ts";
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
@@ -163,6 +164,10 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopPreviewLayer),
);
const desktopSnapShotLayer = DesktopSnapShot.layer.pipe(
Layer.provideMerge(desktopWindowLayer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopAppActivationLayer = DesktopAppActivation.layer.pipe(
Layer.provide(desktopWindowLayer),
);
@@ -200,6 +205,7 @@ const desktopApplicationLayer = Layer.mergeAll(
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
Layer.provideMerge(desktopSnapShotLayer),
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopWslBackendLayer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
+47
View File
@@ -3,12 +3,30 @@ import type {
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
DesktopSnapShotEvent,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
const SNAP_SHOT_EVENT_TYPES = new Set([
"requested",
"started",
"ready",
"failed",
"shortcut-changed",
]);
function isSnapShotEvent(value: unknown): value is DesktopSnapShotEvent {
if (typeof value !== "object" || value === null) return false;
const { type, id } = value as { type?: unknown; id?: unknown };
return (
typeof type === "string" &&
SNAP_SHOT_EVENT_TYPES.has(type) &&
(id === undefined || typeof id === "string")
);
}
exposeClerkBridge({ passkeys: true });
// oxlint-disable-next-line t3code/no-global-process-runtime -- Electron exposes the client platform in its sandboxed preload process.
@@ -55,6 +73,24 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
requestSnapShotPermissions: (includeAccessibility) =>
ipcRenderer.invoke(IpcChannels.REQUEST_SNAP_SHOT_PERMISSIONS_CHANNEL, includeAccessibility),
getSnapShotState: () => ipcRenderer.invoke(IpcChannels.GET_SNAP_SHOT_STATE_CHANNEL),
setupSnapShot: (action) => ipcRenderer.invoke(IpcChannels.SETUP_SNAP_SHOT_CHANNEL, action),
previewSnapShotConfig: (request) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_SNAP_SHOT_CONFIG_CHANNEL, request),
applySnapShotConfig: (id) => ipcRenderer.invoke(IpcChannels.APPLY_SNAP_SHOT_CONFIG_CHANNEL, id),
checkSnapShotShortcut: (shortcut) =>
ipcRenderer.invoke(IpcChannels.CHECK_SNAP_SHOT_SHORTCUT_CHANNEL, shortcut),
setSnapShotShortcutSuppressed: (suppressed) =>
ipcRenderer.invoke(IpcChannels.SET_SNAP_SHOT_SHORTCUT_SUPPRESSED_CHANNEL, suppressed),
listPendingSnapShots: () => ipcRenderer.invoke(IpcChannels.LIST_PENDING_SNAP_SHOTS_CHANNEL),
readSnapShot: (id) => ipcRenderer.invoke(IpcChannels.READ_SNAP_SHOT_CHANNEL, id),
setSnapShotAnimationDestination: (destination) =>
ipcRenderer.invoke(IpcChannels.SET_SNAP_SHOT_ANIMATION_DESTINATION_CHANNEL, destination),
dismissSnapShotAnimation: (id) =>
ipcRenderer.invoke(IpcChannels.DISMISS_SNAP_SHOT_ANIMATION_CHANNEL, id),
acknowledgeSnapShot: (id) => ipcRenderer.invoke(IpcChannels.ACKNOWLEDGE_SNAP_SHOT_CHANNEL, id),
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
setConnectionCatalog: (catalog) =>
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
@@ -130,6 +166,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
onSnapShotEvent: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, event: unknown) => {
if (!isSnapShotEvent(event)) return;
listener(event);
};
ipcRenderer.on(IpcChannels.SNAP_SHOT_EVENT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.SNAP_SHOT_EVENT_CHANNEL, wrappedListener);
};
},
onQuitShortcut: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, hint: unknown) => {
if (typeof hint !== "object" || hint === null || !("state" in hint)) return;
+36 -7
View File
@@ -177,6 +177,7 @@ describe("previewWindowOpenAction", () => {
const {
browserWindowConstructor,
clipboardItemConstructor,
createFromPath,
fromId,
getFocusedWebContents,
@@ -184,23 +185,32 @@ const {
showItemInFolder,
webviewSend,
writeFile,
writeImage,
writeClipboard,
} = vi.hoisted(() => ({
browserWindowConstructor: vi.fn(),
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
clipboardItemConstructor: vi.fn(),
createFromPath: vi.fn((): { readonly isEmpty: () => boolean; readonly toPNG: () => Buffer } => ({
isEmpty: () => false,
toPNG: () => Buffer.from("png"),
})),
fromId: vi.fn<(_id?: number) => Electron.WebContents | null>((_id?: number) => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
writeClipboard: vi.fn(async () => undefined),
}));
vi.mock("electron", () => ({
BrowserWindow: browserWindowConstructor,
ClipboardItem: class {
constructor(data: Record<string, unknown>) {
clipboardItemConstructor(data);
}
},
clipboard: {
writeImage,
write: writeClipboard,
},
nativeImage: {
createFromPath,
@@ -535,7 +545,8 @@ describe("PreviewManager", () => {
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
writeImage.mockClear();
clipboardItemConstructor.mockClear();
writeClipboard.mockClear();
createFromPath.mockClear();
webviewSend.mockClear();
});
@@ -3782,7 +3793,10 @@ describe("PreviewManager", () => {
yield* manager.copyArtifactToClipboard(artifactPath);
expect(createFromPath).toHaveBeenCalledWith(artifactPath);
expect(writeImage).toHaveBeenCalledOnce();
expect(clipboardItemConstructor).toHaveBeenCalledWith({
"image/png": expect.any(Blob),
});
expect(writeClipboard).toHaveBeenCalledOnce();
const exit = yield* Effect.exit(
manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"),
);
@@ -3796,7 +3810,10 @@ describe("PreviewManager", () => {
});
expect("cause" in error).toBe(false);
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
createFromPath.mockReturnValueOnce({
isEmpty: () => true,
toPNG: () => Buffer.from("invalid"),
});
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
expect(Exit.isFailure(invalidImageExit)).toBe(true);
if (Exit.isSuccess(invalidImageExit)) return;
@@ -3804,6 +3821,18 @@ describe("PreviewManager", () => {
_tag: "PreviewArtifactImageLoadError",
artifactPath,
});
const writeCause = new Error("clipboard write failed");
writeClipboard.mockRejectedValueOnce(writeCause);
const writeExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
expect(Exit.isFailure(writeExit)).toBe(true);
if (Exit.isSuccess(writeExit)) return;
expect(Option.getOrThrow(Cause.findErrorOption(writeExit.cause))).toMatchObject({
_tag: "PreviewOperationError",
operation: "copyArtifactToClipboard.write",
artifactPath,
cause: writeCause,
});
}),
),
);
+17 -3
View File
@@ -32,7 +32,15 @@ import type {
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { BrowserWindow, type Session, clipboard, nativeImage, shell, webContents } from "electron";
import {
BrowserWindow,
ClipboardItem,
type Session,
clipboard,
nativeImage,
shell,
webContents,
} from "electron";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
@@ -4143,8 +4151,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
if (image.isEmpty()) {
return yield* new PreviewArtifactImageLoadError({ artifactPath: resolvedPath });
}
yield* attempt({ operation: "copyArtifactToClipboard.write", artifactPath: resolvedPath }, () =>
clipboard.writeImage(image),
yield* attemptPromise(
{ operation: "copyArtifactToClipboard.write", artifactPath: resolvedPath },
() =>
clipboard.write([
new ClipboardItem({
"image/png": new Blob([Uint8Array.from(image.toPNG())], { type: "image/png" }),
}),
]),
);
});
@@ -1,6 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import {
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
type ClientSettings,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -13,6 +17,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
const clientSettings: ClientSettings = {
...DEFAULT_CLIENT_SETTINGS,
appearanceContrast: 100,
browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },
browserDefaultZoomFactor: 1.25,
@@ -0,0 +1,129 @@
import { assert, beforeEach, it, vi } from "vite-plus/test";
const { execFileMock, loadWindowsForegroundApiMock } = vi.hoisted(() => ({
execFileMock: vi.fn(),
loadWindowsForegroundApiMock: vi.fn(),
}));
vi.mock("node:child_process", () => ({ execFile: execFileMock }));
vi.mock("../electron/WindowsForeground.ts", () => ({
loadWindowsForegroundApi: loadWindowsForegroundApiMock,
}));
import { activeWindow } from "./ActiveWindow.ts";
beforeEach(() => {
execFileMock.mockReset();
loadWindowsForegroundApiMock.mockReset();
});
function stubMacLookup(stdout: string) {
execFileMock.mockImplementation(
(
_file: string,
_args: ReadonlyArray<string>,
_options: unknown,
callback: (error: Error | null, stdout: string) => void,
) => callback(null, stdout),
);
}
it("parses the frontmost macOS window from the osascript lookup", async () => {
stubMacLookup(
JSON.stringify({
id: 42,
title: "main.ts",
bounds: { x: 10, y: 20, width: 800, height: 600 },
owner: {
name: "Editor",
processId: 123,
path: "/Applications/Editor.app",
bundleId: "com.example.editor",
},
}) + "\n",
);
const window = await activeWindow("darwin");
assert.deepEqual(window, {
platform: "macos",
id: 42,
title: "main.ts",
bounds: { x: 10, y: 20, width: 800, height: 600 },
owner: {
name: "Editor",
processId: 123,
path: "/Applications/Editor.app",
bundleId: "com.example.editor",
},
});
const [file, args] = execFileMock.mock.calls[0]!;
assert.strictEqual(file, "/usr/bin/osascript");
assert.deepEqual(args.slice(0, 3), ["-l", "JavaScript", "-e"]);
assert.lengthOf(loadWindowsForegroundApiMock.mock.calls, 0);
});
it("omits an empty macOS bundle identifier", async () => {
stubMacLookup(
JSON.stringify({
id: 7,
title: "",
bounds: { x: 0, y: 0, width: 1, height: 1 },
owner: { name: "cli", processId: 9, path: "", bundleId: "" },
}),
);
const window = await activeWindow("darwin");
assert.deepEqual(window?.owner, { name: "cli", processId: 9, path: "" });
});
it("resolves undefined when macOS has no frontmost window", async () => {
stubMacLookup("\n");
assert.isUndefined(await activeWindow("darwin"));
});
it("composes the Windows foreground window from Win32 calls", async () => {
const api = {
getForegroundWindow: vi.fn(() => 0x1_f123_4567n),
getWindowRect: vi.fn(() => ({ x: 10, y: 20, width: 800, height: 600 })),
getWindowThreadAndProcessId: vi.fn(() => ({ threadId: 5, processId: 123 })),
getProcessImagePath: vi.fn(() => "C:\\Program Files\\Editor\\editor.exe"),
getWindowText: vi.fn(() => "main.ts - Editor"),
};
loadWindowsForegroundApiMock.mockResolvedValue(api);
const window = await activeWindow("win32");
assert.deepEqual(window, {
platform: "windows",
id: 0x1_f123_4567,
title: "main.ts - Editor",
bounds: { x: 10, y: 20, width: 800, height: 600 },
owner: { name: "editor.exe", processId: 123, path: "C:\\Program Files\\Editor\\editor.exe" },
});
assert.deepEqual(api.getWindowRect.mock.calls, [[0x1_f123_4567n]]);
assert.deepEqual(api.getProcessImagePath.mock.calls, [[123]]);
assert.lengthOf(execFileMock.mock.calls, 0);
});
it("resolves undefined when Windows reports no foreground window", async () => {
const api = {
getForegroundWindow: vi.fn(() => 0n),
getWindowRect: vi.fn(),
getWindowThreadAndProcessId: vi.fn(),
getProcessImagePath: vi.fn(),
getWindowText: vi.fn(),
};
loadWindowsForegroundApiMock.mockResolvedValue(api);
assert.isUndefined(await activeWindow("win32"));
assert.lengthOf(api.getWindowRect.mock.calls, 0);
});
it("resolves undefined on other platforms without querying the OS", async () => {
assert.isUndefined(await activeWindow("linux"));
assert.lengthOf(execFileMock.mock.calls, 0);
assert.lengthOf(loadWindowsForegroundApiMock.mock.calls, 0);
});
+143
View File
@@ -0,0 +1,143 @@
// @effect-diagnostics nodeBuiltinImport:off -- This platform boundary asks the OS for its foreground window with Node.
import * as NodeChildProcess from "node:child_process";
import * as Schema from "effect/Schema";
import { loadWindowsForegroundApi } from "../electron/WindowsForeground.ts";
/**
* The foreground window as the snapshot service needs it. `id` is the
* CGWindowNumber on macOS and the HWND on Windows, which is what the capture
* backends key on.
*/
export type ActiveWindow = {
readonly platform: "macos" | "windows";
readonly id: number;
readonly title: string;
readonly bounds: {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
};
readonly owner: {
readonly name: string;
readonly processId: number;
readonly path: string;
readonly bundleId?: string;
};
};
const MAC_LOOKUP_TIMEOUT_MS = 5_000;
const MacActiveWindow = Schema.Struct({
id: Schema.Number,
title: Schema.String,
bounds: Schema.Struct({
x: Schema.Number,
y: Schema.Number,
width: Schema.Number,
height: Schema.Number,
}),
owner: Schema.Struct({
name: Schema.String,
processId: Schema.Number,
path: Schema.String,
bundleId: Schema.String,
}),
});
const decodeMacActiveWindow = Schema.decodeUnknownSync(Schema.fromJsonString(MacActiveWindow));
// The frontmost app's first on-screen, layer-0 window in front-to-back order is
// the active window. Window titles need Screen Recording, which the snapshot
// service has already requested by the time this runs.
const MAC_LOOKUP_SCRIPT = `
ObjC.import("CoreGraphics");
ObjC.import("AppKit");
function run() {
const app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
if (app.isNil()) return "";
const pid = app.processIdentifier;
const list = $.CGWindowListCopyWindowInfo(
$.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements,
$.kCGNullWindowID,
);
$.CFMakeCollectable(list);
const count = $.CFArrayGetCount(list);
for (let i = 0; i < count; i++) {
const w = ObjC.castRefToObject($.CFArrayGetValueAtIndex(list, i));
if (w.objectForKey("kCGWindowOwnerPID").js !== pid) continue;
if (w.objectForKey("kCGWindowLayer").js !== 0) continue;
const b = ObjC.deepUnwrap(w.objectForKey("kCGWindowBounds"));
return JSON.stringify({
id: w.objectForKey("kCGWindowNumber").js,
title: String(ObjC.unwrap(w.objectForKey("kCGWindowName")) || ""),
bounds: { x: b.X, y: b.Y, width: b.Width, height: b.Height },
owner: {
name: String(app.localizedName.js || ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || ""),
processId: pid,
path: String(app.bundleURL.path.js || ""),
bundleId: String(app.bundleIdentifier.js || ""),
},
});
}
return "";
}`;
function runMacLookup(): Promise<string> {
return new Promise((resolve, reject) => {
NodeChildProcess.execFile(
"/usr/bin/osascript",
["-l", "JavaScript", "-e", MAC_LOOKUP_SCRIPT],
{ timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 64 * 1024 },
(error, stdout) => {
if (error) reject(error);
else resolve(stdout);
},
);
});
}
async function macActiveWindow(): Promise<ActiveWindow | undefined> {
const output = (await runMacLookup()).trim();
if (!output) return undefined;
const window = decodeMacActiveWindow(output);
return {
platform: "macos",
id: window.id,
title: window.title,
bounds: window.bounds,
owner: {
name: window.owner.name,
processId: window.owner.processId,
path: window.owner.path,
...(window.owner.bundleId ? { bundleId: window.owner.bundleId } : {}),
},
};
}
async function windowsActiveWindow(): Promise<ActiveWindow | undefined> {
const api = await loadWindowsForegroundApi();
const handle = api.getForegroundWindow();
if (handle === 0n) return undefined;
const bounds = api.getWindowRect(handle);
if (!bounds) return undefined;
const { processId } = api.getWindowThreadAndProcessId(handle);
const path = processId === 0 ? "" : api.getProcessImagePath(processId);
const name = path.split(/[\\/]/).pop() ?? "";
return {
platform: "windows",
id: Number(handle),
title: api.getWindowText(handle),
bounds,
owner: { name, processId, path },
};
}
/** Resolve the OS foreground window, or `undefined` when there is none. */
export function activeWindow(platform: NodeJS.Platform): Promise<ActiveWindow | undefined> {
if (platform === "darwin") return macActiveWindow();
if (platform === "win32") return windowsActiveWindow();
return Promise.resolve(undefined);
}
@@ -0,0 +1,263 @@
// @effect-diagnostics nodeBuiltinImport:off -- Isolated config fixtures, never the user's desktop.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as NodeOS from "node:os";
import * as NodeChildProcess from "node:child_process";
import * as NodeUtil from "node:util";
import { afterEach, beforeEach, expect, it as test, vi } from "vite-plus/test";
import { CaptureShortcutConfig, niriCaptureConfigPath } from "./CaptureShortcutConfig.ts";
import { captureConfigBinding } from "./captureConfigEdit.ts";
// oxlint-disable-next-line t3code/no-global-process-runtime -- Test collection checks the host before starting these Linux-native filesystem tests.
const it = test.runIf(process.platform === "linux");
let directory: string;
let path: string;
let setup: CaptureShortcutConfig;
const tools = {
validateNiri: vi.fn<(path: string) => Promise<void>>(),
hyprlandBindings:
vi.fn<() => Promise<{ modmask: number; key: string; dispatcher: string; arg: string }[]>>(),
reloadHyprland: vi.fn<() => Promise<void>>(),
};
const appId = "com.t3tools.T3Code";
const install = { operation: "install", chooseFile: false } as const;
const target = () => ({ desktop: "niri" as const, path, appId });
beforeEach(async () => {
directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-capture-config-"));
path = NodePath.join(directory, "config.kdl");
await NodeFSP.writeFile(path, "binds {\n Mod+Q { quit; }\n}\n", { mode: 0o640 });
tools.validateNiri.mockReset().mockResolvedValue(undefined);
tools.hyprlandBindings.mockReset().mockResolvedValue([]);
tools.reloadHyprland.mockReset().mockResolvedValue(undefined);
setup = new CaptureShortcutConfig(tools);
});
afterEach(async () => {
await NodeFSP.rm(directory, { recursive: true, force: true });
});
it("reads without writing, then applies only the approved diff with a backup", async () => {
const before = await NodeFSP.readFile(path, "utf8");
const preview = await setup.preview(target(), install);
expect(await NodeFSP.readFile(path, "utf8")).toBe(before);
expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
expect(tools.validateNiri).not.toHaveBeenCalled();
expect(preview.before).toBe(before);
expect(preview.after).toContain("Ctrl+Shift+2");
const applied = await setup.apply(preview.id, "niri");
expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.after);
expect(await NodeFSP.readFile(applied.backupPath!, "utf8")).toBe(before);
expect((await NodeFSP.stat(path)).mode & 0o777).toBe(0o640);
expect(tools.validateNiri).toHaveBeenCalledOnce();
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("expired");
});
it("refuses apply without a preview or for the wrong desktop", async () => {
await expect(setup.apply("invented", "niri")).rejects.toThrow("expired");
const preview = await setup.preview(target(), install);
await expect(setup.apply(preview.id, "hyprland")).rejects.toThrow("expired");
expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before);
});
it("rechecks Hyprland conflicts before writing", async () => {
const hypr = {
...target(),
desktop: "hyprland" as const,
path: NodePath.join(directory, "hyprland.conf"),
};
await NodeFSP.writeFile(hypr.path, "# unchanged\n");
const preview = await setup.preview(hypr, install);
tools.hyprlandBindings.mockResolvedValue([
{ modmask: 5, key: "2", dispatcher: "exec", arg: "kitty" },
]);
await expect(setup.apply(preview.id, "hyprland")).rejects.toThrow("already used");
expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(preview.before);
});
it("notices an optional include created while the diff is open", async () => {
await NodeFSP.appendFile(path, 'include optional=true "later.kdl"\n');
const preview = await setup.preview(target(), install);
await NodeFSP.writeFile(
NodePath.join(directory, "later.kdl"),
"binds {\n Ctrl+Shift+2 { quit; }\n}\n",
);
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before);
});
it("invalidates an earlier proposal when another config is opened", async () => {
const first = await setup.preview(target(), install);
await setup.preview(target(), { ...install, shortcut: "Ctrl+Alt+Y" });
await expect(setup.apply(first.id, "niri")).rejects.toThrow("expired");
});
it("does not overwrite edits made after preview", async () => {
const preview = await setup.preview(target(), install);
await NodeFSP.appendFile(path, "// edited elsewhere\n");
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before + "// edited elsewhere\n");
expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
});
it("rechecks after validation and cleans the staged file on concurrent edits", async () => {
const preview = await setup.preview(target(), install);
tools.validateNiri.mockImplementation(async () => {
await NodeFSP.appendFile(path, "// keep this\n");
});
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
expect(await NodeFSP.readFile(path, "utf8")).toContain("keep this");
});
it("preserves symlink-managed dotfiles and identifies their actual target", async () => {
const link = NodePath.join(directory, "linked.kdl");
await NodeFSP.symlink(path, link);
const preview = await setup.preview({ ...target(), path: link }, install);
expect(preview.path).toBe(link);
expect(preview.resolvedPath).toBe(path);
await setup.apply(preview.id, "niri");
expect((await NodeFSP.lstat(link)).isSymbolicLink()).toBe(true);
expect(await NodeFSP.readFile(link, "utf8")).toBe(preview.after);
});
it("refuses a symlink retargeted since preview", async () => {
const link = NodePath.join(directory, "linked.kdl");
const other = NodePath.join(directory, "other.kdl");
await NodeFSP.writeFile(other, "binds {}\n");
await NodeFSP.symlink(path, link);
const preview = await setup.preview({ ...target(), path: link }, install);
await NodeFSP.unlink(link);
await NodeFSP.symlink(other, link);
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
expect(await NodeFSP.readFile(other, "utf8")).toBe("binds {}\n");
});
it("validates symlinked configs from their original directory so relative includes stay valid", async () => {
const active = NodePath.join(directory, "active");
await NodeFSP.mkdir(active);
const link = NodePath.join(active, "config.kdl");
await NodeFSP.symlink(path, link);
await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
await NodeFSP.writeFile(NodePath.join(active, "keys.kdl"), "binds {}\n");
tools.validateNiri.mockImplementation(async (file) => {
expect(NodePath.dirname(file)).toBe(active);
expect(await NodeFSP.readFile(file, "utf8")).toContain("Ctrl+Shift+2");
expect(await NodeFSP.readFile(NodePath.join(NodePath.dirname(file), "keys.kdl"), "utf8")).toBe(
"binds {}\n",
);
});
const preview = await setup.preview({ ...target(), path: link }, install);
await setup.apply(preview.id, "niri");
expect((await NodeFSP.readdir(active)).sort()).toEqual(["config.kdl", "keys.kdl"]);
expect((await NodeFSP.lstat(link)).isSymbolicLink()).toBe(true);
});
it("does not apply invalid Niri configs", async () => {
const preview = await setup.preview(target(), install);
tools.validateNiri.mockRejectedValue(new Error("Invalid config"));
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("Invalid config");
expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before);
expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
});
it("leaves already configured files unchanged, without creating a backup", async () => {
await NodeFSP.writeFile(path, `binds { ${captureConfigBinding("niri", appId, "Ctrl+Alt+Y")} }`);
const preview = await setup.preview(target(), install);
expect(preview.after).toBe(preview.before);
expect(preview.shortcut).toBe("Ctrl+Alt+Y");
expect(await setup.apply(preview.id, "niri")).toEqual({ backupPath: null, warning: null });
expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
});
it("detects conflicts in included Niri configs without changing either file", async () => {
await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
await NodeFSP.writeFile(NodePath.join(directory, "keys.kdl"), "binds { Shift+Ctrl+2 { quit; } }");
await expect(setup.preview(target(), install)).rejects.toThrow("already used");
expect((await NodeFSP.readdir(directory)).sort()).toEqual(["config.kdl", "keys.kdl"]);
});
it("detects included config changes before applying", async () => {
await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
const included = NodePath.join(directory, "keys.kdl");
await NodeFSP.writeFile(included, "binds { Ctrl+Alt+Q { quit; } }");
const preview = await setup.preview(target(), install);
await NodeFSP.writeFile(included, "binds { Ctrl+Shift+2 { quit; } }");
await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
});
it("rejects a conflict from another Hyprland config or dynamic Lua bind", async () => {
const hypr = {
...target(),
desktop: "hyprland" as const,
path: NodePath.join(directory, "bindings.lua"),
};
await NodeFSP.writeFile(hypr.path, "-- user bindings\n");
tools.hyprlandBindings.mockResolvedValue([
{ modmask: 5, key: "2", dispatcher: "exec", arg: "kitty" },
]);
await expect(setup.preview(hypr, install)).rejects.toThrow("already used");
expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe("-- user bindings\n");
});
it("reloads Hyprland after apply, but not after read", async () => {
const hypr = {
...target(),
desktop: "hyprland" as const,
path: NodePath.join(directory, "hyprland.conf"),
};
await NodeFSP.writeFile(hypr.path, "# preferences\n");
const preview = await setup.preview(hypr, install);
expect(tools.reloadHyprland).not.toHaveBeenCalled();
await setup.apply(preview.id, "hyprland");
expect(tools.reloadHyprland).toHaveBeenCalledOnce();
});
it("reports reload failure separately from a successfully saved config", async () => {
const hypr = {
...target(),
desktop: "hyprland" as const,
path: NodePath.join(directory, "hyprland.conf"),
};
await NodeFSP.writeFile(hypr.path, "# preferences\n");
const preview = await setup.preview(hypr, install);
tools.reloadHyprland.mockRejectedValue(new Error("Compositor stopped"));
const result = await setup.apply(preview.id, "hyprland");
expect(result.warning).toContain("Config saved");
expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(preview.after);
});
it("does not edit Omarchy's shipped defaults", async () => {
const defaults = NodePath.join(directory, "omarchy", "default", "hypr");
await NodeFSP.mkdir(defaults, { recursive: true });
const file = NodePath.join(defaults, "bindings.conf");
await NodeFSP.writeFile(file, "# defaults\n");
await expect(
setup.preview({ ...target(), desktop: "hyprland", path: file }, install),
).rejects.toThrow("not system or Omarchy");
});
it("honors NIRI_CONFIG and XDG_CONFIG_HOME", () => {
expect(
niriCaptureConfigPath(
{ NIRI_CONFIG: "/custom/test.kdl", XDG_CONFIG_HOME: "/config" },
"/home/test",
),
).toBe("/custom/test.kdl");
expect(niriCaptureConfigPath({ XDG_CONFIG_HOME: "/config" }, "/home/test")).toBe(
"/config/niri/config.kdl",
);
expect(niriCaptureConfigPath({}, "/home/test")).toBe("/home/test/.config/niri/config.kdl");
});
it("preserves a UTF-8 BOM through preview and apply", async () => {
await NodeFSP.writeFile(path, "\uFEFFbinds {}\r\n");
const preview = await setup.preview(target(), install);
await setup.apply(preview.id, "niri");
expect((await NodeFSP.readFile(path)).subarray(0, 3)).toEqual(Buffer.from([0xef, 0xbb, 0xbf]));
});
it("the installed Niri parser accepts the generated edit and its relative includes", async (context) => {
try {
await NodeUtil.promisify(NodeChildProcess.execFile)("niri", ["--version"]);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
context.skip();
return;
}
throw error;
}
// No compositor is launched: validate only parses the temporary fixture.
await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
await NodeFSP.writeFile(
NodePath.join(directory, "keys.kdl"),
"binds {\n Ctrl+Alt+Q { quit; }\n}\n",
);
const checked = new CaptureShortcutConfig({
...tools,
validateNiri: async (file) => {
await NodeUtil.promisify(NodeChildProcess.execFile)("niri", ["validate", "--config", file]);
},
});
const preview = await checked.preview(target(), install);
await checked.apply(preview.id, "niri");
expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.after);
});
@@ -0,0 +1,303 @@
// @effect-diagnostics nodeBuiltinImport:off -- Native, consent-gated compositor config I/O.
import * as NodeFSP from "node:fs/promises";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeOS from "node:os";
import * as NodeCrypto from "node:crypto";
import * as NodeChildProcess from "node:child_process";
import * as NodeUtil from "node:util";
import * as Schema from "effect/Schema";
import type {
DesktopCaptureConfigApplied,
DesktopCaptureConfigPreview,
DesktopCaptureConfigRequest,
} from "@t3tools/contracts";
import {
captureConfigKeys,
editCaptureConfig,
niriConfigConflict,
niriConfigIncludes,
type CaptureConfigFormat,
} from "./captureConfigEdit.ts";
const execute = (file: string, args: string[], options: { timeout: number; maxBuffer: number }) =>
NodeUtil.promisify(NodeChildProcess.execFile)(file, args, options);
const MAX_BYTES = 1024 * 1024;
const MAX_FILES = 64;
type Target = { desktop: "niri" | "hyprland"; path: string; appId: string };
type Snapshot = Awaited<ReturnType<typeof readSnapshot>>;
const decodeHyprlandBindings = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Array(
Schema.Struct({
modmask: Schema.Number,
key: Schema.String,
dispatcher: Schema.String,
arg: Schema.String,
}),
),
),
);
export function niriCaptureConfigPath(env = process.env, home = NodeOS.homedir()) {
return (
env.NIRI_CONFIG ||
NodePath.join(env.XDG_CONFIG_HOME || NodePath.join(home, ".config"), "niri", "config.kdl")
);
}
async function readSnapshot(path: string) {
const resolvedPath = await NodeFSP.realpath(path);
const file = await NodeFSP.open(
resolvedPath,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK | NodeFS.constants.O_NOFOLLOW,
);
try {
const stat = await file.stat();
if (!stat.isFile() || stat.size > MAX_BYTES)
throw new Error("Choose a config file smaller than 1 MB.");
const bytes = await file.readFile();
if (bytes.length > MAX_BYTES) throw new Error("Choose a config file smaller than 1 MB.");
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
if (text.includes("\0")) throw new Error("Choose a text config file.");
return { path, resolvedPath, text, bytes, stat };
} finally {
await file.close();
}
}
const defaultTools = {
validateNiri: async (path: string) => {
try {
await execute("niri", ["validate", "--config", path], {
timeout: 5000,
maxBuffer: 64 * 1024,
});
} catch {
throw new Error(
"Niri couldn't validate the proposed config. Nothing was changed. Check your config in Advanced.",
);
}
},
hyprlandBindings: async () =>
decodeHyprlandBindings(
(await execute("hyprctl", ["-j", "binds"], { timeout: 5000, maxBuffer: MAX_BYTES })).stdout,
),
reloadHyprland: async () => {
await execute("hyprctl", ["reload"], { timeout: 5000, maxBuffer: 64 * 1024 });
const errors = await execute("hyprctl", ["configerrors"], {
timeout: 5000,
maxBuffer: 64 * 1024,
});
if (errors.stdout.trim()) throw new Error("Hyprland reported config errors.");
},
};
/** The renderer can apply only the exact proposal retained by the desktop process. */
export class CaptureShortcutConfig {
private pending:
| { preview: DesktopCaptureConfigPreview; target: Target; files: Snapshot[]; missing: string[] }
| undefined;
private applying = false;
private readonly tools: typeof defaultTools;
constructor(tools = defaultTools) {
this.tools = tools;
}
private async checkHyprlandKeys(appId: string, shortcut: string) {
const keys = captureConfigKeys(shortcut);
const bindings = await this.tools.hyprlandBindings().catch(() => {
throw new Error(
"Couldn't check Hyprland's current shortcuts. Try again from your Hyprland session.",
);
});
if (
bindings.some(
(binding) =>
binding.modmask === keys.mask &&
binding.key.toUpperCase() === keys.key &&
!(binding.dispatcher === "global" && binding.arg === `${appId}:capture-window`),
)
)
throw new Error(`${keys.label} is already used by Hyprland. Choose another shortcut.`);
}
async preview(
target: Target,
request: DesktopCaptureConfigRequest,
): Promise<DesktopCaptureConfigPreview> {
if (this.applying) throw new Error("Wait for the current config change to finish.");
this.pending = undefined;
const root = await readSnapshot(target.path).catch(() => {
throw new Error("Couldn't read your settings file. Choose a different file in Advanced.");
});
if (root.stat.uid !== process.getuid?.() || /\/omarchy\/default\//.test(root.resolvedPath))
throw new Error("Choose your own config, not system or Omarchy defaults.");
const format: CaptureConfigFormat =
target.desktop === "niri"
? "niri"
: target.path.endsWith(".lua")
? "hyprland-lua"
: "hyprland";
if (
!target.path.endsWith(
format === "niri" ? ".kdl" : format === "hyprland-lua" ? ".lua" : ".conf",
)
)
throw new Error("Choose a .kdl Niri config or a .conf/.lua Hyprland config.");
const edit = editCaptureConfig(
root.text,
format,
target.appId,
request.operation,
request.shortcut,
);
const files = [root];
const missing: string[] = [];
if (target.desktop === "niri") {
const visit = async (file: Snapshot, depth: number) => {
if (
depth > 10 ||
files.length > MAX_FILES ||
files.reduce((size, item) => size + item.bytes.length, 0) > MAX_BYTES
)
throw new Error("This config has too many included files. Use manual setup in Advanced.");
for (const include of niriConfigIncludes(file.text)) {
if (include.path.includes("$") || /[*?[\]]/.test(include.path))
throw new Error("This config uses a dynamic include. Use manual setup in Advanced.");
const path = include.path.startsWith("~/")
? NodePath.join(NodeOS.homedir(), include.path.slice(2))
: NodePath.resolve(NodePath.dirname(file.path), include.path);
let child: Snapshot;
try {
child = await readSnapshot(path);
} catch (error) {
if (include.optional && (error as NodeJS.ErrnoException).code === "ENOENT") {
missing.push(path);
continue;
}
throw new Error(
"Couldn't read an included Niri config. Check its location in Advanced.",
{ cause: error },
);
}
if (files.some((item) => item.resolvedPath === child.resolvedPath)) continue;
files.push(child);
if (
request.operation === "install" &&
niriConfigConflict(child.text, target.appId, edit.shortcut)
)
throw new Error(
`${edit.shortcut} is already used in ${child.path}. Choose another shortcut.`,
);
await visit(child, depth + 1);
}
};
await visit(root, 0);
} else if (request.operation === "install") {
await this.checkHyprlandKeys(target.appId, edit.shortcut);
}
const preview = {
id: NodeCrypto.randomUUID(),
path: root.path,
resolvedPath: root.resolvedPath,
before: root.text,
after: edit.after,
shortcut: edit.shortcut,
operation: request.operation,
};
this.pending = { preview, target, files, missing };
return preview;
}
async apply(id: string, desktop: Target["desktop"]): Promise<DesktopCaptureConfigApplied> {
const pending = this.pending;
if (
this.applying ||
!pending ||
pending.preview.id !== id ||
pending.target.desktop !== desktop
)
throw new Error("This preview expired. Review changes again before saving.");
this.pending = undefined;
this.applying = true;
const { preview, files } = pending;
const root = files[0]!;
const directory = NodePath.dirname(root.resolvedPath);
const temporary = NodePath.join(directory, `.t3-capture-${NodeCrypto.randomUUID()}.tmp`);
let staged = false;
try {
const unchanged = async () => {
for (const path of pending.missing) {
if (
await NodeFSP.lstat(path).then(
() => true,
(error: NodeJS.ErrnoException) => error.code !== "ENOENT",
)
)
throw new Error(
"Your config changed since this preview. Review changes again before saving.",
);
}
for (const original of files) {
const current = await readSnapshot(original.path).catch(() => undefined);
if (
!current ||
current.resolvedPath !== original.resolvedPath ||
current.stat.ino !== original.stat.ino ||
current.stat.mode !== original.stat.mode ||
!current.bytes.equals(original.bytes)
)
throw new Error(
"Your config changed since this preview. Nothing was saved. Review changes again before saving.",
);
}
};
await unchanged();
if (desktop === "hyprland" && preview.operation === "install")
await this.checkHyprlandKeys(pending.target.appId, preview.shortcut);
if (preview.before === preview.after) return { backupPath: null, warning: null };
await NodeFSP.writeFile(temporary, preview.after, {
flag: "wx",
mode: root.stat.mode & 0o777,
});
staged = true;
await NodeFSP.chmod(temporary, root.stat.mode & 0o777);
if (desktop === "niri") {
// Niri resolves includes against the selected path, not a dotfile symlink's target.
const validationPath = NodePath.join(
NodePath.dirname(root.path),
NodePath.basename(temporary),
);
if (NodePath.resolve(validationPath) === NodePath.resolve(temporary)) {
await this.tools.validateNiri(temporary);
} else {
await NodeFSP.symlink(temporary, validationPath);
try {
await this.tools.validateNiri(validationPath);
} finally {
await NodeFSP.unlink(validationPath);
}
}
}
await unchanged();
const backupPath = `${root.resolvedPath}.t3-capture-backup-${NodeCrypto.randomUUID()}`;
await NodeFSP.writeFile(backupPath, root.bytes, { flag: "wx", mode: 0o600 });
await NodeFSP.rename(temporary, root.resolvedPath);
staged = false;
let warning: string | null = null;
if (desktop === "hyprland") {
try {
await this.tools.reloadHyprland();
} catch {
warning =
"Config saved, but Hyprland couldn't reload it cleanly. Check hyprctl configerrors, then run hyprctl reload.";
}
}
return { backupPath, warning };
} finally {
if (staged) await NodeFSP.unlink(temporary).catch(() => undefined);
this.applying = false;
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,61 @@
// @effect-diagnostics globalTimers:off -- The child-process shutdown watchdog runs at a worker callback boundary outside any Effect fiber.
// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node child process for global shortcut capture.
import * as NodeChildProcess from "node:child_process";
import type { SnapShotModifier } from "@t3tools/contracts";
export function startGlobalShiftShortcutProcess(
workerPath: string,
modifier: SnapShotModifier,
onTrigger: () => void,
onFailure: (error: Error) => void,
): Promise<() => void> {
const worker = NodeChildProcess.fork(workerPath, [modifier], {
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
execArgv: [],
stdio: ["ignore", "ignore", "inherit", "ipc"],
});
return new Promise((resolve, reject) => {
let settled = false;
let stopped = false;
const stop = () => {
if (stopped) return;
stopped = true;
worker.kill();
const forceKill = setTimeout(() => worker.kill("SIGKILL"), 1_000);
forceKill.unref?.();
worker.once("exit", () => clearTimeout(forceKill));
};
const fail = (error: Error) => {
if (stopped) return;
if (settled) {
stop();
onFailure(error);
return;
}
settled = true;
stop();
reject(error);
};
worker.on("message", (message) => {
if (message === "ready" && !settled) {
settled = true;
resolve(stop);
return;
}
if (message !== "trigger" || !settled || stopped) return;
try {
onTrigger();
} catch {}
});
worker.once("error", (error) => {
fail(error);
});
worker.once("exit", (code) => {
fail(new Error(`Snapshot shortcut helper exited with code ${code}`));
});
});
}
@@ -0,0 +1,39 @@
// @effect-diagnostics globalTimers:off -- A plain Node child; the poll runs outside any Effect fiber.
// Windows modifier-pair listener. Runs in a forked Node-mode child so a stuck or
// crashed FFI call cannot take the main process with it. Mirrors the macOS
// poller: sample both physical keys at 20 Hz, fire on the rising edge.
import { SNAP_SHOT_MODIFIERS, type SnapShotModifier } from "@t3tools/contracts";
import { loadWindowsForegroundApi } from "../electron/WindowsForeground.ts";
import { WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS } from "./snapShot.ts";
const POLL_INTERVAL_MS = 50;
const requested = process.argv[2];
if (!(SNAP_SHOT_MODIFIERS as readonly string[]).includes(requested ?? "")) {
process.exit(1);
}
const [left, right] = WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS[requested as SnapShotModifier];
async function poll() {
const api = await loadWindowsForegroundApi();
let active = false;
process.send?.("ready");
const timer = setInterval(() => {
const pressed = api.isKeyDown(left) && api.isKeyDown(right);
if (pressed && !active) {
try {
process.send?.("trigger");
} catch {}
}
active = pressed;
}, POLL_INTERVAL_MS);
const shutdown = () => {
clearInterval(timer);
process.exit(0);
};
process.once("disconnect", shutdown);
process.once("SIGTERM", shutdown);
}
void poll().catch(() => process.exit(1));
@@ -0,0 +1,193 @@
// @effect-diagnostics nodeBuiltinImport:off -- Native extension installation uses isolated filesystem fixtures.
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeEvents from "node:events";
import type { Message, MessageBus } from "dbus-next";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
import {
GnomeCaptureSetup,
installGnomeCaptureBundle,
isGnomeCaptureSession,
} from "./GnomeCaptureSetup.ts";
import { GNOME_CAPTURE_FILES, GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts";
let dataHome: string;
const bundle = NodePath.resolve(import.meta.dirname, "../../gnome-extension");
const installedPath = () => NodePath.join(dataHome, "gnome-shell/extensions", GNOME_CAPTURE_UUID);
beforeEach(async () => {
dataHome = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-gnome-setup-test-"));
});
afterEach(async () => {
await NodeFSP.rm(dataHome, { recursive: true, force: true });
});
function fixture(
options: {
state?: number;
version?: number;
shell?: string;
enabled?: boolean;
accepted?: boolean;
error?: string;
} = {},
) {
const call = vi.fn(async (message: Message) => ({
body: [
message.member === "GetAll"
? {
ShellVersion: { value: options.shell ?? "50.0" },
UserExtensionsEnabled: { value: options.enabled ?? true },
}
: message.member === "GetExtensionInfo"
? {
...(options.state === undefined ? {} : { state: { value: options.state } }),
...(options.version === undefined ? {} : { version: { value: options.version } }),
error: { value: options.error ?? "" },
}
: (options.accepted ?? true),
],
}));
const disconnect = vi.fn();
const bus = Object.assign(new NodeEvents.EventEmitter(), { call, disconnect });
return {
setup: new GnomeCaptureSetup({ bundle, dataHome }, bus as unknown as MessageBus),
call,
disconnect,
bus,
};
}
it("installs exactly the bundled payload offline and leaves other extensions alone", async () => {
const other = NodePath.join(dataHome, "gnome-shell/extensions/other@example");
await NodeFSP.mkdir(other, { recursive: true });
await NodeFSP.writeFile(NodePath.join(other, "keep.txt"), "keep");
await installGnomeCaptureBundle({ bundle, dataHome });
expect((await NodeFSP.readdir(installedPath())).sort()).toEqual([...GNOME_CAPTURE_FILES].sort());
for (const file of GNOME_CAPTURE_FILES) {
expect(await NodeFSP.readFile(NodePath.join(installedPath(), file))).toEqual(
await NodeFSP.readFile(NodePath.join(bundle, file)),
);
}
expect(await NodeFSP.readFile(NodePath.join(other, "keep.txt"), "utf8")).toBe("keep");
});
it("preserves the replaced extension as a recoverable backup", async () => {
await installGnomeCaptureBundle({ bundle, dataHome });
await NodeFSP.writeFile(NodePath.join(installedPath(), "custom.txt"), "local change");
await installGnomeCaptureBundle({ bundle, dataHome });
const backups = NodePath.join(dataHome, "t3code/extension-backups");
const [backup] = await NodeFSP.readdir(backups);
expect(
await NodeFSP.readFile(
NodePath.join(backups, backup!, GNOME_CAPTURE_UUID, "custom.txt"),
"utf8",
),
).toBe("local change");
});
it("does not damage an installed extension if a bundled file is missing", async () => {
await installGnomeCaptureBundle({ bundle, dataHome });
const incomplete = NodePath.join(dataHome, "incomplete");
await NodeFSP.mkdir(incomplete);
await NodeFSP.copyFile(
NodePath.join(bundle, "metadata.json"),
NodePath.join(incomplete, "metadata.json"),
);
await expect(installGnomeCaptureBundle({ bundle: incomplete, dataHome })).rejects.toThrow();
expect(await NodeFSP.readFile(NodePath.join(installedPath(), "extension.js"))).toEqual(
await NodeFSP.readFile(NodePath.join(bundle, "extension.js")),
);
expect(await NodeFSP.readdir(NodePath.dirname(installedPath()))).toEqual([GNOME_CAPTURE_UUID]);
});
it("refuses to replace symlinks or downgrade a newer extension", async () => {
await NodeFSP.mkdir(NodePath.dirname(installedPath()), { recursive: true });
await NodeFSP.symlink(bundle, installedPath());
await expect(installGnomeCaptureBundle({ bundle, dataHome })).rejects.toThrow(
"regular directory",
);
await NodeFSP.unlink(installedPath());
await installGnomeCaptureBundle({ bundle, dataHome });
await NodeFSP.writeFile(
NodePath.join(installedPath(), "metadata.json"),
JSON.stringify({ uuid: GNOME_CAPTURE_UUID, version: 99, "shell-version": ["50"] }),
);
await expect(installGnomeCaptureBundle({ bundle, dataHome })).rejects.toThrow("newer extension");
});
it.each([
[{}, "not-installed"],
[{ state: 2, version: 2 }, "disabled"],
[{ state: 1, version: 2 }, "enabled"],
[{ state: 1, version: 1 }, "update-required"],
[{ state: 2, version: 2, enabled: false }, "extensions-disabled"],
[{ state: 3, version: 2, error: "Load failed" }, "error"],
[{ shell: "51.0" }, "unsupported"],
] as const)("reports GNOME setup state %j", async (options, status) => {
const { setup, call } = fixture(options);
expect((await setup.state()).status).toBe(status);
expect(call.mock.calls.map(([message]) => message.member).sort()).toEqual([
"GetAll",
"GetExtensionInfo",
]);
setup.close();
});
it("requires login for local installs and updates until the new version is loaded", async () => {
await installGnomeCaptureBundle({ bundle, dataHome });
for (const options of [{}, { state: 1, version: 1 }]) {
const { setup } = fixture(options);
expect((await setup.state()).status).toBe("restart-required");
setup.close();
}
const { setup } = fixture({ state: 2, version: 2 });
expect((await setup.state()).status).toBe("disabled");
setup.close();
});
it("installs only on explicit action without invoking remote installation", async () => {
const { setup, call } = fixture();
await setup.perform("install-extension");
expect(await NodeFSP.readdir(installedPath())).toHaveLength(GNOME_CAPTURE_FILES.length);
expect(
call.mock.calls.every(([message]) => ["GetAll", "GetExtensionInfo"].includes(message.member)),
).toBe(true);
setup.close();
});
it("enables and disables only the capture UUID", async () => {
const { setup, call } = fixture({ state: 2, version: 2 });
await setup.perform("enable-extension");
await setup.perform("disable-extension");
for (const member of ["EnableExtension", "DisableExtension"]) {
expect(call.mock.calls.find(([message]) => message.member === member)?.[0]).toMatchObject({
destination: "org.gnome.Shell",
path: "/org/gnome/Shell",
signature: "s",
body: [GNOME_CAPTURE_UUID],
});
}
setup.close();
});
it("never changes the global user-extensions preference", async () => {
const { setup, call } = fixture({ state: 2, version: 2, enabled: false });
await expect(setup.perform("enable-extension")).rejects.toThrow("GNOME has disabled");
expect(call.mock.calls.every(([message]) => message.member.startsWith("Get"))).toBe(true);
setup.close();
});
it("surfaces desktop rejection and disconnect as actionable failures", async () => {
const { setup, bus } = fixture({ state: 2, version: 2, accepted: false });
await expect(setup.perform("enable-extension")).rejects.toThrow("Sign out");
bus.emit("error", new Error("Session bus disconnected"));
expect(await setup.state()).toEqual({ status: "error", message: "Session bus disconnected" });
setup.close();
});
it("does not offer host extension installation in another desktop or sandbox", () => {
expect(isGnomeCaptureSession({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBe(true);
expect(isGnomeCaptureSession({ XDG_CURRENT_DESKTOP: "niri", GDMSESSION: "gnome" })).toBe(false);
expect(isGnomeCaptureSession({ XDG_CURRENT_DESKTOP: "GNOME", FLATPAK_ID: "com.t3" })).toBe(false);
});
@@ -0,0 +1,246 @@
// @effect-diagnostics nodeBuiltinImport:off -- GNOME's per-user installation is a native adapter boundary.
// @effect-diagnostics globalTimers:off -- Bound calls into the user's desktop session.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import { Message, sessionBus, type MessageBus, type MessageLike } from "dbus-next";
import * as Schema from "effect/Schema";
import type { DesktopCaptureExtensionState } from "@t3tools/contracts";
import { GNOME_CAPTURE_FILES, GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts";
export { isGnomeCaptureSession } from "./linuxCaptureSession.ts";
const SHELL = "org.gnome.Shell";
const SHELL_PATH = "/org/gnome/Shell";
const EXTENSIONS = "org.gnome.Shell.Extensions";
const NumberValue = Schema.Struct({ value: Schema.Number });
const decodeInfo = Schema.decodeUnknownSync(
Schema.Struct({
state: Schema.optional(NumberValue),
version: Schema.optional(NumberValue),
error: Schema.optional(Schema.Struct({ value: Schema.String })),
}),
);
const decodeProperties = Schema.decodeUnknownSync(
Schema.Struct({
ShellVersion: Schema.Struct({ value: Schema.String }),
UserExtensionsEnabled: Schema.Struct({ value: Schema.Boolean }),
}),
);
const Metadata = Schema.Struct({
uuid: Schema.Literal(GNOME_CAPTURE_UUID),
version: Schema.Number,
"shell-version": Schema.Array(Schema.String),
});
const decodeMetadata = Schema.decodeUnknownSync(Schema.fromJsonString(Metadata));
type SetupPaths = { readonly bundle: string; readonly dataHome: string };
/** Copies only the shipped extension, offline. Replaced versions are kept for recovery. */
export async function installGnomeCaptureBundle({ bundle, dataHome }: SetupPaths) {
const metadata = decodeMetadata(
await NodeFSP.readFile(NodePath.join(bundle, "metadata.json"), "utf8"),
);
const parent = NodePath.join(dataHome, "gnome-shell", "extensions");
const target = NodePath.join(parent, GNOME_CAPTURE_UUID);
await NodeFSP.mkdir(parent, { recursive: true });
const existing = await NodeFSP.lstat(target).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
return undefined;
});
if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
throw new Error(
"The extension installation is not a regular directory. Manage it in GNOME Extensions instead.",
);
if (existing) {
const installed = decodeMetadata(
await NodeFSP.readFile(NodePath.join(target, "metadata.json"), "utf8"),
);
if (installed.version > metadata.version)
throw new Error("A newer extension is installed. Update T3 Code instead of replacing it.");
}
const staged = await NodeFSP.mkdtemp(NodePath.join(parent, ".t3-capture-install-"));
let backup: string | undefined;
try {
for (const name of GNOME_CAPTURE_FILES) {
await NodeFSP.copyFile(NodePath.join(bundle, name), NodePath.join(staged, name));
await NodeFSP.chmod(NodePath.join(staged, name), 0o644);
}
await NodeFSP.chmod(staged, 0o755);
if (existing) {
const backupParent = NodePath.join(dataHome, "t3code", "extension-backups");
await NodeFSP.mkdir(backupParent, { recursive: true });
backup = NodePath.join(
await NodeFSP.mkdtemp(NodePath.join(backupParent, "capture-")),
GNOME_CAPTURE_UUID,
);
await NodeFSP.rename(target, backup);
}
try {
await NodeFSP.rename(staged, target);
} catch (error) {
if (backup) await NodeFSP.rename(backup, target);
throw error;
}
} finally {
await NodeFSP.rm(staged, { recursive: true, force: true });
}
}
/** A short-lived, read-only probe unless the user explicitly invokes an action. */
export class GnomeCaptureSetup {
private readonly disconnected: Promise<never>;
private readonly paths: SetupPaths;
private readonly bus: MessageBus;
private failure: Error | undefined;
constructor(paths: SetupPaths, bus: MessageBus = sessionBus()) {
this.paths = paths;
this.bus = bus;
this.disconnected = new Promise((_, reject) =>
bus.on("error", (error: Error) => {
this.failure = error;
reject(error);
}),
);
void this.disconnected.catch(() => undefined);
}
close() {
this.bus.disconnect();
}
private async call(message: Omit<MessageLike, "destination" | "path">) {
if (this.failure) throw this.failure;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const reply = await Promise.race([
this.bus.call(new Message({ destination: SHELL, path: SHELL_PATH, ...message })),
this.disconnected,
new Promise<never>((_, reject) => {
timer = setTimeout(
() =>
reject(
new Error(
"GNOME did not respond. Sign in to a GNOME Wayland session and try again.",
),
),
5_000,
);
}),
]);
if (!reply) throw new Error("GNOME returned no setup information.");
return reply.body[0] as unknown;
} finally {
clearTimeout(timer);
}
}
async state(): Promise<DesktopCaptureExtensionState> {
try {
const [properties, info, bundled, installed] = await Promise.all([
this.call({
interface: "org.freedesktop.DBus.Properties",
member: "GetAll",
signature: "s",
body: [EXTENSIONS],
}).then(decodeProperties),
this.call({
interface: EXTENSIONS,
member: "GetExtensionInfo",
signature: "s",
body: [GNOME_CAPTURE_UUID],
}).then(decodeInfo),
NodeFSP.readFile(NodePath.join(this.paths.bundle, "metadata.json"), "utf8").then(
decodeMetadata,
),
NodeFSP.readFile(
NodePath.join(
this.paths.dataHome,
"gnome-shell",
"extensions",
GNOME_CAPTURE_UUID,
"metadata.json",
),
"utf8",
)
.then(decodeMetadata)
.catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
return undefined;
}),
]);
const major = properties.ShellVersion.value.split(".")[0]!;
if (!bundled["shell-version"].includes(major))
return {
status: "unsupported",
message: `The bundled extension supports GNOME ${bundled["shell-version"].join(", ")}. This session runs GNOME ${major}.`,
};
if (!info.state && !installed)
return {
status: "not-installed",
message:
"Install the bundled extension to capture the active window without a picker. No download or administrator password is needed.",
};
if (installed && (!info.state || (info.version && installed.version > info.version.value)))
return {
status: "restart-required",
message:
"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.",
};
if ((installed?.version ?? info.version?.value ?? 0) < bundled.version)
return {
status: "update-required",
message:
"A newer extension is bundled with this app. Install it, then sign out and back in to load the update.",
};
if (!properties.UserExtensionsEnabled.value)
return {
status: "extensions-disabled",
message:
"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.",
};
if (info.state?.value === 1)
return {
status: "enabled",
message: "The T3 Code extension is running. Active-window snapshots are available.",
};
if (info.state?.value === 3 || info.state?.value === 4)
return {
status: "error",
message:
info.error?.value ||
"GNOME could not load the extension. Check GNOME Extensions for details, or sign out and back in.",
};
return {
status: "disabled",
message:
"Enable the T3 Code extension to allow active-window snapshots. You can disable it here at any time.",
};
} catch (error) {
return {
status: "error",
message: error instanceof Error ? error.message : "Could not check GNOME extension setup.",
};
}
}
async perform(action: "install-extension" | "enable-extension" | "disable-extension") {
const state = await this.state();
if (action === "install-extension") {
if (state.status !== "not-installed" && state.status !== "update-required")
throw new Error(state.message);
await installGnomeCaptureBundle(this.paths);
// GNOME discovers a newly installed local extension at the next login.
return;
}
if (action === "enable-extension" && state.status !== "disabled")
throw new Error(state.message);
const result = await this.call({
interface: EXTENSIONS,
member: action === "enable-extension" ? "EnableExtension" : "DisableExtension",
signature: "s",
body: [GNOME_CAPTURE_UUID],
});
if (result !== true)
throw new Error("GNOME has not loaded the extension. Sign out and back in, then try again.");
}
}
@@ -0,0 +1,171 @@
// @effect-diagnostics nodeBuiltinImport:off -- Isolated installation/config fixtures; no user's desktop state.
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const execute = vi.hoisted(() => vi.fn());
const startEffects = vi.hoisted(() => vi.fn());
vi.mock("node:child_process", () => ({ execFile: execute }));
vi.mock("./NativeCaptureFeedback.ts", () => ({ startNativeCaptureFeedback: startEffects }));
vi.mock("electron", () => ({
nativeImage: {
createFromBuffer: () => ({ isEmpty: () => false, getSize: () => ({ width: 2, height: 1 }) }),
},
}));
import {
HyprlandCaptureSetup,
captureHyprlandWindow,
hyprlandCaptureExecutable,
hyprlandCaptureShortcut,
isHyprlandCaptureSession,
} from "./HyprlandSnapShot.ts";
let directory: string;
let paths: { bundle: string; dataHome: string };
let setup: HyprlandCaptureSetup;
let denial: boolean;
let metadata: typeof window | null;
const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]);
const window = {
title: "Notes",
appName: "editor",
appIdentifier: "editor",
processId: 123,
bounds: { x: -1920, y: 20, width: 800, height: 600 },
clientBounds: { x: -1920, y: 20, width: 800, height: 600 },
};
beforeEach(async () => {
directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hypr-test-"));
paths = {
bundle: NodePath.join(directory, "bundle"),
dataHome: NodePath.join(directory, "user data"),
};
await NodeFSP.writeFile(paths.bundle, "bundled executable");
setup = new HyprlandCaptureSetup(paths);
denial = false;
metadata = window;
startEffects.mockReset().mockResolvedValue(undefined);
execute
.mockReset()
.mockImplementation(
(
_file: string,
args: string[],
_options: unknown,
callback: (error: Error | null, stdout: string, stderr: string) => void,
) => {
if (args[0] === "capture") {
if (denial) callback(new Error("Denied"), "", "Check screen-sharing permission.");
else
void NodeFSP.writeFile(NodePath.join(args[1]!, "capture.png"), png).then(() =>
callback(null, JSON.stringify({ window: metadata }), ""),
);
} else callback(null, '{"feedbackAvailable":true}', "");
},
);
});
afterEach(async () => {
await NodeFSP.rm(directory, { recursive: true, force: true });
});
it("does not select Hyprland from a stale socket environment or sandbox", () => {
expect(isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe(true);
expect(
isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "KDE", HYPRLAND_INSTANCE_SIGNATURE: "old" }),
).toBe(false);
expect(isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "Hyprland", FLATPAK_ID: "app" })).toBe(
false,
);
expect(isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "Hyprland", SNAP: "app" })).toBe(false);
});
it("discovery neither installs a helper nor requests a screenshot", async () => {
expect((await setup.state()).status).toBe("not-installed");
expect(execute).not.toHaveBeenCalled();
await expect(NodeFSP.stat(paths.dataHome)).rejects.toMatchObject({ code: "ENOENT" });
});
it("installs offline at a stable executable path and probes only capabilities", async () => {
await setup.perform("install-hyprland-helper");
expect((await NodeFSP.stat(hyprlandCaptureExecutable(paths))).mode & 0o777).toBe(0o755);
expect(await setup.state()).toMatchObject({ status: "ready", feedbackAvailable: true });
expect(execute.mock.calls.map(([file, args]) => [file, args])).toEqual([
[hyprlandCaptureExecutable(paths), ["check"]],
]);
});
it("updates explicitly and removes only its helper", async () => {
await setup.perform("install-hyprland-helper");
const unrelated = NodePath.join(paths.dataHome, "keep.txt");
await NodeFSP.writeFile(unrelated, "keep");
await NodeFSP.writeFile(paths.bundle, "update");
expect((await setup.state()).status).toBe("update-required");
await setup.perform("install-hyprland-helper");
expect((await setup.state()).status).toBe("ready");
await setup.perform("remove-hyprland-helper");
expect((await setup.state()).status).toBe("not-installed");
expect(await NodeFSP.readFile(unrelated, "utf8")).toBe("keep");
});
it("does not overwrite a linked executable", async () => {
const executable = hyprlandCaptureExecutable(paths);
await NodeFSP.mkdir(NodePath.dirname(executable), { recursive: true });
await NodeFSP.symlink(paths.bundle, executable);
await expect(setup.perform("install-hyprland-helper")).rejects.toThrow("not a link");
expect(await NodeFSP.readFile(paths.bundle, "utf8")).toBe("bundled executable");
});
it.each([true, false])("uses the active config syntax and user bindings (Lua: %s)", async (lua) => {
const config = NodePath.join(directory, "hypr");
await NodeFSP.mkdir(config);
await NodeFSP.writeFile(
NodePath.join(config, lua ? "hyprland.lua" : "hyprland.conf"),
"custom config",
);
await NodeFSP.writeFile(
NodePath.join(config, lua ? "bindings.lua" : "bindings.conf"),
"custom bindings",
);
const result = await hyprlandCaptureShortcut("com.t3tools.T3Code", directory);
expect(result.shortcutConfigPath).toBe(
NodePath.join(config, lua ? "bindings.lua" : "bindings.conf"),
);
expect(result.shortcutBinding).toBe(
lua
? 'hl.bind("CTRL + SHIFT + 2", hl.dsp.global("com.t3tools.T3Code:capture-window"))'
: "bind = CTRL SHIFT, 2, global, com.t3tools.T3Code:capture-window",
);
expect(await NodeFSP.readFile(result.shortcutConfigPath, "utf8")).toBe("custom bindings");
});
it("captures exact-window metadata for accessibility and focuses only through the installed helper", async () => {
await setup.perform("install-hyprland-helper");
const result = await captureHyprlandWindow(paths);
expect(result.png).toEqual(png);
expect(result.window).toEqual(window);
await result.feedback?.activate("T3 destination");
expect(execute.mock.calls.find(([, args]) => args[0] === "activate")?.slice(0, 2)).toEqual([
hyprlandCaptureExecutable(paths),
["activate", String(process.pid), "T3 destination"],
]);
const captureDirectory = execute.mock.calls.find(([, args]) => args[0] === "capture")![1][1];
await expect(NodeFSP.stat(captureDirectory)).rejects.toMatchObject({ code: "ENOENT" });
result.feedback?.close();
});
it("does not guess accessibility metadata when the captured window changed", async () => {
await setup.perform("install-hyprland-helper");
metadata = null;
const result = await captureHyprlandWindow(paths, { flash: true, animate: true });
expect(result.window).toBeUndefined();
expect(startEffects).not.toHaveBeenCalled();
result.feedback?.close();
});
it("surfaces a capture denial without a picker fallback and removes temporary output", async () => {
await setup.perform("install-hyprland-helper");
denial = true;
await expect(captureHyprlandWindow(paths)).rejects.toThrow("screen-sharing permission");
const path = execute.mock.calls.find(([, args]) => args[0] === "capture")![1][1];
await expect(NodeFSP.stat(path)).rejects.toMatchObject({ code: "ENOENT" });
});
it("keeps capture working when an overlay cannot start", async () => {
await setup.perform("install-hyprland-helper");
startEffects.mockRejectedValue(new Error("No layer shell"));
const result = await captureHyprlandWindow(paths, { flash: true, animate: true });
expect(result.png).toEqual(png);
expect(result.feedback?.animationStarted).toBe(false);
result.feedback?.close();
});
@@ -0,0 +1,221 @@
// @effect-diagnostics nodeBuiltinImport:off -- Bundled Wayland helper installed only by explicit setup.
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as Schema from "effect/Schema";
import type { DesktopCaptureHelperState } from "@t3tools/contracts";
import type { LinuxWindowSnapshot } from "./LinuxSnapShot.ts";
import { readPortalPng } from "./linuxCaptureSession.ts";
import { startNativeCaptureFeedback } from "./NativeCaptureFeedback.ts";
import { HYPRLAND_CAPTURE_ACTION } from "./linuxCaptureSession.ts";
export { isHyprlandCaptureSession } from "./linuxCaptureSession.ts";
export const HYPRLAND_CAPTURE_EXECUTABLE = "t3-hyprland-snap-shot";
export type HyprlandCapturePaths = { readonly bundle: string; readonly dataHome: string };
export function hyprlandCaptureExecutable(paths: HyprlandCapturePaths) {
return NodePath.join(paths.dataHome, "t3code", "hyprland-capture", HYPRLAND_CAPTURE_EXECUTABLE);
}
function hyprlandCaptureBinding(appId: string, lua: boolean): string {
if (!/^[A-Za-z0-9_.-]+$/.test(appId)) throw new Error("Invalid capture application ID.");
const action = `${appId}:${HYPRLAND_CAPTURE_ACTION}`;
return lua
? `hl.bind("CTRL + SHIFT + 2", hl.dsp.global("${action}"))`
: `bind = CTRL SHIFT, 2, global, ${action}`;
}
/** Omarchy owns its defaults; instructions always point at a user-owned config. */
export async function hyprlandCaptureShortcut(
appId: string,
configHome = process.env.XDG_CONFIG_HOME || NodePath.join(NodeOS.homedir(), ".config"),
) {
const directory = NodePath.join(configHome, "hypr");
const exists = async (name: string) =>
NodeFSP.access(NodePath.join(directory, name)).then(
() => true,
() => false,
);
const lua = await exists("hyprland.lua");
const bindings = lua ? "bindings.lua" : "bindings.conf";
const config = (await exists(bindings)) ? bindings : lua ? "hyprland.lua" : "hyprland.conf";
return {
shortcutBinding: hyprlandCaptureBinding(appId, lua),
shortcutConfigPath: NodePath.join(directory, config),
};
}
function run(executable: string, args: string[], signal?: AbortSignal): Promise<string> {
return new Promise((resolve, reject) => {
NodeChildProcess.execFile(
executable,
args,
{ timeout: 20_000, maxBuffer: 128 * 1024, encoding: "utf8", ...(signal ? { signal } : {}) },
(error, stdout, stderr) => {
if (error)
reject(
new Error(
stderr.trim() ||
"Hyprland capture did not respond. Check capture setup and try again.",
),
);
else resolve(stdout);
},
);
});
}
async function regularFile(path: string): Promise<Buffer | undefined> {
const stat = await NodeFSP.lstat(path).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
return undefined;
});
if (!stat) return undefined;
if (!stat.isFile() || stat.isSymbolicLink())
throw new Error("The capture helper must be a regular file, not a link.");
return NodeFSP.readFile(path);
}
const decodeCapabilities = Schema.decodeUnknownSync(
Schema.fromJsonString(Schema.Struct({ feedbackAvailable: Schema.Boolean })),
);
export class HyprlandCaptureSetup {
private readonly paths: HyprlandCapturePaths;
constructor(paths: HyprlandCapturePaths) {
this.paths = paths;
}
async state(): Promise<DesktopCaptureHelperState> {
try {
const installed = await regularFile(hyprlandCaptureExecutable(this.paths));
if (!installed)
return {
status: "not-installed",
message: "Install the bundled helper to capture the window you're using.",
};
const bundle = await regularFile(this.paths.bundle);
if (!bundle)
throw new Error(
"The Hyprland capture helper is missing from this build. Update or reinstall T3 Code.",
);
if (!installed.equals(bundle))
return {
status: "update-required",
message: "Update the bundled capture helper to continue.",
};
return {
status: "ready",
message:
"Helper ready. Hyprland may ask for screen-sharing permission on your first capture.",
...decodeCapabilities(await run(hyprlandCaptureExecutable(this.paths), ["check"])),
};
} catch (error) {
return {
status: "error",
message: error instanceof Error ? error.message : "Couldn't check Hyprland capture access.",
};
}
}
async perform(action: "install-hyprland-helper" | "remove-hyprland-helper") {
const executable = hyprlandCaptureExecutable(this.paths);
const directory = NodePath.dirname(executable);
const stat = await NodeFSP.lstat(directory).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
return undefined;
});
if (stat && (!stat.isDirectory() || stat.isSymbolicLink()))
throw new Error("The capture helper directory must not be a link.");
await regularFile(executable);
if (action === "remove-hyprland-helper") {
await NodeFSP.rm(executable, { force: true });
return;
}
const bundle = await regularFile(this.paths.bundle);
if (!bundle) throw new Error("The Hyprland capture helper is missing from this build.");
await NodeFSP.mkdir(directory, { recursive: true });
const staging = await NodeFSP.mkdtemp(NodePath.join(directory, ".install-"));
try {
const staged = NodePath.join(staging, HYPRLAND_CAPTURE_EXECUTABLE);
await NodeFSP.writeFile(staged, bundle, { mode: 0o755, flag: "wx" });
await NodeFSP.rename(staged, executable);
} finally {
await NodeFSP.rm(staging, { recursive: true, force: true });
}
}
}
const Dimension = Schema.Int.check(Schema.isGreaterThan(0));
const Bounds = Schema.Struct({ x: Schema.Int, y: Schema.Int, width: Dimension, height: Dimension });
const decodeCapture = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Struct({
window: Schema.NullOr(
Schema.Struct({
title: Schema.String,
appName: Schema.String,
appIdentifier: Schema.String,
processId: Dimension,
bounds: Bounds,
clientBounds: Bounds,
}),
),
}),
),
);
export async function captureHyprlandWindow(
paths: HyprlandCapturePaths,
options?: { readonly flash: boolean; readonly animate: boolean },
): Promise<LinuxWindowSnapshot> {
const state = await new HyprlandCaptureSetup(paths).state();
if (state.status !== "ready")
throw new Error(`${state.message} Open Settings → SnapShots to continue setup.`);
const executable = hyprlandCaptureExecutable(paths);
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-"));
const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true });
let retained = false;
try {
const result = decodeCapture(await run(executable, ["capture", directory]));
const png = await readPortalPng(
NodeURL.pathToFileURL(NodePath.join(directory, "capture.png")).href,
);
const effects =
state.feedbackAvailable && result.window && options && (options.flash || options.animate)
? await startNativeCaptureFeedback(executable, directory, {
bounds: result.window.bounds,
pid: process.pid,
...options,
}).catch(() => undefined)
: undefined;
if (effects) {
retained = true;
void effects.closed.then(cleanup).catch(() => undefined);
}
const activation = new AbortController();
let targetTitle = "";
return {
png,
...(result.window ? { window: result.window } : {}),
feedback: {
animationStarted: effects?.animationStarted ?? false,
activate: async (title) => {
targetTitle = title;
await run(executable, ["activate", String(process.pid), title], activation.signal);
},
animateTo: async (frame) => {
await effects?.animateTo(targetTitle, frame);
},
complete: async () => {
await effects?.complete();
activation.abort();
await cleanup();
},
close: () => {
effects?.close();
activation.abort();
},
},
};
} finally {
if (!retained) await cleanup();
}
}
@@ -0,0 +1,238 @@
// @effect-diagnostics nodeBuiltinImport:off -- Isolated helper installation fixtures, never the user's data directory.
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const execute = vi.hoisted(() => vi.fn());
const startEffects = vi.hoisted(() => vi.fn());
vi.mock("node:child_process", () => ({ execFile: execute }));
vi.mock("./NativeCaptureFeedback.ts", () => ({ startNativeCaptureFeedback: startEffects }));
vi.mock("electron", () => ({
nativeImage: {
createFromBuffer: () => ({ isEmpty: () => false, getSize: () => ({ width: 2, height: 1 }) }),
},
}));
import {
KdeCaptureSetup,
captureKdeWindow,
isKdeCaptureSession,
kdeCaptureDesktopEntry,
kdeCapturePaths,
} from "./KdeSnapShot.ts";
let directory: string;
let paths: { bundle: string; dataHome: string };
let setup: KdeCaptureSetup;
let denial = false;
const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]);
const window = {
title: "Document",
appName: "Kate",
appIdentifier: "org.kde.kate",
processId: 123,
bounds: { x: 20, y: 10, width: 800, height: 600 },
clientBounds: { x: 20, y: 39, width: 800, height: 571 },
};
beforeEach(async () => {
directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-test-"));
paths = {
bundle: NodePath.join(directory, "bundled-helper"),
dataHome: NodePath.join(directory, "user data"),
};
await NodeFSP.writeFile(paths.bundle, "bundled executable");
setup = new KdeCaptureSetup(paths);
denial = false;
startEffects.mockReset();
startEffects.mockResolvedValue(undefined);
execute.mockReset();
execute.mockImplementation(
(
executable: string,
args: string[],
_options: unknown,
callback: (error: Error | null, stdout: string, stderr: string) => void,
) => {
if (args[0] === "capture") {
void NodeFSP.writeFile(NodePath.join(args[1]!, "capture.png"), png).then(() =>
callback(null, JSON.stringify({ window }), ""),
);
} else if (args[0] === "check" && denial)
callback(new Error("Denied"), "", "org.kde.KWin.ScreenShot2.Error.NoAuthorized");
else
callback(
null,
executable === "kbuildsycoca6" ? "" : '{"ready":true,"feedbackAvailable":true}',
"",
);
},
);
});
afterEach(async () => {
await NodeFSP.rm(directory, { recursive: true, force: true });
});
it("detects KDE only outside a sandbox", () => {
expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "KDE" })).toBe(true);
expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "GNOME" })).toBe(false);
expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "KDE", FLATPAK_ID: "app" })).toBe(false);
expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "KDE", SNAP: "/snap/app" })).toBe(false);
});
it("does not install or request screenshots during initial discovery", async () => {
expect((await setup.state()).status).toBe("not-installed");
expect(execute).not.toHaveBeenCalled();
await expect(NodeFSP.stat(paths.dataHome)).rejects.toMatchObject({ code: "ENOENT" });
});
it("installs offline at a stable path and verifies permissions using the installed identity", async () => {
await setup.perform("install-kde-helper");
const { executable, desktop } = kdeCapturePaths(paths);
expect(await NodeFSP.readFile(executable, "utf8")).toBe("bundled executable");
expect((await NodeFSP.stat(executable)).mode & 0o777).toBe(0o755);
expect(await NodeFSP.readFile(desktop, "utf8")).toBe(kdeCaptureDesktopEntry(executable));
expect(kdeCaptureDesktopEntry(executable)).toContain(`Exec="${executable}" check`);
expect((await setup.state()).status).toBe("ready");
expect((await setup.state()).feedbackAvailable).toBe(true);
expect(execute.mock.calls.map(([file, args]) => [file, args])).toEqual([
["kbuildsycoca6", ["--noincremental"]],
[
"systemd-run",
[
"--user",
"--quiet",
"--wait",
"--collect",
"--pipe",
"--service-type=exec",
"kbuildsycoca6",
"--noincremental",
],
],
[executable, ["check"]],
[executable, ["check"]],
]);
});
it("does not mistake installed files for KDE authorization, or fall back to a picker on denial", async () => {
await setup.perform("install-kde-helper");
denial = true;
expect(await setup.state()).toMatchObject({
status: "error",
message: expect.stringContaining("Reinstall"),
});
await expect(captureKdeWindow(paths)).rejects.toThrow("Settings → SnapShots");
expect(execute.mock.calls.some(([, args]) => args[0] === "capture")).toBe(false);
});
it("detects a bundled update, updates explicitly, and removes only capture's registration", async () => {
await setup.perform("install-kde-helper");
const unrelated = NodePath.join(paths.dataHome, "applications", "another-app.desktop");
await NodeFSP.writeFile(unrelated, "keep me");
await NodeFSP.writeFile(paths.bundle, "updated helper");
expect((await setup.state()).status).toBe("update-required");
await setup.perform("install-kde-helper");
expect((await setup.state()).status).toBe("ready");
await setup.perform("remove-kde-helper");
expect((await setup.state()).status).toBe("not-installed");
expect(await NodeFSP.readFile(unrelated, "utf8")).toBe("keep me");
});
it("repairs the old semicolon permission entry without replacing unrelated registrations", async () => {
await setup.perform("install-kde-helper");
const { desktop } = kdeCapturePaths(paths);
const installed = await NodeFSP.readFile(desktop, "utf8");
const permission = "X-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2";
expect(installed.split("\n")).toContain(permission);
await NodeFSP.writeFile(desktop, installed.replace(`${permission}\n`, `${permission};\n`));
execute.mockClear();
expect((await setup.state()).status).toBe("update-required");
expect(execute).not.toHaveBeenCalled();
await setup.perform("install-kde-helper");
expect((await setup.state()).status).toBe("ready");
expect((await NodeFSP.readFile(desktop, "utf8")).split("\n")).toContain(permission);
expect(await NodeFSP.readdir(NodePath.dirname(desktop))).toEqual([NodePath.basename(desktop)]);
});
it("still verifies capture access when a systemd user manager is unavailable", async () => {
const executeNormally = execute.getMockImplementation()!;
execute.mockImplementation((file, args, options, callback) => {
if (file === "systemd-run") callback(new Error("ENOENT"), "", "");
else executeNormally(file, args, options, callback);
});
await setup.perform("install-kde-helper");
expect((await setup.state()).status).toBe("ready");
denial = true;
expect((await setup.state()).status).toBe("error");
});
it("does not report a successful install when the registry cannot be refreshed", async () => {
execute.mockImplementation((_file, _args, _options, callback) =>
callback(new Error("Failed"), "", "Failed to rebuild registry"),
);
await expect(setup.perform("install-kde-helper")).rejects.toThrow("KDE couldn't register");
});
it("refuses symlink destinations and unrelated desktop entries", async () => {
const { desktop, executable } = kdeCapturePaths(paths);
await NodeFSP.mkdir(NodePath.dirname(desktop), { recursive: true });
await NodeFSP.writeFile(desktop, "[Desktop Entry]\nName=Unrelated");
await expect(setup.perform("install-kde-helper")).rejects.toThrow("Another desktop entry");
await NodeFSP.unlink(desktop);
await NodeFSP.mkdir(NodePath.dirname(executable), { recursive: true });
await NodeFSP.symlink(paths.bundle, executable);
await expect(setup.perform("install-kde-helper")).rejects.toThrow("regular files");
expect(await NodeFSP.readFile(paths.bundle, "utf8")).toBe("bundled executable");
});
it("captures with verified identity, cleans private files, and activates only the owning T3 PID/title", async () => {
await setup.perform("install-kde-helper");
const capture = await captureKdeWindow(paths);
expect(capture.png).toEqual(png);
expect(capture.window).toEqual(window);
expect(capture.feedback?.animationStarted).toBe(false);
const [, args] = execute.mock.calls.find(([, args]) => args[0] === "capture")!;
await expect(NodeFSP.stat(args[1])).rejects.toMatchObject({ code: "ENOENT" });
await capture.feedback?.activate('My "Draft"');
const [, activation] = execute.mock.calls.find(([, args]) => args[0] === "activate")!;
expect(activation.slice(2)).toEqual([String(process.pid), 'My "Draft"']);
await expect(NodeFSP.stat(activation[1])).rejects.toMatchObject({ code: "ENOENT" });
capture.feedback?.close();
});
it("retains the frozen screenshot for feedback and removes it after the renderer acknowledges landing", async () => {
await setup.perform("install-kde-helper");
const closed = Promise.withResolvers<void>();
const animateTo = vi.fn().mockResolvedValue(undefined);
startEffects.mockResolvedValue({
animationStarted: true,
closed: closed.promise,
animateTo,
complete: async () => {
closed.resolve();
},
close: () => closed.resolve(),
});
const capture = await captureKdeWindow(paths, { flash: true, animate: true });
const [, args] = execute.mock.calls.find(([, args]) => args[0] === "capture")!;
expect(await NodeFSP.readFile(NodePath.join(args[1], "capture.png"))).toEqual(png);
expect(capture.feedback?.animationStarted).toBe(true);
await capture.feedback?.activate("Draft");
const frame = { x: 0.2, y: 0.5, width: 0.1, height: 0.2 };
await capture.feedback?.animateTo(frame);
expect(animateTo).toHaveBeenCalledWith("Draft", frame);
await capture.feedback?.complete();
await expect(NodeFSP.stat(args[1])).rejects.toMatchObject({ code: "ENOENT" });
});
it("keeps a successfully captured image when optional KDE effects fail", async () => {
await setup.perform("install-kde-helper");
startEffects.mockRejectedValue(new Error("QML unavailable"));
const capture = await captureKdeWindow(paths, { flash: true, animate: true });
expect(capture.png).toEqual(png);
expect(capture.feedback?.animationStarted).toBe(false);
const [, args] = execute.mock.calls.find(([, args]) => args[0] === "capture")!;
await expect(NodeFSP.stat(args[1])).rejects.toMatchObject({ code: "ENOENT" });
capture.feedback?.close();
});
+285
View File
@@ -0,0 +1,285 @@
// @effect-diagnostics nodeBuiltinImport:off -- KDE authorizes a dedicated, installed native executable.
import * as NodeCrypto from "node:crypto";
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as Schema from "effect/Schema";
import type { DesktopCaptureHelperState } from "@t3tools/contracts";
import { escapeDesktopEntryExecArgument } from "../app/DesktopLinuxUrlHandler.ts";
import type { LinuxWindowSnapshot } from "./LinuxSnapShot.ts";
import { readPortalPng } from "./linuxCaptureSession.ts";
import { startNativeCaptureFeedback } from "./NativeCaptureFeedback.ts";
export { isKdeCaptureSession } from "./linuxCaptureSession.ts";
export const KDE_CAPTURE_EXECUTABLE = "t3-kde-snap-shot";
const DESKTOP_FILE = "com.t3tools.T3Code.KdeCapture.desktop";
const MARKER = "X-T3Code-Capture-Helper=true";
const decodeCapabilities = Schema.decodeUnknownSync(
Schema.fromJsonString(Schema.Struct({ feedbackAvailable: Schema.optional(Schema.Boolean) })),
);
export type KdeCapturePaths = { readonly bundle: string; readonly dataHome: string };
export function kdeCapturePaths(paths: KdeCapturePaths) {
return {
executable: NodePath.join(paths.dataHome, "t3code", "kde-capture", KDE_CAPTURE_EXECUTABLE),
desktop: NodePath.join(paths.dataHome, "applications", DESKTOP_FILE),
};
}
export function kdeCaptureDesktopEntry(executable: string): string {
return [
"[Desktop Entry]",
"Type=Application",
"Name=T3 Code SnapShots",
"NoDisplay=true",
`Exec=${escapeDesktopEntryExecArgument(executable)} check`,
// KService reads this custom property as a KConfig list, not an XDG ';' list.
"X-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2",
MARKER,
"",
].join("\n");
}
function run(executable: string, args: string[], signal?: AbortSignal): Promise<string> {
return new Promise((resolve, reject) => {
NodeChildProcess.execFile(
executable,
args,
{
timeout: 20_000,
maxBuffer: 128 * 1024,
encoding: "utf8",
...(signal ? { signal } : {}),
},
(error, stdout, stderr) => {
if (!error) return resolve(stdout);
if (executable === "kbuildsycoca6") {
reject(
new Error(
"KDE couldn't register the capture helper. Make sure KDE's service tools (kbuildsycoca6) are installed, then reinstall the helper.",
),
);
return;
}
if (stderr.includes("NoAuthorized")) {
reject(
new Error(
"KDE hasn't granted capture access. Reinstall the capture helper in setup, then try again.",
),
);
} else
reject(
new Error(
stderr.trim() ||
"The KDE capture helper did not respond. Reopen capture setup and check access.",
),
);
},
);
});
}
async function regularFile(path: string): Promise<Buffer | undefined> {
const stat = await NodeFSP.lstat(path).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
return undefined;
});
if (!stat) return undefined;
if (!stat.isFile() || stat.isSymbolicLink())
throw new Error(
"Capture helper files must be regular files. Remove the conflicting link before trying again.",
);
return NodeFSP.readFile(path);
}
/** No install on launch: writes happen only after the user chooses Install helper. */
export class KdeCaptureSetup {
private readonly paths: KdeCapturePaths;
constructor(paths: KdeCapturePaths) {
this.paths = paths;
}
async state(): Promise<DesktopCaptureHelperState> {
try {
const { executable, desktop } = kdeCapturePaths(this.paths);
const [installed, entry] = await Promise.all([regularFile(executable), regularFile(desktop)]);
if (!installed || !entry)
return {
status: "not-installed",
message:
"Install the bundled helper to capture the window you're using without a picker.",
};
const bundle = await regularFile(this.paths.bundle);
if (!bundle)
return {
status: "error",
message: "The capture helper is missing from this build. Update or reinstall T3 Code.",
};
if (!installed.equals(bundle) || entry.toString() !== kdeCaptureDesktopEntry(executable))
return {
status: "update-required",
message: "Update the bundled capture helper to continue.",
};
const capabilities = decodeCapabilities(await run(executable, ["check"]));
return {
status: "ready",
message: "KDE capture access is ready. Next, choose your shortcut.",
feedbackAvailable: capabilities.feedbackAvailable ?? false,
};
} catch (error) {
return {
status: "error",
message: error instanceof Error ? error.message : "Couldn't check KDE capture access.",
};
}
}
async perform(action: "install-kde-helper" | "remove-kde-helper") {
const { executable, desktop } = kdeCapturePaths(this.paths);
const entry = await regularFile(desktop);
if (entry && !entry.toString().split("\n").includes(MARKER))
throw new Error(
"Another desktop entry uses the capture helper's name. Rename it before continuing.",
);
// Never overwrite/follow a symlink, including the installation directory itself.
const directory = NodePath.dirname(executable);
const existing = await NodeFSP.lstat(directory).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
return undefined;
});
if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
throw new Error("The capture helper directory is not a regular directory.");
await regularFile(executable);
if (action === "remove-kde-helper") {
if (entry) await NodeFSP.unlink(desktop);
await NodeFSP.unlink(executable).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
});
} else {
const bundle = await regularFile(this.paths.bundle);
if (!bundle)
throw new Error(
"The capture helper is missing from this build. Update or reinstall T3 Code.",
);
await NodeFSP.mkdir(directory, { recursive: true });
await NodeFSP.mkdir(NodePath.dirname(desktop), { recursive: true });
const staging = await NodeFSP.mkdtemp(NodePath.join(directory, ".install-"));
const stagedDesktop = `${desktop}.${NodeCrypto.randomUUID()}.tmp`;
try {
const staged = NodePath.join(staging, KDE_CAPTURE_EXECUTABLE);
await NodeFSP.writeFile(staged, bundle, { mode: 0o755 });
await NodeFSP.rename(staged, executable);
await NodeFSP.writeFile(stagedDesktop, kdeCaptureDesktopEntry(executable), {
mode: 0o644,
flag: "wx",
});
await NodeFSP.rename(stagedDesktop, desktop);
} finally {
await NodeFSP.rm(stagedDesktop, { force: true });
await NodeFSP.rm(staging, { recursive: true, force: true });
}
}
// KService must see the new desktop entry before KWin checks the executable.
await run("kbuildsycoca6", ["--noincremental"]);
// AppImages change XDG search paths, and KService caches are also locale-specific.
// Refresh Plasma's cache in its session environment, not just the app's cache.
// Non-systemd sessions use the direct refresh and atomic directory notification above.
await run("systemd-run", [
"--user",
"--quiet",
"--wait",
"--collect",
"--pipe",
"--service-type=exec",
"kbuildsycoca6",
"--noincremental",
]).catch(() => undefined);
}
}
const Dimension = Schema.Int.check(Schema.isGreaterThan(0));
const Bounds = Schema.Struct({ x: Schema.Int, y: Schema.Int, width: Dimension, height: Dimension });
const Window = Schema.Struct({
title: Schema.String,
appName: Schema.String,
appIdentifier: Schema.String,
processId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
bounds: Bounds,
clientBounds: Bounds,
});
const decodeCapture = Schema.decodeUnknownSync(
Schema.fromJsonString(Schema.Struct({ window: Schema.NullOr(Window) })),
);
export async function captureKdeWindow(
paths: KdeCapturePaths,
options?: { readonly flash: boolean; readonly animate: boolean },
): Promise<LinuxWindowSnapshot> {
const state = await new KdeCaptureSetup(paths).state();
if (state.status !== "ready")
throw new Error(`${state.message} Open Settings → SnapShots to continue setup.`);
const { executable } = kdeCapturePaths(paths);
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-capture-"));
let retained = false;
const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true });
try {
const result = decodeCapture(await run(executable, ["capture", directory]));
const png = await readPortalPng(
NodeURL.pathToFileURL(NodePath.join(directory, "capture.png")).href,
);
const feedback = new AbortController();
const effects =
state.feedbackAvailable && result.window && options && (options.flash || options.animate)
? await startNativeCaptureFeedback(executable, directory, {
bounds: result.window.bounds,
pid: process.pid,
...options,
}).catch(() => undefined)
: undefined;
if (effects) {
retained = true;
void effects.closed.then(cleanup).catch(() => undefined);
}
let targetTitle = "";
const close = () => {
effects?.close();
feedback.abort();
};
return {
png,
...(result.window ? { window: result.window } : {}),
feedback: {
animationStarted: effects?.animationStarted ?? false,
activate: async (title) => {
targetTitle = title;
const activation = await NodeFSP.mkdtemp(
NodePath.join(NodeOS.tmpdir(), "t3-kde-activate-"),
);
try {
await run(
executable,
["activate", activation, String(process.pid), title],
feedback.signal,
);
} finally {
await NodeFSP.rm(activation, { recursive: true, force: true });
}
},
animateTo: async (frame) => {
await effects?.animateTo(targetTitle, frame);
},
complete: async () => {
await effects?.complete();
feedback.abort();
await cleanup();
},
close,
},
};
} finally {
if (!retained) await cleanup();
}
}
@@ -0,0 +1,281 @@
// @effect-diagnostics nodeBuiltinImport:off -- Isolated D-Bus integration fixture, never the user's session bus.
import * as NodeChildProcess from "node:child_process";
import * as NodeEvents from "node:events";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeReadline from "node:readline";
import * as NodeURL from "node:url";
import { Message, NameFlag, Variant, sessionBus, type MessageBus } from "dbus-next";
import { expect, it, vi } from "vite-plus/test";
vi.mock("electron", () => ({
nativeImage: {
createFromBuffer: () => ({
isEmpty: () => false,
getSize: () => ({ width: 800, height: 600 }),
}),
},
}));
import { LinuxCaptureConnection } from "./LinuxSnapShot.ts";
import { startNiriCaptureShortcut } from "./NiriCaptureShortcut.ts";
import { GnomeCaptureSetup } from "./GnomeCaptureSetup.ts";
import { GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts";
const hasDbus =
NodeChildProcess.spawnSync("dbus-daemon", ["--version"]).status === 0 &&
NodeChildProcess.spawnSync("gdbus", ["help"]).status === 0;
it.runIf(hasDbus)("captures through real D-Bus marshalling on a private bus", async () => {
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-private-dbus-"));
let daemon: NodeChildProcess.ChildProcess | undefined;
let server: MessageBus | undefined;
const clients: LinuxCaptureConnection[] = [];
let stopNiriShortcut: (() => void) | undefined;
try {
vi.stubEnv("XDG_CURRENT_DESKTOP", "GNOME");
vi.stubEnv("FLATPAK_ID", "");
vi.stubEnv("SNAP", "");
daemon = NodeChildProcess.spawn(
"dbus-daemon",
[
"--session",
"--nofork",
"--nopidfile",
"--print-address",
`--address=unix:path=${NodePath.join(directory, "bus")}`,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
const lines = NodeReadline.createInterface({ input: daemon.stdout! });
const [address] = await Promise.race([
NodeEvents.EventEmitter.once(lines, "line"),
NodeEvents.EventEmitter.once(daemon, "exit").then(() => {
throw new Error("Private D-Bus daemon failed to start.");
}),
]);
lines.close();
server = sessionBus({ busAddress: String(address) });
server.on("error", () => undefined);
await server.requestName("org.freedesktop.portal.Desktop", NameFlag.DO_NOT_QUEUE);
await server.requestName("org.gnome.Shell.Extensions.T3SnapShot", NameFlag.DO_NOT_QUEUE);
await server.requestName("org.gnome.Shell", NameFlag.DO_NOT_QUEUE);
await server.requestName("org.kde.KWin.ScreenShot2", NameFlag.DO_NOT_QUEUE);
const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]);
const imagePath = NodePath.join(directory, "image.png");
await NodeFSP.writeFile(imagePath, png);
let portalVersion = 3;
let extensionVersion = 1;
let feedbackArgs: unknown[] | undefined;
let activateTitle: unknown;
let animateFrame: unknown[] | undefined;
let target: unknown;
let clientName: string | undefined;
let shellExtensionState = 2;
server.addMethodHandler((message: Message) => {
if (message.member === "Register") {
server!.send(Message.newMethodReturn(message));
} else if (message.member === "GetAll") {
const properties =
message.body[0] === "org.gnome.Shell.Extensions"
? {
ShellVersion: new Variant("s", "50.0"),
UserExtensionsEnabled: new Variant("b", true),
}
: message.body[0] === "org.kde.KWin.ScreenShot2"
? { Version: new Variant("u", 5) }
: message.body[0] === "org.freedesktop.portal.Screenshot"
? {
version: new Variant("u", portalVersion),
AvailableTargets: new Variant("u", 8),
}
: { Version: new Variant("u", extensionVersion) };
server!.send(Message.newMethodReturn(message, "a{sv}", [properties]));
} else if (message.member === "GetExtensionInfo") {
server!.send(
Message.newMethodReturn(message, "a{sv}", [
{ state: new Variant("d", shellExtensionState), version: new Variant("d", 2) },
]),
);
} else if (message.member === "EnableExtension" || message.member === "DisableExtension") {
expect(message.body).toEqual([GNOME_CAPTURE_UUID]);
shellExtensionState = message.member === "EnableExtension" ? 1 : 2;
server!.send(Message.newMethodReturn(message, "b", [true]));
} else if (message.member === "Screenshot") {
const options = message.body[1] as Record<string, Variant<unknown>>;
target = options.target?.value;
const path = `/org/freedesktop/portal/desktop/request/${message.sender.slice(1).replaceAll(".", "_")}/${options.handle_token?.value}`;
// The real transport also has to handle Response before the method reply.
const signal = Message.newSignal(
path,
"org.freedesktop.portal.Request",
"Response",
"ua{sv}",
[0, { uri: new Variant("s", NodeURL.pathToFileURL(imagePath).href) }],
);
signal.destination = message.sender;
server!.send(signal);
server!.send(Message.newMethodReturn(message, "o", [path]));
} else if (message.member === "Activate") {
activateTitle = message.body[0];
server!.send(Message.newMethodReturn(message));
} else if (message.member === "Animate") {
animateFrame = message.body;
server!.send(Message.newMethodReturn(message));
} else if (message.member === "Capture" || message.member === "CaptureWithFeedback") {
const feedback = message.member === "CaptureWithFeedback";
if (feedback) feedbackArgs = message.body;
clientName = message.sender;
server!.send(
Message.newMethodReturn(message, feedback ? "aysb" : "ays", [
png,
JSON.stringify({
title: "Editor",
appName: "Editor",
appIdentifier: "editor.desktop",
processId: 42,
bounds: { x: 0, y: 0, width: 800, height: 600 },
}),
...(feedback ? [true] : []),
]),
);
} else return false;
return true;
});
const connect = () => {
const client = new LinuxCaptureConnection(sessionBus({ busAddress: String(address) }));
clients.push(client);
return client;
};
const setup = new GnomeCaptureSetup(
{
bundle: NodePath.resolve(import.meta.dirname, "../../gnome-extension"),
dataHome: directory,
},
sessionBus({ busAddress: String(address) }),
);
try {
expect((await setup.state()).status).toBe("disabled");
await setup.perform("enable-extension");
expect((await setup.state()).status).toBe("enabled");
await setup.perform("disable-extension");
expect((await setup.state()).status).toBe("disabled");
} finally {
setup.close();
}
const portal = connect();
expect(await portal.backend("com.t3tools.T3Code")).toBe("screenshot-portal");
expect(await portal.capturePortal()).toEqual({ png });
expect(target).toBe(8);
portalVersion = 2;
const extension = connect();
expect(await extension.backend("com.t3tools.T3Code")).toBe("gnome-extension");
expect(await extension.captureExtension("com.t3tools.T3Code")).toMatchObject({
png,
window: { processId: 42 },
});
const owner = await server.call(
new Message({
destination: "org.freedesktop.DBus",
path: "/org/freedesktop/DBus",
interface: "org.freedesktop.DBus",
member: "GetNameOwner",
signature: "s",
body: ["com.t3tools.T3Code.SnapShot"],
}),
);
expect(owner?.body[0]).toBe(clientName);
extension.close();
extensionVersion = 2;
const updated = connect();
expect(await updated.backend("com.t3tools.T3Code")).toBe("gnome-extension");
const snapshot = await updated.captureExtension("com.t3tools.T3Code", {
flash: true,
animate: true,
});
expect(snapshot.feedback?.animationStarted).toBe(true);
await snapshot.feedback!.activate("T3 Code");
await snapshot.feedback!.animateTo({ x: 0.1, y: 0.8, width: 0.2, height: 0.1 });
await snapshot.feedback!.complete();
expect(feedbackArgs).toEqual([true, true]);
expect(activateTitle).toBe("T3 Code");
expect(animateFrame).toEqual([0.1, 0.8, 0.2, 0.1]);
vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE");
const kde = connect();
expect(await kde.backend("com.t3tools.T3Code")).toBe("kde");
expect(kde.feedbackAvailable).toBe(false);
kde.close();
const triggered = vi.fn();
const failed = vi.fn();
const niriBus = sessionBus({ busAddress: String(address) });
stopNiriShortcut = await startNiriCaptureShortcut(
"com.t3tools.T3Code.NiriTest",
triggered,
failed,
niriBus,
);
const command = [
"call",
"--session",
"--dest",
"com.t3tools.T3Code.NiriTest.SnapShot",
"--object-path",
"/com/t3tools/SnapShot",
"--method",
"com.t3tools.SnapShot.Capture",
];
// Exercise the actual command copied to Niri's configuration, including gdbus introspection.
await new Promise<void>((resolve, reject) => {
NodeChildProcess.execFile(
"gdbus",
command,
{
env: { ...process.env, DBUS_SESSION_BUS_ADDRESS: String(address) },
timeout: 3_000,
},
(error) => (error ? reject(error) : resolve()),
);
});
expect(triggered).toHaveBeenCalledOnce();
expect(failed).not.toHaveBeenCalled();
const invalid = server.call(
new Message({
destination: "com.t3tools.T3Code.NiriTest.SnapShot",
path: "/com/t3tools/SnapShot",
interface: "com.t3tools.SnapShot",
member: "Capture",
signature: "s",
body: ["not allowed"],
}),
);
await expect(invalid).rejects.toThrow("Capture takes no arguments");
expect(triggered).toHaveBeenCalledOnce();
await expect(
startNiriCaptureShortcut(
"com.t3tools.T3Code.NiriTest",
triggered,
failed,
sessionBus({ busAddress: String(address) }),
),
).rejects.toThrow("already owns");
stopNiriShortcut();
const restarted = await startNiriCaptureShortcut(
"com.t3tools.T3Code.NiriTest",
triggered,
failed,
sessionBus({ busAddress: String(address) }),
);
restarted();
} finally {
vi.unstubAllEnvs();
stopNiriShortcut?.();
for (const client of clients) client.close();
server?.disconnect();
if (daemon && daemon.exitCode === null) {
const exited = NodeEvents.EventEmitter.once(daemon, "exit");
daemon.kill("SIGTERM");
await exited;
}
await NodeFSP.rm(directory, { recursive: true });
}
});
@@ -0,0 +1,414 @@
// @effect-diagnostics nodeBuiltinImport:off -- Real temporary files exercise the native portal URI boundary.
import * as NodeEvents from "node:events";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import {
DBusError,
Message,
MessageType,
RequestNameReply,
Variant,
type MessageBus,
} from "dbus-next";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const { connect, resize, imageSize } = vi.hoisted(() => ({
connect: vi.fn(),
resize: vi.fn(() => ({ toPNG: () => Buffer.from("resized") })),
imageSize: { width: 800, height: 600 },
}));
vi.mock("dbus-next", async (original) => ({
...(await original<typeof import("dbus-next")>()),
sessionBus: connect,
}));
vi.mock("electron", () => ({
nativeImage: {
createFromBuffer: () => ({
isEmpty: () => false,
getSize: () => imageSize,
resize,
}),
},
}));
import {
captureLinuxWindow,
getLinuxCaptureSupport,
readPortalPng,
resizeLinuxCapture,
} from "./LinuxSnapShot.ts";
const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]);
const appId = "com.t3tools.T3Code";
const metadata = {
title: "Editor",
appName: "Text Editor",
appIdentifier: "org.gnome.TextEditor.desktop",
processId: 42,
bounds: { x: -100, y: 20, width: 800, height: 600 },
};
class FakeBus extends NodeEvents.EventEmitter {
calls: Message[] = [];
portalVersion = 3;
targets: number | undefined = 8;
extensionVersion: number | undefined;
kdeVersion: number | undefined = 5;
kdeError: Error | undefined;
status = 0;
uri = "file:///missing.png";
registryError: Error | undefined;
screenshotError: Error | undefined;
extensionError: Error | undefined;
activationError: Error | undefined;
animation: Promise<void> | undefined;
sendResponse = true;
differentHandle = false;
wrongSender = false;
requestName = vi.fn(async () => RequestNameReply.PRIMARY_OWNER);
disconnect = vi.fn();
send = vi.fn();
signal(path: string, body: unknown[], sender = ":1.2") {
this.emit(
"message",
new Message({
type: MessageType.SIGNAL,
sender,
path,
interface: "org.freedesktop.portal.Request",
member: "Response",
body,
}),
);
}
async call(message: Message) {
this.calls.push(message);
const reply = (body: unknown[]) =>
new Message({
type: MessageType.METHOD_RETURN,
replySerial: "1",
destination: ":1.23",
body,
});
switch (message.member) {
case "Register":
if (this.registryError) throw this.registryError;
return reply([]);
case "GetAll":
if (message.destination === "org.kde.KWin.ScreenShot2") {
if (this.kdeError) throw this.kdeError;
if (this.kdeVersion === undefined)
throw new DBusError("org.freedesktop.DBus.Error.ServiceUnknown", "Absent");
return reply([{ Version: new Variant("u", this.kdeVersion) }]);
}
if (message.destination === "org.freedesktop.portal.Desktop")
return reply([
{
version: new Variant("u", this.portalVersion),
...(this.targets === undefined
? {}
: { AvailableTargets: new Variant("u", this.targets) }),
},
]);
if (this.extensionVersion === undefined)
throw new DBusError("org.freedesktop.DBus.Error.ServiceUnknown", "Absent");
return reply([{ Version: new Variant("u", this.extensionVersion) }]);
case "GetNameOwner":
return reply([":1.2"]);
case "AddMatch":
return reply([]);
case "Screenshot": {
if (this.screenshotError) throw this.screenshotError;
const options = message.body[1] as Record<string, Variant<unknown>>;
const handle = `/org/freedesktop/portal/desktop/request/1_23/${this.differentHandle ? "actual" : options.handle_token?.value}`;
if (this.sendResponse)
this.signal(
handle,
[this.status, { uri: new Variant("s", this.uri) }],
this.wrongSender ? ":1.99" : ":1.2",
);
return reply([handle]);
}
case "Capture":
if (this.extensionError) throw this.extensionError;
return reply([png, JSON.stringify(metadata)]);
case "CaptureWithFeedback":
return reply([png, JSON.stringify(metadata), message.body[1]]);
case "Activate":
if (this.activationError) throw this.activationError;
return reply([]);
case "Animate":
await this.animation;
return reply([]);
default:
throw new Error(`Unexpected method ${message.member}`);
}
}
}
let bus: FakeBus;
let directory: string;
beforeEach(async () => {
bus = new FakeBus();
connect.mockImplementation(() => bus as unknown as MessageBus);
directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-portal-test-"));
bus.uri = NodeURL.pathToFileURL(NodePath.join(directory, "image.png")).href;
await NodeFSP.writeFile(NodePath.join(directory, "image.png"), png);
imageSize.width = 800;
imageSize.height = 600;
vi.stubEnv("FLATPAK_ID", "");
vi.stubEnv("SNAP", "");
vi.stubEnv("NIRI_SOCKET", "");
vi.stubEnv("XDG_CURRENT_DESKTOP", "GNOME");
});
it("uses native KWin only in an unsandboxed KDE session", async () => {
vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE");
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("kde");
vi.stubEnv("FLATPAK_ID", "com.example.App");
expect((await getLinuxCaptureSupport(appId)).linuxBackend).not.toBe("kde");
});
it("redetects the desktop without using another session's extension or stale Niri socket", async () => {
bus.portalVersion = 2;
bus.extensionVersion = 2;
vi.stubEnv("NIRI_SOCKET", "/previous-session/niri.sock");
expect(await getLinuxCaptureSupport(appId)).toEqual({
linuxBackend: "gnome-extension",
linuxFeedbackAvailable: true,
});
vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE");
expect(await getLinuxCaptureSupport(appId)).toEqual({
linuxBackend: "kde",
linuxFeedbackAvailable: false,
});
bus.kdeVersion = undefined;
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("picker");
vi.stubEnv("XDG_CURRENT_DESKTOP", "GNOME");
expect(await getLinuxCaptureSupport(appId)).toEqual({
linuxBackend: "gnome-extension",
linuxFeedbackAvailable: true,
});
});
it("uses the standard path when KWin's native capability is missing, but not when denied", async () => {
vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE");
bus.kdeVersion = undefined;
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("screenshot-portal");
bus.kdeVersion = 1;
bus.portalVersion = 2;
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("picker");
bus.kdeError = new DBusError("org.freedesktop.DBus.Error.AccessDenied", "Denied");
await expect(getLinuxCaptureSupport(appId)).rejects.toThrow("Denied");
});
it("does not fall through to the picker when KDE needs helper setup", async () => {
vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE");
await expect(captureLinuxWindow(appId)).rejects.toThrow("KDE capture setup");
expect(bus.calls.some((call) => call.member === "Screenshot")).toBe(false);
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it("selects Hyprland without probing a different desktop or falling back on missing setup", async () => {
vi.stubEnv("XDG_CURRENT_DESKTOP", "Hyprland");
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("hyprland");
await expect(captureLinuxWindow(appId)).rejects.toThrow("Hyprland capture setup");
expect(bus.calls).toEqual([]);
});
afterEach(async () => {
vi.useRealTimers();
vi.unstubAllEnvs();
await NodeFSP.rm(directory, { recursive: true });
});
it.each([
[2, 8, 1, "gnome-extension"],
[3, undefined, 1, "gnome-extension"],
[3, 7, undefined, "picker"],
[3, 8, 1, "screenshot-portal"],
[4, 15, undefined, "screenshot-portal"],
[2, undefined, 2, "gnome-extension"],
[2, undefined, 99, "picker"],
] as const)(
"selects capabilities v%s / targets %s / extension %s",
async (version, targets, extension, expected) => {
bus.portalVersion = version;
bus.targets = targets;
bus.extensionVersion = extension;
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe(expected);
expect(bus.calls[0]?.member).toBe("Register");
expect(bus.disconnect).toHaveBeenCalledOnce();
},
);
it.each([1, 2])(
"reports feedback separately from capture support for extension v%s",
async (version) => {
bus.portalVersion = 2;
bus.extensionVersion = version;
expect(await getLinuxCaptureSupport(appId)).toEqual({
linuxBackend: "gnome-extension",
linuxFeedbackAvailable: version === 2,
});
},
);
it("retains the authenticated connection until the compositor flight has landed", async () => {
bus.portalVersion = 2;
bus.extensionVersion = 2;
const snapshot = await captureLinuxWindow(appId, { flash: false, animate: true });
const feedback = snapshot!.feedback!;
expect(snapshot).toMatchObject({ png, window: metadata, feedback: { animationStarted: true } });
expect(bus.disconnect).not.toHaveBeenCalled();
await feedback.activate("T3 Code");
const landed = Promise.withResolvers<void>();
bus.animation = landed.promise;
const flight = feedback.animateTo({ x: 0.1, y: 0.8, width: 0.2, height: 0.1 });
const complete = feedback.complete();
expect(bus.disconnect).not.toHaveBeenCalled();
landed.resolve();
await Promise.all([flight, complete]);
expect(
bus.calls
.filter((call) => ["CaptureWithFeedback", "Activate", "Animate"].includes(call.member))
.map((call) => call.body),
).toEqual([[false, true], ["T3 Code"], [0.1, 0.8, 0.2, 0.1]]);
expect(bus.disconnect).toHaveBeenCalledOnce();
feedback.close();
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it("keeps capture working with v1 and does not request unavailable effects", async () => {
bus.portalVersion = 2;
bus.extensionVersion = 1;
expect(await captureLinuxWindow(appId, { flash: true, animate: true })).toEqual({
png,
window: metadata,
});
expect(bus.calls.some((call) => call.member === "CaptureWithFeedback")).toBe(false);
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it("can activate without animation, and expires a renderer-abandoned capture", async () => {
vi.useFakeTimers();
bus.portalVersion = 2;
bus.extensionVersion = 2;
const snapshot = await captureLinuxWindow(appId, { flash: false, animate: false });
expect(snapshot!.feedback!.animationStarted).toBe(false);
bus.activationError = new Error("No window");
await expect(snapshot!.feedback!.activate("T3 Code")).rejects.toThrow("No window");
expect(snapshot!.png).toEqual(png);
await vi.advanceTimersByTimeAsync(15_000);
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it.each([false, true])(
"accepts an early Response with a changed request path: %s",
async (differentHandle) => {
bus.differentHandle = differentHandle;
expect(await captureLinuxWindow(appId)).toEqual({ png });
const screenshot = bus.calls.find((call) => call.member === "Screenshot");
expect(screenshot?.body[1]).toMatchObject({
target: { signature: "u", value: 8 },
interactive: { value: false },
});
expect(bus.calls.findIndex((call) => call.member === "AddMatch")).toBeLessThan(
bus.calls.indexOf(screenshot!),
);
expect(bus.listenerCount("message")).toBe(0);
expect(bus.disconnect).toHaveBeenCalledOnce();
},
);
it.each([1, 2])(
"does not try the extension or picker after portal rejection %s",
async (status) => {
bus.extensionVersion = 1;
bus.status = status;
await expect(captureLinuxWindow(appId)).rejects.toThrow(
status === 1 ? "cancelled" : "did not allow",
);
expect(bus.calls.some((call) => call.member === "Capture")).toBe(false);
expect(bus.disconnect).toHaveBeenCalledOnce();
},
);
it("does not downgrade a failed screenshot request", async () => {
bus.screenshotError = new DBusError("org.freedesktop.DBus.Error.AccessDenied", "Denied");
await expect(captureLinuxWindow(appId)).rejects.toThrow("Denied");
expect(bus.send).toHaveBeenCalledWith(expect.objectContaining({ member: "Close" }));
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it.each([false, true])(
"times out and closes requests, ignoring forged responses: %s",
async (wrongSender) => {
vi.useFakeTimers();
bus.sendResponse = wrongSender;
bus.wrongSender = wrongSender;
const capture = expect(captureLinuxWindow(appId)).rejects.toThrow("timed out");
await vi.advanceTimersByTimeAsync(120_001);
await capture;
expect(bus.send).toHaveBeenCalledWith(expect.objectContaining({ member: "Close" }));
expect(bus.listenerCount("message")).toBe(0);
expect(bus.disconnect).toHaveBeenCalledOnce();
},
);
it("uses the GNOME extension and preserves its window identity", async () => {
bus.portalVersion = 2;
bus.extensionVersion = 1;
expect(await captureLinuxWindow(appId)).toEqual({ png, window: metadata });
expect(bus.requestName).toHaveBeenCalledWith(`${appId}.SnapShot`, expect.any(Number));
expect(bus.calls.some((call) => call.member === "Screenshot")).toBe(false);
});
it("fails instead of opening a picker after an extension denial", async () => {
bus.portalVersion = 2;
bus.extensionVersion = 1;
bus.extensionError = new Error("Locked session");
await expect(captureLinuxWindow(appId)).rejects.toThrow("Locked session");
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it("allows the picker only when both automatic backends are absent", async () => {
bus.portalVersion = 2;
expect(await captureLinuxWindow(appId)).toBeUndefined();
expect(bus.calls.some((call) => call.member === "Screenshot" || call.member === "Capture")).toBe(
false,
);
});
it("tolerates an older portal without Registry, but not registration denial", async () => {
bus.registryError = new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "Old portal");
expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("screenshot-portal");
bus.registryError = new DBusError("org.freedesktop.DBus.Error.AccessDenied", "Denied identity");
await expect(getLinuxCaptureSupport(appId)).rejects.toThrow("Denied identity");
});
it("does not register a host identity from inside a sandbox", async () => {
vi.stubEnv("FLATPAK_ID", appId);
await getLinuxCaptureSupport(appId);
expect(bus.calls.some((call) => call.member === "Register")).toBe(false);
});
it("reads only local PNG files without removing the portal file", async () => {
expect(await readPortalPng(bus.uri)).toEqual(png);
expect(await readPortalPng(bus.uri)).toEqual(png);
await expect(readPortalPng("https://example.com/image.png")).rejects.toThrow();
await expect(readPortalPng("file://remote/image.png")).rejects.toThrow();
await NodeFSP.writeFile(NodePath.join(directory, "image.png"), "not a PNG");
await expect(readPortalPng(bus.uri)).rejects.toThrow("Invalid");
});
it("bounds large images without distorting their aspect ratio", () => {
imageSize.width = 4000;
imageSize.height = 2000;
resizeLinuxCapture(png);
expect(resize).toHaveBeenLastCalledWith({ width: 2560, height: 1280, quality: "best" });
});
+422
View File
@@ -0,0 +1,422 @@
// @effect-diagnostics globalTimers:off -- D-Bus deadlines run at a native async boundary.
// @effect-diagnostics nodeBuiltinImport:off -- Read the portal file through one bounded file descriptor at the native adapter boundary.
import * as NodeCrypto from "node:crypto";
import {
DBusError,
Message,
MessageFlag,
MessageType,
NameFlag,
RequestNameReply,
Variant,
sessionBus,
type MessageBus,
type MessageLike,
} from "dbus-next";
import * as Schema from "effect/Schema";
import { isKdeCaptureSession, type KdeCapturePaths } from "./KdeSnapShot.ts";
import { isGnomeCaptureSession, readPortalPng, resizeLinuxCapture } from "./linuxCaptureSession.ts";
export { readPortalPng, resizeLinuxCapture } from "./linuxCaptureSession.ts";
import { isHyprlandCaptureSession, type HyprlandCapturePaths } from "./HyprlandSnapShot.ts";
const PORTAL = "org.freedesktop.portal.Desktop";
const PORTAL_PATH = "/org/freedesktop/portal/desktop";
const SCREENSHOT = "org.freedesktop.portal.Screenshot";
const REQUEST = "org.freedesktop.portal.Request";
const EXTENSION = "org.gnome.Shell.Extensions.T3SnapShot";
const EXTENSION_PATH = "/org/gnome/Shell/Extensions/T3SnapShot";
const DBUS = "org.freedesktop.DBus";
const DBUS_PATH = "/org/freedesktop/DBus";
const UInt = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 0xffff_ffff }));
const UIntVariant = Schema.Struct({ signature: Schema.Literal("u"), value: UInt });
const StringVariant = Schema.Struct({ signature: Schema.Literal("s"), value: Schema.String });
const PortalProperties = Schema.Struct({
version: UIntVariant,
AvailableTargets: Schema.optional(UIntVariant),
});
const WindowMetadata = Schema.Struct({
title: Schema.String,
appName: Schema.String,
appIdentifier: Schema.String,
processId: UInt,
bounds: Schema.Struct({
x: Schema.Int,
y: Schema.Int,
width: Schema.Int.check(Schema.isGreaterThan(0)),
height: Schema.Int.check(Schema.isGreaterThan(0)),
}),
});
export type LinuxWindowMetadata = typeof WindowMetadata.Type & {
readonly clientBounds?: typeof WindowMetadata.Type.bounds;
readonly accessibilityBoundsReliable?: boolean;
};
const decodeProperties = Schema.decodeUnknownSync(PortalProperties);
const decodeExtension = Schema.decodeUnknownSync(Schema.Struct({ Version: UIntVariant }));
const decodeKde = Schema.decodeUnknownSync(Schema.Struct({ Version: UIntVariant }));
const decodeString = Schema.decodeUnknownSync(Schema.String);
const decodeBoolean = Schema.decodeUnknownSync(Schema.Boolean);
const decodeResponse = Schema.decodeUnknownSync(
Schema.Tuple([UInt, Schema.Record(Schema.String, Schema.Unknown)]),
);
const decodeUri = Schema.decodeUnknownSync(StringVariant);
const decodeWindow = Schema.decodeUnknownSync(Schema.fromJsonString(WindowMetadata));
export type LinuxCaptureBackend =
| "screenshot-portal"
| "gnome-extension"
| "niri"
| "kde"
| "hyprland"
| "picker";
export type LinuxWindowSnapshot = {
readonly png: Buffer;
readonly window?: LinuxWindowMetadata;
readonly feedback?: LinuxCaptureFeedback;
};
export type LinuxCaptureFeedback = {
readonly animationStarted: boolean;
readonly activate: (title: string) => Promise<void>;
readonly animateTo: (frame: {
x: number;
y: number;
width: number;
height: number;
}) => Promise<void>;
readonly complete: () => Promise<void>;
readonly close: () => void;
};
type FeedbackOptions = { readonly flash: boolean; readonly animate: boolean };
function unavailable(error: unknown): boolean {
return (
error instanceof DBusError &&
["ServiceUnknown", "NameHasNoOwner", "UnknownObject", "UnknownInterface", "UnknownMethod"].some(
(name) => error.type === `${DBUS}.Error.${name}`,
)
);
}
/** One connection per operation: portal registration and request ownership stay together. */
export class LinuxCaptureConnection {
private readonly bus: MessageBus;
private readonly disconnected: Promise<never>;
private uniqueName = "";
private extensionVersion = 0;
private closed = false;
private feedbackTimer: ReturnType<typeof setTimeout> | undefined;
get feedbackAvailable() {
return this.extensionVersion === 2;
}
constructor(bus = sessionBus()) {
this.bus = bus;
this.disconnected = new Promise((_, reject) => {
bus.on("error", reject);
});
// A disconnect between calls must not become an unhandled rejection.
void this.disconnected.catch(() => undefined);
}
close() {
if (this.closed) return;
this.closed = true;
clearTimeout(this.feedbackTimer);
this.bus.disconnect();
}
private async wait<T>(pending: Promise<T>, timeoutMs = 5_000): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
pending,
this.disconnected,
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error("Snapshot timed out.")), timeoutMs);
}),
]);
} finally {
clearTimeout(timer);
}
}
private async call(message: MessageLike) {
const reply = await this.wait(this.bus.call(new Message(message)));
if (!reply) throw new Error("Missing D-Bus reply.");
this.uniqueName = reply.destination;
return reply;
}
private async properties(destination: string, path: string, iface: string) {
const reply = await this.call({
destination,
path,
interface: "org.freedesktop.DBus.Properties",
member: "GetAll",
signature: "s",
body: [iface],
});
return reply.body[0] as unknown;
}
async backend(appId: string): Promise<LinuxCaptureBackend> {
if (isKdeCaptureSession()) {
const kde = await this.properties(
"org.kde.KWin.ScreenShot2",
"/org/kde/KWin/ScreenShot2",
"org.kde.KWin.ScreenShot2",
).catch((error: unknown) => {
if (!unavailable(error)) throw error;
return undefined;
});
if (kde !== undefined && decodeKde(kde).Version.value >= 2) return "kde";
}
// Sandboxed apps already have an identity. Host apps register before any portal calls.
if (!process.env.FLATPAK_ID && !process.env.SNAP) {
await this.call({
destination: PORTAL,
path: PORTAL_PATH,
interface: "org.freedesktop.host.portal.Registry",
member: "Register",
signature: "sa{sv}",
body: [appId, {}],
}).catch((error: unknown) => {
if (!unavailable(error)) throw error;
});
}
const properties = await this.properties(PORTAL, PORTAL_PATH, SCREENSHOT).catch(
(error: unknown) => {
if (!unavailable(error)) throw error;
return undefined;
},
);
if (properties !== undefined) {
const parsed = decodeProperties(properties);
if (parsed.version.value >= 3 && ((parsed.AvailableTargets?.value ?? 0) & 8) !== 0) {
return "screenshot-portal";
}
}
if (!isGnomeCaptureSession(process.env)) return "picker";
const extension = await this.properties(EXTENSION, EXTENSION_PATH, EXTENSION).catch(
(error: unknown) => {
if (!unavailable(error)) throw error;
return undefined;
},
);
if (extension !== undefined) {
const parsed = decodeExtension(extension);
this.extensionVersion = parsed.Version.value;
if (this.extensionVersion === 1 || this.extensionVersion === 2) return "gnome-extension";
}
return "picker";
}
async capturePortal(): Promise<LinuxWindowSnapshot> {
const owner = await this.call({
destination: DBUS,
path: DBUS_PATH,
interface: DBUS,
member: "GetNameOwner",
signature: "s",
body: [PORTAL],
});
const sender = decodeString(owner.body[0]);
const token = `t3_${NodeCrypto.randomUUID().replaceAll("-", "")}`;
const namespace = `${PORTAL_PATH}/request/${this.uniqueName.slice(1).replaceAll(".", "_")}/`;
let handle = namespace + token;
let completed = false;
// Subscribe before Screenshot: the response may precede its method reply.
const responses = new Map<string, unknown>();
let deliver: ((body: unknown) => void) | undefined;
const listener = (message: Message) => {
if (
message.type !== MessageType.SIGNAL ||
message.sender !== sender ||
message.interface !== REQUEST ||
message.member !== "Response" ||
!message.path.startsWith(namespace)
)
return;
if (deliver && message.path === handle) deliver(message.body);
else if (responses.size < 8) responses.set(message.path, message.body);
};
this.bus.on("message", listener);
try {
await this.call({
destination: DBUS,
path: DBUS_PATH,
interface: DBUS,
member: "AddMatch",
signature: "s",
body: [
`type='signal',sender='${sender}',interface='${REQUEST}',member='Response',path_namespace='${namespace.slice(0, -1)}'`,
],
});
const reply = await this.call({
destination: sender,
path: PORTAL_PATH,
interface: SCREENSHOT,
member: "Screenshot",
signature: "sa{sv}",
body: [
"",
{
handle_token: new Variant("s", token),
interactive: new Variant("b", false),
modal: new Variant("b", false),
target: new Variant("u", 8),
},
],
});
handle = decodeString(reply.body[0]);
if (!handle.startsWith(namespace)) throw new Error("Invalid screenshot request handle.");
const body = await this.wait(
new Promise<unknown>((resolve) => {
deliver = resolve;
if (responses.has(handle)) resolve(responses.get(handle));
}),
120_000,
);
const [status, results] = decodeResponse(body);
completed = true;
if (status === 1) throw new Error("Snapshot was cancelled.");
if (status !== 0) throw new Error("Your desktop did not allow the snapshot.");
const uri = decodeUri(results.uri).value;
return { png: await readPortalPng(uri) };
} finally {
this.bus.removeListener("message", listener);
if (!completed) {
this.bus.send(
new Message({
destination: sender,
path: handle,
interface: REQUEST,
member: "Close",
flags: MessageFlag.NO_REPLY_EXPECTED,
}),
);
}
// Closing this dedicated connection also removes the signal match.
}
}
async captureExtension(appId: string, options?: FeedbackOptions): Promise<LinuxWindowSnapshot> {
const result = await this.wait(
this.bus.requestName(`${appId}.SnapShot`, NameFlag.DO_NOT_QUEUE),
);
if (result !== RequestNameReply.PRIMARY_OWNER) {
throw new Error("Another T3 Code instance is capturing a window. Try again.");
}
const withFeedback = this.feedbackAvailable && options !== undefined;
const reply = await this.call({
destination: EXTENSION,
path: EXTENSION_PATH,
interface: EXTENSION,
member: withFeedback ? "CaptureWithFeedback" : "Capture",
...(withFeedback ? { signature: "bb", body: [options.flash, options.animate] } : {}),
});
const bytes: unknown = reply.body[0];
if (!(bytes instanceof Uint8Array)) throw new Error("Invalid extension screenshot.");
const window = decodeWindow(reply.body[1]);
const png = resizeLinuxCapture(Buffer.from(bytes));
if (!withFeedback) return { png, window };
const animationStarted = decodeBoolean(reply.body[2]);
// Keep the same authenticated sender alive through activation and the compositor flight.
this.feedbackTimer = setTimeout(() => this.close(), 15_000);
let flight: Promise<void> | undefined;
const feedback: LinuxCaptureFeedback = {
animationStarted,
activate: async (title) => {
await this.feedbackCall("Activate", "s", [title]);
},
animateTo: (frame) => {
flight ??= this.feedbackCall("Animate", "dddd", [
frame.x,
frame.y,
frame.width,
frame.height,
]);
return flight;
},
complete: async () => {
try {
await flight;
} finally {
this.close();
}
},
close: () => this.close(),
};
return { png, window, feedback };
}
private async feedbackCall(member: string, signature: string, body: unknown[]): Promise<void> {
if (this.closed) return;
await this.call({
destination: EXTENSION,
path: EXTENSION_PATH,
interface: EXTENSION,
member,
signature,
body,
});
}
}
export async function getLinuxCaptureSupport(appId: string) {
if (isHyprlandCaptureSession())
return { linuxBackend: "hyprland" as const, linuxFeedbackAvailable: false };
const { niriSocketPath, checkNiriCaptureSupport } = await import("./NiriSnapShot.ts");
const niri = niriSocketPath();
if (niri) {
await checkNiriCaptureSupport(niri);
return { linuxBackend: "niri" as const, linuxFeedbackAvailable: false };
}
const connection = new LinuxCaptureConnection();
try {
const linuxBackend = await connection.backend(appId);
return { linuxBackend, linuxFeedbackAvailable: connection.feedbackAvailable };
} finally {
connection.close();
}
}
/** Undefined means capability missing, not denied: only that case may open the picker. */
export async function captureLinuxWindow(
appId: string,
options?: FeedbackOptions,
kdePaths?: KdeCapturePaths,
hyprlandPaths?: HyprlandCapturePaths,
): Promise<LinuxWindowSnapshot | undefined> {
if (isHyprlandCaptureSession()) {
if (!hyprlandPaths) throw new Error("Hyprland capture setup is unavailable in this build.");
const { captureHyprlandWindow } = await import("./HyprlandSnapShot.ts");
return captureHyprlandWindow(hyprlandPaths, options);
}
const { niriSocketPath, captureNiriWindow } = await import("./NiriSnapShot.ts");
const niri = niriSocketPath();
if (niri) return captureNiriWindow(niri);
const connection = new LinuxCaptureConnection();
let retained = false;
try {
switch (await connection.backend(appId)) {
case "kde": {
if (!kdePaths) throw new Error("KDE capture setup is unavailable in this build.");
const { captureKdeWindow } = await import("./KdeSnapShot.ts");
return await captureKdeWindow(kdePaths, options);
}
case "screenshot-portal":
return await connection.capturePortal();
case "gnome-extension": {
const snapshot = await connection.captureExtension(appId, options);
retained = snapshot.feedback !== undefined;
return snapshot;
}
case "picker":
return undefined;
}
} finally {
if (!retained) connection.close();
}
}
@@ -0,0 +1,93 @@
import { describe, expect, it, vi } from "vite-plus/test";
const { spawnedPollers } = vi.hoisted(() => ({
spawnedPollers: [] as Array<{
command: string;
args: ReadonlyArray<string>;
kill: ReturnType<typeof vi.fn>;
emitStderr: (text: string) => void;
emitExit: (code: number) => void;
}>,
}));
vi.mock("node:child_process", () => ({
spawn: (command: string, args: ReadonlyArray<string>) => {
const stderrListeners: Array<(chunk: Buffer) => void> = [];
const onceListeners = new Map<string, Array<(value?: unknown) => void>>();
const record = {
command,
args,
kill: vi.fn(() => true),
emitStderr: (text: string) => {
for (const listener of stderrListeners) listener(Buffer.from(text));
},
emitExit: (code: number) => {
for (const listener of onceListeners.get("exit") ?? []) listener(code);
},
};
spawnedPollers.push(record);
const child = {
stderr: {
on: (_event: "data", listener: (chunk: Buffer) => void) => {
stderrListeners.push(listener);
return child;
},
},
once: (event: string, listener: (value?: unknown) => void) => {
onceListeners.set(event, [...(onceListeners.get(event) ?? []), listener]);
return child;
},
kill: record.kill,
};
return child;
},
}));
import { startMacModifierPairShortcutProcess } from "./MacModifierPairShortcutProcess.ts";
describe("macOS modifier pair poller", () => {
it("resolves on ready, triggers on lines, and kills on stop", async () => {
spawnedPollers.length = 0;
const onTrigger = vi.fn();
const onFailure = vi.fn();
const started = startMacModifierPairShortcutProcess("meta", onTrigger, onFailure);
const poller = spawnedPollers[0]!;
expect(poller.command).toBe("/usr/bin/osascript");
expect(poller.args.slice(-2)).toEqual(["8", "16"]);
poller.emitStderr("ready\ntrig");
const stop = await started;
poller.emitStderr("ger\ntrigger\n");
expect(onTrigger).toHaveBeenCalledTimes(2);
stop();
expect(poller.kill).toHaveBeenCalledOnce();
poller.emitStderr("trigger\n");
expect(onTrigger).toHaveBeenCalledTimes(2);
poller.emitExit(0);
expect(onFailure).not.toHaveBeenCalled();
});
it("reports an unexpected exit after startup", async () => {
spawnedPollers.length = 0;
const onFailure = vi.fn();
const started = startMacModifierPairShortcutProcess("shift", () => undefined, onFailure);
const poller = spawnedPollers[0]!;
poller.emitStderr("ready\n");
await started;
poller.emitExit(1);
expect(onFailure).toHaveBeenCalledOnce();
});
it("rejects when the poller dies before it is ready", async () => {
spawnedPollers.length = 0;
const started = startMacModifierPairShortcutProcess(
"control",
() => undefined,
() => undefined,
);
spawnedPollers[0]!.emitExit(1);
await expect(started).rejects.toThrow(/exited with code 1/);
});
});
@@ -0,0 +1,89 @@
// @effect-diagnostics nodeBuiltinImport:off -- This macOS platform boundary spawns the native modifier-key poller with Node.
import * as NodeChildProcess from "node:child_process";
import type { SnapShotModifier } from "@t3tools/contracts";
const MAC_MODIFIER_PAIR_DEVICE_MASKS: Record<SnapShotModifier, readonly [number, number]> = {
shift: [0x2, 0x4],
control: [0x1, 0x2000],
alt: [0x20, 0x40],
meta: [0x8, 0x10],
};
const POLLER_SCRIPT = `
ObjC.import("CoreGraphics");
ObjC.import("unistd");
function run(argv) {
const left = Number(argv[0]);
const right = Number(argv[1]);
const both = left | right;
let active = false;
console.log("ready");
while ($.getppid() !== 1) {
const pressed = ($.CGEventSourceFlagsState(0) & both) === both;
if (pressed && !active) console.log("trigger");
active = pressed;
delay(0.05);
}
return "orphaned";
}`;
export function startMacModifierPairShortcutProcess(
modifier: SnapShotModifier,
onTrigger: () => void,
onFailure: (error: Error) => void,
): Promise<() => void> {
const [left, right] = MAC_MODIFIER_PAIR_DEVICE_MASKS[modifier];
const poller = NodeChildProcess.spawn(
"/usr/bin/osascript",
["-l", "JavaScript", "-e", POLLER_SCRIPT, String(left), String(right)],
{ stdio: ["ignore", "ignore", "pipe"] },
);
return new Promise((resolve, reject) => {
let settled = false;
let stopped = false;
let buffered = "";
const stop = () => {
if (stopped) return;
stopped = true;
poller.kill();
};
const fail = (error: Error) => {
if (stopped) return;
if (settled) {
stop();
onFailure(error);
return;
}
settled = true;
stop();
reject(error);
};
poller.stderr.on("data", (chunk: Buffer) => {
buffered += chunk.toString();
const lines = buffered.split("\n");
buffered = lines.pop() ?? "";
for (const line of lines) {
const message = line.trim();
if (message === "ready" && !settled) {
settled = true;
resolve(stop);
continue;
}
if (message !== "trigger" || !settled || stopped) continue;
try {
onTrigger();
} catch {}
}
});
poller.once("error", (error) => {
fail(error);
});
poller.once("exit", (code) => {
fail(new Error(`Snapshot shortcut helper exited with code ${code}`));
});
});
}
@@ -0,0 +1,103 @@
import { assert, beforeEach, expect, it, vi } from "vite-plus/test";
const { createFromBufferMock, execFileMock, readFileMock, writeFileMock } = vi.hoisted(() => ({
createFromBufferMock: vi.fn(),
execFileMock: vi.fn(),
readFileMock: vi.fn(),
writeFileMock: vi.fn(),
}));
vi.mock("node:child_process", () => ({ execFile: execFileMock }));
vi.mock("node:fs/promises", () => ({ readFile: readFileMock, writeFile: writeFileMock }));
vi.mock("electron", () => ({ nativeImage: { createFromBuffer: createFromBufferMock } }));
import { captureMacWindowSnapshot, macSnapShotArguments } from "./MacSnapShot.ts";
beforeEach(() => {
execFileMock
.mockReset()
.mockImplementation(
(
_path: string,
_args: ReadonlyArray<string>,
_options: { readonly timeout: number },
callback: (error: Error | null) => void,
) => callback(null),
);
readFileMock.mockReset();
writeFileMock.mockReset();
createFromBufferMock.mockReset().mockReturnValue({
getSize: () => ({ width: 100, height: 80 }),
isEmpty: () => false,
});
});
it("captures one macOS window directly as a silent shadowless PNG", async () => {
const png = Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
Buffer.from("image"),
]);
readFileMock.mockResolvedValue(png);
const active = {
id: 42,
title: "Editor",
owner: { name: "Code" },
} as Parameters<typeof captureMacWindowSnapshot>[0];
const capture = await captureMacWindowSnapshot(active, "/tmp/window.png", {
width: 100,
height: 80,
});
assert.deepEqual(execFileMock.mock.calls[0]?.slice(0, 3), [
"/usr/sbin/screencapture",
macSnapShotArguments(42, "/tmp/window.png"),
{ timeout: 15_000 },
]);
assert.deepEqual(readFileMock.mock.calls, [["/tmp/window.png"]]);
assert.lengthOf(writeFileMock.mock.calls, 0);
assert.strictEqual(capture.png, png);
assert.deepEqual(capture.source, { name: "Editor" });
});
it("bounds Retina captures without changing their aspect ratio", async () => {
const capturedPng = Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
Buffer.from("retina"),
]);
const resizedPng = Buffer.from("bounded png");
const resizeMock = vi.fn().mockReturnValue({ toPNG: () => resizedPng });
readFileMock.mockResolvedValue(capturedPng);
createFromBufferMock.mockReturnValue({
getSize: () => ({ width: 2_000, height: 1_200 }),
isEmpty: () => false,
resize: resizeMock,
});
const active = {
id: 42,
title: "Editor",
owner: { name: "Code" },
} as Parameters<typeof captureMacWindowSnapshot>[0];
const capture = await captureMacWindowSnapshot(active, "/tmp/window.png", {
width: 1_000,
height: 1_000,
});
assert.deepEqual(resizeMock.mock.calls, [[{ width: 1_000, height: 600, quality: "best" }]]);
assert.deepEqual(writeFileMock.mock.calls, [["/tmp/window.png", resizedPng]]);
assert.strictEqual(capture.png, resizedPng);
});
it("rejects a successful command that did not produce a PNG", async () => {
readFileMock.mockResolvedValue(Buffer.from("not a png"));
const active = {
id: 42,
title: "",
owner: { name: "Code" },
} as Parameters<typeof captureMacWindowSnapshot>[0];
await expect(
captureMacWindowSnapshot(active, "/tmp/window.png", { width: 100, height: 80 }),
).rejects.toThrow("macOS returned an invalid snapshot.");
});
+70
View File
@@ -0,0 +1,70 @@
// @effect-diagnostics nodeBuiltinImport:off -- This macOS platform boundary spawns native capture tools and reads their temporary output with Node.
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as Electron from "electron";
import type { ActiveWindow } from "./ActiveWindow.ts";
const MAC_SCREEN_CAPTURE_PATH = "/usr/sbin/screencapture";
const MAC_SCREEN_CAPTURE_TIMEOUT_MS = 15_000;
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
export type MacSnapShotSource = {
readonly appIcon?: Electron.NativeImage;
readonly name: string;
};
export function macSnapShotArguments(windowId: number, outputPath: string): string[] {
return ["-l", String(windowId), "-o", "-x", "-t", "png", outputPath];
}
function runMacSnapShot(windowId: number, outputPath: string): Promise<void> {
return new Promise((resolve, reject) => {
NodeChildProcess.execFile(
MAC_SCREEN_CAPTURE_PATH,
macSnapShotArguments(windowId, outputPath),
{ timeout: MAC_SCREEN_CAPTURE_TIMEOUT_MS },
(error) => {
if (error) reject(error);
else resolve();
},
);
});
}
export async function captureMacWindowSnapshot(
active: ActiveWindow,
outputPath: string,
maxSize: Electron.Size,
): Promise<{ readonly source: MacSnapShotSource; readonly png: Buffer }> {
await runMacSnapShot(active.id, outputPath);
const capturedPng = await NodeFSP.readFile(outputPath);
if (
capturedPng.length < PNG_SIGNATURE.length ||
!capturedPng.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)
) {
throw new Error("macOS returned an invalid snapshot.");
}
const image = Electron.nativeImage.createFromBuffer(capturedPng);
if (image.isEmpty()) throw new Error("macOS returned an invalid snapshot.");
const size = image.getSize();
const scale = Math.min(maxSize.width / size.width, maxSize.height / size.height, 1);
const png =
scale < 1
? image
.resize({
width: Math.max(1, Math.round(size.width * scale)),
height: Math.max(1, Math.round(size.height * scale)),
quality: "best",
})
.toPNG()
: capturedPng;
if (png !== capturedPng) await NodeFSP.writeFile(outputPath, png);
return {
source: {
name: active.title.trim() || active.owner.name.trim() || "Window",
},
png,
};
}
@@ -0,0 +1,112 @@
// @effect-diagnostics nodeBuiltinImport:off -- Isolated child-process streams; no desktop session is touched.
import * as NodeEvents from "node:events";
import * as NodeStream from "node:stream";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const spawn = vi.hoisted(() => vi.fn());
vi.mock("node:child_process", () => ({ spawn }));
import { startNativeCaptureFeedback } from "./NativeCaptureFeedback.ts";
const options = {
bounds: { x: -800, y: 0, width: 800, height: 600 },
pid: 123,
flash: true,
animate: true,
};
let child: NodeEvents.EventEmitter & {
stdin: NodeStream.PassThrough;
stdout: NodeStream.PassThrough;
kill: ReturnType<typeof vi.fn>;
};
let commands: string[];
beforeEach(() => {
vi.useFakeTimers();
commands = [];
child = Object.assign(new NodeEvents.EventEmitter(), {
stdin: new NodeStream.PassThrough(),
stdout: new NodeStream.PassThrough(),
kill: vi.fn(),
});
child.stdin.on("data", (value: Buffer) => commands.push(value.toString()));
spawn.mockReturnValue(child);
});
afterEach(() => {
child.emit("close");
vi.useRealTimers();
});
function event(value: unknown) {
child.stdout.write(`${JSON.stringify(value)}\n`);
}
it("waits for compositor readiness and landing, then waits for cleanup on acknowledgement", async () => {
const starting = startNativeCaptureFeedback("/helper", "/private", options);
let ready = false;
void starting.then(() => {
ready = true;
});
await Promise.resolve();
expect(ready).toBe(false);
event({ event: "ready", animate: true });
const feedback = (await starting)!;
expect(feedback.animationStarted).toBe(true);
const frame = { x: 0.1, y: 0.7, width: 0.2, height: 0.1 };
const flight = feedback.animateTo('My "Draft"', frame);
let completed = false;
const complete = feedback.complete().then(() => {
completed = true;
});
expect(commands.map((line) => JSON.parse(line))).toEqual([
{ command: "animate", title: 'My "Draft"', frame },
]);
event({ event: "landed" });
await flight;
expect(commands.map((line) => JSON.parse(line))).toHaveLength(2);
expect(completed).toBe(false);
child.emit("close");
await complete;
expect(completed).toBe(true);
expect(child.kill).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
});
it("doesn't claim a flight when the compositor disables motion; flash still works", async () => {
const starting = startNativeCaptureFeedback("/helper", "/private", options);
event({ event: "ready", animate: false });
const feedback = (await starting)!;
expect(feedback.animationStarted).toBe(false);
await feedback.animateTo("Draft", { x: 0, y: 0, width: 1, height: 1 });
expect(commands).toEqual([]);
const complete = feedback.complete();
child.emit("close");
await complete;
});
it("falls back on startup failure, malformed replies, and timeout without leaving timers", async () => {
const starting = startNativeCaptureFeedback("/helper", "/private", options);
child.stdout.write("not JSON\n");
expect(commands).toEqual(['{"command":"close"}\n']);
await vi.advanceTimersByTimeAsync(1000);
expect(child.kill).toHaveBeenCalledOnce();
child.emit("close");
expect(await starting).toBeUndefined();
expect(vi.getTimerCount()).toBe(0);
});
it("bounds a missing ready receipt and cancels an in-flight animation on compositor failure", async () => {
const timed = startNativeCaptureFeedback("/helper", "/private", options);
await vi.advanceTimersByTimeAsync(2000);
child.emit("close");
expect(await timed).toBeUndefined();
});
it("releases waiters if the overlay closes during flight", async () => {
const starting = startNativeCaptureFeedback("/helper", "/private", options);
event({ event: "ready", animate: true });
const feedback = (await starting)!;
const flight = feedback.animateTo("Draft", { x: 0, y: 0, width: 1, height: 1 });
event({ event: "done" });
await flight;
child.emit("close");
await feedback.complete();
expect(vi.getTimerCount()).toBe(0);
});
@@ -0,0 +1,113 @@
// @effect-diagnostics nodeBuiltinImport:off -- Short-lived native helper with private stdio, no shell.
// @effect-diagnostics globalTimers:off -- Deadlines bound a native child/overlay; progress is receipt-driven.
import * as NodeChildProcess from "node:child_process";
import * as Schema from "effect/Schema";
import type { LinuxCaptureFeedback, LinuxWindowMetadata } from "./LinuxSnapShot.ts";
const decodeEvent = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Union([
Schema.Struct({ event: Schema.Literal("ready"), animate: Schema.Boolean }),
Schema.Struct({ event: Schema.Literals(["landed", "done"]) }),
]),
),
);
/** Ready and landed are compositor receipts. A requested animation is not proof it started. */
export async function startNativeCaptureFeedback(
executable: string,
directory: string,
options: { bounds: LinuxWindowMetadata["bounds"]; pid: number; flash: boolean; animate: boolean },
) {
const child = NodeChildProcess.spawn(
executable,
["feedback", directory, JSON.stringify(options)],
{
stdio: ["pipe", "pipe", "ignore"],
},
);
const ready = Promise.withResolvers<boolean | undefined>();
const landed = Promise.withResolvers<void>();
const exited = Promise.withResolvers<void>();
let closed = false;
let closing = false;
let flying = false;
let buffer = "";
let killTimer: ReturnType<typeof setTimeout> | undefined;
const close = () => {
if (closing || closed) return;
closing = true;
ready.resolve(undefined);
landed.resolve();
child.stdin.end('{"command":"close"}\n');
// Kill only our own child if the compositor fails to acknowledge cancellation.
killTimer = setTimeout(() => child.kill(), 1000);
killTimer.unref();
};
const deadline = setTimeout(close, 10_000);
deadline.unref();
const readyDeadline = setTimeout(close, 2000);
readyDeadline.unref();
child.stdin.on("error", close);
child.once("error", close);
child.once("close", () => {
closed = true;
clearTimeout(deadline);
clearTimeout(readyDeadline);
if (killTimer) clearTimeout(killTimer);
ready.resolve(undefined);
landed.resolve();
exited.resolve();
});
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => {
buffer += chunk;
if (buffer.length > 4096) return close();
let end: number;
while ((end = buffer.indexOf("\n")) !== -1) {
const line = buffer.slice(0, end);
buffer = buffer.slice(end + 1);
try {
const event = decodeEvent(line);
switch (event.event) {
case "ready":
clearTimeout(readyDeadline);
ready.resolve(event.animate);
break;
case "landed":
landed.resolve();
break;
case "done":
close();
break;
}
} catch {
close();
}
}
});
const animationStarted = await ready.promise;
if (animationStarted === undefined) {
close();
await exited.promise;
return undefined;
}
return {
animationStarted,
closed: exited.promise,
async animateTo(title: string, frame: Parameters<LinuxCaptureFeedback["animateTo"]>[0]) {
if (closing || closed || !animationStarted) return;
if (!flying) {
flying = true;
child.stdin.write(`${JSON.stringify({ command: "animate", title, frame })}\n`);
}
await landed.promise;
},
async complete() {
if (flying) await landed.promise;
close();
await exited.promise;
},
close,
};
}
@@ -0,0 +1,66 @@
// @effect-diagnostics globalTimers:off -- Bound session-bus registration at a native callback boundary.
import { Message, MessageType, NameFlag, RequestNameReply, sessionBus } from "dbus-next";
import {
NIRI_CAPTURE_INTERFACE as INTERFACE,
NIRI_CAPTURE_PATH as PATH,
} from "./linuxCaptureSession.ts";
/** Niri owns the keybinding; this endpoint triggers capture without first focusing T3. */
export async function startNiriCaptureShortcut(
appId: string,
onCapture: () => void,
onFailure: () => void,
bus = sessionBus(),
): Promise<() => void> {
let closed = false;
const close = () => {
if (closed) return;
closed = true;
bus.disconnect();
};
const failure = new Promise<never>((_, reject) => {
bus.on("error", (error: Error) => {
reject(error);
if (!closed) onFailure();
close();
});
});
void failure.catch(() => undefined);
bus.addMethodHandler((message: Message) => {
if (message.path !== PATH || message.interface !== INTERFACE || message.member !== "Capture")
return false;
if (message.signature || message.body.length) {
// Preserve dbus-next's numeric reply serial; its newError factory has incorrect types.
const reply = Message.newMethodReturn(message, "s", ["Capture takes no arguments."]);
reply.type = MessageType.ERROR;
reply.errorName = "org.freedesktop.DBus.Error.InvalidArgs";
bus.send(reply);
return true;
}
if (!closed) onCapture();
bus.send(Message.newMethodReturn(message));
return true;
});
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const result = await Promise.race([
bus.requestName(`${appId}.SnapShot`, NameFlag.DO_NOT_QUEUE),
failure,
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error("Niri capture shortcut registration timed out.")),
5_000,
);
}),
]);
if (result !== RequestNameReply.PRIMARY_OWNER)
throw new Error("Another T3 Code instance already owns the capture shortcut.");
return close;
} catch (error) {
close();
throw error;
} finally {
clearTimeout(timer);
}
}
@@ -0,0 +1,248 @@
// @effect-diagnostics nodeBuiltinImport:off -- Private Unix sockets exercise the real compositor transport.
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
vi.mock("electron", () => ({
nativeImage: {
createFromBuffer: () => ({
isEmpty: () => false,
getSize: () => ({ width: 800, height: 600 }),
}),
},
}));
import { captureNiriWindow, checkNiriCaptureSupport, niriSocketPath } from "./NiriSnapShot.ts";
import { captureLinuxWindow, getLinuxCaptureSupport } from "./LinuxSnapShot.ts";
const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]);
const window = {
id: 42,
title: "Editor",
app_id: "org.example.Editor",
pid: 123,
layout: { window_size: [800, 600] },
};
type Request =
| string
| { Action: { ScreenshotWindow?: { id: number; path: string }; FocusWindow?: { id: number } } };
let directory: string;
let socketPath: string;
let server: NodeNet.Server;
let sockets: Set<NodeNet.Socket>;
let events: NodeNet.Socket[];
let calls: Request[];
let handler: (request: Request, socket: NodeNet.Socket) => Promise<void>;
let focused: typeof window | null;
let windows: (typeof window)[];
let capturePath: string | undefined;
let version: string;
const send = (socket: NodeNet.Socket, value: unknown) => socket.write(`${JSON.stringify(value)}\n`);
beforeEach(async () => {
directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-niri-test-"));
socketPath = NodePath.join(directory, "ipc");
sockets = new Set();
events = [];
calls = [];
focused = window;
windows = [window];
capturePath = undefined;
version = "26.04 (v26.04)";
handler = async (request, socket) => {
if (request === "EventStream") {
events.push(socket);
send(socket, { Ok: "Handled" });
send(socket, { WindowsChanged: { windows } });
} else if (request === "Version") send(socket, { Ok: { Version: version } });
else if (request === "FocusedWindow") send(socket, { Ok: { FocusedWindow: focused } });
else if (request === "Windows") send(socket, { Ok: { Windows: windows } });
else if (typeof request !== "string" && request.Action.ScreenshotWindow) {
const screenshot = request.Action.ScreenshotWindow;
capturePath = screenshot.path;
// Focus may change between discovery and capture. The request must keep the original ID.
focused = { ...window, id: 99, title: "Another app" };
await NodeFSP.writeFile(screenshot.path, png);
for (const event of events) {
send(event, { ScreenshotCaptured: { path: "/another-app.png" } });
send(event, { ScreenshotCaptured: { path: screenshot.path } });
}
// The event may beat the command reply.
send(socket, { Ok: "Handled" });
} else send(socket, { Ok: "Handled" });
};
server = NodeNet.createServer((socket) => {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
socket.on("error", () => undefined);
socket.setEncoding("utf8");
let pending = "";
socket.on("data", (chunk: string) => {
pending += chunk;
let end: number;
while ((end = pending.indexOf("\n")) !== -1) {
const request = JSON.parse(pending.slice(0, end)) as Request;
pending = pending.slice(end + 1);
calls.push(request);
void handler(request, socket).catch((error: unknown) =>
socket.destroy(error instanceof Error ? error : undefined),
);
}
});
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(socketPath, resolve);
});
vi.stubEnv("NIRI_SOCKET", socketPath);
vi.stubEnv("XDG_CURRENT_DESKTOP", "niri");
vi.stubEnv("FLATPAK_ID", "");
vi.stubEnv("SNAP", "");
});
afterEach(async () => {
vi.useRealTimers();
vi.unstubAllEnvs();
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve) => server.close(() => resolve()));
await NodeFSP.rm(directory, { recursive: true, force: true });
});
it("selects the native adapter without needing a portal or GNOME extension", async () => {
expect(await getLinuxCaptureSupport("com.t3tools.T3Code")).toEqual({
linuxBackend: "niri",
linuxFeedbackAvailable: false,
});
const snapshot = await captureLinuxWindow("com.t3tools.T3Code");
expect(snapshot?.png).toEqual(png);
expect(snapshot?.window).toMatchObject({
processId: 123,
title: "Editor",
accessibilityBoundsReliable: false,
});
expect(calls).toContainEqual({
Action: {
ScreenshotWindow: { id: 42, path: capturePath, write_to_disk: true, show_pointer: false },
},
});
expect(snapshot?.feedback?.animationStarted).toBe(false);
expect(await NodeFSP.stat(NodePath.dirname(capturePath!)).catch(() => undefined)).toBeUndefined();
});
it("does not activate T3 until requested, then matches PID and title", async () => {
const snapshot = await captureNiriWindow(socketPath);
expect(calls.some((call) => typeof call !== "string" && call.Action.FocusWindow)).toBe(false);
windows = [
{ ...window, id: 1, pid: 999, title: "T3 Code" },
{ ...window, id: 2, pid: process.pid, title: "Other T3" },
{ ...window, id: 3, pid: process.pid, title: "T3 Code" },
];
await snapshot.feedback!.activate("T3 Code");
expect(calls).toContainEqual({ Action: { FocusWindow: { id: 3 } } });
});
it("waits for the restored T3 window to map instead of polling", async () => {
const snapshot = await captureNiriWindow(socketPath);
const original = handler;
handler = async (request, socket) => {
await original(request, socket);
if (request === "EventStream")
send(socket, {
WindowOpenedOrChanged: { window: { ...window, id: 4, pid: process.pid, title: "T3 Code" } },
});
};
await snapshot.feedback!.activate("T3 Code");
expect(calls).toContainEqual({ Action: { FocusWindow: { id: 4 } } });
});
it("rejects ambiguous activation targets", async () => {
const snapshot = await captureNiriWindow(socketPath);
windows = [1, 2].map((id) => ({ ...window, id, pid: process.pid, title: "T3 Code" }));
await expect(snapshot.feedback!.activate("T3 Code")).rejects.toThrow("More than one");
});
it("cancels pending activation when capture feedback is closed", async () => {
const snapshot = await captureNiriWindow(socketPath);
const started = Promise.withResolvers<void>();
const original = handler;
handler = async (request, socket) => {
await original(request, socket);
if (request === "EventStream") started.resolve();
};
const activation = expect(snapshot.feedback!.activate("T3 Code")).rejects.toThrow("cancelled");
await started.promise;
snapshot.feedback!.close();
await activation;
expect(calls.some((call) => typeof call !== "string" && call.Action.FocusWindow)).toBe(false);
});
it("does not attach accessibility identity if the captured window changed", async () => {
windows = [{ ...window, title: "Different document" }];
const snapshot = await captureNiriWindow(socketPath);
expect(snapshot.png).toEqual(png);
expect(snapshot.window).toBeUndefined();
});
it("fails without a focused window rather than taking the screen", async () => {
focused = null;
await expect(captureNiriWindow(socketPath)).rejects.toThrow("no focused window");
expect(capturePath).toBeUndefined();
});
it("rejects compositor errors and cleans up its temporary image", async () => {
const original = handler;
handler = async (request, socket) => {
if (typeof request !== "string" && request.Action.ScreenshotWindow) {
capturePath = request.Action.ScreenshotWindow.path;
send(socket, { Err: "window disappeared" });
} else await original(request, socket);
};
await expect(captureLinuxWindow("com.t3tools.T3Code")).rejects.toThrow("window disappeared");
expect(await NodeFSP.stat(NodePath.dirname(capturePath!)).catch(() => undefined)).toBeUndefined();
});
it.each(["24.11", "25.05", "unknown"])("rejects unsupported Niri version %s", async (value) => {
version = value;
await expect(checkNiriCaptureSupport(socketPath)).rejects.toThrow("25.11 or newer");
});
it.each(["25.11", "26.04", "niri 26.04 (abc)"])("accepts Niri version %s", async (value) => {
version = value;
await checkNiriCaptureSupport(socketPath);
});
it.each(["garbage\n", "x".repeat(4 * 1024 * 1024 + 1)])(
"bounds malformed compositor replies",
async (reply) => {
handler = async (_request, socket) => {
socket.write(reply);
};
await expect(checkNiriCaptureSupport(socketPath)).rejects.toThrow(/invalid|oversized/);
},
);
it("fails promptly when Niri disconnects", async () => {
handler = async (_request, socket) => {
socket.end();
};
await expect(checkNiriCaptureSupport(socketPath)).rejects.toThrow("disconnected");
});
it("bounds requests even when the compositor never answers", async () => {
vi.useFakeTimers();
const received = Promise.withResolvers<void>();
handler = async () => received.resolve();
const result = expect(checkNiriCaptureSupport(socketPath)).rejects.toThrow("timed out");
await received.promise;
await vi.advanceTimersByTimeAsync(5_000);
await result;
});
it("does not use stale, relative, or sandboxed Niri sockets", () => {
expect(niriSocketPath()).toBe(socketPath);
expect(niriSocketPath({ XDG_CURRENT_DESKTOP: "GNOME", NIRI_SOCKET: socketPath })).toBeUndefined();
expect(niriSocketPath({ XDG_CURRENT_DESKTOP: "niri", NIRI_SOCKET: "relative" })).toBeUndefined();
expect(
niriSocketPath({ XDG_CURRENT_DESKTOP: "niri", NIRI_SOCKET: socketPath, FLATPAK_ID: "app" }),
).toBeUndefined();
});
+263
View File
@@ -0,0 +1,263 @@
// @effect-diagnostics nodeBuiltinImport:off -- Niri exposes its compositor API through a local Unix socket.
// @effect-diagnostics globalTimers:off -- Bound native socket operations outside Effect fibers.
import * as NodeFSP from "node:fs/promises";
import * as NodeNet from "node:net";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as Schema from "effect/Schema";
import type { LinuxWindowSnapshot } from "./LinuxSnapShot.ts";
import { readPortalPng } from "./linuxCaptureSession.ts";
const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
const TIMEOUT_MS = 5_000;
const Id = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }));
const Size = Schema.Int.check(Schema.isGreaterThan(0));
const Window = Schema.Struct({
id: Id,
title: Schema.NullOr(Schema.String),
app_id: Schema.NullOr(Schema.String),
pid: Schema.NullOr(Size),
layout: Schema.Struct({ window_size: Schema.Tuple([Size, Size]) }),
});
const Reply = Schema.Union([
Schema.Struct({ Ok: Schema.Unknown }),
Schema.Struct({ Err: Schema.String }),
]);
const WindowsChanged = Schema.Struct({
WindowsChanged: Schema.Struct({ windows: Schema.Array(Window) }),
});
const WindowChanged = Schema.Struct({
WindowOpenedOrChanged: Schema.Struct({ window: Window }),
});
const WindowClosed = Schema.Struct({ WindowClosed: Schema.Struct({ id: Id }) });
const ScreenshotCaptured = Schema.Struct({
ScreenshotCaptured: Schema.Struct({ path: Schema.NullOr(Schema.String) }),
});
const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
const decodeReply = Schema.decodeUnknownSync(Reply);
const decodeFocused = Schema.decodeUnknownSync(
Schema.Struct({ FocusedWindow: Schema.NullOr(Window) }),
);
const decodeWindows = Schema.decodeUnknownSync(Schema.Struct({ Windows: Schema.Array(Window) }));
const decodeVersion = Schema.decodeUnknownSync(Schema.Struct({ Version: Schema.String }));
const isWindowsChanged = Schema.is(WindowsChanged);
const isWindowChanged = Schema.is(WindowChanged);
const isWindowClosed = Schema.is(WindowClosed);
const isScreenshotCaptured = Schema.is(ScreenshotCaptured);
/** A session hint, never a probe of another compositor or a sandbox escape. */
export function niriSocketPath(env = process.env): string | undefined {
if (env.FLATPAK_ID || env.SNAP) return undefined;
if (!env.XDG_CURRENT_DESKTOP?.split(":").some((name) => name.toLowerCase() === "niri"))
return undefined;
return env.NIRI_SOCKET && NodePath.isAbsolute(env.NIRI_SOCKET) ? env.NIRI_SOCKET : undefined;
}
/** One bounded exchange or event subscription. All waiters end when the socket closes. */
class NiriConnection {
private readonly socket: NodeNet.Socket;
private readonly listeners = new Set<(value: unknown) => void>();
private readonly failures = new Set<(error: Error) => void>();
private failure: Error | undefined;
constructor(path: string) {
this.socket = NodeNet.createConnection(path);
this.socket.setEncoding("utf8");
let pending = "";
this.socket.on("data", (chunk: string) => {
pending += chunk;
// Bound even an unterminated or malicious reply; ignore unrelated events without retaining them.
if (Buffer.byteLength(pending) > MAX_MESSAGE_BYTES) {
this.close(new Error("Niri returned an oversized message."));
return;
}
let end: number;
while ((end = pending.indexOf("\n")) !== -1) {
const line = pending.slice(0, end);
pending = pending.slice(end + 1);
try {
const value = decodeJson(line);
for (const listener of this.listeners) listener(value);
} catch {
this.close(new Error("Niri returned an invalid message."));
return;
}
}
});
this.socket.on("error", (error) => this.close(error));
this.socket.on("close", () => this.close(new Error("Niri disconnected.")));
}
waitFor<T>(select: (value: unknown) => T | undefined): Promise<T> {
if (this.failure) return Promise.reject(this.failure);
return new Promise((resolve, reject) => {
const finish = () => {
clearTimeout(timer);
this.listeners.delete(listener);
this.failures.delete(fail);
};
const fail = (error: Error) => {
finish();
reject(error);
};
const listener = (value: unknown) => {
try {
const selected = select(value);
if (selected !== undefined) {
finish();
resolve(selected);
}
} catch (error) {
fail(error instanceof Error ? error : new Error("Invalid Niri response."));
}
};
const timer = setTimeout(() => fail(new Error("Niri snapshot timed out.")), TIMEOUT_MS);
this.listeners.add(listener);
this.failures.add(fail);
});
}
send(request: unknown) {
this.socket.write(`${JSON.stringify(request)}\n`);
}
close(error = new Error("Niri connection closed.")) {
if (this.failure) return;
this.failure = error;
for (const fail of this.failures) fail(error);
this.socket.destroy();
}
}
async function request(path: string, message: unknown): Promise<unknown> {
const connection = new NiriConnection(path);
try {
const reply = connection.waitFor((value) => ({ value: decodeReply(value) }));
connection.send(message);
const { value } = await reply;
if ("Err" in value) throw new Error(`Niri: ${value.Err}`);
return value.Ok;
} finally {
connection.close();
}
}
export async function checkNiriCaptureSupport(path: string): Promise<void> {
const version = decodeVersion(await request(path, "Version")).Version;
// 25.11 introduced both caller-selected screenshot paths and completion events.
const match = /^(?:niri )?(\d+)\.(\d+)/.exec(version);
if (!match || Number(match[1]) < 25 || (Number(match[1]) === 25 && Number(match[2]) < 11))
throw new Error("SnapShots require Niri 25.11 or newer.");
}
async function activateNiriWindow(path: string, title: string, signal: AbortSignal): Promise<void> {
signal.throwIfAborted();
const connection = new NiriConnection(path);
const abort = () => connection.close(new Error("Niri activation cancelled."));
signal.addEventListener("abort", abort, { once: true });
const windows = new Map<number, typeof Window.Type>();
try {
const target = connection.waitFor((value) => {
if (isWindowsChanged(value)) {
windows.clear();
for (const window of value.WindowsChanged.windows) windows.set(window.id, window);
} else if (isWindowChanged(value)) {
const window = value.WindowOpenedOrChanged.window;
windows.set(window.id, window);
} else if (isWindowClosed(value)) {
windows.delete(value.WindowClosed.id);
} else return undefined;
// Never activate another process's lookalike window, or guess between multiple T3 windows.
const matches = [...windows.values()].filter(
(window) => window.pid === process.pid && window.title === title,
);
if (matches.length > 1)
throw new Error("More than one T3 Code window matches the capture destination.");
return matches[0];
});
connection.send("EventStream");
const window = await target;
signal.throwIfAborted();
await request(path, { Action: { FocusWindow: { id: window.id } } });
} finally {
signal.removeEventListener("abort", abort);
connection.close();
}
}
export async function captureNiriWindow(path: string): Promise<LinuxWindowSnapshot> {
const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-niri-capture-"));
const imagePath = NodePath.join(directory, "capture.png");
const events = new NiriConnection(path);
try {
// An initial state event proves subscription, whereas the EventStream reply alone does not.
const ready = events.waitFor((value) => (isWindowsChanged(value) ? true : undefined));
events.send("EventStream");
await ready;
const window = decodeFocused(await request(path, "FocusedWindow")).FocusedWindow;
if (!window) throw new Error("Niri has no focused window to capture.");
const captured = events.waitFor((value) =>
isScreenshotCaptured(value) && value.ScreenshotCaptured.path === imagePath ? true : undefined,
);
// Observe rejection even if the compositor rejects the command before we await its event.
void captured.catch(() => undefined);
await request(path, {
Action: {
ScreenshotWindow: {
id: window.id,
write_to_disk: true,
show_pointer: false,
path: imagePath,
},
},
});
await captured;
const png = await readPortalPng(NodeURL.pathToFileURL(imagePath).href);
const after = decodeWindows(await request(path, "Windows")).Windows.find(
(item) => item.id === window.id,
);
// A changed/closed window still yields an image, but never attach text from its replacement.
const identityUnchanged =
after &&
after.pid === window.pid &&
after.title === window.title &&
after.app_id === window.app_id &&
after.layout.window_size.every((size, i) => size === window.layout.window_size[i]);
const feedback = new AbortController();
return {
png,
...(identityUnchanged
? {
window: {
title: window.title ?? "",
appName: window.app_id ?? "Application",
appIdentifier: window.app_id ?? "",
processId: window.pid ?? 0,
// Niri reports logical size, not a globally comparable screen origin.
bounds: {
x: 0,
y: 0,
width: window.layout.window_size[0],
height: window.layout.window_size[1],
},
accessibilityBoundsReliable: false,
},
}
: {}),
feedback: {
animationStarted: false,
activate: (title) => activateNiriWindow(path, title, feedback.signal),
animateTo: async () => undefined,
complete: async () => feedback.abort(),
close: () => feedback.abort(),
},
};
} finally {
events.close();
// The private directory is ours; never remove compositor/user-owned screenshot paths.
await NodeFSP.rm(directory, { recursive: true, force: true });
}
}
@@ -0,0 +1,179 @@
// @effect-diagnostics nodeBuiltinImport:off -- Private D-Bus integration fixture, never the user's session bus.
import * as NodeChildProcess from "node:child_process";
import * as NodeEvents from "node:events";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeReadline from "node:readline";
import { Message, NameFlag, Variant, sessionBus, type MessageBus } from "dbus-next";
import { expect, it, vi } from "vite-plus/test";
import { PortalCaptureShortcut } from "./PortalCaptureShortcut.ts";
it.runIf(NodeChildProcess.spawnSync("dbus-daemon", ["--version"]).status === 0)(
"registers, rebinds saved keys, receives activations, and replaces sessions over real D-Bus",
async () => {
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-shortcut-dbus-"));
let daemon: NodeChildProcess.ChildProcess | undefined;
let server: MessageBus | undefined;
const clients: PortalCaptureShortcut[] = [];
try {
vi.stubEnv("FLATPAK_ID", "");
vi.stubEnv("SNAP", "");
daemon = NodeChildProcess.spawn(
"dbus-daemon",
[
"--session",
"--nofork",
"--nopidfile",
"--print-address",
`--address=unix:path=${NodePath.join(dir, "bus")}`,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
const lines = NodeReadline.createInterface({ input: daemon.stdout! });
const [address] = await Promise.race([
NodeEvents.EventEmitter.once(lines, "line"),
NodeEvents.EventEmitter.once(daemon, "exit").then(() => {
throw new Error("Private bus failed to start");
}),
]);
lines.close();
const connect = () => sessionBus({ busAddress: String(address) });
server = connect();
server.on("error", () => undefined);
await server.requestName("org.freedesktop.portal.Desktop", NameFlag.DO_NOT_QUEUE);
const root = "/org/freedesktop/portal/desktop";
const iface = "org.freedesktop.portal.GlobalShortcuts";
const sessions = new Map<string, string>();
const bindings = new Map<string, string>();
const identities = new Set<string>();
const closed = new Set<string>();
const closeWaiters = new Map<string, () => void>();
let bindCount = 0;
server.addMethodHandler((message: Message) => {
if (message.member === "Register") {
expect(message.body[0]).toBe("com.t3tools.T3Code");
identities.add(message.sender);
server!.send(Message.newMethodReturn(message));
} else if (message.member === "Get") {
server!.send(Message.newMethodReturn(message, "v", [new Variant("u", 2)]));
} else if (message.member === "Close") {
closed.add(message.path);
closeWaiters.get(message.path)?.();
} else if (["CreateSession", "BindShortcuts"].includes(message.member)) {
expect(identities.has(message.sender)).toBe(true);
const options = message.body.at(-1) as Record<string, Variant<string>>;
const sender = message.sender.slice(1).replaceAll(".", "_");
const handle = `${root}/request/${sender}/${options.handle_token!.value}`;
let results: Record<string, Variant<unknown>>;
if (message.member === "CreateSession") {
const session = `${root}/session/${sender}/${options.session_handle_token!.value}`;
sessions.set(message.sender, session);
results = { session_handle: new Variant("s", session) };
} else {
bindCount++;
const shortcuts = message.body[1] as Array<
[string, { preferred_trigger: Variant<string> }]
>;
expect(shortcuts).toHaveLength(1);
const [id, properties] = shortcuts[0]!;
expect(properties.preferred_trigger.signature).toBe("s");
bindings.set(message.sender, id);
const bound = [
[
id,
{
description: new Variant("s", "Capture a window"),
trigger_description: new Variant("s", properties.preferred_trigger.value),
},
],
];
results = { shortcuts: new Variant("a(sa{sv})", bound) };
}
// Exercise the fast-portal race: Response is delivered before the method's handle reply.
const response = Message.newSignal(
handle,
"org.freedesktop.portal.Request",
"Response",
"ua{sv}",
[0, results],
);
response.destination = message.sender;
server!.send(response);
server!.send(Message.newMethodReturn(message, "o", [handle]));
} else return false;
return true;
});
const shortcut = {
key: "2",
modKey: true,
ctrlKey: false,
shiftKey: true,
altKey: false,
metaKey: false,
};
const start = (key = "2") => {
const received = Promise.withResolvers<void>();
const capture = vi.fn(() => received.resolve());
const client = new PortalCaptureShortcut(
"com.t3tools.T3Code",
{ ...shortcut, key },
capture,
() => {},
connect(),
);
clients.push(client);
return { client, capture, received: received.promise };
};
const activate = (sender: string) => {
const signal = Message.newSignal(root, iface, "Activated", "osta{sv}", [
sessions.get(sender),
bindings.get(sender),
123,
{},
]);
signal.destination = sender;
server!.send(signal);
};
const first = start();
await first.client.ready;
expect(first.client.state.shortcutRegistered).toBe(true);
const firstSender = [...bindings.keys()][0]!;
activate(firstSender);
await first.received;
expect(first.capture).toHaveBeenCalledOnce();
const sessionClosed = new Promise<void>((resolve) =>
closeWaiters.set(sessions.get(firstSender)!, resolve),
);
first.client.close();
await sessionClosed;
expect(closed.has(sessions.get(firstSender)!)).toBe(true);
const restoredClient = start();
await restoredClient.client.ready;
expect(restoredClient.client.state.shortcutRegistered).toBe(true);
expect(bindCount).toBe(2);
expect([...bindings.values()][1]).toBe(bindings.get(firstSender));
const next = start("8");
await next.client.ready;
expect(next.client.state.shortcutLabel).toBe("CTRL+SHIFT+8");
expect(bindCount).toBe(3);
const lastSender = [...bindings.keys()].at(-1)!;
expect(bindings.get(lastSender)).not.toBe(bindings.get(firstSender));
activate(lastSender);
await next.received;
expect(next.capture).toHaveBeenCalledOnce();
} finally {
clients.forEach((client) => client.close());
server?.disconnect();
if (daemon && daemon.exitCode === null) {
const exited = NodeEvents.EventEmitter.once(daemon, "exit");
daemon.kill();
await exited;
}
vi.unstubAllEnvs();
await NodeFSP.rm(dir, { recursive: true, force: true });
}
},
);
@@ -0,0 +1,418 @@
// @effect-diagnostics nodeBuiltinImport:off -- Event-driven fake of the portal transport.
import * as NodeEvents from "node:events";
import { DBusError, Message, MessageType, Variant, type MessageBus } from "dbus-next";
import { afterEach, expect, it, vi } from "vite-plus/test";
import { PortalCaptureShortcut, portalShortcutTrigger } from "./PortalCaptureShortcut.ts";
const chord = {
key: "2",
modKey: true,
ctrlKey: false,
altKey: false,
shiftKey: true,
metaKey: false,
};
const root = "/org/freedesktop/portal/desktop";
const portal = "org.freedesktop.portal.GlobalShortcuts";
const clients: PortalCaptureShortcut[] = [];
type Shortcut = [string, { description?: Variant<string>; trigger_description?: Variant<string> }];
class FakeBus extends NodeEvents.EventEmitter {
calls: Message[] = [];
sends: Message[] = [];
disconnect = vi.fn();
registryError: Error | undefined;
version = 2;
autoBind = true;
actualLabel = "Ctrl+Shift+2";
bindStatus = 0;
session = "";
requestPath = "";
boundId = "";
foreignHandle = false;
send(message: Message) {
this.sends.push(message);
}
signal(
iface: string,
member: string,
path: string,
body: unknown[],
sender = ":1.2",
signature = "",
) {
this.emit(
"message",
new Message({
type: MessageType.SIGNAL,
sender,
interface: iface,
member,
path,
body,
signature,
}),
);
}
response(path: string, status: number, results: Record<string, Variant<unknown>>) {
this.signal("org.freedesktop.portal.Request", "Response", path, [status, results]);
}
respondBind(status = this.bindStatus) {
this.response(this.requestPath, status, {
shortcuts: new Variant("a(sa{sv})", [
[
this.boundId,
{
description: new Variant("s", "Capture a window"),
trigger_description: new Variant("s", this.actualLabel),
},
],
]),
});
}
activate(id = this.boundId, session = this.session, sender = ":1.2") {
this.signal(portal, "Activated", root, [session, id, 1, {}], sender, "osta{sv}");
}
async call(message: Message) {
this.calls.push(message);
const reply = (body: unknown[] = []) =>
new Message({
type: MessageType.METHOD_RETURN,
replySerial: "1",
destination: ":1.23",
body,
});
if (message.member === "Register") {
if (this.registryError) throw this.registryError;
return reply();
}
if (message.member === "GetNameOwner") return reply([":1.2"]);
if (message.member === "Get") return reply([new Variant("u", this.version)]);
if (message.member === "AddMatch" || message.member === "ConfigureShortcuts") return reply();
const options = message.body.at(-1) as Record<string, Variant<string>>;
const path = `${root}/request/1_23/${options.handle_token!.value}`;
if (message.member === "CreateSession") {
this.session = `${root}/session/1_23/${options.session_handle_token!.value}`;
this.response(path, 0, {
session_handle: new Variant(
"s",
this.foreignHandle ? `${root}/session/9_9/other` : this.session,
),
});
} else if (message.member === "BindShortcuts") {
this.boundId = (message.body[1] as Shortcut[])[0]![0];
this.requestPath = path;
this.emit("bind");
if (this.autoBind) this.respondBind();
} else throw new Error(`Unexpected call: ${message.member}`);
return reply([path]);
}
}
function start(bus = new FakeBus(), shortcut = chord, managedByHyprland = false) {
const capture = vi.fn();
const changed = vi.fn();
const client = new PortalCaptureShortcut(
"com.t3tools.T3Code",
shortcut,
capture,
changed,
bus as unknown as MessageBus,
managedByHyprland,
);
clients.push(client);
return { bus, client, capture, changed };
}
afterEach(() => {
for (const client of clients.splice(0)) client.close();
vi.useRealTimers();
vi.unstubAllEnvs();
});
it("accepts Hyprland's action-only binding without claiming the keys are reserved", async () => {
const bus = new FakeBus();
bus.actualLabel = "";
const { client, capture } = start(bus, chord, true);
await client.ready;
expect(client.state).toMatchObject({
shortcutRegistered: false,
shortcutActionRegistered: true,
shortcutPending: false,
shortcutCanRetry: false,
});
expect(bus.boundId).toBe("capture-window");
expect(bus.calls.find((call) => call.member === "BindShortcuts")?.body[1]).toEqual([
["capture-window", { description: new Variant("s", "Capture a window") }],
]);
bus.activate("wrong");
bus.activate(bus.boundId, bus.session, ":1.999");
expect(capture).not.toHaveBeenCalled();
bus.activate();
expect(capture).toHaveBeenCalledOnce();
await expect(client.configure()).rejects.toThrow("Hyprland config");
bus.signal(portal, "ShortcutsChanged", root, [bus.session, []]);
bus.activate();
expect(capture).toHaveBeenCalledOnce();
expect(client.state.shortcutActionRegistered).toBe(false);
});
it("keeps the Hyprland action ID stable regardless of a saved key chord", async () => {
const first = start(new FakeBus(), chord, true);
const second = start(new FakeBus(), { ...chord, key: "7" }, true);
await Promise.all([first.client.ready, second.client.ready]);
expect(first.bus.boundId).toBe(second.bus.boundId);
});
it("does not accept an empty trigger as approval on other desktops", async () => {
const bus = new FakeBus();
bus.actualLabel = "";
const { client, capture } = start(bus);
await client.ready;
expect(client.state.shortcutRegistered).toBe(false);
expect(client.state.shortcutActionRegistered).not.toBe(true);
bus.activate();
expect(capture).not.toHaveBeenCalled();
});
it.each([
["2", "CTRL+SHIFT+2"],
["f12", "CTRL+SHIFT+F12"],
["pageup", "CTRL+SHIFT+Page_Up"],
["+", "CTRL+SHIFT+plus"],
["arrowleft", "CTRL+SHIFT+Left"],
[" ", "CTRL+SHIFT+space"],
])("encodes %s as an XDG shortcut", (key, expected) => {
expect(portalShortcutTrigger({ ...chord, key })).toBe(expected);
});
it("normalizes Ctrl/Mod and rejects unsupported keys before requesting access", () => {
expect(portalShortcutTrigger({ ...chord, ctrlKey: true, metaKey: true })).toBe(
"CTRL+SHIFT+LOGO+2",
);
expect(() => portalShortcutTrigger({ ...chord, key: "unknown-key" })).toThrow("isn't supported");
});
it("does not call submission approval, then reads the actual assigned shortcut", async () => {
const bus = new FakeBus();
bus.autoBind = false;
bus.actualLabel = "Ctrl+Shift+7";
const binding = NodeEvents.EventEmitter.once(bus, "bind");
const { client } = start(bus);
await binding;
expect(client.state.shortcutRegistered).toBe(false);
expect(client.state.shortcutPending).toBe(true);
bus.respondBind();
await client.ready;
expect(client.state).toMatchObject({
shortcutRegistered: true,
shortcutPending: false,
shortcutLabel: "Ctrl+Shift+7",
});
});
it("binds only the requested shortcut with a stable ID across sessions", async () => {
const first = start();
await first.client.ready;
first.client.close();
const { bus, client, capture } = start();
await client.ready;
expect(bus.boundId).toBe(first.bus.boundId);
const binds = bus.calls.filter((call) => call.member === "BindShortcuts");
expect(binds).toHaveLength(1);
expect(binds[0]!.body[1]).toEqual([
[
bus.boundId,
{
description: new Variant("s", "Capture a window"),
preferred_trigger: new Variant("s", "CTRL+SHIFT+2"),
},
],
]);
bus.activate();
expect(capture).toHaveBeenCalledOnce();
expect(bus.calls[0]?.member).toBe("Register");
});
it("ignores other shortcuts, sessions, and forged activations", async () => {
const { bus, client, capture } = start();
await client.ready;
bus.activate("stale-shortcut");
bus.activate(bus.boundId, `${root}/session/9_9/other`);
bus.activate(bus.boundId, bus.session, ":1.999");
expect(capture).not.toHaveBeenCalled();
bus.activate();
expect(capture).toHaveBeenCalledOnce();
});
it("replaces a binding without restarting the application and stops the old callback", async () => {
const first = start();
await first.client.ready;
first.client.close();
const next = start(new FakeBus(), { ...chord, key: "8" });
await next.client.ready;
expect(next.bus.boundId).not.toBe(first.bus.boundId);
expect(next.bus.calls.find((call) => call.member === "BindShortcuts")?.body[1]).toEqual([
[
next.bus.boundId,
{
description: new Variant("s", "Capture a window"),
preferred_trigger: new Variant("s", "CTRL+SHIFT+8"),
},
],
]);
first.bus.activate();
next.bus.activate();
expect(first.capture).not.toHaveBeenCalled();
expect(next.capture).toHaveBeenCalledOnce();
expect(
first.bus.sends.some(
(message) =>
message.interface === "org.freedesktop.portal.Session" && message.member === "Close",
),
).toBe(true);
});
it.each([1, 2])(
"reports denied/cancelled response %s and offers the desktop permissions UI",
async (status) => {
const bus = new FakeBus();
bus.bindStatus = status;
const { client, capture } = start(bus);
await client.ready;
expect(client.state.shortcutRegistered).toBe(false);
expect(client.state.shortcutPending).toBe(false);
expect(client.state.shortcutCanRetry).toBe(true);
expect(client.state.shortcutMessage).toContain("wasn't granted");
bus.activate();
expect(capture).not.toHaveBeenCalled();
await client.configure();
expect(bus.calls.at(-1)?.member).toBe("ConfigureShortcuts");
},
);
it("treats a remembered empty binding as unassigned, then observes desktop-side edits", async () => {
const bus = new FakeBus();
bus.actualLabel = "";
const { client, capture } = start(bus);
await client.ready;
expect(client.state.shortcutRegistered).toBe(false);
bus.activate();
expect(capture).not.toHaveBeenCalled();
bus.signal(portal, "ShortcutsChanged", root, [
bus.session,
[[bus.boundId, { trigger_description: new Variant("s", "Meta+F12") }]],
]);
expect(client.state.shortcutLabel).toBe("Meta+F12");
expect(client.state.shortcutRegistered).toBe(true);
bus.activate();
expect(capture).toHaveBeenCalledOnce();
});
it("guides users to manual desktop settings when the portal cannot open them", async () => {
const bus = new FakeBus();
bus.version = 1;
bus.bindStatus = 1;
const { client } = start(bus);
await client.ready;
expect(client.hasSession).toBe(true);
expect(client.state.shortcutCanRetry).toBe(false);
expect(client.state.shortcutMessage).toBe(
"Shortcut permission wasn't granted. Allow T3 Code in your desktop's shortcut settings.",
);
await expect(client.configure()).rejects.toThrow("Open your desktop's shortcut settings");
expect(bus.calls.some((message) => message.member === "ConfigureShortcuts")).toBe(false);
client.close();
expect(client.hasSession).toBe(false);
});
it("captures on older portals without offering an unsupported permission dialog", async () => {
const bus = new FakeBus();
bus.version = 1;
const { client, capture } = start(bus);
await client.ready;
expect(client.state).toMatchObject({ shortcutRegistered: true, shortcutCanRetry: false });
bus.activate();
expect(capture).toHaveBeenCalledOnce();
bus.signal(portal, "ShortcutsChanged", root, [bus.session, []]);
expect(client.state).toMatchObject({
shortcutRegistered: false,
shortcutCanRetry: false,
shortcutMessage: "No shortcut is assigned. Choose one in your desktop's shortcut settings.",
});
bus.signal("org.freedesktop.portal.Session", "Closed", bus.session, []);
expect(client.hasSession).toBe(false);
expect(client.state.shortcutCanRetry).toBe(true);
});
it("closes an outstanding consent request and ignores its late response", async () => {
const bus = new FakeBus();
bus.autoBind = false;
const binding = NodeEvents.EventEmitter.once(bus, "bind");
const { client, capture, changed } = start(bus);
await binding;
client.close();
bus.respondBind();
await client.ready;
bus.activate();
expect(capture).not.toHaveBeenCalled();
expect(changed).not.toHaveBeenCalled();
expect(bus.sends.filter((message) => message.member === "Close")).toHaveLength(2);
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it("bounds unanswered consent and cleans up the pending request", async () => {
vi.useFakeTimers();
const bus = new FakeBus();
bus.autoBind = false;
const binding = NodeEvents.EventEmitter.once(bus, "bind");
const { client } = start(bus);
await binding;
await vi.advanceTimersByTimeAsync(120_000);
await client.ready;
expect(client.state.shortcutPending).toBe(false);
expect(client.state.shortcutMessage).toContain("timed out");
expect(bus.disconnect).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
it("handles a disappearing portal without keeping a false registered state", async () => {
const { bus, client } = start();
await client.ready;
bus.signal(
"org.freedesktop.DBus",
"NameOwnerChanged",
"/org/freedesktop/DBus",
["org.freedesktop.portal.Desktop", ":1.2", ""],
"org.freedesktop.DBus",
);
expect(client.state.shortcutRegistered).toBe(false);
expect(client.state.shortcutMessage).toContain("restarted");
expect(bus.disconnect).toHaveBeenCalledOnce();
});
it("accepts old portals without Registry but does not ignore permission denial", async () => {
const bus = new FakeBus();
bus.registryError = new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "Old portal");
const first = start(bus);
await first.client.ready;
expect(first.client.state.shortcutRegistered).toBe(true);
const denied = new FakeBus();
denied.registryError = new DBusError(
"org.freedesktop.portal.Error.NotAllowed",
"App is not allowed",
);
const second = start(denied);
await second.client.ready;
expect(second.client.state.shortcutRegistered).toBe(false);
expect(denied.calls.some((call) => call.member === "CreateSession")).toBe(false);
});
it("rejects a foreign session without trying to close someone else's session", async () => {
const bus = new FakeBus();
bus.foreignHandle = true;
const { client } = start(bus);
await client.ready;
expect(client.state.shortcutRegistered).toBe(false);
expect(bus.sends.some((message) => message.path.includes("9_9"))).toBe(false);
});
@@ -0,0 +1,429 @@
// @effect-diagnostics nodeBuiltinImport:off -- Stable shortcut IDs and unique portal request tokens.
// @effect-diagnostics globalTimers:off -- Bounded D-Bus calls and user-consent requests at the native boundary.
import * as NodeCrypto from "node:crypto";
import {
DBusError,
Message,
MessageFlag,
MessageType,
Variant,
sessionBus,
type MessageBus,
type MessageLike,
} from "dbus-next";
import * as Schema from "effect/Schema";
import type { SnapShotKeyChord } from "@t3tools/contracts";
import { HYPRLAND_CAPTURE_ACTION, portalShortcutTrigger } from "./linuxCaptureSession.ts";
export { portalShortcutTrigger } from "./linuxCaptureSession.ts";
const PORTAL = "org.freedesktop.portal.Desktop";
const PATH = "/org/freedesktop/portal/desktop";
const SHORTCUTS = "org.freedesktop.portal.GlobalShortcuts";
const REQUEST = "org.freedesktop.portal.Request";
const SESSION = "org.freedesktop.portal.Session";
const DBUS = "org.freedesktop.DBus";
const string = Schema.decodeUnknownSync(Schema.String);
const StringVariant = Schema.Struct({ signature: Schema.Literal("s"), value: Schema.String });
const Shortcuts = Schema.Array(
Schema.Tuple([
Schema.String,
Schema.Struct({
description: Schema.optional(StringVariant),
trigger_description: Schema.optional(StringVariant),
}),
]),
);
const decodeShortcuts = Schema.decodeUnknownSync(Shortcuts);
const decodeShortcutsResult = Schema.decodeUnknownSync(
Schema.Struct({
shortcuts: Schema.Struct({ signature: Schema.Literal("a(sa{sv})"), value: Shortcuts }),
}),
);
const decodeSession = Schema.decodeUnknownSync(Schema.Struct({ session_handle: StringVariant }));
const decodeResponse = Schema.decodeUnknownSync(
Schema.Tuple([Schema.Int, Schema.Record(Schema.String, Schema.Unknown)]),
);
const decodeVersion = Schema.decodeUnknownSync(
Schema.Struct({
signature: Schema.Literal("u"),
value: Schema.Int,
}),
);
export interface PortalShortcutState {
readonly shortcutActionRegistered?: boolean;
readonly shortcutRegistered: boolean;
readonly shortcutPending: boolean;
/** Whether retry-shortcut can reopen permissions or start a new session. */
readonly shortcutCanRetry?: boolean;
readonly shortcutLabel?: string;
readonly shortcutMessage: string | null;
}
/** Own the portal session, including consent and release; Electron only reports submission. */
export class PortalCaptureShortcut {
state: PortalShortcutState = {
shortcutRegistered: false,
shortcutPending: true,
shortcutMessage: "Waiting for shortcut permission. Approve the desktop prompt if one appears.",
};
readonly ready: Promise<void>;
private closed = false;
private owner = "";
private namespace = "";
private session = "";
private shortcutId = "";
private version = 0;
private pending: { path: string; resolve: (body: unknown) => void } | undefined;
private responses = new Map<string, unknown>();
private readonly stopped: Promise<never>;
private rejectStopped!: (reason: Error) => void;
private readonly onCapture: () => void;
private readonly onStateChanged: () => void;
private readonly bus: MessageBus;
private readonly managedByHyprland: boolean;
constructor(
appId: string,
shortcut: SnapShotKeyChord,
onCapture: () => void,
onStateChanged: () => void,
bus: MessageBus = sessionBus(),
managedByHyprland = false,
) {
this.onCapture = onCapture;
this.onStateChanged = onStateChanged;
this.bus = bus;
this.managedByHyprland = managedByHyprland;
if (managedByHyprland)
this.state = {
shortcutRegistered: false,
shortcutPending: true,
shortcutMessage: "Connecting to Hyprland shortcuts…",
};
this.stopped = new Promise((_, reject) => {
this.rejectStopped = reject;
});
void this.stopped.catch(() => undefined);
bus.on("error", this.failed);
bus.on("message", this.message);
this.ready = this.initialize(appId, shortcut).catch(this.failed);
}
close = () => {
if (this.closed) return;
this.closed = true;
this.rejectStopped(new Error("Capture shortcut registration closed."));
try {
if (this.pending) this.closeObject(this.pending.path, REQUEST);
if (this.session) this.closeObject(this.session, SESSION);
} catch {
// A broken bus is already closing its sessions; local cleanup must still run.
}
this.bus.removeListener("message", this.message);
this.responses.clear();
this.bus.disconnect();
};
/** A previously denied binding is changed by the desktop, not by bypassing its decision. */
get hasSession() {
return !this.closed && Boolean(this.session);
}
async configure() {
if (this.managedByHyprland)
throw new Error("Change the capture binding in your Hyprland config, then save it.");
if (!this.hasSession || this.version < 2)
throw new Error(
"Open your desktop's shortcut settings and allow T3 Code's capture shortcut.",
);
await this.call({
destination: this.owner,
path: PATH,
interface: SHORTCUTS,
member: "ConfigureShortcuts",
signature: "osa{sv}",
body: [this.session, "", {}],
});
}
private update(state: PortalShortcutState) {
if (this.closed) return;
this.state = {
shortcutCanRetry: !this.managedByHyprland && (!this.hasSession || this.version >= 2),
...state,
};
this.onStateChanged();
}
private failed = (error: unknown) => {
if (this.closed) return;
this.update({
shortcutRegistered: false,
shortcutPending: false,
// This failed session is closing, so retry can register a fresh one.
shortcutCanRetry: !this.managedByHyprland,
shortcutMessage: this.managedByHyprland
? "Couldn't connect to Hyprland shortcuts. Make sure xdg-desktop-portal-hyprland is running, then restart T3 Code."
: error instanceof Error
? error.message
: "Could not register the capture shortcut.",
});
this.close();
};
private async wait<T>(promise: Promise<T>, timeoutMs = 5_000): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
this.stopped,
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error("Shortcut permission request timed out. Try again.")),
timeoutMs,
);
}),
]);
} finally {
clearTimeout(timer);
}
}
private async call(message: MessageLike) {
if (this.closed) throw new Error("Capture shortcut registration closed.");
const reply = await this.wait(this.bus.call(new Message(message)));
if (!reply) throw new Error("Missing shortcut portal reply.");
return reply;
}
private closeObject(path: string, iface: string) {
this.bus.send(
new Message({
destination: this.owner,
path,
interface: iface,
member: "Close",
flags: MessageFlag.NO_REPLY_EXPECTED,
}),
);
}
private message = (message: Message) => {
if (this.closed || message.type !== MessageType.SIGNAL) return;
if (
message.sender === "org.freedesktop.DBus" &&
message.interface === DBUS &&
message.member === "NameOwnerChanged" &&
message.body[0] === PORTAL &&
message.body[1] === this.owner
) {
this.failed(new Error("The desktop shortcut service restarted. Retry the shortcut request."));
return;
}
if (!this.owner || message.sender !== this.owner) return;
if (
message.interface === REQUEST &&
message.member === "Response" &&
message.path.startsWith(this.namespace)
) {
if (message.path === this.pending?.path) this.pending.resolve(message.body);
else if (this.responses.size < 8) this.responses.set(message.path, message.body);
return;
}
if (
this.session &&
message.path === this.session &&
message.interface === SESSION &&
message.member === "Closed"
) {
this.failed(
new Error("Your desktop closed the capture shortcut. Retry the shortcut request."),
);
return;
}
if (
message.path !== PATH ||
message.interface !== SHORTCUTS ||
message.body[0] !== this.session
)
return;
if (
message.member === "Activated" &&
message.signature === "osta{sv}" &&
message.body[1] === this.shortcutId &&
(this.state.shortcutRegistered || this.state.shortcutActionRegistered)
)
this.onCapture();
if (message.member === "ShortcutsChanged") {
try {
this.bound(decodeShortcuts(message.body[1]));
} catch (error) {
this.failed(error);
}
}
};
private async request(
member: string,
signature: string,
body: unknown[],
options: Record<string, Variant<unknown>> = {},
) {
const token = `t3_${NodeCrypto.randomUUID().replaceAll("-", "")}`;
const expectedPath = this.namespace + token;
let resolve!: (body: unknown) => void;
const response = new Promise<unknown>((done) => {
resolve = done;
});
this.pending = { path: expectedPath, resolve };
this.responses.clear();
let completed = false;
try {
const reply = await this.call({
destination: this.owner,
path: PATH,
interface: SHORTCUTS,
member,
signature: signature + "a{sv}",
body: [...body, { ...options, handle_token: new Variant("s", token) }],
});
const handle = string(reply.body[0]);
if (!handle.startsWith(this.namespace)) throw new Error("Invalid shortcut request handle.");
this.pending.path = handle;
if (this.responses.has(handle)) resolve(this.responses.get(handle));
const [status, results] = decodeResponse(
await this.wait(response, member === "BindShortcuts" ? 120_000 : 5_000),
);
completed = true;
if (status !== 0) {
if (member === "BindShortcuts") {
this.update({
shortcutRegistered: false,
shortcutPending: false,
shortcutMessage:
this.version >= 2
? "Shortcut permission wasn't granted. Open shortcut permissions to allow it."
: "Shortcut permission wasn't granted. Allow T3 Code in your desktop's shortcut settings.",
});
return undefined;
}
throw new Error("Your desktop could not create a capture shortcut session.");
}
return results;
} finally {
if (!completed && !this.closed && this.pending) this.closeObject(this.pending.path, REQUEST);
this.pending = undefined;
this.responses.clear();
}
}
private bound(shortcuts: typeof Shortcuts.Type) {
const shortcut = shortcuts.find(([id]) => id === this.shortcutId);
if (this.managedByHyprland) {
this.update({
shortcutRegistered: false,
shortcutActionRegistered: Boolean(shortcut),
shortcutPending: false,
shortcutMessage: shortcut
? "Managed by Hyprland. Add the binding to your config and save it."
: "Hyprland did not register the capture action. Check that xdg-desktop-portal-hyprland is running, then restart T3 Code.",
});
return;
}
const label = shortcut?.[1].trigger_description?.value.trim();
this.update({
shortcutRegistered: Boolean(shortcut && label),
shortcutPending: false,
...(label ? { shortcutLabel: label } : {}),
shortcutMessage: label
? `Desktop shortcut: ${label}`
: this.version >= 2
? "No shortcut is assigned. Open shortcut permissions to choose one."
: "No shortcut is assigned. Choose one in your desktop's shortcut settings.",
});
}
private async initialize(appId: string, shortcut: SnapShotKeyChord) {
const trigger = portalShortcutTrigger(shortcut);
if (!process.env.FLATPAK_ID && !process.env.SNAP) {
await this.call({
destination: PORTAL,
path: PATH,
interface: "org.freedesktop.host.portal.Registry",
member: "Register",
signature: "sa{sv}",
body: [appId, {}],
}).catch((error: unknown) => {
if (
!(
error instanceof DBusError &&
["UnknownMethod", "UnknownInterface"].some(
(name) => error.type === `${DBUS}.Error.${name}`,
)
)
)
throw error;
});
}
const owner = await this.call({
destination: DBUS,
path: "/org/freedesktop/DBus",
interface: DBUS,
member: "GetNameOwner",
signature: "s",
body: [PORTAL],
});
this.owner = string(owner.body[0]);
this.namespace = `${PATH}/request/${owner.destination.slice(1).replaceAll(".", "_")}/`;
const version = await this.call({
destination: this.owner,
path: PATH,
interface: "org.freedesktop.DBus.Properties",
member: "Get",
signature: "ss",
body: [SHORTCUTS, "version"],
});
this.version = decodeVersion(version.body[0]).value;
for (const rule of [
`type='signal',sender='${this.owner}',path_namespace='${PATH}'`,
`type='signal',sender='org.freedesktop.DBus',interface='${DBUS}',member='NameOwnerChanged',arg0='${PORTAL}'`,
])
await this.call({
destination: DBUS,
path: "/org/freedesktop/DBus",
interface: DBUS,
member: "AddMatch",
signature: "s",
body: [rule],
});
const created = await this.request("CreateSession", "", [], {
session_handle_token: new Variant(
"s",
`t3_capture_${NodeCrypto.randomUUID().replaceAll("-", "")}`,
),
});
const session = decodeSession(created).session_handle.value;
const sessionNamespace = this.namespace.replace("/request/", "/session/");
if (!session.startsWith(sessionNamespace)) throw new Error("Invalid shortcut session handle.");
this.session = session;
this.shortcutId = this.managedByHyprland
? HYPRLAND_CAPTURE_ACTION
: `t3-snap-shot-${NodeCrypto.createHash("sha256").update(trigger).digest("hex").slice(0, 16)}`;
// Every session must bind, even when the desktop remembers this shortcut's approval.
const bound = await this.request("BindShortcuts", "oa(sa{sv})s", [
this.session,
[
[
this.shortcutId,
{
description: new Variant("s", "Capture a window"),
...(!this.managedByHyprland ? { preferred_trigger: new Variant("s", trigger) } : {}),
},
],
],
"",
]);
if (bound) this.bound(decodeShortcutsResult(bound).shortcuts.value);
}
}
@@ -0,0 +1,295 @@
import type * as Electron from "electron";
import { assert, beforeEach, expect, it, vi } from "vite-plus/test";
import type { ActiveWindow } from "./ActiveWindow.ts";
import type { RegionSnapShotChild, RegionSnapShotProcess } from "./RegionSnapShot.ts";
const { createFromBufferMock, resizeMock } = vi.hoisted(() => ({
createFromBufferMock: vi.fn(),
resizeMock: vi.fn(),
}));
vi.mock("electron", () => ({
nativeImage: { createFromBuffer: createFromBufferMock },
}));
import {
captureRegionWindowSnapshot,
makeRegionSnapShotPool,
startRegionSnapShotProcess,
} from "./RegionSnapShot.ts";
beforeEach(() => {
vi.clearAllMocks();
createFromBufferMock.mockReturnValue({ resize: resizeMock });
});
const active = {
title: "Editor",
owner: { name: "Editor", processId: 123 },
bounds: { x: 10, y: 20, width: 800, height: 600 },
} as ActiveWindow;
it("returns a small capture's PNG untouched", async () => {
const png = Buffer.from([1, 2, 3]);
const capture = vi.fn(async () => ({ width: 400, height: 300, png }));
const region = { x: 5, y: 10, width: 400, height: 300 };
const result = await captureRegionWindowSnapshot({ capture }, active, region, region);
assert.deepEqual(capture.mock.calls, [[region]]);
assert.strictEqual(result.png, png);
assert.deepEqual(result.source, { name: "Editor" });
assert.lengthOf(createFromBufferMock.mock.calls, 0);
});
it.each([
{ width: 600, height: 400, expected: { width: 240, height: 160 } },
{ width: 400, height: 600, expected: { width: 107, height: 160 } },
{ width: 600, height: 1, expected: { width: 256, height: 1 } },
])(
"bounds $width x $height physical pixels before encoding",
async ({ width, height, expected }) => {
const png = Buffer.from([1, 2, 3]);
const resizedPng = Buffer.from([4, 5, 6]);
const capture = vi.fn(async () => ({ width, height, png }));
resizeMock.mockReturnValue({ toPNG: () => resizedPng });
const result = await captureRegionWindowSnapshot({ capture }, active, active.bounds, {
width: 256,
height: 160,
});
assert.deepEqual(createFromBufferMock.mock.calls, [[png]]);
assert.deepEqual(resizeMock.mock.calls, [[{ ...expected, quality: "best" }]]);
assert.strictEqual(result.png, resizedPng);
},
);
function fakeChild() {
const messageListeners: Array<(message: unknown) => void> = [];
const exitListeners: Array<() => void> = [];
const send = vi.fn();
const kill = vi.fn();
const child: RegionSnapShotChild = {
send,
onMessage: (listener) => messageListeners.push(listener),
onExit: (listener) => exitListeners.push(listener),
kill,
};
return {
child,
send,
kill,
emit: (message: unknown) => {
for (const listener of messageListeners) listener(message);
},
exit: () => {
for (const listener of exitListeners) listener();
},
};
}
const region = { x: 0, y: 0, width: 2, height: 1 };
it("resolves the decoded capture once the child is ready and replies", async () => {
const fake = fakeChild();
const fork = vi.fn(() => fake.child);
const png = Buffer.from([9, 8, 7]);
const child = startRegionSnapShotProcess("worker.cjs", fork);
assert.deepEqual(fork.mock.calls, [["worker.cjs"]]);
assert.isTrue(child.alive);
const capture = child.capture(region);
await Promise.resolve();
assert.lengthOf(fake.send.mock.calls, 0);
fake.emit("ready");
await vi.waitFor(() => assert.deepEqual(fake.send.mock.calls, [[{ region }]]));
fake.emit({ type: "result", width: 2, height: 1, png: png.toString("base64") });
assert.deepEqual(await capture, { width: 2, height: 1, png });
assert.isFalse(child.alive);
assert.lengthOf(fake.kill.mock.calls, 1);
});
it("rejects with the child's error message", async () => {
const fake = fakeChild();
const child = startRegionSnapShotProcess("worker.cjs", () => fake.child);
const capture = child.capture(region);
fake.emit("ready");
fake.emit({ type: "error", message: "Screen capture failed" });
await expect(capture).rejects.toThrow("Screen capture failed");
assert.isFalse(child.alive);
});
it("rejects when the child exits before replying", async () => {
const fake = fakeChild();
const child = startRegionSnapShotProcess("worker.cjs", () => fake.child);
const capture = child.capture(region);
fake.emit("ready");
fake.exit();
await expect(capture).rejects.toThrow(/helper exited/);
});
it("serves a single capture per child", async () => {
const fake = fakeChild();
const child = startRegionSnapShotProcess("worker.cjs", () => fake.child);
const first = child.capture(region);
fake.emit("ready");
await vi.waitFor(() => assert.lengthOf(fake.send.mock.calls, 1));
fake.emit({ type: "result", width: 1, height: 1, png: Buffer.from([1]).toString("base64") });
await first;
await expect(child.capture(region)).rejects.toThrow(/already used/);
assert.lengthOf(fake.send.mock.calls, 1);
});
it("cancels a pending capture on close and kills the child", async () => {
const fake = fakeChild();
const child = startRegionSnapShotProcess("worker.cjs", () => fake.child);
const capture = child.capture(region);
child.close();
await expect(capture).rejects.toThrow(/cancelled/);
assert.lengthOf(fake.kill.mock.calls, 1);
assert.isFalse(child.alive);
fake.emit("ready");
assert.lengthOf(fake.send.mock.calls, 0);
});
it("reports an unavailable helper when the child cannot be forked", async () => {
const child = startRegionSnapShotProcess("worker.cjs", () => {
throw new Error("fork failed");
});
assert.isFalse(child.alive);
await expect(child.capture(region)).rejects.toThrow(/unavailable/);
});
it("times out a stalled capture", async () => {
vi.useFakeTimers();
try {
const fake = fakeChild();
const child = startRegionSnapShotProcess("worker.cjs", () => fake.child);
const failure = expect(child.capture(region)).rejects.toThrow(/timed out/);
fake.emit("ready");
await vi.advanceTimersByTimeAsync(15_000);
await failure;
assert.lengthOf(fake.kill.mock.calls, 1);
} finally {
vi.useRealTimers();
}
});
function fakeProcess() {
const result = Promise.withResolvers<{ width: number; height: number; png: Buffer }>();
void result.promise.catch(() => undefined);
let alive = true;
const close = vi.fn(() => {
alive = false;
result.reject(new Error("Windows window capture cancelled."));
});
const capture = vi.fn((_region: Electron.Rectangle) => result.promise);
const process: RegionSnapShotProcess = {
get alive() {
return alive;
},
capture,
close,
};
return {
process,
capture,
close,
resolve: (value: { width: number; height: number; png: Buffer }) => {
alive = false;
result.resolve(value);
},
};
}
function fakePool() {
const processes: Array<ReturnType<typeof fakeProcess>> = [];
const start = vi.fn(() => {
const process = fakeProcess();
processes.push(process);
return process.process;
});
return { pool: makeRegionSnapShotPool("worker.cjs", start), processes, start };
}
it("warms one standby child and keeps it while alive", () => {
const { pool, start } = fakePool();
pool.warm();
pool.warm();
assert.deepEqual(start.mock.calls, [["worker.cjs"]]);
});
it("captures with the standby child and warms a replacement afterwards", async () => {
const { pool, processes, start } = fakePool();
pool.warm();
const shot = { width: 1, height: 1, png: Buffer.from([1]) };
const capture = pool.capture(region);
assert.deepEqual(processes[0]!.capture.mock.calls, [[region]]);
assert.lengthOf(start.mock.calls, 1);
processes[0]!.resolve(shot);
assert.deepEqual(await capture, shot);
assert.lengthOf(start.mock.calls, 2);
assert.lengthOf(processes[1]!.capture.mock.calls, 0);
});
it("starts a child on demand when no standby is warm", async () => {
const { pool, processes, start } = fakePool();
const shot = { width: 1, height: 1, png: Buffer.from([1]) };
const capture = pool.capture(region);
assert.lengthOf(start.mock.calls, 1);
processes[0]!.resolve(shot);
assert.deepEqual(await capture, shot);
});
it("rejects a second capture while one is in flight", async () => {
const { pool, processes } = fakePool();
const first = pool.capture(region);
await expect(pool.capture(region)).rejects.toThrow(/still in progress/);
assert.lengthOf(processes, 1);
processes[0]!.resolve({ width: 1, height: 1, png: Buffer.from([1]) });
await first;
});
it("cools the standby child", () => {
const { pool, processes, start } = fakePool();
pool.warm();
pool.cool();
assert.lengthOf(processes[0]!.close.mock.calls, 1);
pool.warm();
assert.lengthOf(start.mock.calls, 2);
});
it("closes the standby and the in-flight child", async () => {
const { pool, processes } = fakePool();
pool.warm();
const capture = pool.capture(region);
pool.warm();
assert.lengthOf(processes, 2);
pool.close();
await expect(capture).rejects.toThrow(/cancelled/);
assert.lengthOf(processes[0]!.close.mock.calls, 1);
assert.lengthOf(processes[1]!.close.mock.calls, 1);
await expect(pool.capture(region)).rejects.toThrow(/unavailable/);
assert.lengthOf(processes, 2);
});
+204
View File
@@ -0,0 +1,204 @@
// @effect-diagnostics globalTimers:off -- Child-process deadlines run outside Effect fibers.
// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node child process.
import * as NodeChildProcess from "node:child_process";
import * as Electron from "electron";
import type { ActiveWindow } from "./ActiveWindow.ts";
const CAPTURE_TIMEOUT_MS = 15_000;
export type RegionSnapShotRequest = { readonly region: Electron.Rectangle };
export type RegionSnapShotResult =
| {
readonly type: "result";
readonly width: number;
readonly height: number;
readonly png: string;
}
| { readonly type: "error"; readonly message: string };
export type RegionSnapShotSource = {
readonly appIcon?: Electron.NativeImage;
readonly name: string;
};
export type RegionSnapShotChild = {
readonly send: (request: RegionSnapShotRequest) => void;
readonly onMessage: (listener: (message: unknown) => void) => void;
readonly onExit: (listener: () => void) => void;
readonly kill: () => void;
};
function forkRegionSnapShotChild(workerPath: string): RegionSnapShotChild {
const child = NodeChildProcess.fork(workerPath, [], {
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
execArgv: [],
stdio: ["ignore", "ignore", "inherit", "ipc"],
});
return {
send: (request) => child.send(request),
onMessage: (listener) => child.on("message", listener),
onExit: (listener) => {
child.once("exit", listener);
child.once("error", listener);
},
kill: () => child.kill(),
};
}
export type RegionSnapShotProcess = {
readonly alive: boolean;
readonly capture: (
region: Electron.Rectangle,
) => Promise<{ width: number; height: number; png: Buffer }>;
readonly close: () => void;
};
/**
* One capture child. `warm` it ahead of time so the native module is loaded
* before the shortcut fires; each child serves a single capture and exits.
*/
export function startRegionSnapShotProcess(
workerPath: string,
fork: (workerPath: string) => RegionSnapShotChild = forkRegionSnapShotChild,
): RegionSnapShotProcess {
let child: RegionSnapShotChild;
try {
child = fork(workerPath);
} catch {
return {
alive: false,
capture: () => Promise.reject(new Error("Windows window capture is unavailable.")),
close: () => undefined,
};
}
const ready = Promise.withResolvers<void>();
const result = Promise.withResolvers<{ width: number; height: number; png: Buffer }>();
let settled = false;
const finish = (error?: Error, value?: { width: number; height: number; png: Buffer }) => {
if (settled) return;
settled = true;
ready.resolve();
if (value) result.resolve(value);
else result.reject(error ?? new Error("Windows window capture failed."));
child.kill();
};
child.onMessage((message) => {
if (message === "ready") {
ready.resolve();
return;
}
const response = message as RegionSnapShotResult;
if (response.type === "error") finish(new Error(response.message));
else if (response.type === "result") {
finish(undefined, {
width: response.width,
height: response.height,
png: Buffer.from(response.png, "base64"),
});
}
});
child.onExit(() => finish(new Error("Windows window capture helper exited.")));
void result.promise.catch(() => undefined);
return {
get alive() {
return !settled;
},
capture: async (region) => {
if (settled) throw new Error("Windows window capture helper already used.");
const timeout = setTimeout(
() => finish(new Error("Windows window capture timed out. Try again.")),
CAPTURE_TIMEOUT_MS,
);
timeout.unref();
try {
await ready.promise;
if (settled) return await result.promise;
child.send({ region });
return await result.promise;
} finally {
clearTimeout(timeout);
}
},
close: () => finish(new Error("Windows window capture cancelled.")),
};
}
export type RegionSnapShotPool = {
readonly warm: () => void;
readonly cool: () => void;
readonly capture: (
region: Electron.Rectangle,
) => Promise<{ width: number; height: number; png: Buffer }>;
readonly close: () => void;
};
export function makeRegionSnapShotPool(
workerPath: string,
start: (workerPath: string) => RegionSnapShotProcess = startRegionSnapShotProcess,
): RegionSnapShotPool {
let standby: RegionSnapShotProcess | undefined;
let inFlight: RegionSnapShotProcess | undefined;
let closed = false;
const warm = () => {
if (closed || standby?.alive) return;
standby = start(workerPath);
};
const cool = () => {
standby?.close();
standby = undefined;
};
return {
warm,
cool,
capture: async (region) => {
if (closed) throw new Error("Windows window capture is unavailable.");
if (inFlight?.alive) {
throw new Error("Windows window capture is still in progress. Try again.");
}
const current = standby?.alive ? standby : start(workerPath);
standby = undefined;
inFlight = current;
try {
return await current.capture(region);
} finally {
if (inFlight === current) inFlight = undefined;
warm();
}
},
close: () => {
closed = true;
cool();
inFlight?.close();
},
};
}
export async function captureRegionWindowSnapshot(
pool: Pick<RegionSnapShotPool, "capture">,
active: ActiveWindow,
region: Electron.Rectangle,
maxSize: Electron.Size,
): Promise<{ readonly source: RegionSnapShotSource; readonly png: Buffer }> {
const shot = await pool.capture(region);
const scale = Math.min(maxSize.width / shot.width, maxSize.height / shot.height, 1);
const png =
scale < 1
? Electron.nativeImage
.createFromBuffer(shot.png)
.resize({
width: Math.max(1, Math.round(shot.width * scale)),
height: Math.max(1, Math.round(shot.height * scale)),
quality: "best",
})
.toPNG()
: shot.png;
return {
source: {
name: active.title.trim() || active.owner.name.trim() || "Window",
},
png,
};
}
@@ -0,0 +1,29 @@
// Windows region capture. Runs in a forked Node-mode child so the native
// screenshot call cannot crash or stall the main process. One request per child.
import type { RegionSnapShotRequest, RegionSnapShotResult } from "./RegionSnapShot.ts";
process.once("disconnect", () => process.exit(0));
async function capture() {
const imported = await import("@crowecawcaw/xa11y");
const xa11y = (imported as unknown as { readonly default?: typeof imported }).default ?? imported;
process.send?.("ready");
const request = await new Promise<RegionSnapShotRequest>((resolve) => {
process.once("message", resolve);
});
const shot = await xa11y.screenshot({ region: request.region });
const result: RegionSnapShotResult = {
type: "result",
width: shot.width,
height: shot.height,
png: shot.toPng().toString("base64"),
};
process.send?.(result);
}
void capture().catch((error: unknown) =>
process.send?.({
type: "error",
message: error instanceof Error ? error.message : "Windows window capture failed.",
} satisfies RegionSnapShotResult),
);
@@ -0,0 +1,223 @@
// @effect-diagnostics globalTimers:off -- Accessibility timeouts run outside Effect fibers.
import {
SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS,
type SnapShotAccessibility,
} from "@t3tools/contracts";
import type * as Electron from "electron";
import {
accessibleWindowElementTree,
accessibleWindowText,
compactAccessibilityTree,
findAccessibleWindow,
isWaylandSession,
} from "./snapShot.ts";
const ACCESSIBILITY_TIMEOUT_MS = 3_000;
export type AccessibleWindowIdentity = {
readonly title: string;
readonly bounds: Electron.Rectangle;
readonly clientBounds?: Electron.Rectangle;
readonly owner: { readonly processId: number };
readonly accessibilityBoundsReliable?: boolean;
};
export type CapturedWindowAccessibilityContext = {
readonly accessibleText?: string;
readonly accessibility?: SnapShotAccessibility;
};
export type SnapShotAccessibilityRequest = {
readonly active: AccessibleWindowIdentity;
readonly platform: NodeJS.Platform;
readonly sourceTitle: string;
readonly imageSize: Electron.Size;
};
type AccessibilityApp = (typeof import("@crowecawcaw/xa11y"))["App"];
type AccessibilityReadProgress = {
accessibleText: string | undefined;
flatComplete: boolean;
richComplete: boolean;
richLocationsReliable: boolean;
richRoot?: Extract<SnapShotAccessibility, { format: "element-tree" }>["root"];
richTruncated: boolean;
timedOut: boolean;
};
function accessibilityReadSnapshot(
progress: AccessibilityReadProgress,
imageSize: Electron.Size,
): CapturedWindowAccessibilityContext | undefined {
const richTree = progress.richRoot
? compactAccessibilityTree(progress.richRoot, {
descendantLocationsReliable: progress.richLocationsReliable,
})
: undefined;
const accessibleText =
progress.accessibleText ??
(richTree
? accessibleWindowText(richTree.root, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS)
: undefined);
const accessibility: SnapShotAccessibility | undefined =
progress.richComplete && richTree
? {
format: "element-tree",
coordinateSpace: "captured-image",
imageSize,
truncated: progress.richTruncated || richTree.truncated,
root: richTree.root,
}
: progress.flatComplete && accessibleText
? {
format: "flat-text",
text: accessibleText,
truncated: accessibleText.length >= SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS,
}
: richTree
? {
format: "element-tree",
coordinateSpace: "captured-image",
imageSize,
truncated: true,
root: richTree.root,
}
: undefined;
if (!accessibleText && !accessibility) return undefined;
return JSON.parse(
JSON.stringify({
...(accessibleText ? { accessibleText } : {}),
...(accessibility ? { accessibility } : {}),
}),
) as CapturedWindowAccessibilityContext;
}
async function readCapturedWindowAccessibility(
App: AccessibilityApp,
request: SnapShotAccessibilityRequest,
progress: AccessibilityReadProgress,
onStarted: () => void,
): Promise<CapturedWindowAccessibilityContext | undefined> {
const { active, platform, sourceTitle, imageSize } = request;
const foreground = platform === "win32" ? await App.foreground({ timeout: 0 }) : undefined;
const windows =
foreground !== undefined
? foreground.pid === active.owner.processId
? [foreground.asElement()]
: []
: await (await App.byPid(active.owner.processId, { timeout: 0 })).children();
const matchMode = isWaylandSession(platform, process.env) ? "wayland" : "screen-bounds";
const window = findAccessibleWindow(
windows,
{ title: active.title, sourceTitle, bounds: active.bounds, clientBounds: active.clientBounds },
matchMode,
);
if (!window) {
onStarted();
return undefined;
}
const accessibleBounds = window.bounds;
const matchingBounds =
matchMode === "wayland" &&
active.clientBounds &&
accessibleBounds &&
Math.abs(accessibleBounds.width - active.clientBounds.width) <= 2 &&
Math.abs(accessibleBounds.height - active.clientBounds.height) <= 2
? active.clientBounds
: active.bounds;
const locationsReliable =
active.accessibilityBoundsReliable !== false &&
(matchMode === "screen-bounds" ||
(accessibleBounds !== null &&
Math.abs(accessibleBounds.x - matchingBounds.x) <= 2 &&
Math.abs(accessibleBounds.y - matchingBounds.y) <= 2));
const flatRead = window
.tree()
.then((tree) => {
progress.accessibleText =
accessibleWindowText(tree, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS) || undefined;
progress.flatComplete = true;
})
.catch(() => {
progress.flatComplete = true;
});
// A decorated screenshot contains more than the accessibility client area. Keep its
// frame origin/scale so element coordinates include the actual decoration offset.
const sourceBounds =
matchMode === "wayland" && active.clientBounds
? active.bounds
: (accessibleBounds ?? active.bounds);
const richRead = accessibleWindowElementTree(window, sourceBounds, imageSize, {
locationsReliable,
onProgress: (root, truncated, descendantLocationsReliable) => {
progress.richLocationsReliable = descendantLocationsReliable;
progress.richRoot = root;
progress.richTruncated = truncated;
},
shouldContinue: () => !progress.timedOut,
verifyDescendantLocations: matchMode === "wayland",
})
.then((rich) => {
progress.richComplete = true;
if (rich) {
progress.richRoot = rich.root;
progress.richTruncated = rich.truncated;
}
})
.catch(() => {
progress.richComplete = true;
});
onStarted();
await Promise.all([flatRead, richRead]);
return accessibilityReadSnapshot(progress, imageSize);
}
let activeAccessibilityRead: Promise<unknown> | undefined;
async function raceAccessibleRead<T>(
run: () => Promise<T>,
timeoutValue: () => T | undefined,
): Promise<T | undefined> {
if (activeAccessibilityRead) return undefined;
const read = run().catch(() => undefined);
activeAccessibilityRead = read;
void read.finally(() => {
if (activeAccessibilityRead === read) activeAccessibilityRead = undefined;
});
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
read,
new Promise<T | undefined>((resolve) => {
timeout = setTimeout(() => resolve(timeoutValue()), ACCESSIBILITY_TIMEOUT_MS);
}),
]);
} finally {
if (timeout) clearTimeout(timeout);
}
}
export function readAccessibleWindowContextWithApp(
App: AccessibilityApp,
request: SnapShotAccessibilityRequest,
onStarted: () => void = () => undefined,
): Promise<CapturedWindowAccessibilityContext | undefined> {
const progress: AccessibilityReadProgress = {
accessibleText: undefined,
flatComplete: false,
richComplete: false,
richLocationsReliable: false,
richTruncated: false,
timedOut: false,
};
return raceAccessibleRead(
() => readCapturedWindowAccessibility(App, request, progress, onStarted),
() => {
progress.timedOut = true;
return accessibilityReadSnapshot(progress, request.imageSize);
},
);
}
@@ -0,0 +1,141 @@
import { assert, beforeEach, it } from "@effect/vitest";
import * as NodeEvents from "node:events";
import * as NodeProcess from "node:process";
import { vi } from "vite-plus/test";
const forkMock = vi.hoisted(() =>
vi.fn<
(
_path: string,
_args: ReadonlyArray<string>,
_options: { env?: NodeJS.ProcessEnv; execPath?: string },
) => unknown
>(),
);
vi.mock("node:child_process", () => ({ fork: forkMock }));
import {
makeSnapShotAccessibilityProcessPool,
startSnapShotAccessibilityProcess,
} from "./SnapShotAccessibilityProcess.ts";
const makeWorker = () =>
Object.assign(new NodeEvents.EventEmitter(), {
kill: vi.fn(() => true),
send: vi.fn(),
});
let worker = makeWorker();
const request = {
active: {
title: "Zoom Meeting",
bounds: { x: 10, y: 20, width: 800, height: 600 },
owner: { processId: 42 },
},
platform: "darwin" as const,
sourceTitle: "Zoom Meeting",
imageSize: { width: 1_600, height: 1_200 },
};
beforeEach(() => {
worker = makeWorker();
forkMock.mockReset().mockReturnValue(worker);
});
it("keeps T3 alive when Zoom crashes accessibility extraction", async () => {
const process = startSnapShotAccessibilityProcess("accessibility.cjs");
const read = process.read(request);
worker.emit("message", "ready");
worker.emit("message", "started");
await read.started;
worker.emit("exit", null, "SIGABRT");
assert.isUndefined(await read.result);
});
it("returns immediately when accessibility crashes before the screenshot is ready", async () => {
const process = startSnapShotAccessibilityProcess("accessibility.cjs");
worker.emit("exit", null, "SIGABRT");
const read = process.read(request);
await read.started;
assert.isUndefined(await read.result);
});
it("returns accessibility extracted by the helper", async () => {
const process = startSnapShotAccessibilityProcess("accessibility.cjs");
const read = process.read(request);
const context = { accessibleText: "Meeting controls" };
worker.emit("message", "ready");
worker.emit("message", "started");
worker.emit("message", { type: "result", context });
await read.started;
assert.deepEqual(await read.result, context);
assert.strictEqual(forkMock.mock.calls[0]?.[2]?.env?.ELECTRON_RUN_AS_NODE, "1");
assert.strictEqual(forkMock.mock.calls[0]?.[2]?.execPath, NodeProcess.execPath);
});
it("hands a warm helper to the capture and prewarms its replacement", async () => {
const warmWorker = makeWorker();
const replacementWorker = makeWorker();
forkMock.mockReset().mockReturnValueOnce(warmWorker).mockReturnValueOnce(replacementWorker);
const pool = makeSnapShotAccessibilityProcessPool("accessibility.cjs");
pool.warm();
warmWorker.emit("message", "ready");
const read = pool.read(request);
assert.lengthOf(forkMock.mock.calls, 2);
assert.deepEqual(warmWorker.send.mock.calls[0]?.[0], request);
assert.lengthOf(replacementWorker.send.mock.calls, 0);
warmWorker.emit("message", "started");
warmWorker.emit("message", { type: "result", context: { accessibleText: "Ready" } });
assert.deepEqual(await read.result, { accessibleText: "Ready" });
pool.close();
assert.lengthOf(replacementWorker.kill.mock.calls, 1);
});
it("replaces a warm helper that exits before capture", async () => {
const exitedWorker = makeWorker();
const captureWorker = makeWorker();
const replacementWorker = makeWorker();
forkMock
.mockReset()
.mockReturnValueOnce(exitedWorker)
.mockReturnValueOnce(captureWorker)
.mockReturnValueOnce(replacementWorker);
const pool = makeSnapShotAccessibilityProcessPool("accessibility.cjs");
pool.warm();
exitedWorker.emit("exit", 1);
const read = pool.read(request);
captureWorker.emit("message", "ready");
captureWorker.emit("message", "started");
captureWorker.emit("message", { type: "result", context: { accessibleText: "Recovered" } });
assert.deepEqual(await read.result, { accessibleText: "Recovered" });
assert.lengthOf(forkMock.mock.calls, 3);
assert.deepEqual(captureWorker.send.mock.calls[0]?.[0], request);
pool.close();
});
it("allows cold startup to exceed the request-start budget", async () => {
vi.useFakeTimers();
const process = startSnapShotAccessibilityProcess("accessibility.cjs");
try {
const read = process.read(request);
await vi.advanceTimersByTimeAsync(1_500);
assert.lengthOf(worker.kill.mock.calls, 0);
worker.emit("message", "ready");
assert.deepEqual(worker.send.mock.calls[0]?.[0], request);
worker.emit("message", "started");
worker.emit("message", { type: "result", context: { accessibleText: "Ready" } });
assert.deepEqual(await read.result, { accessibleText: "Ready" });
} finally {
process.close();
vi.useRealTimers();
}
});
@@ -0,0 +1,176 @@
// @effect-diagnostics globalTimers:off -- Helper timeouts run at child-process callback boundaries outside Effect fibers.
// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node child process.
import * as NodeChildProcess from "node:child_process";
import type {
CapturedWindowAccessibilityContext,
SnapShotAccessibilityRequest,
} from "./SnapShotAccessibility.ts";
const START_TIMEOUT_MS = 1_000;
const RESULT_TIMEOUT_MS = 4_000;
export type AccessibilityRead = {
readonly started: Promise<void>;
readonly result: Promise<CapturedWindowAccessibilityContext | undefined>;
};
export type AccessibilityProcess = {
readonly alive: boolean;
readonly read: (request: SnapShotAccessibilityRequest) => AccessibilityRead;
readonly close: () => void;
};
export type AccessibilityProcessPool = {
readonly warm: () => void;
readonly cool: () => void;
readonly read: (request: SnapShotAccessibilityRequest) => AccessibilityRead;
readonly close: () => void;
};
type AccessibilityMessage =
| "ready"
| "started"
| { readonly type: "result"; readonly context?: CapturedWindowAccessibilityContext };
const completedRead = (context?: CapturedWindowAccessibilityContext): AccessibilityRead => ({
started: Promise.resolve(),
result: Promise.resolve(context),
});
const unavailableProcess = (): AccessibilityProcess => ({
alive: false,
read: () => completedRead(),
close: () => undefined,
});
export function startSnapShotAccessibilityProcess(workerPath: string): AccessibilityProcess {
let worker: NodeChildProcess.ChildProcess;
try {
worker = NodeChildProcess.fork(workerPath, ["read"], {
// Electron defaults to its Helper executable on macOS, which does not
// share the main app's Accessibility grant checked during setup.
execPath: process.execPath,
env: {
...process.env,
ELECTRON_RUN_AS_NODE: "1",
},
execArgv: [],
stdio: ["ignore", "ignore", "inherit", "ipc"],
});
} catch {
return unavailableProcess();
}
let ready = false;
let request: SnapShotAccessibilityRequest | undefined;
let startedResolve: (() => void) | undefined;
let resultResolve: ((value: CapturedWindowAccessibilityContext | undefined) => void) | undefined;
let startTimeout: ReturnType<typeof setTimeout> | undefined;
let resultTimeout: ReturnType<typeof setTimeout> | undefined;
let settled = false;
let settledContext: CapturedWindowAccessibilityContext | undefined;
const clearTimers = () => {
if (startTimeout) clearTimeout(startTimeout);
if (resultTimeout) clearTimeout(resultTimeout);
};
const finish = (context?: CapturedWindowAccessibilityContext) => {
if (settled) return;
settled = true;
settledContext = context;
clearTimers();
startedResolve?.();
resultResolve?.(context);
worker.kill();
};
const sendRequest = () => {
if (!ready || !request || settled) return;
startTimeout ??= setTimeout(() => finish(), START_TIMEOUT_MS);
startTimeout.unref();
try {
worker.send(request, (error) => {
if (error) finish();
});
} catch {
finish();
}
};
worker.on("message", (rawMessage) => {
const message = rawMessage as AccessibilityMessage;
if (message === "ready") {
ready = true;
sendRequest();
} else if (message === "started") {
if (startTimeout) clearTimeout(startTimeout);
startedResolve?.();
} else {
finish(message.context);
}
});
worker.once("error", () => finish());
worker.once("exit", () => finish());
return {
get alive() {
return !settled;
},
read: (nextRequest) => {
if (settled) return completedRead(settledContext);
request = nextRequest;
const started = Promise.withResolvers<void>();
const result = Promise.withResolvers<CapturedWindowAccessibilityContext | undefined>();
startedResolve = started.resolve;
resultResolve = result.resolve;
resultTimeout = setTimeout(() => finish(), RESULT_TIMEOUT_MS);
resultTimeout.unref();
sendRequest();
return { started: started.promise, result: result.promise };
},
close: () => finish(),
};
}
export function makeSnapShotAccessibilityProcessPool(workerPath: string): AccessibilityProcessPool {
let standby: AccessibilityProcess | undefined;
const active = new Set<AccessibilityProcess>();
let closed = false;
const warm = () => {
if (closed || standby?.alive) return;
standby = startSnapShotAccessibilityProcess(workerPath);
};
const cool = () => {
standby?.close();
standby = undefined;
};
return {
warm,
cool,
read: (request) => {
if (closed) return completedRead();
const workerProcess = standby?.alive
? standby
: startSnapShotAccessibilityProcess(workerPath);
standby = undefined;
warm();
active.add(workerProcess);
const read = workerProcess.read(request);
void read.result.then(
() => active.delete(workerProcess),
() => active.delete(workerProcess),
);
return read;
},
close: () => {
if (closed) return;
closed = true;
cool();
for (const workerProcess of active) workerProcess.close();
active.clear();
},
};
}
@@ -0,0 +1,29 @@
import {
readAccessibleWindowContextWithApp,
type SnapShotAccessibilityRequest,
} from "./SnapShotAccessibility.ts";
process.once("disconnect", () => process.exit(0));
async function readAccessibility() {
const { App } = await import("@crowecawcaw/xa11y");
process.send?.("ready");
const request = await new Promise<SnapShotAccessibilityRequest>((resolve) => {
process.once("message", resolve);
});
let started = false;
const markStarted = () => {
if (started) return;
started = true;
process.send?.("started");
};
const context = await readAccessibleWindowContextWithApp(App, request, markStarted).catch(
() => undefined,
);
markStarted();
process.send?.({ type: "result", context });
}
if (process.argv[2] === "read") {
void readAccessibility().catch(() => process.send?.({ type: "result" }));
}
@@ -0,0 +1,450 @@
import * as Effect from "effect/Effect";
import type * as Fiber from "effect/Fiber";
import * as Electron from "electron";
const MIN_DURATION_MS = 280;
const MAX_DURATION_MS = 680;
const DURATION_DISTANCE_SCALE = 2_000;
const EASING = "cubic-bezier(.2,.8,.2,1)";
const TIMEOUT_MS = 6_000;
type SnapShotAnimationDetails = {
readonly appName: string;
readonly windowTitle: string;
readonly appIconDataUrl?: string | undefined;
};
export type SnapShotAnimationDestination = {
readonly frame: Electron.Rectangle;
/** Unit coordinates in T3's content area; GNOME supplies the real compositor origin. */
readonly relativeFrame?: Electron.Rectangle | undefined;
readonly backgroundColor: string;
readonly borderColor: string;
readonly borderWidth: number;
readonly cornerRadius: number;
readonly scaleFactor: number;
readonly details?: SnapShotAnimationDetails | undefined;
};
export function snapShotAnimationDurationMs(
source: Electron.Rectangle,
target: Electron.Rectangle,
): number {
const distance = Math.hypot(
source.x + source.width / 2 - target.x - target.width / 2,
source.y + source.height / 2 - target.y - target.height / 2,
);
return (
MAX_DURATION_MS -
(MAX_DURATION_MS - MIN_DURATION_MS) * Math.exp(-distance / DURATION_DISTANCE_SCALE)
);
}
type ActiveTransition = {
readonly id: string;
readonly source: Electron.Rectangle;
readonly snapshotDataUrl: string;
readonly overlays: Array<{
readonly window: Electron.BrowserWindow;
readonly requestedBounds: Electron.Rectangle;
bounds: Electron.Rectangle;
}>;
details?: SnapShotAnimationDetails | undefined;
timer?: Fiber.Fiber<void> | undefined;
flight?: Promise<void> | undefined;
};
type SnapShotTransitionOptions = {
readonly showWindow?: ((window: Electron.BaseWindow) => void) | undefined;
readonly boundOverlayToCaptureDisplays?: boolean | undefined;
readonly waitForCompositorFrame?: boolean | undefined;
readonly alwaysOnTopLevel?:
| NonNullable<Parameters<Electron.BrowserWindow["setAlwaysOnTop"]>[1]>
| undefined;
};
export function snapShotAnimationOverlayBounds(
displays: ReadonlyArray<Pick<Electron.Display, "bounds">>,
): Electron.Rectangle {
const firstDisplay = displays[0];
const first = firstDisplay?.bounds ?? { x: 0, y: 0, width: 1, height: 1 };
let left = first.x;
let top = first.y;
let right = first.x + first.width;
let bottom = first.y + first.height;
for (const display of displays.slice(1)) {
const bounds = display.bounds;
left = Math.min(left, bounds.x);
top = Math.min(top, bounds.y);
right = Math.max(right, bounds.x + bounds.width);
bottom = Math.max(bottom, bounds.y + bounds.height);
}
return { x: left, y: top, width: right - left, height: bottom - top };
}
export function snapShotAnimationDisplayBounds(
displays: ReadonlyArray<Pick<Electron.Display, "bounds">>,
source: Electron.Rectangle,
destination: Electron.Rectangle,
): Array<Electron.Rectangle> {
const flight = snapShotAnimationOverlayBounds([{ bounds: source }, { bounds: destination }]);
return displays
.map((display) => display.bounds)
.filter(
(bounds) =>
bounds.x < flight.x + flight.width &&
bounds.x + bounds.width > flight.x &&
bounds.y < flight.y + flight.height &&
bounds.y + bounds.height > flight.y,
);
}
function createWindow(
bounds: Electron.Rectangle,
alwaysOnTopLevel: SnapShotTransitionOptions["alwaysOnTopLevel"],
): Electron.BrowserWindow {
const window = new Electron.BrowserWindow({
...bounds,
alwaysOnTop: true,
backgroundColor: "#00000000",
focusable: false,
frame: false,
hasShadow: false,
resizable: false,
show: false,
skipTaskbar: true,
title: "T3 Code Snapshot Animation",
transparent: true,
webPreferences: {
backgroundThrottling: false,
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
if (alwaysOnTopLevel) window.setAlwaysOnTop(true, alwaysOnTopLevel);
window.setIgnoreMouseEvents(true);
return window;
}
function transitionHtml(
sourceBounds: Electron.Rectangle,
overlayBounds: Electron.Rectangle,
flash: boolean,
): string {
const source = {
x: sourceBounds.x - overlayBounds.x,
y: sourceBounds.y - overlayBounds.y,
width: sourceBounds.width,
height: sourceBounds.height,
};
return `<!doctype html><style>
html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent}
#card{position:absolute;left:${source.x}px;top:${source.y}px;width:${source.width}px;height:${source.height}px;contain:strict;overflow:hidden;border-radius:12px;background:#fff;box-shadow:0 24px 70px rgba(0,0,0,.24);transform-origin:center;will-change:transform}
#content{position:absolute;inset:0;overflow:hidden;border-radius:inherit;transform-origin:center;will-change:transform}
#snapshot{position:absolute;inset:0;width:100%;height:100%;object-fit:fill;transform-origin:center;will-change:transform}
#flash{position:absolute;inset:0;background:#fff;opacity:0;${flash ? "" : "display:none"}}
#details{--scale:1;position:absolute;inset-inline:0;bottom:0;display:flex;align-items:center;gap:calc(6px * var(--scale));padding:calc(24px * var(--scale)) calc(10px * var(--scale)) calc(8px * var(--scale));background:linear-gradient(to top,rgba(0,0,0,.85),rgba(0,0,0,.55),transparent);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;opacity:0}
#details:not([data-ready]){visibility:hidden}
#icon,#fallback{width:calc(28px * var(--scale));height:calc(28px * var(--scale));flex:none;border-radius:calc(6px * var(--scale))}
#icon{display:none;object-fit:cover}
#fallback{display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.2);color:#fff;font-size:calc(10px * var(--scale));font-weight:500;text-transform:uppercase}
#copy{min-width:0;flex:1}#app,#title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:calc(14px * var(--scale))}
#app{color:#fff;font-size:calc(11px * var(--scale));font-weight:500}#title{color:rgba(255,255,255,.7);font-size:calc(9px * var(--scale))}
#border{position:absolute;z-index:2;inset:0;box-sizing:border-box;border:0 solid transparent;border-radius:inherit;opacity:0}
</style><div id="card"><div id="content"><img id="snapshot"><div id="details"><img id="icon"><div id="fallback"></div><div id="copy"><div id="app"></div><div id="title"></div></div></div></div><div id="border"></div><div id="flash"></div></div><script>
const source=${JSON.stringify(source)},card=document.getElementById("card"),content=document.getElementById("content"),snapshot=document.getElementById("snapshot"),details=document.getElementById("details"),border=document.getElementById("border");
const afterPaint=()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
window.setCaptureSnapshot=async src=>{snapshot.src=src;await snapshot.decode();await afterPaint()};
window.rebaseCaptureSource=next=>{Object.assign(source,next);Object.assign(card.style,{left:source.x+"px",top:source.y+"px",width:source.width+"px",height:source.height+"px"})};
window.startCaptureFlash=()=>document.getElementById("flash").animate([{opacity:.08},{offset:.38,opacity:.08},{offset:.68,opacity:.02},{opacity:0}],{duration:300,fill:"forwards",easing:"${EASING}"});
const applyDetails=value=>{
if(!value)return;
details.dataset.ready="";
document.getElementById("app").textContent=value.appName;
document.getElementById("title").textContent=value.windowTitle||"Captured window";
document.getElementById("fallback").textContent=value.appName.slice(0,1);
if(value.appIconDataUrl){
const icon=document.getElementById("icon");icon.src=value.appIconDataUrl;icon.style.display="block";document.getElementById("fallback").style.display="none";
}
};
window.updateCaptureDetails=applyDetails;
window.prepareCaptureTransition=async destination=>{
const target=destination.frame,borderWidth=Math.min(Math.max(0,destination.borderWidth),Math.max(0,(Math.min(target.width,target.height)-1)/2));
const inner={width:Math.max(1,target.width-borderWidth*2),height:Math.max(1,target.height-borderWidth*2)};
const sourceCenter={x:source.x+source.width/2,y:source.y+source.height/2},targetCenter={x:target.x+target.width/2,y:target.y+target.height/2};
const initial="translate3d("+(sourceCenter.x-targetCenter.x)+"px,"+(sourceCenter.y-targetCenter.y)+"px,0) scale("+(source.width/target.width)+","+(source.height/target.height)+")";
const imageWidth=Math.max(1,snapshot.naturalWidth||source.width),imageHeight=Math.max(1,snapshot.naturalHeight||source.height),cover=Math.max(inner.width/imageWidth,inner.height/imageHeight);
Object.assign(card.style,{left:target.x+"px",top:target.y+"px",width:target.width+"px",height:target.height+"px",borderRadius:destination.cornerRadius+"px",backgroundColor:destination.backgroundColor,boxShadow:"none"});
Object.assign(content.style,{inset:borderWidth+"px",borderRadius:Math.max(0,destination.cornerRadius-borderWidth)+"px"});
Object.assign(border.style,{borderWidth:borderWidth+"px",borderColor:destination.borderColor});
details.style.setProperty("--scale",String(destination.scaleFactor));
applyDetails(destination.details);
const options={duration:destination.durationMs,fill:"forwards",easing:"${EASING}"};
const animations=[
card.animate([{transform:initial},{transform:"translate3d(0,0,0) scale(1)"}],options),
content.animate([{transform:"scale("+(target.width/inner.width)+","+(target.height/inner.height)+")"},{transform:"scale(1)"}],options),
snapshot.animate([{transform:"scale(1)"},{transform:"scale("+((imageWidth*cover)/inner.width)+","+((imageHeight*cover)/inner.height)+")"}],options),
border.animate([{opacity:0},{opacity:1}],options),
details.animate([{opacity:0},{opacity:1}],{delay:Math.max(0,destination.durationMs-125),duration:125,fill:"both",easing:"ease-in"})
];
for(const animation of animations){animation.pause();animation.currentTime=0}
window.playCaptureTransition=async()=>{
for(const animation of animations)animation.play();
await Promise.all(animations.map(animation=>animation.finished.catch(()=>undefined)));
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
};
await afterPaint();
};
</script>`;
}
export class SnapShotTransition {
private active: ActiveTransition | undefined;
private readonly boundOverlayToCaptureDisplays: boolean;
private readonly waitForCompositorFrame: boolean;
private readonly alwaysOnTopLevel: SnapShotTransitionOptions["alwaysOnTopLevel"];
private readonly showWindow: (window: Electron.BaseWindow) => void;
constructor(options: SnapShotTransitionOptions = {}) {
this.boundOverlayToCaptureDisplays = options.boundOverlayToCaptureDisplays ?? false;
this.waitForCompositorFrame = options.waitForCompositorFrame ?? false;
this.alwaysOnTopLevel = options.alwaysOnTopLevel;
this.showWindow = options.showWindow ?? ((window) => window.showInactive());
}
async begin(
id: string,
source: Electron.Rectangle,
snapshotDataUrl: string,
flash: boolean,
destinationWindowBounds?: Electron.Rectangle,
): Promise<void> {
this.dispose();
const sourceDisplay = Electron.screen.getDisplayMatching(source);
const requestedBounds = this.boundOverlayToCaptureDisplays
? snapShotAnimationDisplayBounds(
[
sourceDisplay,
...Electron.screen.getAllDisplays().filter((d) => d.id !== sourceDisplay.id),
],
source,
destinationWindowBounds ?? source,
)
: [snapShotAnimationOverlayBounds(Electron.screen.getAllDisplays())];
const active: ActiveTransition = {
id,
source,
snapshotDataUrl,
overlays: [],
};
active.timer = Effect.runFork(
Effect.sleep(TIMEOUT_MS).pipe(
Effect.andThen(
Effect.sync(() => {
if (this.active === active) this.dispose();
}),
),
),
);
this.active = active;
try {
await this.showOverlays(active, requestedBounds, flash);
} catch (error) {
if (this.active === active) this.dispose();
throw error;
}
}
private async showOverlays(
active: ActiveTransition,
requestedBounds: ReadonlyArray<Electron.Rectangle>,
flash: boolean,
): Promise<void> {
const overlays: ActiveTransition["overlays"] = [];
try {
for (const bounds of requestedBounds) {
const window = createWindow(bounds, this.alwaysOnTopLevel);
const overlay = { window, requestedBounds: bounds, bounds: window.getBounds() };
active.overlays.push(overlay);
overlays.push(overlay);
}
await Promise.all(
overlays.map(async (overlay) => {
await overlay.window.loadURL(
"data:text/html;charset=utf-8," +
encodeURIComponent(transitionHtml(active.source, overlay.bounds, flash)),
);
if (this.active === active && !overlay.window.isDestroyed()) {
await overlay.window.webContents.executeJavaScript(
`window.setCaptureSnapshot(${JSON.stringify(active.snapshotDataUrl)})`,
);
}
}),
);
for (const overlay of overlays) {
if (this.active !== active) return;
if (overlay.window.isDestroyed()) continue;
this.showWindow(overlay.window);
const bounds = overlay.window.getBounds();
if (
bounds.x !== overlay.bounds.x ||
bounds.y !== overlay.bounds.y ||
bounds.width !== overlay.bounds.width ||
bounds.height !== overlay.bounds.height
) {
overlay.bounds = bounds;
await overlay.window.webContents.executeJavaScript(
`window.rebaseCaptureSource(${JSON.stringify({
x: active.source.x - bounds.x,
y: active.source.y - bounds.y,
width: active.source.width,
height: active.source.height,
})})`,
);
}
}
if (this.waitForCompositorFrame) {
// Cover the source with a composited snapshot before the caller reveals T3.
// Decoding and renderer animation frames alone can leave a transparent gap.
await Promise.all(
overlays.map(async (overlay) => {
if (this.active !== active || overlay.window.isDestroyed()) return;
await overlay.window.webContents.capturePage({ x: 0, y: 0, width: 1, height: 1 });
}),
);
}
if (this.active !== active) return;
if (flash) {
await Promise.all(
overlays.map(async (overlay) => {
if (overlay.window.isDestroyed()) return;
await overlay.window.webContents
.executeJavaScript("window.startCaptureFlash()")
.catch(() => undefined);
}),
);
}
} catch (error) {
for (const overlay of overlays) {
if (!overlay.window.isDestroyed()) overlay.window.destroy();
}
throw error;
}
}
animateTo(id: string, destination: SnapShotAnimationDestination): void {
const active = this.active;
if (!active || active.id !== id) return;
if (destination.details) active.details = destination.details;
if (active.flight) {
if (destination.details) {
for (const overlay of active.overlays) {
if (overlay.window.isDestroyed()) continue;
void overlay.window.webContents
.executeJavaScript(
"window.updateCaptureDetails(" + JSON.stringify(destination.details) + ")",
)
.catch(() => undefined);
}
}
return;
}
active.flight = this.runFlight(active, destination);
}
private async runFlight(
active: ActiveTransition,
destination: SnapShotAnimationDestination,
): Promise<void> {
if (this.active !== active) return;
if (this.boundOverlayToCaptureDisplays) {
const missingBounds = snapShotAnimationDisplayBounds(
Electron.screen.getAllDisplays(),
active.source,
destination.frame,
).filter(
(bounds) =>
!active.overlays.some(
(overlay) =>
!overlay.window.isDestroyed() &&
overlay.requestedBounds.x === bounds.x &&
overlay.requestedBounds.y === bounds.y &&
overlay.requestedBounds.width === bounds.width &&
overlay.requestedBounds.height === bounds.height,
),
);
if (missingBounds.length > 0) {
await this.showOverlays(active, missingBounds, false).catch(() => undefined);
}
}
if (this.active !== active) return;
const durationMs = snapShotAnimationDurationMs(active.source, destination.frame);
const prepared = await Promise.allSettled(
active.overlays.map(async (overlay) => {
if (overlay.window.isDestroyed()) return;
await overlay.window.webContents.executeJavaScript(
`window.prepareCaptureTransition(${JSON.stringify({
...destination,
frame: {
x: destination.frame.x - overlay.bounds.x,
y: destination.frame.y - overlay.bounds.y,
width: destination.frame.width,
height: destination.frame.height,
},
borderWidth: Math.max(0, destination.borderWidth),
cornerRadius: Math.max(0, destination.cornerRadius),
scaleFactor: Math.max(0.1, destination.scaleFactor),
details: active.details,
durationMs,
})})`,
);
if (this.active !== active || overlay.window.isDestroyed()) return;
if (this.waitForCompositorFrame) {
// Read back one pixel after preparation to flush queued compositor work
// before the animation clock starts on any of the display surfaces.
await overlay.window.webContents.capturePage({ x: 0, y: 0, width: 1, height: 1 });
}
return overlay;
}),
);
if (this.active !== active) return;
// One display failing must not cut the flight short on the others.
await Promise.allSettled(
prepared.map((result) => {
if (result.status !== "fulfilled" || !result.value || result.value.window.isDestroyed()) {
return;
}
return result.value.window.webContents.executeJavaScript("window.playCaptureTransition()");
}),
);
}
async waitForLanding(id: string): Promise<void> {
const active = this.active;
if (!active || active.id !== id) return;
await active.flight?.catch(() => undefined);
}
async complete(id: string): Promise<void> {
const active = this.active;
if (!active || active.id !== id) return;
await this.waitForLanding(id);
if (this.active === active) this.dispose();
}
dismiss(id: string): void {
if (this.active?.id === id) this.dispose();
}
dispose(): void {
const active = this.active;
this.active = undefined;
if (!active) return;
active.timer?.interruptUnsafe();
for (const overlay of active.overlays) {
if (!overlay.window.isDestroyed()) overlay.window.destroy();
}
}
}
@@ -0,0 +1,61 @@
import type * as Electron from "electron";
import { beforeEach, expect, it, vi } from "vite-plus/test";
const switches = vi.hoisted(() => new Set<string>());
vi.mock("electron", () => ({
app: {
commandLine: {
hasSwitch: (name: string) => switches.has(name),
appendSwitch: (name: string) => switches.add(name),
removeSwitch: (name: string) => switches.delete(name),
},
},
}));
import { showWindowsCaptureOverlay } from "./WindowsCaptureFeedback.ts";
const animationSwitch = "wm-window-animations-disabled";
function overlay(showInactive: () => void) {
return { showInactive } as Electron.BaseWindow;
}
beforeEach(() => {
switches.clear();
switches.add("unrelated-switch");
});
it("disables Chromium window animation only while showing the capture overlay", () => {
const flagsDuringShow: string[][] = [];
showWindowsCaptureOverlay(overlay(() => flagsDuringShow.push([...switches])));
expect(flagsDuringShow).toEqual([["unrelated-switch", animationSwitch]]);
expect([...switches]).toEqual(["unrelated-switch"]);
});
it("preserves an animation switch supplied before capture", () => {
switches.add(animationSwitch);
const flagsDuringShow: string[][] = [];
showWindowsCaptureOverlay(overlay(() => flagsDuringShow.push([...switches])));
expect(flagsDuringShow).toEqual([["unrelated-switch", animationSwitch]]);
expect([...switches]).toEqual(["unrelated-switch", animationSwitch]);
});
it.each([false, true])(
"restores the original switch state when showing throws (preexisting: %s)",
(preexisting) => {
if (preexisting) switches.add(animationSwitch);
const original = [...switches];
const failure = new Error("Overlay was destroyed");
const window = overlay(() => {
expect(switches.has(animationSwitch)).toBe(true);
throw failure;
});
expect(() => showWindowsCaptureOverlay(window)).toThrow(failure);
expect([...switches]).toEqual(original);
},
);
@@ -0,0 +1,16 @@
import * as Electron from "electron";
const WINDOW_ANIMATIONS_DISABLED = "wm-window-animations-disabled";
/** Show capture feedback without Aura's extra 200 ms fade/scale on transparent windows. */
export function showWindowsCaptureOverlay(window: Electron.BaseWindow): void {
// Chromium reads this switch synchronously inside Show(). Restore it before returning
// so other windows and CSS animations keep their normal behavior.
const alreadyDisabled = Electron.app.commandLine.hasSwitch(WINDOW_ANIMATIONS_DISABLED);
if (!alreadyDisabled) Electron.app.commandLine.appendSwitch(WINDOW_ANIMATIONS_DISABLED);
try {
window.showInactive();
} finally {
if (!alreadyDisabled) Electron.app.commandLine.removeSwitch(WINDOW_ANIMATIONS_DISABLED);
}
}
@@ -0,0 +1,135 @@
import { describe, expect, it } from "vite-plus/test";
import {
captureConfigBinding,
editCaptureConfig,
niriConfigConflict,
niriConfigIncludes,
} from "./captureConfigEdit.ts";
import { readKdlNodes } from "./captureConfigKdl.ts";
const app = "com.t3tools.T3Code";
const binding = captureConfigBinding("niri", app, "Ctrl+Shift+2");
describe("Niri capture config edits", () => {
it("inserts into the existing top-level binds, preserving unrelated text", () => {
const before =
'// My desktop\ninput { keyboard { xkb { layout "us"; }; }; }\nbinds {\n Mod+Q { spawn "kitty"; } // keep me\n}\n';
const result = editCaptureConfig(before, "niri", app, "install");
expect(result.after).toBe(before.replace("\n}\n", `\n ${binding}\n}\n`));
expect(readKdlNodes(result.after).filter((node) => node.name === "binds")).toHaveLength(1);
});
it("ignores commented, nested, and string-valued binds and braces", () => {
const before = `// binds { fake\n/* binds { /* nested */ } */\n/- binds { Ctrl+Shift+2 { quit; } }\nrecent-windows { binds { Alt+Tab { next-window; } }; }\nspawn-at-startup "echo" r#"binds { }"#\n"binds" {\n Mod+Q { spawn "a } \\" b"; }\n}\n`;
// A quoted brace in a valid shell argument must not close the binds section.
const valid = before.replace('"a } \\" b"', '"a } b"');
const result = editCaptureConfig(valid, "niri", app, "install");
expect(result.after).toContain(` ${binding}\n}\n`);
expect(result.after.startsWith(valid.slice(0, valid.indexOf('"binds" {')))).toBe(true);
});
it.each(["binds {}", "binds { Mod+Q { quit; }; }", "input { }\n", ""])(
"handles compact or absent binds: %s",
(before) => {
const result = editCaptureConfig(before, "niri", app, "install");
const block = readKdlNodes(result.after).find((node) => node.name === "binds")!;
expect(block.children.some((node) => node.name === "Ctrl+Shift+2")).toBe(true);
},
);
it("preserves CRLF and the UTF-8 BOM", () => {
const before = "\uFEFFbinds {\r\n}\r\n";
expect(editCaptureConfig(before, "niri", app, "install").after).toBe(
`\uFEFFbinds {\r\n ${binding}\r\n}\r\n`,
);
});
it("preserves Unicode spacing around nodes and line continuations", () => {
const spaces =
"\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000";
const before = `binds${spaces}\\${spaces}\n{\n}\n`;
expect(editCaptureConfig(before, "niri", app, "install").after).toBe(
before.replace("}\n", ` ${binding}\n}\n`),
);
});
it("does not duplicate an existing binding, including a custom chord", () => {
const before = `binds {\n ${binding.replace("Ctrl+Shift+2", "Alt+Ctrl+Y")}\n}\n`;
const result = editCaptureConfig(before, "niri", app, "install");
expect(result.after).toBe(before);
expect(result.shortcut).toBe("Ctrl+Alt+Y");
});
it("replaces and removes only this app's capture binding", () => {
const other = captureConfigBinding("niri", "com.t3tools.Other", "Ctrl+Alt+4");
const before = `binds {\n ${binding}\n ${other}\n}\n`;
const result = editCaptureConfig(before, "niri", app, "install", "Ctrl+Alt+Y");
expect(result.after).toContain(other);
expect(result.after).not.toContain("Ctrl+Shift+2");
expect(result.after).toContain("Ctrl+Alt+Y");
const removed = editCaptureConfig(result.after, "niri", app, "remove");
expect(removed.after).toBe(`binds {\n ${other}\n}\n`);
});
it("refuses occupied keys regardless of modifier order, without removing them", () => {
const before = "binds { Shift+Control+2 { quit; } }";
expect(niriConfigConflict(before, app, "Ctrl+Shift+2")).toBe(true);
expect(() => editCaptureConfig(before, "niri", app, "install")).toThrow("already used");
});
it("does not count a slash-dash-disabled key as occupied", () => {
expect(niriConfigConflict("binds { /- Ctrl+Shift+2 { quit; }; }", app, "Ctrl+Shift+2")).toBe(
false,
);
});
it.each(["binds {", "binds {}\nbinds {}", "/* unfinished", 'spawn "unfinished'])(
"fails safely for malformed structure: %s",
(source) => {
expect(() => editCaptureConfig(source, "niri", app, "install")).toThrow();
},
);
it("reads only real top-level include directives", () => {
expect(
niriConfigIncludes(
'// include "no"\n/- include "no"\ninclude "keys.kdl"\ninclude optional=true "extra.kdl"',
),
).toEqual([
{ path: "keys.kdl", optional: false },
{ path: "extra.kdl", optional: true },
]);
});
});
describe("Hyprland capture config edits", () => {
it.each(["hyprland", "hyprland-lua"] as const)(
"is idempotent and reversible for %s",
(format) => {
const before =
format === "hyprland"
? "# Keep my preferences\n$mainMod = SUPER\n"
: "-- Keep my preferences\nhl.config({ general = { border_size = 2 } })\n";
const added = editCaptureConfig(before, format, app, "install");
expect(added.after.startsWith(before)).toBe(true);
expect(editCaptureConfig(added.after, format, app, "install").after).toBe(added.after);
const changed = editCaptureConfig(added.after, format, app, "install", "Ctrl+Alt+Y");
expect(changed.after).not.toContain(captureConfigBinding(format, app, "Ctrl+Shift+2"));
expect(changed.after).toContain(captureConfigBinding(format, app, "Ctrl+Alt+Y"));
expect(editCaptureConfig(changed.after, format, app, "remove").after.trim()).toBe(
before.trim(),
);
},
);
it("does not steal an existing legacy shortcut", () => {
expect(() =>
editCaptureConfig("bind = SHIFT CTRL, 2, exec, kitty\n", "hyprland", app, "install"),
).toThrow("already used");
});
it("leaves commented bindings alone", () => {
const before = "# bind = CTRL SHIFT, 2, global, com.t3tools.T3Code:capture-window\n";
expect(editCaptureConfig(before, "hyprland", app, "remove").after).toBe(before);
});
it.each([
"return {}",
'--[[\nhl.bind("CTRL + SHIFT + 2", hl.dsp.global("com.t3tools.T3Code:capture-window"))\n]]',
])("does not guess how to edit complex Lua", (source) => {
expect(() => editCaptureConfig(source, "hyprland-lua", app, "install")).toThrow("manual edit");
});
it.each(['Ctrl+"\nexec', "Ctrl+;", "2", "Mod+2"])(
"rejects unsafe or ambiguous keys: %s",
(keys) => {
expect(() => editCaptureConfig("", "hyprland", app, "install", keys)).toThrow();
},
);
});
@@ -0,0 +1,195 @@
import { parseKeybindingShortcut } from "@t3tools/shared/keybindings";
import { readKdlNodes, type KdlNode } from "./captureConfigKdl.ts";
import { niriCaptureBinding } from "./linuxCaptureSession.ts";
export type CaptureConfigFormat = "niri" | "hyprland" | "hyprland-lua";
export function captureConfigKeys(input = "Ctrl+Shift+2") {
const keys = parseKeybindingShortcut(input.replace(/super/gi, "meta"));
if (
!keys ||
keys.modKey ||
!/^(?:[a-z0-9]|f(?:[1-9]|1[0-9]|2[0-4]))$/.test(keys.key) ||
!(keys.ctrlKey || keys.altKey || keys.metaKey)
)
throw new Error("Choose a letter, number, or function key with Ctrl, Alt, or Super.");
const modifiers = [
keys.ctrlKey && "Ctrl",
keys.altKey && "Alt",
keys.shiftKey && "Shift",
keys.metaKey && "Super",
].filter(Boolean);
return {
label: [...modifiers, keys.key.toUpperCase()].join("+"),
modifiers: modifiers.map((key) => String(key).toUpperCase()).join(" "),
key: keys.key.toUpperCase(),
mask:
(keys.shiftKey ? 1 : 0) |
(keys.ctrlKey ? 4 : 0) |
(keys.altKey ? 8 : 0) |
(keys.metaKey ? 64 : 0),
};
}
function sameKeys(left: string, right: string) {
try {
return captureConfigKeys(left).label === captureConfigKeys(right).label;
} catch {
return false;
}
}
export function captureConfigBinding(format: CaptureConfigFormat, appId: string, keys: string) {
if (!/^[A-Za-z0-9_.-]+$/.test(appId)) throw new Error("Invalid capture application ID.");
const chord = captureConfigKeys(keys);
if (format === "niri") return niriCaptureBinding(appId).replace("Ctrl+Shift+2", chord.label);
const action = `${appId}:capture-window`;
return format === "hyprland-lua"
? `hl.bind("${chord.label.toUpperCase().replaceAll("+", " + ")}", hl.dsp.global("${action}"))`
: `bind = ${chord.modifiers}, ${chord.key}, global, ${action}`;
}
function niriBinds(source: string) {
const blocks = readKdlNodes(source).filter((node) => node.name === "binds");
if (blocks.length > 1 || blocks.some((node) => node.close === undefined))
throw new Error("This Niri config has an unexpected binds section. Check it in Advanced.");
return blocks[0];
}
function niriCaptureNode(node: KdlNode, appId: string) {
const expected = readKdlNodes(captureConfigBinding("niri", appId, "Ctrl+Shift+2"))[0]!
.children[0]!;
const action = node.children[0];
return (
node.children.length === 1 &&
action?.children.length === 0 &&
JSON.stringify(action.header.map((token) => token.value)) ===
JSON.stringify(expected.header.map((token) => token.value))
);
}
function hyprlandBinds(source: string, lua: boolean) {
const bindings: { start: number; end: number; keys: string; action: string }[] = [];
let start = 0;
for (const line of source.split(/(?<=\n)/)) {
const legacy =
!lua &&
/^\s*bind[a-z]*\s*=\s*([^,]*),\s*([^,]*),\s*([^,]*),\s*(.*?)\s*(?:#.*)?$/.exec(
line.trimEnd(),
);
const modern =
lua &&
/^\s*hl\.bind\(\s*(["'])(.*?)\1\s*,\s*hl\.dsp\.global\(\s*(["'])(.*?)\3\s*\)\s*\)\s*;?\s*(?:--.*)?$/.exec(
line.trimEnd(),
);
if (legacy)
bindings.push({
start,
end: start + line.length,
keys: `${legacy[1]!.trim().replace(/\s+/g, "+")}+${legacy[2]!.trim()}`,
action: legacy[3]!.trim() === "global" ? legacy[4]!.trim() : "",
});
if (modern)
bindings.push({ start, end: start + line.length, keys: modern[2]!, action: modern[4]! });
start += line.length;
}
return bindings;
}
export function niriConfigIncludes(source: string) {
return readKdlNodes(source)
.filter((node) => node.name === "include")
.map((node) => {
const path = node.header.find(
(token, index) => index > 0 && token.quoted && node.header[index - 1]?.value !== "=",
)?.value;
if (!path) throw new Error("Couldn't resolve a Niri include. Choose the config in Advanced.");
const optional = node.header.some(
(token, index) =>
token.value === "optional" &&
node.header[index + 1]?.value === "=" &&
node.header[index + 2]?.value === "true",
);
return { path, optional };
});
}
export function niriConfigConflict(source: string, appId: string, keys: string) {
return (
niriBinds(source)?.children.some(
(node) => sameKeys(node.name, keys) && !niriCaptureNode(node, appId),
) ?? false
);
}
function removeNodes(source: string, ranges: { start: number; end: number }[]) {
let result = source;
for (const range of [...ranges].sort((a, b) => b.start - a.start)) {
const lineStart = source.lastIndexOf("\n", range.start - 1) + 1;
const nextLine = source.indexOf("\n", range.end);
const lineEnd = nextLine < 0 ? source.length : nextLine;
const wholeLine =
!source.slice(lineStart, range.start).trim() && !source.slice(range.end, lineEnd).trim();
result =
result.slice(0, wholeLine ? lineStart : range.start) +
result.slice(wholeLine ? Math.min(lineEnd + 1, source.length) : range.end);
}
return result;
}
export function editCaptureConfig(
source: string,
format: CaptureConfigFormat,
appId: string,
operation: "install" | "remove",
requestedKeys?: string,
) {
if (format === "hyprland-lua" && (/^\s*return\b/m.test(source) || /\[=*\[/.test(source)))
throw new Error(
"This Lua config needs a manual edit. Choose your bindings file or use manual setup in Advanced.",
);
const niri = format === "niri";
const existing = niri
? (niriBinds(source)?.children ?? [])
.filter((node) => niriCaptureNode(node, appId))
.map((node) => ({ ...node, keys: node.name }))
: hyprlandBinds(source, format === "hyprland-lua").filter(
(bind) => bind.action === `${appId}:capture-window`,
);
const keys = captureConfigKeys(requestedKeys ?? existing[0]?.keys).label;
if (operation === "install" && existing.length === 1 && sameKeys(existing[0]!.keys, keys))
return { after: source, shortcut: keys };
let after = removeNodes(source, existing);
if (operation === "remove") return { after, shortcut: keys };
const conflict = niri
? niriConfigConflict(after, appId, keys)
: hyprlandBinds(after, false).some((bind) => sameKeys(bind.keys, keys));
if (conflict) throw new Error(`${keys} is already used in this config. Choose another shortcut.`);
const newline = source.includes("\r\n") ? "\r\n" : "\n";
const binding = captureConfigBinding(format, appId, keys);
if (niri) {
const block = niriBinds(after);
if (block?.close !== undefined) {
const lineStart = after.lastIndexOf("\n", block.close - 1) + 1;
const indent = after.slice(lineStart, block.close);
if (!indent.trim())
after =
after.slice(0, lineStart) + indent + " " + binding + newline + after.slice(lineStart);
else
after =
after.slice(0, block.close) +
newline +
" " +
binding +
newline +
after.slice(block.close);
} else
after += `${after && !after.endsWith("\n") ? newline : ""}${newline}binds {${newline} ${binding}${newline}}${newline}`;
readKdlNodes(after);
} else {
// Do not append executable Lua inside a block/string, or after an early return.
// The normal Omarchy binding file is a sequence of top-level hl.bind calls.
after += `${after && !after.endsWith("\n") ? newline : ""}${newline}${binding}${newline}`;
}
return { after, shortcut: keys };
}
@@ -0,0 +1,146 @@
import * as Schema from "effect/Schema";
const decodeString = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.String));
/** A lossless structural reader: edits only binding nodes, never reformats a user's KDL. */
type Token = { value: string; start: number; end: number; quoted: boolean };
export type KdlNode = {
name: string;
header: Token[];
children: KdlNode[];
start: number;
end: number;
close: number | undefined;
};
export function readKdlNodes(source: string): KdlNode[] {
const tokens: Token[] = [];
let offset = 0;
const invalid = () =>
new Error("Couldn't read this Niri config. Use Advanced to configure it manually.");
while (offset < source.length) {
const start = offset;
const rest = source.slice(offset);
if (/^[\t \r\uFEFF\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/.test(rest)) {
offset++;
continue;
}
if (rest.startsWith("//")) {
const end = source.indexOf("\n", offset);
offset = end < 0 ? source.length : end;
continue;
}
if (rest.startsWith("/*")) {
offset += 2;
let depth = 1;
while (depth && offset < source.length) {
if (source.startsWith("/*", offset)) {
depth++;
offset += 2;
} else if (source.startsWith("*/", offset)) {
depth--;
offset += 2;
} else offset++;
}
if (depth) throw invalid();
continue;
}
const continuation = /^\\[\t \r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]*\n/.exec(rest);
if (continuation) {
offset += continuation[0].length;
continue;
}
const raw = /^r(#{0,32})"/.exec(rest);
if (raw) {
const terminator = `"${raw[1]}`;
const end = source.indexOf(terminator, offset + raw[0].length);
if (end < 0) throw invalid();
offset = end + terminator.length;
tokens.push({
value: source.slice(start + raw[0].length, end),
start,
end: offset,
quoted: true,
});
continue;
}
if (rest[0] === '"') {
offset++;
while (offset < source.length && source[offset] !== '"') {
if (source[offset] === "\\") offset++;
offset++;
}
if (offset === source.length) throw invalid();
offset++;
// KDL's unicode escapes differ from JSON; names needing those stay on the manual path.
let value: string;
try {
value = decodeString(source.slice(start, offset));
} catch {
throw invalid();
}
tokens.push({ value, start, end: offset, quoted: true });
continue;
}
if (rest.startsWith("/-")) offset += 2;
else if ("{};\n=()".includes(rest[0]!)) offset++;
else {
while (offset < source.length && !/[\s{};="()]/.test(source[offset]!)) {
if (["//", "/*", "/-"].some((prefix) => source.startsWith(prefix, offset))) break;
offset++;
}
}
if (offset === start) throw invalid();
tokens.push({ value: source.slice(start, offset), start, end: offset, quoted: false });
}
let cursor = 0;
const is = (token: Token | undefined, value: string) =>
token && !token.quoted && token.value === value;
const nodes = (nested: boolean): KdlNode[] => {
const result: KdlNode[] = [];
while (cursor < tokens.length) {
if (is(tokens[cursor], "\n") || is(tokens[cursor], ";")) {
cursor++;
continue;
}
if (is(tokens[cursor], "}")) {
if (!nested) throw invalid();
return result;
}
const disabled = is(tokens[cursor], "/-");
if (disabled) cursor++;
const name = tokens[cursor++];
if (!name || ["{", "}", "=", ";", "\n", "("].includes(name.value)) throw invalid();
const node: KdlNode = {
name: name.value,
header: [name],
children: [],
start: name.start,
end: name.end,
close: undefined,
};
while (
cursor < tokens.length &&
!is(tokens[cursor], "\n") &&
!is(tokens[cursor], ";") &&
!is(tokens[cursor], "}")
) {
const token = tokens[cursor++]!;
if (is(token, "{")) {
node.children = nodes(true);
const close = tokens[cursor++];
if (!is(close, "}")) throw invalid();
node.close = close!.start;
node.end = close!.end;
break;
}
node.header.push(token);
node.end = token.end;
}
if (!disabled) result.push(node);
}
if (nested) throw invalid();
return result;
};
return nodes(false);
}
@@ -0,0 +1,4 @@
import bundle from "../../gnome-extension/bundle.json" with { type: "json" };
export const GNOME_CAPTURE_UUID = bundle.uuid;
export const GNOME_CAPTURE_FILES = bundle.files;
@@ -0,0 +1,150 @@
// @effect-diagnostics nodeBuiltinImport:off -- Reads portal-owned screenshot files at the native boundary.
import * as NodeFSP from "node:fs/promises";
import * as NodeURL from "node:url";
import type { SnapShotKeyChord } from "@t3tools/contracts";
import { nativeImage } from "electron";
// Linux helpers that need no D-Bus. Keep this module free of dbus-next so the main
// process can answer "which desktop is this" and read a PNG without loading it.
export const HYPRLAND_CAPTURE_ACTION = "capture-window";
export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot";
export const NIRI_CAPTURE_INTERFACE = "com.t3tools.SnapShot";
function isDesktopSession(env: NodeJS.ProcessEnv, desktop: string): boolean {
return (
!env.FLATPAK_ID &&
!env.SNAP &&
Boolean(env.XDG_CURRENT_DESKTOP?.split(":").some((name) => name.toLowerCase() === desktop))
);
}
export function isGnomeCaptureSession(env: NodeJS.ProcessEnv): boolean {
return isDesktopSession(env, "gnome");
}
export function isKdeCaptureSession(env = process.env): boolean {
return isDesktopSession(env, "kde");
}
export function isHyprlandCaptureSession(env = process.env): boolean {
return isDesktopSession(env, "hyprland");
}
export function niriCaptureBinding(appId: string): string {
return `Ctrl+Shift+2 repeat=false { spawn "gdbus" "call" "--session" "--dest" "${appId}.SnapShot" "--object-path" "${NIRI_CAPTURE_PATH}" "--method" "${NIRI_CAPTURE_INTERFACE}.Capture"; }`;
}
const KEY_NAMES: Readonly<Record<string, string>> = {
" ": "space",
escape: "Escape",
esc: "Escape",
enter: "Return",
tab: "Tab",
backspace: "BackSpace",
delete: "Delete",
insert: "Insert",
home: "Home",
end: "End",
pageup: "Page_Up",
pagedown: "Page_Down",
arrowup: "Up",
arrowdown: "Down",
arrowleft: "Left",
arrowright: "Right",
up: "Up",
down: "Down",
left: "Left",
right: "Right",
"+": "plus",
"-": "minus",
"=": "equal",
",": "comma",
".": "period",
"/": "slash",
";": "semicolon",
"'": "apostrophe",
"[": "bracketleft",
"]": "bracketright",
"\\": "backslash",
"`": "grave",
"!": "exclam",
"@": "at",
"#": "numbersign",
$: "dollar",
"%": "percent",
"^": "asciicircum",
"&": "ampersand",
"*": "asterisk",
"(": "parenleft",
")": "parenright",
_: "underscore",
":": "colon",
'"': "quotedbl",
"{": "braceleft",
"}": "braceright",
"|": "bar",
"<": "less",
">": "greater",
"?": "question",
"~": "asciitilde",
};
export function portalShortcutTrigger(shortcut: SnapShotKeyChord): string {
const key = shortcut.key.toLowerCase();
const keysym =
KEY_NAMES[key] ??
(/^[a-z0-9]$/.test(key) || /^f([1-9]|1\d|2[0-4])$/.test(key) ? key.toUpperCase() : undefined);
if (!keysym)
throw new Error("This key isn't supported as a Wayland capture shortcut. Choose another key.");
return [
shortcut.ctrlKey || shortcut.modKey ? "CTRL" : null,
shortcut.altKey ? "ALT" : null,
shortcut.shiftKey ? "SHIFT" : null,
shortcut.metaKey ? "LOGO" : null,
keysym,
]
.filter(Boolean)
.join("+");
}
const PNG_HEADER = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const MAX_PNG_BYTES = 32 * 1024 * 1024;
export function resizeLinuxCapture(png: Buffer): Buffer {
if (png.length > MAX_PNG_BYTES || !png.subarray(0, 8).equals(PNG_HEADER)) {
throw new Error("Invalid or oversized window screenshot.");
}
const image = nativeImage.createFromBuffer(png);
if (image.isEmpty()) throw new Error("The window screenshot is empty.");
const { width, height } = image.getSize();
const scale = Math.min(2_560 / width, 1_600 / height, 1);
return scale < 1
? image
.resize({
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale)),
quality: "best",
})
.toPNG()
: png;
}
export async function readPortalPng(uri: string): Promise<Buffer> {
// fileURLToPath rejects network schemes/hosts. Never delete a portal-owned file.
const file = await NodeFSP.open(NodeURL.fileURLToPath(uri), "r");
try {
const stat = await file.stat();
if (!stat.isFile() || stat.size > MAX_PNG_BYTES) throw new Error("Invalid screenshot file.");
const buffer = Buffer.alloc(stat.size);
let offset = 0;
while (offset < buffer.length) {
const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, offset);
if (!bytesRead) throw new Error("Incomplete screenshot file.");
offset += bytesRead;
}
return resizeLinuxCapture(buffer);
} finally {
await file.close();
}
}
+760
View File
@@ -0,0 +1,760 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import { describe, expect, it, vi } from "vite-plus/test";
import {
accessibleWindowElementTree,
accessibleWindowText,
capturedImageBounds,
compactAccessibilityTree,
findAccessibleWindow,
findCaptureSource,
hideAndWaitForBlur,
isWaylandSession,
snapShotShortcutRegistrationFailureMessage,
snapShotShortcutSystemConflict,
toElectronAccelerator,
} from "./snapShot.ts";
import { DesktopSnapShotError } from "./DesktopSnapShot.ts";
describe("window capture errors", () => {
it.each([
["unsupported", "SnapShots are not supported here."],
["disabled", "Enable SnapShots in Settings first."],
["no-window-selected", "No window was selected."],
["window-unavailable", "The active window is not available for capture."],
["capture", "Could not capture the active window."],
] as const)("keeps %s failures user-facing", (operation, message) => {
expect(new DesktopSnapShotError({ operation }).message).toBe(message);
});
});
describe("accessibleWindowText", () => {
it("keeps unique names and values in tree order", () => {
expect(
accessibleWindowText(
{
name: "Settings",
children: [
{
name: "General",
children: [],
},
{
name: "Name",
value: "Bilal",
children: [],
},
],
},
100,
),
).toBe("Settings\nGeneral\nName\nBilal");
});
it("caps large text without splitting a surrogate pair", () => {
expect(
accessibleWindowText(
{
value: "abc😀def",
children: [],
},
5,
),
).toBe("abc😀");
});
it("stops traversing very large trees", () => {
expect(
accessibleWindowText(
{
children: [
...Array.from({ length: 10_000 }, () => ({ children: [] })),
{ value: "past node limit", children: [] },
],
},
100,
),
).not.toContain("past node limit");
});
});
describe("accessibleWindowElementTree", () => {
it("maps element bounds into captured-image pixels and keeps semantic state", async () => {
const tree = await accessibleWindowElementTree(
{
role: "window",
name: "Editor",
bounds: { x: 100, y: 200, width: 800, height: 600 },
active: true,
children: async () => [
{
role: "button",
name: "Save",
description: "Save the document",
bounds: { x: 300, y: 350, width: 100, height: 50 },
focused: true,
actions: ["press", "press"],
children: async () => [],
},
],
},
{ x: 100, y: 200, width: 800, height: 600 },
{ width: 1_600, height: 1_200 },
);
expect(tree).toEqual({
truncated: false,
root: {
role: "window",
name: "Editor",
bounds: { x: 0, y: 0, width: 1_600, height: 1_200 },
state: { active: true },
children: [
{
role: "button",
name: "Save",
description: "Save the document",
bounds: { x: 400, y: 300, width: 200, height: 100 },
state: { focused: true },
actions: ["press"],
children: [],
},
],
},
});
});
it("uses null child bounds when a Wayland provider reports only the root origin", async () => {
const tree = await accessibleWindowElementTree(
{
role: "window",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: async () => [
{
role: "button",
name: "Save",
bounds: { x: 0, y: 0, width: 100, height: 50 },
children: async () => [],
},
],
},
{ x: 0, y: 0, width: 800, height: 600 },
{ width: 1_600, height: 1_200 },
{ locationsReliable: true, verifyDescendantLocations: true },
);
expect(tree?.root.bounds).toEqual({ x: 0, y: 0, width: 1_600, height: 1_200 });
expect(tree?.root.children[0]?.bounds).toBeNull();
});
it("keeps Wayland child bounds after observing real position variation", async () => {
const tree = await accessibleWindowElementTree(
{
role: "window",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: async () => [
{
role: "button",
name: "Save",
bounds: { x: 20, y: 30, width: 100, height: 50 },
children: async () => [],
},
],
},
{ x: 0, y: 0, width: 800, height: 600 },
{ width: 1_600, height: 1_200 },
{ locationsReliable: true, verifyDescendantLocations: true },
);
expect(tree?.root.children[0]?.bounds).toEqual({ x: 40, y: 60, width: 200, height: 100 });
});
it("does not mistake a title-bar offset for varying descendant positions", async () => {
const tree = await accessibleWindowElementTree(
{
role: "window",
bounds: { x: 100, y: 229, width: 800, height: 571 },
children: async () => [
{
role: "button",
name: "Save",
bounds: { x: 100, y: 229, width: 100, height: 50 },
children: async () => [],
},
],
},
{ x: 100, y: 200, width: 800, height: 600 },
{ width: 1_600, height: 1_200 },
{ locationsReliable: true, verifyDescendantLocations: true },
);
expect(tree?.root.children[0]?.bounds).toBeNull();
});
it("collapses anonymous wrapper chains and removes duplicate text fields", async () => {
const tree = await accessibleWindowElementTree(
{
role: "window",
name: "Editor",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: async () => [
{
role: "group",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: async () => [
{
role: "group",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: async () => [
{
role: "button",
name: "Save",
value: "Save",
description: "Save",
bounds: { x: 20, y: 30, width: 80, height: 24 },
actions: ["press"],
children: async () => [],
},
{
role: "group",
bounds: null,
children: async () => [],
},
],
},
],
},
],
},
{ x: 0, y: 0, width: 800, height: 600 },
{ width: 800, height: 600 },
);
expect(tree?.root.children).toEqual([
{
role: "button",
name: "Save",
bounds: { x: 20, y: 30, width: 80, height: 24 },
actions: ["press"],
children: [],
},
]);
});
it("marks trees truncated before their serialized payload grows without bound", async () => {
const tree = await accessibleWindowElementTree(
{
role: "window",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: async () =>
Array.from({ length: 10 }, (_, index) => ({
role: "text",
value: `${index}${"x".repeat(8_000)}`,
bounds: null,
children: async () => [],
})),
},
{ x: 0, y: 0, width: 800, height: 600 },
{ width: 800, height: 600 },
);
expect(tree?.truncated).toBe(true);
expect(tree?.root.children.length).toBeLessThan(10);
expect(JSON.stringify(tree).length).toBeLessThanOrEqual(32_000);
});
});
describe("compactAccessibilityTree", () => {
it("keeps anonymous groups that organize multiple semantic children", () => {
const compacted = compactAccessibilityTree({
role: "window",
bounds: { x: 0, y: 0, width: 800, height: 600 },
children: [
{
role: "group",
bounds: { x: 0, y: 0, width: 800, height: 100 },
children: [
{ role: "button", name: "Back", bounds: null, children: [] },
{ role: "button", name: "Forward", bounds: null, children: [] },
],
},
],
});
expect(compacted.root.children[0]?.role).toBe("group");
expect(compacted.root.children[0]?.children).toHaveLength(2);
});
});
describe("capturedImageBounds", () => {
it("clips locations to the attached image", () => {
expect(
capturedImageBounds(
{ x: 50, y: 150, width: 200, height: 200 },
{ x: 100, y: 200, width: 800, height: 600 },
{ width: 1_600, height: 1_200 },
),
).toEqual({ x: 0, y: 0, width: 300, height: 300 });
});
it("returns null when an accessibility provider omits a location", () => {
expect(
capturedImageBounds(
null,
{ x: 0, y: 0, width: 800, height: 600 },
{ width: 800, height: 600 },
),
).toBeNull();
});
});
describe("findAccessibleWindow", () => {
const captured = {
title: "Editor",
bounds: { x: 100, y: 200, width: 800, height: 600 },
};
it("matches one window by its captured bounds", () => {
const windows = [
{ name: "Private", bounds: { x: 0, y: 0, width: 400, height: 300 } },
{ name: "Editor", bounds: { x: 101, y: 199, width: 800, height: 601 } },
];
expect(findAccessibleWindow(windows, captured)).toBe(windows[1]);
});
it("uses the matched source title when macOS omits the active title", () => {
const windows = [{ name: "Editor", bounds: captured.bounds }];
expect(
findAccessibleWindow(windows, {
...captured,
title: "",
sourceTitle: "Editor",
}),
).toBe(windows[0]);
});
it("uses the captured source title when the active title changed", () => {
const windows = [{ name: "Editor — saved", bounds: captured.bounds }];
expect(
findAccessibleWindow(windows, {
...captured,
title: "Editor — saving",
sourceTitle: "Editor — saved",
}),
).toBe(windows[0]);
});
it("uses the active match to disambiguate equal windows", () => {
const windows = [
{ name: "Editor", bounds: captured.bounds, active: false },
{ name: "Editor", bounds: captured.bounds, active: true },
];
expect(findAccessibleWindow(windows, captured)).toBe(windows[1]);
});
it("does not match equal bounds with a different title", () => {
expect(
findAccessibleWindow(
[{ name: "Private", bounds: { x: 100, y: 200, width: 800, height: 600 } }],
captured,
),
).toBeUndefined();
});
it("does not use a title match when the bounds differ", () => {
expect(
findAccessibleWindow(
[{ name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 600 } }],
captured,
),
).toBeUndefined();
});
it("matches a Wayland window whose accessibility provider omits its screen position", () => {
const captured = {
title: "hello world (Draft) - Text Editor",
bounds: { x: 479, y: 342, width: 700, height: 520 },
};
const windows = [{ name: captured.title, bounds: { x: 0, y: 0, width: 700, height: 520 } }];
expect(findAccessibleWindow(windows, captured, "wayland")).toBe(windows[0]);
expect(findAccessibleWindow(windows, captured)).toBeUndefined();
});
it("matches a decorated Wayland window by its verified client size", () => {
const clientBounds = { x: 100, y: 229, width: 800, height: 571 };
const windows = [{ name: captured.title, bounds: { ...clientBounds, x: 0, y: 0 } }];
expect(findAccessibleWindow(windows, { ...captured, clientBounds }, "wayland")).toBe(
windows[0],
);
expect(findAccessibleWindow(windows, { ...captured, clientBounds })).toBeUndefined();
expect(findAccessibleWindow(windows, captured, "wayland")).toBeUndefined();
});
it("does not guess between client-size and frame-size matches", () => {
const clientBounds = { x: 100, y: 229, width: 800, height: 571 };
const windows = [
{ name: captured.title, bounds: clientBounds },
{ name: captured.title, bounds: captured.bounds },
];
expect(findAccessibleWindow(windows, { ...captured, clientBounds }, "wayland")).toBeUndefined();
expect(
findAccessibleWindow(
[
{ name: "Private", bounds: clientBounds },
{ name: captured.title, bounds: { ...clientBounds, height: 550 } },
],
{ ...captured, clientBounds },
"wayland",
),
).toBeUndefined();
});
it("distinguishes same-title Wayland windows by size", () => {
const windows = [
{ name: "Editor", bounds: { x: 0, y: 0, width: 400, height: 300 } },
{ name: "Editor", bounds: { x: 0, y: 0, width: 801, height: 599 } },
];
expect(findAccessibleWindow(windows, captured, "wayland")).toBe(windows[1]);
});
it.each([
{ name: "Private", bounds: { x: 0, y: 0, width: 800, height: 600 } },
{ name: "Editor", bounds: { x: 0, y: 0, width: 400, height: 600 } },
{ name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 300 } },
{ name: "Editor", bounds: null },
])("rejects an unverified Wayland window: %j", (window) => {
expect(findAccessibleWindow([window], captured, "wayland")).toBeUndefined();
});
it("rejects ambiguous Wayland windows even when one reports the captured screen position", () => {
const windows = [
{ name: "Editor", bounds: captured.bounds },
{ name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 600 } },
];
expect(findAccessibleWindow(windows, captured, "wayland")).toBeUndefined();
});
it("does not match an untitled Wayland window by size alone", () => {
const windows = [{ name: "", bounds: captured.bounds }];
expect(findAccessibleWindow(windows, { ...captured, title: "" }, "wayland")).toBeUndefined();
});
it.each(["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])(
"ignores a leading Wayland title spinner frame %s",
(frame) => {
const windows = [{ name: `${frame} t3code`, bounds: captured.bounds }];
expect(findAccessibleWindow(windows, { ...captured, title: "⠋ t3code" }, "wayland")).toBe(
windows[0],
);
},
);
it.each([
["⠋ t3code", "t3code"],
["t3code", "⠙ t3code"],
])("matches a Wayland spinner starting or stopping: %s → %s", (title, name) => {
const windows = [{ name, bounds: captured.bounds }];
expect(findAccessibleWindow(windows, { ...captured, title }, "wayland")).toBe(windows[0]);
});
it.each([
["⠋ t3code", "⠙ private"],
["t3code ⠋", "t3code ⠙"],
["⠋t3code", "⠙t3code"],
["⠁ t3code", "⠙ t3code"],
["⠋", "⠋"],
])("does not guess a Wayland title match: %s → %s", (title, name) => {
expect(
findAccessibleWindow([{ name, bounds: captured.bounds }], { ...captured, title }, "wayland"),
).toBeUndefined();
});
it("rejects matching spinners when the window sizes differ", () => {
expect(
findAccessibleWindow(
[{ name: "⠙ t3code", bounds: { ...captured.bounds, width: 400 } }],
{ ...captured, title: "⠋ t3code" },
"wayland",
),
).toBeUndefined();
});
it("rejects ambiguous normalized titles even if one matches the captured spinner exactly", () => {
const windows = [
{ name: "⠋ t3code", bounds: captured.bounds },
{ name: "⠙ t3code", bounds: captured.bounds },
];
expect(
findAccessibleWindow(windows, { ...captured, title: "⠋ t3code" }, "wayland"),
).toBeUndefined();
});
it("keeps exact title matching outside Wayland", () => {
expect(
findAccessibleWindow([{ name: "⠙ t3code", bounds: captured.bounds }], {
...captured,
title: "⠋ t3code",
}),
).toBeUndefined();
});
});
describe("hideAndWaitForBlur", () => {
it("waits for a delayed blur after hiding the window", async () => {
let blur: (() => void) | undefined;
let settled = false;
const hidden = hideAndWaitForBlur({
hide: () => undefined,
once: (_event, listener) => {
blur = listener;
},
removeListener: () => undefined,
}).then(() => {
settled = true;
});
await Promise.resolve();
expect(settled).toBe(false);
blur?.();
await hidden;
expect(settled).toBe(true);
});
it("rejects when the hidden window never blurs", async () => {
vi.useFakeTimers();
try {
let rejected = false;
const hidden = hideAndWaitForBlur({
hide: () => undefined,
once: () => undefined,
removeListener: () => undefined,
}).catch(() => {
rejected = true;
});
await vi.advanceTimersByTimeAsync(1_000);
expect(rejected).toBe(true);
await hidden;
} finally {
vi.useRealTimers();
}
});
});
describe("toElectronAccelerator", () => {
it("converts the default portable shortcut", () => {
expect(
toElectronAccelerator({
key: "2",
metaKey: false,
ctrlKey: false,
shiftKey: true,
altKey: false,
modKey: true,
}),
).toBe("CommandOrControl+Shift+2");
});
it("maps the portable meta key to Super", () => {
expect(
toElectronAccelerator({
key: "k",
metaKey: true,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: false,
}),
).toBe("Super+K");
});
it("normalizes Electron key names", () => {
expect(
toElectronAccelerator({
key: "ArrowUp",
metaKey: false,
ctrlKey: true,
shiftKey: false,
altKey: true,
modKey: false,
}),
).toBe("Control+Alt+Up");
});
});
describe("findCaptureSource", () => {
const sources = [
{ id: "window:42:0", name: "Terminal" },
{ id: "window:84:0", name: "Editor" },
];
it("matches the native window id before its title", () => {
expect(
findCaptureSource(sources, {
id: 84,
title: "Changed title",
}),
).toEqual(sources[1]);
});
it("falls back to a unique title match", () => {
expect(
findCaptureSource(sources, {
id: 100,
title: "Terminal",
}),
).toEqual(sources[0]);
});
it("does not guess when a title is ambiguous", () => {
expect(
findCaptureSource(
[
{ id: "window:42:0", name: "Editor" },
{ id: "window:84:0", name: "Editor" },
],
{
id: 100,
title: "Editor",
},
),
).toBeUndefined();
});
});
describe("isWaylandSession", () => {
it.each([
["linux", { XDG_SESSION_TYPE: "wayland" }, true],
["linux", { WAYLAND_DISPLAY: "wayland-0" }, true],
["linux", { XDG_SESSION_TYPE: "x11" }, false],
["darwin", { XDG_SESSION_TYPE: "wayland", WAYLAND_DISPLAY: "wayland-0" }, false],
] as const)("detects %s session %o as portal=%s", (platform, environment, expected) => {
expect(isWaylandSession(platform, environment)).toBe(expected);
});
effectIt.effect(
"falls back to a live runtime directory socket when session variables are stripped",
() =>
Effect.gen(function* () {
if ((yield* HostProcessPlatform) !== "linux") return;
yield* Effect.promise(async () => {
const { mkdtemp, rm, writeFile } = await import("node:fs/promises");
const { createServer } = await import("node:net");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const runtimeDirectory = await mkdtemp(join(tmpdir(), "t3-wayland-"));
const socketPath = join(runtimeDirectory, "wayland-0");
const server = createServer();
try {
expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: runtimeDirectory })).toBe(false);
await writeFile(socketPath, "");
expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: runtimeDirectory })).toBe(false);
await rm(socketPath);
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(socketPath, resolve);
});
expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: runtimeDirectory })).toBe(true);
expect(
isWaylandSession("linux", {
XDG_RUNTIME_DIR: runtimeDirectory,
XDG_SESSION_TYPE: "x11",
}),
).toBe(false);
expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: "/nonexistent-t3-test" })).toBe(
false,
);
} finally {
if (server.listening) {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
await rm(runtimeDirectory, { recursive: true, force: true });
}
});
}),
);
});
describe("snapShotShortcutRegistrationFailureMessage", () => {
it("distinguishes a modifier listener failure from a reserved key chord", () => {
expect(
snapShotShortcutRegistrationFailureMessage({ kind: "both-shift-keys" }, "darwin"),
).toMatch(/Shift \+ Shift is not available/);
expect(
snapShotShortcutRegistrationFailureMessage(
{ kind: "modifier-pair", modifier: "meta" },
"darwin",
),
).toMatch(/Command \+ Command is not available/);
expect(
snapShotShortcutRegistrationFailureMessage(
{ kind: "modifier-pair", modifier: "meta" },
"linux",
),
).toMatch(/Super \+ Super is not available/);
expect(
snapShotShortcutRegistrationFailureMessage(
{
key: "2",
metaKey: false,
ctrlKey: false,
shiftKey: true,
altKey: false,
modKey: true,
},
"darwin",
),
).toMatch(/already used/);
});
});
describe("snapShotShortcutSystemConflict", () => {
it("blocks shortcuts that would break typing or common app actions", () => {
expect(
snapShotShortcutSystemConflict({
key: "s",
metaKey: false,
ctrlKey: false,
shiftKey: true,
altKey: false,
modKey: false,
}),
).toMatch(/typing/);
expect(
snapShotShortcutSystemConflict({
key: "c",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
}),
).toMatch(/Copy/);
});
it("allows a specific multi-modifier shortcut", () => {
expect(
snapShotShortcutSystemConflict({
key: "2",
metaKey: false,
ctrlKey: false,
shiftKey: true,
altKey: false,
modKey: true,
}),
).toBeNull();
});
});
+591
View File
@@ -0,0 +1,591 @@
// @effect-diagnostics globalTimers:off -- The Electron window-blur handshake uses a native timeout outside any Effect fiber.
// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only platform check reads procfs and resolves Wayland socket paths with Node.
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import {
SNAP_SHOT_ACCESSIBILITY_MAX_NODES,
SNAP_SHOT_ACCESSIBILITY_MAX_SERIALIZED_CHARS,
isModifierPairShortcut,
snapShotModifierPairLabel,
snapShotShortcutModifierPair,
type SnapShotAccessibilityNode,
type SnapShotKeyChord,
type SnapShotModifier,
type SnapShotShortcut,
} from "@t3tools/contracts";
interface AccessibilityTreeNode {
readonly name?: string;
readonly value?: string;
readonly children: ReadonlyArray<AccessibilityTreeNode>;
}
const MAX_ACCESSIBILITY_TREE_NODES = 10_000;
const WINDOW_BLUR_TIMEOUT_MS = 1_000;
/** Win32 virtual-key codes for the left and right key of each modifier pair. */
export const WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS: Record<
SnapShotModifier,
readonly [number, number]
> = {
shift: [0xa0, 0xa1],
control: [0xa2, 0xa3],
alt: [0xa4, 0xa5],
meta: [0x5b, 0x5c],
};
export function snapShotShortcutRegistrationFailureMessage(
shortcut: SnapShotShortcut,
platform: NodeJS.Platform,
): string {
return isModifierPairShortcut(shortcut)
? `${snapShotModifierPairLabel(
snapShotShortcutModifierPair(shortcut),
platform === "darwin",
)} is not available on this system.`
: "This shortcut is already used by the system or another app.";
}
const COMMON_MOD_ACTIONS: Readonly<Record<string, string>> = {
a: "Select All",
c: "Copy",
f: "Find",
n: "New",
o: "Open",
p: "Print",
q: "Quit",
s: "Save",
t: "New Tab",
v: "Paste",
w: "Close Window",
x: "Cut",
z: "Undo",
};
export function snapShotShortcutSystemConflict(shortcut: SnapShotKeyChord): string | null {
const modifierCount = [
shortcut.modKey,
shortcut.metaKey,
shortcut.ctrlKey,
shortcut.altKey,
shortcut.shiftKey,
].filter(Boolean).length;
if (modifierCount !== 1) return null;
if (shortcut.shiftKey) {
return "Shift combinations are used for typing and text selection. Add another modifier.";
}
const key = shortcut.key.toLowerCase();
if (shortcut.modKey) {
const action = COMMON_MOD_ACTIONS[key];
return action ? `This shortcut is ${action} in most apps.` : null;
}
if (shortcut.ctrlKey && ["c", "d", "z"].includes(key)) {
return "This shortcut controls running commands in terminals.";
}
if (shortcut.altKey && key === "tab") return "The system uses Alt+Tab to switch apps.";
if (shortcut.metaKey && ["l", " "].includes(key)) {
return "The system already uses this shortcut.";
}
return null;
}
export function accessibleWindowText(root: AccessibilityTreeNode, maxChars: number): string {
const seen = new Set<string>();
const stack = [root];
let text = "";
let visited = 0;
while (stack.length > 0 && text.length < maxChars && visited < MAX_ACCESSIBILITY_TREE_NODES) {
const node = stack.pop()!;
visited += 1;
for (const value of [node.name, node.value]) {
const candidate = value?.replaceAll("\0", "").trim();
if (!candidate || seen.has(candidate)) continue;
const separator = text ? "\n" : "";
const remaining = maxChars - text.length - separator.length;
if (remaining <= 0) return text;
const candidateEnd =
candidate.length <= remaining
? candidate.length
: /[\uD800-\uDBFF]/.test(candidate[remaining - 1] ?? "")
? remaining - 1
: remaining;
if (candidateEnd === 0) return text;
text += separator + candidate.slice(0, candidateEnd);
if (candidateEnd < candidate.length) return text;
seen.add(candidate);
}
stack.push(...node.children.toReversed());
}
return text;
}
type AccessibilityElement = {
readonly role?: string;
readonly name?: string | null;
readonly value?: string | null;
readonly description?: string | null;
readonly bounds?: WindowBounds | null;
readonly actions?: ReadonlyArray<string>;
readonly active?: boolean;
readonly busy?: boolean;
readonly checked?: "on" | "off" | "mixed" | null;
readonly editable?: boolean;
readonly enabled?: boolean;
readonly expanded?: boolean | null;
readonly focused?: boolean;
readonly selected?: boolean;
readonly visible?: boolean;
readonly children?: () => Promise<ReadonlyArray<AccessibilityElement>>;
};
type MutableAccessibilityNode = Omit<SnapShotAccessibilityNode, "children"> & {
children: Array<MutableAccessibilityNode>;
};
type CapturedImageSize = { readonly width: number; readonly height: number };
function safeProperty<T>(read: () => T): T | undefined {
try {
return read();
} catch {
return undefined;
}
}
export function boundedSnapShotString(value: unknown, maxChars: number): string | undefined {
if (typeof value !== "string") return undefined;
const candidate = value.replaceAll("\0", "").trim();
if (!candidate) return undefined;
if (candidate.length <= maxChars) return candidate;
const end = /[\uD800-\uDBFF]/.test(candidate[maxChars - 1] ?? "") ? maxChars - 1 : maxChars;
return candidate.slice(0, end).trimEnd();
}
export function capturedImageBounds(
bounds: WindowBounds | null | undefined,
sourceBounds: WindowBounds,
imageSize: CapturedImageSize,
): SnapShotAccessibilityNode["bounds"] {
if (
bounds === null ||
bounds === undefined ||
sourceBounds.width <= 0 ||
sourceBounds.height <= 0 ||
imageSize.width <= 0 ||
imageSize.height <= 0 ||
![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)
) {
return null;
}
const scaleX = imageSize.width / sourceBounds.width;
const scaleY = imageSize.height / sourceBounds.height;
const left = Math.max(0, Math.round((bounds.x - sourceBounds.x) * scaleX));
const top = Math.max(0, Math.round((bounds.y - sourceBounds.y) * scaleY));
const right = Math.min(
imageSize.width,
Math.round((bounds.x + bounds.width - sourceBounds.x) * scaleX),
);
const bottom = Math.min(
imageSize.height,
Math.round((bounds.y + bounds.height - sourceBounds.y) * scaleY),
);
return right > left && bottom > top
? { x: left, y: top, width: right - left, height: bottom - top }
: null;
}
function accessibilityNode(
element: AccessibilityElement,
elementBounds: WindowBounds | null | undefined,
sourceBounds: WindowBounds,
imageSize: CapturedImageSize,
isRoot: boolean,
locationsReliable: boolean,
): MutableAccessibilityNode {
const name = boundedSnapShotString(
safeProperty(() => element.name),
1_000,
);
const value = boundedSnapShotString(
safeProperty(() => element.value),
8_000,
);
const description = boundedSnapShotString(
safeProperty(() => element.description),
2_000,
);
const checked = safeProperty(() => element.checked);
const expanded = safeProperty(() => element.expanded);
const state = {
...(safeProperty(() => element.active) === true ? { active: true } : {}),
...(safeProperty(() => element.busy) === true ? { busy: true } : {}),
...(checked === "on" || checked === "off" || checked === "mixed" ? { checked } : {}),
...(safeProperty(() => element.editable) === true ? { editable: true } : {}),
...(safeProperty(() => element.enabled) === false ? { enabled: false } : {}),
...(typeof expanded === "boolean" ? { expanded } : {}),
...(safeProperty(() => element.focused) === true ? { focused: true } : {}),
...(safeProperty(() => element.selected) === true ? { selected: true } : {}),
...(safeProperty(() => element.visible) === false ? { visible: false } : {}),
};
const actions = Array.from(
new Set(
(safeProperty(() => element.actions) ?? [])
.map((action) => boundedSnapShotString(action, 100))
.filter((action): action is string => action !== undefined),
),
).slice(0, 32);
return {
role:
boundedSnapShotString(
safeProperty(() => element.role),
100,
) ?? "unknown",
...(name ? { name } : {}),
...(value && value !== name ? { value } : {}),
...(description && description !== name && description !== value ? { description } : {}),
bounds: isRoot
? { x: 0, y: 0, width: imageSize.width, height: imageSize.height }
: locationsReliable
? capturedImageBounds(elementBounds, sourceBounds, imageSize)
: null,
...(Object.keys(state).length > 0 ? { state } : {}),
...(actions.length > 0 ? { actions } : {}),
children: [],
};
}
function isAnonymousGroup(node: SnapShotAccessibilityNode): boolean {
return (
node.role === "group" &&
node.name === undefined &&
node.value === undefined &&
node.description === undefined &&
node.state === undefined &&
node.actions === undefined
);
}
function compactAccessibilityNodes(
node: SnapShotAccessibilityNode,
isRoot: boolean,
descendantLocationsReliable: boolean,
): Array<MutableAccessibilityNode> {
const children = node.children.flatMap((child) =>
compactAccessibilityNodes(child, false, descendantLocationsReliable),
);
const compacted: MutableAccessibilityNode = {
...node,
...(!isRoot && !descendantLocationsReliable ? { bounds: null } : {}),
children,
};
if (!isRoot && isAnonymousGroup(compacted)) {
if (children.length === 0) return [];
if (children.length === 1) return children;
}
return [compacted];
}
export function compactAccessibilityTree(
root: SnapShotAccessibilityNode,
options: { readonly descendantLocationsReliable?: boolean } = {},
): {
readonly root: SnapShotAccessibilityNode;
readonly truncated: boolean;
} {
const compactedRoot = compactAccessibilityNodes(
root,
true,
options.descendantLocationsReliable !== false,
)[0]!;
let nodes = 0;
let serializedChars = 256;
let truncated = false;
const visit = (
node: SnapShotAccessibilityNode,
required: boolean,
): MutableAccessibilityNode | undefined => {
const copy: MutableAccessibilityNode = { ...node, children: [] };
const nodeChars = JSON.stringify(copy).length + 1;
if (
!required &&
(nodes >= SNAP_SHOT_ACCESSIBILITY_MAX_NODES ||
serializedChars + nodeChars > SNAP_SHOT_ACCESSIBILITY_MAX_SERIALIZED_CHARS)
) {
truncated = true;
return undefined;
}
nodes += 1;
serializedChars += nodeChars;
for (const child of node.children) {
const childCopy = visit(child, false);
if (!childCopy) break;
copy.children.push(childCopy);
}
return copy;
};
return { root: visit(compactedRoot, true)!, truncated };
}
type AccessibleWindowElementTreeOptions = {
readonly locationsReliable?: boolean;
readonly onProgress?: (
root: SnapShotAccessibilityNode,
truncated: boolean,
descendantLocationsReliable: boolean,
) => void;
readonly shouldContinue?: () => boolean;
readonly verifyDescendantLocations?: boolean;
};
export async function accessibleWindowElementTree(
element: AccessibilityElement,
sourceBounds: WindowBounds,
imageSize: CapturedImageSize,
options: AccessibleWindowElementTreeOptions = {},
): Promise<{ readonly root: SnapShotAccessibilityNode; readonly truncated: boolean } | undefined> {
if (typeof element.children !== "function") return undefined;
let nodes = 0;
let truncated = false;
let root: MutableAccessibilityNode | undefined;
const shouldContinue = options.shouldContinue ?? (() => true);
let descendantLocationVaries = false;
let rootBounds = sourceBounds;
const descendantLocationsReliable = () =>
options.locationsReliable !== false &&
(options.verifyDescendantLocations !== true || descendantLocationVaries);
const visit = async (
current: AccessibilityElement,
required: boolean,
): Promise<MutableAccessibilityNode | undefined> => {
if (!shouldContinue()) {
truncated = true;
return undefined;
}
if (nodes >= SNAP_SHOT_ACCESSIBILITY_MAX_NODES) {
truncated = true;
return undefined;
}
const elementBounds = safeProperty(() => current.bounds);
if (required && elementBounds) rootBounds = elementBounds;
if (
!required &&
elementBounds !== null &&
elementBounds !== undefined &&
(Math.abs(elementBounds.x - rootBounds.x) > 2 || Math.abs(elementBounds.y - rootBounds.y) > 2)
) {
descendantLocationVaries = true;
}
const node = accessibilityNode(
current,
elementBounds,
sourceBounds,
imageSize,
required,
options.locationsReliable !== false,
);
nodes += 1;
root ??= node;
options.onProgress?.(root, true, descendantLocationsReliable());
const readChildren = safeProperty(() => current.children);
if (typeof readChildren !== "function") return node;
let children: ReadonlyArray<AccessibilityElement>;
try {
children = await readChildren.call(current);
} catch {
truncated = true;
return node;
}
if (!shouldContinue()) {
truncated = true;
return node;
}
for (const child of children) {
const childNode = await visit(child, false);
if (!childNode) break;
node.children.push(childNode);
options.onProgress?.(root, true, descendantLocationsReliable());
}
return node;
};
const completedRoot = await visit(element, true);
if (!completedRoot) return undefined;
const locationsReliable = descendantLocationsReliable();
const compacted = compactAccessibilityTree(completedRoot, {
descendantLocationsReliable: locationsReliable,
});
const completedTruncated = truncated || compacted.truncated;
options.onProgress?.(compacted.root, completedTruncated, locationsReliable);
return { root: compacted.root, truncated: completedTruncated };
}
export function hideAndWaitForBlur(window: {
readonly hide: () => void;
readonly once: (event: "blur", listener: () => void) => unknown;
readonly removeListener: (event: "blur", listener: () => void) => unknown;
}): Promise<void> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
window.removeListener("blur", onBlur);
reject(new Error("Timed out waiting for T3 Code to lose focus."));
}, WINDOW_BLUR_TIMEOUT_MS);
const onBlur = () => {
clearTimeout(timeout);
resolve();
};
window.once("blur", onBlur);
window.hide();
});
}
type WindowBounds = {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
};
export function findAccessibleWindow<
T extends {
readonly name: string | null;
readonly bounds: WindowBounds | null;
readonly active?: boolean;
},
>(
windows: readonly T[],
captured: {
readonly title: string;
readonly sourceTitle?: string;
readonly bounds: WindowBounds;
readonly clientBounds?: WindowBounds | undefined;
},
matchMode: "screen-bounds" | "wayland" = "screen-bounds",
): T | undefined {
const normalizeTitle = (value: string) => {
const title = value.trim();
// Terminal apps can animate a leading CLI spinner between capture and AT-SPI lookup.
return matchMode === "wayland" ? title.replace(/^[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏](?:\s+|$)/u, "") : title;
};
const titles = new Set(
[captured.title, captured.sourceTitle ?? ""].map(normalizeTitle).filter(Boolean),
);
if (titles.size === 0) return undefined;
// Wayland accessibility providers can expose window size without a screen position.
const boundsKeys =
matchMode === "wayland"
? (["width", "height"] as const)
: (["x", "y", "width", "height"] as const);
const candidateBounds =
matchMode === "wayland" && captured.clientBounds
? [captured.bounds, captured.clientBounds]
: [captured.bounds];
const matches = windows.filter((window) => {
const bounds = window.bounds;
return (
titles.has(normalizeTitle(window.name ?? "")) &&
bounds !== null &&
candidateBounds.some((candidate) =>
boundsKeys.every((key) => Math.abs(bounds[key] - candidate[key]) <= 2),
)
);
});
if (matches.length === 1) return matches[0];
const activeMatches = matches.filter((window) => safeProperty(() => window.active) === true);
return activeMatches.length === 1 ? activeMatches[0] : undefined;
}
const ELECTRON_KEY_NAMES: Readonly<Record<string, string>> = {
" ": "Space",
"+": "Plus",
ArrowDown: "Down",
ArrowLeft: "Left",
ArrowRight: "Right",
ArrowUp: "Up",
Escape: "Esc",
};
/** Two shortcuts are the same when they would register the same listener. */
export function sameSnapShotShortcut(left: SnapShotShortcut, right: SnapShotShortcut): boolean {
if (isModifierPairShortcut(left) || isModifierPairShortcut(right)) {
return (
isModifierPairShortcut(left) &&
isModifierPairShortcut(right) &&
snapShotShortcutModifierPair(left) === snapShotShortcutModifierPair(right)
);
}
return toElectronAccelerator(left) === toElectronAccelerator(right);
}
export function toElectronAccelerator(shortcut: SnapShotKeyChord): string {
const parts: string[] = [];
if (shortcut.modKey) parts.push("CommandOrControl");
if (shortcut.metaKey) parts.push("Super");
if (shortcut.ctrlKey) parts.push("Control");
if (shortcut.altKey) parts.push("Alt");
if (shortcut.shiftKey) parts.push("Shift");
parts.push(ELECTRON_KEY_NAMES[shortcut.key] ?? shortcut.key.toUpperCase());
return parts.join("+");
}
interface CaptureSourceLike {
readonly id: string;
readonly name: string;
}
interface ActiveWindowLike {
readonly id: number;
readonly title: string;
}
export function findCaptureSource<T extends CaptureSourceLike>(
sources: readonly T[],
activeWindow: ActiveWindowLike,
): T | undefined {
const idPrefix = `window:${activeWindow.id}:`;
const idMatch = sources.find((source) => source.id.startsWith(idPrefix));
if (idMatch) return idMatch;
const title = activeWindow.title.trim();
if (!title) return undefined;
const titleMatches = sources.filter((source) => source.name.trim() === title);
return titleMatches.length === 1 ? titleMatches[0] : undefined;
}
export function isWaylandSession(
platform: NodeJS.Platform,
environment: NodeJS.ProcessEnv,
): boolean {
if (platform !== "linux") return false;
if (
environment.XDG_SESSION_TYPE?.toLowerCase() === "wayland" ||
Boolean(environment.WAYLAND_DISPLAY)
) {
return true;
}
if (environment.XDG_SESSION_TYPE?.toLowerCase() === "x11") return false;
const runtimeDirectory = environment.XDG_RUNTIME_DIR;
if (!runtimeDirectory) return false;
try {
const liveSockets = new Set(
NodeFS.readFileSync("/proc/net/unix", "utf8")
.split("\n")
.flatMap((line) => line.match(/\s(\/.*)$/)?.[1] ?? []),
);
return NodeFS.readdirSync(runtimeDirectory, { withFileTypes: true }).some(
(entry) =>
/^wayland-\d+$/.test(entry.name) &&
entry.isSocket() &&
liveSockets.has(NodePath.join(runtimeDirectory, entry.name)),
);
} catch {
return false;
}
}
@@ -97,6 +97,7 @@ function makeElectronWindowLayer(window: ReturnType<typeof makeTestWindow>["wind
focusedMainOrFirst: Effect.succeed(Option.some(window as Electron.BrowserWindow)),
setMain: () => Effect.void,
clearMain: () => Effect.void,
prepareReveal: () => Effect.succeed(false),
reveal: () => Effect.void,
sendAll: () => Effect.void,
destroyAll: Effect.void,
@@ -111,6 +111,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
focusedMainOrFirst: Effect.succeed(Option.none()),
setMain: () => Effect.void,
clearMain: () => Effect.void,
prepareReveal: () => Effect.succeed(false),
reveal: () => Effect.void,
sendAll: (_channel, state) =>
Effect.sync(() => {
@@ -84,7 +84,9 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
prepareCaptureReveal: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
dispatchSnapShotEvent: () => Effect.void,
zoomMain: (direction) =>
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
syncAppearance: Effect.void,
+152 -3
View File
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import { DesktopSnapShotId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
@@ -43,7 +44,11 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import {
MENU_ACTION_CHANNEL,
SNAP_SHOT_EVENT_CHANNEL,
WINDOW_FULLSCREEN_STATE_CHANNEL,
} from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -75,7 +80,7 @@ function makeFakeBrowserWindow() {
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
once: vi.fn<(eventName: string, listener: (...args: readonly unknown[]) => void) => void>(),
openDevTools: vi.fn(),
reload: vi.fn(),
replaceMisspelling: vi.fn(),
@@ -132,6 +137,7 @@ function makeFakeBrowserWindow() {
setFullScreen: window.setFullScreen,
setOpacity: window.setOpacity,
webContentsListeners,
webContentsOnce: webContents.once,
windowListeners,
};
}
@@ -209,6 +215,7 @@ function makeTestLayer(input: {
) => Effect.Effect<void>;
readonly openedExternalUrls?: unknown[];
readonly previewZoomReapplies?: number[];
readonly onReveal?: (window: Electron.BrowserWindow) => void;
}) {
let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
@@ -257,7 +264,8 @@ function makeTestLayer(input: {
focusedMainOrFirst: Ref.get(input.mainWindow),
setMain: (window) => Ref.set(input.mainWindow, Option.some(window)),
clearMain: () => Ref.set(input.mainWindow, Option.none()),
reveal: () => Effect.void,
prepareReveal: () => Effect.succeed(false),
reveal: (window) => Effect.sync(() => input.onReveal?.(window)),
sendAll: () => Effect.void,
destroyAll: Effect.void,
syncAllAppearance: (sync) => sync(input.window),
@@ -363,6 +371,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
focusedMainOrFirst: currentMainOrFirst,
setMain: (window) => Ref.set(mainWindow, Option.some(window)),
clearMain: () => Ref.set(mainWindow, Option.none()),
prepareReveal: () => Effect.succeed(false),
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
sendAll: () => Effect.void,
destroyAll: Effect.void,
@@ -399,6 +408,9 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
return { layer, createCalls, mainWindow, revealedWindows } as const;
});
const captureOne = DesktopSnapShotId.make("11111111-1111-4111-8111-111111111111");
const captureTwo = DesktopSnapShotId.make("22222222-2222-4222-8222-222222222222");
describe("DesktopWindow", () => {
it("leaves fullscreen before concealing a pending quit", () => {
const fakeWindow = makeFakeBrowserWindow();
@@ -1260,4 +1272,141 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("delivers capture completion and late errors without taking focus back", () =>
Effect.gen(function* () {
const operations: Array<string> = [];
let foreground = "Discord";
const fakeWindow = makeFakeBrowserWindow();
fakeWindow.send.mockImplementation(() => {
operations.push("send");
});
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
onReveal: () => {
foreground = "T3 Code";
operations.push("reveal");
},
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
yield* desktopWindow.dispatchSnapShotEvent({ type: "started", id: captureOne });
assert.equal(foreground, "T3 Code");
foreground = "Explorer";
yield* desktopWindow.dispatchSnapShotEvent({ type: "ready", id: captureOne });
yield* desktopWindow.dispatchSnapShotEvent({ type: "failed", id: captureTwo });
assert.equal(foreground, "Explorer");
assert.deepEqual(operations, ["send", "reveal", "send", "send"]);
assert.deepEqual(fakeWindow.send.mock.calls, [
[SNAP_SHOT_EVENT_CHANNEL, { type: "started", id: captureOne }],
[SNAP_SHOT_EVENT_CHANNEL, { type: "ready", id: captureOne }],
[SNAP_SHOT_EVENT_CHANNEL, { type: "failed", id: captureTwo }],
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("delivers the renderer event even when the reveal fails", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
onReveal: () => {
throw new Error("another process kept the foreground");
},
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
yield* Effect.exit(
desktopWindow.dispatchSnapShotEvent({ type: "started", id: captureOne }),
);
assert.deepEqual(fakeWindow.send.mock.calls, [
[SNAP_SHOT_EVENT_CHANNEL, { type: "started", id: captureOne }],
]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("leaves a completed capture pending while only the connecting splash exists", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
yield* desktopWindow.dispatchSnapShotEvent({ type: "ready", id: captureOne });
assert.equal(yield* Ref.get(scenario.createCalls), 1);
assert.equal(splash.send.mock.calls.length, 0);
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), []);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("does not reopen a closed main window for a completed capture", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const onReveal = vi.fn();
const layer = makeTestLayer({ window: fakeWindow.window, createCount, mainWindow, onReveal });
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
fakeWindow.isDestroyed.mockReturnValue(true);
yield* Ref.set(mainWindow, Option.none());
yield* desktopWindow.dispatchSnapShotEvent({ type: "ready", id: captureOne });
assert.equal(yield* Ref.get(createCount), 1);
assert.equal(fakeWindow.send.mock.calls.length, 0);
assert.equal(onReveal.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it.effect("waits for a loading renderer without foregrounding it when capture is ready", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(
Option.some(fakeWindow.window),
);
const onReveal = vi.fn();
const layer = makeTestLayer({ window: fakeWindow.window, createCount, mainWindow, onReveal });
vi.mocked(fakeWindow.window.webContents.isLoadingMainFrame).mockReturnValue(true);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.dispatchSnapShotEvent({ type: "ready", id: captureOne });
assert.equal(fakeWindow.send.mock.calls.length, 0);
const onLoad = fakeWindow.webContentsOnce.mock.calls.find(
([event]) => event === "did-finish-load",
)?.[1];
assert.isDefined(onLoad);
onLoad?.();
assert.deepEqual(fakeWindow.send.mock.calls, [
[SNAP_SHOT_EVENT_CHANNEL, { type: "ready", id: captureOne }],
]);
assert.equal(onReveal.mock.calls.length, 0);
assert.equal(yield* Ref.get(createCount), 0);
}).pipe(Effect.provide(layer));
}),
);
});
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff. Show more