Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(desktop): capture screenshots natively so Wayland sessions work

Luis Ortiz0090a6449511
diff --git a/AGENTS.md b/AGENTS.md
index bcd83af..dafb9f9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -233,25 +233,33 @@ app in `apps/desktop/dist`. `electron-builder.yml` targets dmg/zip, nsis and App
## Desktop Capture Primitives
-`apps/desktop/src/main/capture` holds the four things a desktop capture needs. Three come from
-Electron; only two need anything native, and both are prebuilt npm packages rather than a crate we
-maintain.
+`apps/desktop/src/main/capture` holds the four things a desktop capture needs. Only one comes from
+Electron; the other three are prebuilt npm packages rather than a crate we maintain.
| Primitive | Source | Native |
|---|---|---|
| Displays, DPI, cursor | Electron `screen` | no |
-| Screenshot of a display | Electron `desktopCapturer` | no |
+| Screenshot of a display | `node-screenshots` | prebuilt |
| Focused foreign window | `get-windows` | prebuilt |
| Global clicks and keys | `uiohook-napi` | prebuilt |
+Screenshots do not go through Electron's `desktopCapturer`. That route asks the xdg desktop portal
+on Wayland and fails outright when the portal does not answer, and it was returning frames that
+decoded to nothing on Windows. `node-screenshots` talks to each platform's own capture API, so it
+has a Wayland path and needs no portal. Monitor identifiers there have nothing to do with Electron
+display ids, so the monitor is resolved from a point inside the display's bounds rather than matched
+by id.
+
Anything richer than these four β€” the accessibility tree in particular β€” needs an addon we build and
maintain ourselves, and that is a separate task.
-**Linux is X11 only.** `uiohook-napi` links `libX11`/`libXtst` and hooks through `XRecord`, with no
-Wayland path; on a Wayland session the hook starts and then silently delivers nothing. `get-windows`
-shells out to `xwininfo`, also X11. Both are gated on `XDG_SESSION_TYPE` and refuse up front with
-`reason: 'unsupported-session'` rather than appearing to work. Linux also needs `xwininfo` and
-`xprop` on `PATH`. macOS and Windows are unaffected.
+**On Linux, input and window lookup are X11 only; screenshots are not.** `uiohook-napi` links
+`libX11`/`libXtst` and hooks through `XRecord`, with no Wayland path; on a Wayland session the hook
+starts and then silently delivers nothing. `get-windows` shells out to `xwininfo`, also X11. Both are
+gated on `XDG_SESSION_TYPE` and refuse up front with `reason: 'unsupported-session'` rather than
+appearing to work. Screenshots work on both, so a Wayland machine can still exercise the capture and
+export path even though it cannot record clicks. Linux also needs `xwininfo` and `xprop` on `PATH`.
+macOS and Windows are unaffected.
`pnpm --filter @mimik/desktop check:capture` builds and exercises every primitive, printing `ok`,
`n/a` for a platform limit, or `FAIL`. Only `FAIL` sets a non-zero exit, so the check is meaningful
@@ -360,9 +368,9 @@ control under the cursor is. Reading that needs the accessibility tree and is a
`DesktopRecorder` takes the display grab as a constructor argument defaulting to `captureDisplay`, so
`check:pipeline` feeds it a generated frame. The crop arithmetic, the sink, the step write and all
-four document exporters then run without a working screen-capture path, which matters because
-`desktopCapturer` on Wayland goes through the xdg desktop portal and fails outright when the portal
-does not answer. Whether a real grab works is `check:capture`'s question, not this one's.
+four document exporters then run without a working screen-capture path, which matters because a real
+grab depends on the machine it runs on. Whether a real grab works is `check:capture`'s question, not
+this one's.
`pnpm --filter @mimik/desktop check:pipeline` captures two clicks into a throwaway guide, then
asserts the steps landed on the guide, the screenshot is cropped to the region, the description came
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index f651721..64becb4 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -20,6 +20,7 @@
"dexie": "^4.3.0",
"electron-updater": "^6.6.2",
"get-windows": "^9.3.0",
+ "node-screenshots": "^0.2.8",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"uiohook-napi": "^1.5.5"
diff --git a/apps/desktop/scripts/check-capture.ts b/apps/desktop/scripts/check-capture.ts
index 0460add..9017ef1 100644
--- a/apps/desktop/scripts/check-capture.ts
+++ b/apps/desktop/scripts/check-capture.ts
@@ -1,6 +1,15 @@
-import { app } from 'electron';
+import { app, nativeImage, screen } from 'electron';
import { captureCursorDisplay, cursorPoint, focusedWindow, InputHook, listDisplays } from '../src/main/capture';
+function distinctColours(png: Buffer): number {
+ const bitmap = nativeImage.createFromBuffer(png).toBitmap();
+ const seen = new Set<string>();
+ for (let i = 0; i < bitmap.length && seen.size <= 64; i += 4 * 997) {
+ seen.add(`${bitmap[i]},${bitmap[i + 1]},${bitmap[i + 2]}`);
+ }
+ return seen.size;
+}
+
type Verdict = 'ok' | 'fail' | 'n/a';
function line(name: string, verdict: Verdict, detail: string): void {
@@ -26,6 +35,24 @@ app.whenReady().then(async () => {
const ok = shot.png.length > 0 && shot.width > 0;
if (!ok) failures++;
line('screenshot', ok ? 'ok' : 'fail', `${shot.width}x${shot.height}, ${(shot.png.length / 1024).toFixed(0)} KB png`);
+
+ const display = screen.getDisplayNearestPoint(point);
+ const expected = {
+ width: Math.round(display.bounds.width * shot.scaleFactor),
+ height: Math.round(display.bounds.height * shot.scaleFactor),
+ };
+ const sized = shot.width === expected.width && shot.height === expected.height;
+ if (!sized) failures++;
+ line(
+ 'frame covers display',
+ sized ? 'ok' : 'fail',
+ `${shot.width}x${shot.height}, expected ${expected.width}x${expected.height} at ${shot.scaleFactor}x`,
+ );
+
+ const colours = distinctColours(shot.png);
+ const painted = colours > 1;
+ if (!painted) failures++;
+ line('frame is not blank', painted ? 'ok' : 'fail', `${colours} distinct colours sampled`);
} catch (error) {
failures++;
line('screenshot', 'fail', error instanceof Error ? error.message : String(error));
diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.ts
index 12a4b57..43001ff 100644
--- a/apps/desktop/scripts/check-pipeline.ts
+++ b/apps/desktop/scripts/check-pipeline.ts
@@ -6,7 +6,7 @@ import { DesktopRecorder, shouldCapture } from '../src/main/capture/recorder';
import { clampToDisplays } from '../src/main/capture/region';
import { registerScreenshotProtocol, SCREENSHOT_SCHEME, sweepScreenshots } from '../src/main/capture/screenshot-store';
import { DEFAULT_CAPTURE_SETTINGS, loadSettings, normaliseSettings, saveSettings } from '../src/main/capture/settings';
-import type { Capture } from '../src/main/capture/screenshot';
+import type { Capture, Rect } from '../src/main/capture/screenshot';
interface CheckResult {
name: string;
@@ -39,10 +39,10 @@ app.whenReady().then(async () => {
const region = clampToDisplays({ x: 0, y: 0, width: 800, height: 600 });
const display = screen.getDisplayMatching(region);
- function syntheticDisplay(displayId: number): Promise<Capture> {
+ function syntheticDisplay(area: Rect): Promise<Capture> {
const scale = display.scaleFactor;
- const width = Math.round(display.bounds.width * scale);
- const height = Math.round(display.bounds.height * scale);
+ const width = Math.round(area.width * scale);
+ const height = Math.round(area.height * scale);
const pixels = Buffer.alloc(width * height * 4);
for (let i = 0; i < pixels.length; i += 4) {
pixels[i] = (i / 4) % 256;
@@ -51,7 +51,7 @@ app.whenReady().then(async () => {
pixels[i + 3] = 255;
}
const image = nativeImage.createFromBuffer(pixels, { width, height });
- return Promise.resolve({ png: image.toPNG(), width, height, scaleFactor: scale, displayId });
+ return Promise.resolve({ png: image.toPNG(), width, height, scaleFactor: scale, displayId: display.id });
}
let settings = { ...DEFAULT_CAPTURE_SETTINGS, showCursor: false };
diff --git a/apps/desktop/src/main/capture/recorder.ts b/apps/desktop/src/main/capture/recorder.ts
index cd3a75a..70f1034 100644
--- a/apps/desktop/src/main/capture/recorder.ts
+++ b/apps/desktop/src/main/capture/recorder.ts
@@ -1,11 +1,11 @@
import { randomUUID } from 'node:crypto';
import type { CaptureImage } from '@mimik/core/capture/sink';
import type { ElementMeta } from '@mimik/core/guides/types';
-import { nativeImage, screen } from 'electron';
+import { screen } from 'electron';
import { focusedWindow } from './focused-window';
import { type InputAction, InputHook } from './input-hook';
import type { Region } from './region';
-import { type Capture, captureDisplay } from './screenshot';
+import { type Capture, captureArea, type Rect } from './screenshot';
import { writeScreenshot } from './screenshot-store';
import { type CaptureSettings, DEFAULT_CAPTURE_SETTINGS } from './settings';
@@ -55,7 +55,7 @@ export class DesktopRecorder {
private readonly region: () => Region,
private readonly withHidden: <T>(fn: () => Promise<T>) => Promise<T>,
private readonly send: (request: CaptureRequest) => Promise<unknown>,
- private readonly grab: (displayId: number) => Promise<Capture> = captureDisplay,
+ private readonly grab: (area: Rect) => Promise<Capture> = captureArea,
private readonly settings: () => CaptureSettings = () => DEFAULT_CAPTURE_SETTINGS,
) {}
@@ -94,28 +94,23 @@ export class DesktopRecorder {
}
private enqueue(point: { x: number; y: number }): void {
- this.queue = this.queue.then(() => this.capture(point)).catch(() => undefined);
+ this.queue = this.queue
+ .then(() => this.capture(point))
+ .catch((error) => {
+ process.stderr.write(`mimik: capture failed: ${error instanceof Error ? error.message : String(error)}\n`);
+ });
}
async capture(point: { x: number; y: number }): Promise<void> {
const settings = this.settings();
const region = this.region();
const framed = inside(region, point) ? region : screen.getDisplayNearestPoint(point).bounds;
- const display = screen.getDisplayMatching(framed);
- const scale = display.scaleFactor;
const shot = await this.withHidden(async () => {
await delay(SETTLE_MS + settings.screenshotDelayMs);
- return this.grab(display.id);
+ return this.grab(framed);
});
-
- const cropped = nativeImage.createFromBuffer(Buffer.from(shot.png)).crop({
- x: Math.round((framed.x - display.bounds.x) * scale),
- y: Math.round((framed.y - display.bounds.y) * scale),
- width: Math.round(framed.width * scale),
- height: Math.round(framed.height * scale),
- });
- const size = cropped.getSize();
+ const scale = shot.scaleFactor;
const screenshotId = randomUUID();
const local = { x: point.x - framed.x, y: point.y - framed.y };
@@ -143,9 +138,9 @@ export class DesktopRecorder {
},
image: {
screenshotId,
- src: writeScreenshot(screenshotId, cropped.toPNG()),
- width: size.width,
- height: size.height,
+ src: writeScreenshot(screenshotId, shot.png),
+ width: shot.width,
+ height: shot.height,
},
...(settings.showCursor ? { cursor: { x: local.x, y: local.y, style: settings.cursorStyle, scale } } : {}),
});
diff --git a/apps/desktop/src/main/capture/screenshot.ts b/apps/desktop/src/main/capture/screenshot.ts
index 1d5549f..9cc28f2 100644
--- a/apps/desktop/src/main/capture/screenshot.ts
+++ b/apps/desktop/src/main/capture/screenshot.ts
@@ -1,4 +1,5 @@
-import { desktopCapturer, screen } from 'electron';
+import { screen } from 'electron';
+import { Monitor } from 'node-screenshots';
export interface Capture {
png: Buffer;
@@ -8,24 +9,57 @@ export interface Capture {
displayId: number;
}
-export async function captureDisplay(displayId: number): Promise<Capture> {
- const display = screen.getAllDisplays().find((d) => d.id === displayId);
- if (!display) throw new Error(`no display with id ${displayId}`);
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, value));
+}
- const { width, height } = display.size;
- const scaleFactor = display.scaleFactor;
- const sources = await desktopCapturer.getSources({
- types: ['screen'],
- thumbnailSize: { width: Math.round(width * scaleFactor), height: Math.round(height * scaleFactor) },
- fetchWindowIcons: false,
- });
+function monitorAt(x: number, y: number): Monitor {
+ const found = Monitor.fromPoint(Math.round(x), Math.round(y));
+ if (found) return found;
+ const all = Monitor.all();
+ if (all.length === 0) throw new Error('no monitors available');
+ return all[0];
+}
+
+export async function captureArea(area: Rect): Promise<Capture> {
+ const display = screen.getDisplayMatching(area);
+ const monitor = monitorAt(area.x + area.width / 2, area.y + area.height / 2);
+ const frame = await monitor.captureImage();
+
+ const scale = display.bounds.width > 0 ? frame.width / display.bounds.width : display.scaleFactor;
+ const x = clamp(Math.round((area.x - display.bounds.x) * scale), 0, Math.max(0, frame.width - 1));
+ const y = clamp(Math.round((area.y - display.bounds.y) * scale), 0, Math.max(0, frame.height - 1));
+ const width = clamp(Math.round(area.width * scale), 1, frame.width - x);
+ const height = clamp(Math.round(area.height * scale), 1, frame.height - y);
+
+ const cropped = width === frame.width && height === frame.height ? frame : await frame.crop(x, y, width, height);
+ const png = await cropped.toPng(true);
+ if (png.length === 0 || cropped.width === 0 || cropped.height === 0) {
+ throw new Error(
+ `capture produced an empty image: frame ${frame.width}x${frame.height}, area ${area.width}x${area.height} at ${scale}x`,
+ );
+ }
- const source = sources.find((s) => s.display_id === String(displayId)) ?? sources[0];
- if (!source) throw new Error('no screen sources available');
- if (source.thumbnail.isEmpty()) throw new Error('screen capture returned an empty frame');
+ return {
+ png,
+ width: cropped.width,
+ height: cropped.height,
+ scaleFactor: area.width > 0 ? cropped.width / area.width : 1,
+ displayId: monitor.id(),
+ };
+}
- const size = source.thumbnail.getSize();
- return { png: source.thumbnail.toPNG(), width: size.width, height: size.height, scaleFactor, displayId };
+export async function captureDisplay(displayId: number): Promise<Capture> {
+ const display = screen.getAllDisplays().find((d) => d.id === displayId);
+ if (!display) throw new Error(`no display with id ${displayId}`);
+ return captureArea(display.bounds);
}
export async function captureCursorDisplay(): Promise<Capture> {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2ed92df..9df0951 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -167,6 +167,9 @@ importers:
get-windows:
specifier: ^9.3.0
version: 9.3.0([email protected])
+ node-screenshots:
+ specifier: ^0.2.8
+ version: 0.2.8
react:
specifier: ^19.2.4
version: 19.2.4
@@ -4257,6 +4260,68 @@ packages:
resolution: {integrity: sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==}
+ resolution: {integrity: sha512-CEJE47gG2ceTc1fQRE3T/8lBwCGFJ+0iJiP+CQgCUAll4kKd32DQ7lCANqUseo96/xi6HuDOlrjLkAp7x2TzFw==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-3WIw4QaEP3pIUtSYh2NThwmzQl00H1bTPwPS7sYRLihAzB3NA/FOnIqRmvtadI0KEnnRGX4apdZgIhfXtgbNZA==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-aXJKtekSzQLJX6hh/VT5gilyloiN3DE4oE5xu9z7nLcTPyfC089dqVoERXJxnT+aqSQzx0KkI2te8BZNkjaMtQ==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-+982Yn7L7XID/FhYR6W6S2IVTLiueOBcHs/BP1Te5W6MtwlIIRg593zFh5HPQp7G+IaHqEXQzQj6D7kjJhXzsQ==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [loong64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-xF0hLfPMm9NEF4WtiQnbCyCUxU15M25lFkBzK4WS1CGOcxM7e30tvvwyYfmrMp3OtW/hESQFtiTb4cjKcOdaSA==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-mu/sVwDMt2yQM5ql2rtyQm+mq6Im2ycQLzQxXFXVJOB+k5A+Hk9h65J+G+Iy3rn1uNrYVDjgUQGvIkgpkIonCg==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-g7nnuoJO2yjO8Ovr+Uz9e+LYJMlYc5eqoGPQq7U7NK1LVc2DpyCJ18VT8WdP2f098lfHvE12D3X7Es8NLFjiPg==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-Qsh4Ggs7MzO2XuDPFMRcRxRuiUGxxtHEFuqAfLFL1DiOfBIhLpukZ8JUHlEBdzjPxMFFRJw/4nOm0tnyHP/fiQ==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [ia32]
+ os: [win32]
+
+ resolution: {integrity: sha512-DdFORB74FghM1L6UtE1TltIR2H0CCCmfQEa8gp2CTSdtBr2b0TKL7ZlbEV6x/wVKRFT59w7Kd6BULdeMmp0X2w==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-7O2ab89hkUgiXkrYj9iYCbJjY1iFJqIyZt0vuVtHFKlnajeFoyW+hur4CPxwwrnCUK0ahr0WLWQ5A6rCzF8rWQ==}
+ engines: {node: '>= 12.22.0 < 13 || >= 14.17.0 < 15 || >= 15.12.0 < 16 || >= 16.0.0'}
+
resolution: {integrity: sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==}
engines: {node: '>=6'}
@@ -9635,6 +9700,45 @@ snapshots:
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optionalDependencies:
+ node-screenshots-darwin-arm64: 0.2.8
+ node-screenshots-darwin-x64: 0.2.8
+ node-screenshots-linux-arm64-gnu: 0.2.8
+ node-screenshots-linux-loong64-gnu: 0.2.8
+ node-screenshots-linux-x64-gnu: 0.2.8
+ node-screenshots-linux-x64-musl: 0.2.8
+ node-screenshots-win32-arm64-msvc: 0.2.8
+ node-screenshots-win32-ia32-msvc: 0.2.8
+ node-screenshots-win32-x64-msvc: 0.2.8
+
dependencies:
abbrev: 1.1.1