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): record shortcuts and named keys as their own steps

Luis Ortiz85771a096a88
diff --git a/AGENTS.md b/AGENTS.md
index 42e77c0..fd732cc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -308,7 +308,8 @@ the way in and the rectangle with `screenToDipRect` on the way out, the same con
name.
`focusedElement()` is the second call, and it is what makes typing capture possible without reading
-keystrokes. It reports `isPassword` alongside the usual fields, and the value is discarded at the
+keystrokes. `keyLabel()` is the third, and unlike the other two it is synchronous, because resolving
+a scancode against a keyboard layout is a local call with nothing to wait on. It reports `isPassword` alongside the usual fields, and the value is discarded at the
addon boundary when that flag is set, so a password never reaches our data even though UIAutomation
already withholds it.
@@ -529,6 +530,18 @@ typing into a surface that exposes no value, costs nothing. The exception is a p
by design reports no value at all: there the step is written anyway, with no `inputValue`, and
`buildFallbackDescription` words it as "Type password" rather than naming the field's contents.
+Keys that are not typing get their own step. A shortcut always does; `Enter`, `Tab` and `Escape` do
+only when no typing session was open, because the `Enter` that submits a field is part of that
+field's step rather than a step of its own. Auto-repeat is collapsed the way a double click is β€”
+`isRepeatKey` drops the same keycode within 500 ms, so holding a key down is one step.
+
+Naming the key is the only place a keyboard layout is consulted. `keyLabel` maps the hook's scancode
+through `MapVirtualKeyExW` against the **foreground window's** layout, so the same physical key reads
+as `Q` on QWERTY and `A` on AZERTY, which is what the application being recorded will have acted on.
+`ToUnicodeEx` is deliberately not used: it would name punctuation too, but it mutates the thread's
+dead-key state as a side effect, and a shortcut only needs the letter, digit or named key. A key that
+maps to none of those yields no label and therefore no step, rather than a step nobody can follow.
+
Rich text is the gap. `ValuePattern` is what the value is read through, and a word processor or a
browser's `contenteditable` exposes `TextPattern` instead, so typing there closes a session and
writes nothing. Clicks in those applications still capture normally.
diff --git a/apps/desktop/scripts/check-capture.ts b/apps/desktop/scripts/check-capture.ts
index 42e7157..0b7197f 100644
--- a/apps/desktop/scripts/check-capture.ts
+++ b/apps/desktop/scripts/check-capture.ts
@@ -5,6 +5,7 @@ import {
elementAt,
elementLookupAvailable,
focusedWindow,
+ keyLabel,
InputHook,
listDisplays,
} from '../src/main/capture';
@@ -87,6 +88,14 @@ app.whenReady().then(async () => {
: 'the accessibility addon has no build for this platform',
);
+ const named = lookup ? await keyLabel(28) : null;
+ if (lookup && named !== 'Enter') failures++;
+ line(
+ 'key names',
+ lookup ? (named === 'Enter' ? 'ok' : 'fail') : 'n/a',
+ lookup ? `scancode 28 resolved to ${named ?? 'nothing'} on the foreground layout` : 'no addon on this platform',
+ );
+
const hook = new InputHook();
const started = await hook.start(() => {});
if (!started.ok && started.reason !== 'unsupported-session') failures++;
diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.ts
index 0e0229c..0e26cbf 100644
--- a/apps/desktop/scripts/check-pipeline.ts
+++ b/apps/desktop/scripts/check-pipeline.ts
@@ -8,7 +8,9 @@ import {
type CaptureRequest,
DesktopRecorder,
frameFor,
+ comboLabel,
isRepeatClick,
+ isRepeatKey,
isTypingKey,
shouldCapture,
targetRect,
@@ -168,6 +170,7 @@ app.whenReady().then(async () => {
settings: () => ({ ...REGION_MODE, showCursor: true }),
lookup: () => Promise.resolve(control),
focused: () => Promise.resolve(field),
+ label: (keycode) => Promise.resolve(keycode === 31 ? 'S' : null),
},
);
await metaRecorder.capture({ x: region.x + 60, y: region.y + 40 });
@@ -258,6 +261,38 @@ app.whenReady().then(async () => {
detail: 'a letter types, shift still types, a shortcut does not, and Enter, Tab, Escape and Shift all close the session',
});
+ const pressed = (keycode: number, held: Partial<KeyAction> = {}): KeyAction => ({
+ kind: 'keydown',
+ keycode,
+ shift: false,
+ alt: false,
+ ctrl: false,
+ meta: false,
+ at: 0,
+ ...held,
+ });
+
+ seen = null;
+ field = { ...control };
+ await metaRecorder.captureKey(pressed(31, { ctrl: true }));
+ const shortcut = seen as CaptureRequest | null;
+
+ seen = null;
+ await metaRecorder.captureKey(pressed(99, { ctrl: true }));
+ const unnamed = seen as CaptureRequest | null;
+
+ results.push({
+ name: 'a shortcut is its own step',
+ ok:
+ shortcut?.action === 'keydown:Ctrl+S' &&
+ comboLabel(pressed(31, { ctrl: true, shift: true }), 'S') === 'Ctrl+Shift+S' &&
+ unnamed === null &&
+ isRepeatKey({ keycode: 28, at: 1_000 }, 28, 1_400) &&
+ !isRepeatKey({ keycode: 28, at: 1_000 }, 28, 1_600) &&
+ !isRepeatKey({ keycode: 28, at: 1_000 }, 15, 1_100),
+ detail: `wrote ${shortcut?.action ?? 'nothing'}; an unnameable key wrote nothing, auto-repeat collapses, a different key does not`,
+ });
+
const page = { x: 0, y: 0, width: 800, height: 600 };
const click = { x: 160, y: 66 };
const boxed = (rect: ScreenElement['rect']) => targetRect({ ...control, rect }, page, click).width;
diff --git a/apps/desktop/src/main/capture/element.ts b/apps/desktop/src/main/capture/element.ts
index e9479a8..196e463 100644
--- a/apps/desktop/src/main/capture/element.ts
+++ b/apps/desktop/src/main/capture/element.ts
@@ -19,6 +19,7 @@ const TEXT_ROLES = new Set(['textbox', 'combobox']);
type Addon = {
elementAtPoint(x: number, y: number): Promise<UiElement | null>;
focusedElement(): Promise<UiElement | null>;
+ keyLabel(keycode: number): string | null;
isSupported(): boolean;
};
@@ -88,6 +89,11 @@ export async function focusedField(): Promise<ScreenElement | null> {
return found ? describe(found) : null;
}
+export async function keyLabel(keycode: number): Promise<string | null> {
+ const native = await load();
+ return native?.keyLabel(keycode) ?? null;
+}
+
export async function elementLookupAvailable(): Promise<boolean> {
const native = await load();
return native?.isSupported() ?? false;
diff --git a/apps/desktop/src/main/capture/index.ts b/apps/desktop/src/main/capture/index.ts
index 2da581b..e4c9754 100644
--- a/apps/desktop/src/main/capture/index.ts
+++ b/apps/desktop/src/main/capture/index.ts
@@ -1,5 +1,5 @@
export { cursorPoint, type DisplayInfo, displayAt, listDisplays } from './displays';
-export { elementAt, elementLookupAvailable, type ScreenElement } from './element';
+export { elementAt, elementLookupAvailable, focusedField, isTextField, keyLabel, type ScreenElement } from './element';
export { type FocusedWindow, type FocusedWindowResult, focusedWindow } from './focused-window';
export { type InputAction, InputHook, type InputHookStart, type KeyAction, type PointerAction } from './input-hook';
export { type Capture, captureCursorDisplay, captureDisplay } from './screenshot';
diff --git a/apps/desktop/src/main/capture/recorder.ts b/apps/desktop/src/main/capture/recorder.ts
index 5df08f7..15d3e54 100644
--- a/apps/desktop/src/main/capture/recorder.ts
+++ b/apps/desktop/src/main/capture/recorder.ts
@@ -3,7 +3,7 @@ import type { CaptureImage } from '@mimik/core/capture/sink';
import type { ElementMeta } from '@mimik/core/guides/types';
import { screen } from 'electron';
import { cursorPoint } from './displays';
-import { elementAt, focusedField, isTextField, type ScreenElement } from './element';
+import { elementAt, focusedField, isTextField, keyLabel, type ScreenElement } from './element';
import { focusedWindow } from './focused-window';
import { type InputAction, InputHook, type KeyAction, type PointerAction } from './input-hook';
import type { Region } from './region';
@@ -70,6 +70,7 @@ export interface RecorderHooks {
ignores?: (point: Point) => boolean;
lookup?: (point: Point) => Promise<ScreenElement | null>;
focused?: () => Promise<ScreenElement | null>;
+ label?: (keycode: number) => Promise<string | null>;
}
export type RecorderStart = { ok: true } | { ok: false; reason: string; detail: string };
@@ -103,6 +104,19 @@ export function frameFor(mode: CaptureMode, point: Point, region: Region, window
return inside(region, point) ? region : display;
}
+export function isRepeatKey(previous: { keycode: number; at: number } | null, keycode: number, at: number): boolean {
+ return previous !== null && previous.keycode === keycode && at - previous.at <= REPEAT_CLICK_MS;
+}
+
+export function comboLabel(action: KeyAction, key: string): string {
+ const held: string[] = [];
+ if (action.meta) held.push('Meta');
+ if (action.ctrl) held.push('Ctrl');
+ if (action.alt) held.push('Alt');
+ if (action.shift) held.push('Shift');
+ return [...held, key].join('+');
+}
+
export function isTypingKey(action: KeyAction): boolean {
if (MODIFIER_KEYS.has(action.keycode)) return false;
if (action.ctrl || action.alt || action.meta) return false;
@@ -138,6 +152,7 @@ export class DesktopRecorder {
private paused = false;
private running = false;
private lastClickAt: number | null = null;
+ private lastKey: { keycode: number; at: number } | null = null;
private typing = false;
private idle: NodeJS.Timeout | null = null;
private readonly grab: (area: Rect) => Promise<Capture>;
@@ -145,6 +160,7 @@ export class DesktopRecorder {
private readonly ignores: (point: Point) => boolean;
private readonly lookup: (point: Point) => Promise<ScreenElement | null>;
private readonly focused: () => Promise<ScreenElement | null>;
+ private readonly label: (keycode: number) => Promise<string | null>;
constructor(
private readonly region: () => Region,
@@ -157,6 +173,7 @@ export class DesktopRecorder {
this.ignores = hooks.ignores ?? (() => false);
this.lookup = hooks.lookup ?? elementAt;
this.focused = hooks.focused ?? focusedField;
+ this.label = hooks.label ?? keyLabel;
}
async start(): Promise<RecorderStart> {
@@ -209,14 +226,30 @@ export class DesktopRecorder {
private onKey(action: KeyAction): void {
if (MODIFIER_KEYS.has(action.keycode)) return;
- if (!isTypingKey(action)) {
- this.commitTyping();
+ if (isTypingKey(action)) {
+ this.typing = true;
+ if (this.idle) clearTimeout(this.idle);
+ this.idle = setTimeout(() => this.commitTyping(), TYPING_IDLE_MS);
+ this.idle.unref?.();
return;
}
- this.typing = true;
- if (this.idle) clearTimeout(this.idle);
- this.idle = setTimeout(() => this.commitTyping(), TYPING_IDLE_MS);
- this.idle.unref?.();
+
+ const submitted = this.typing;
+ this.commitTyping();
+
+ const at = Date.now();
+ const repeat = isRepeatKey(this.lastKey, action.keycode, at);
+ this.lastKey = { keycode: action.keycode, at };
+ if (repeat) return;
+ if (submitted && !action.ctrl && !action.alt && !action.meta) return;
+ this.enqueue(() => this.captureKey(action));
+ }
+
+ async captureKey(action: KeyAction): Promise<void> {
+ const key = await this.label(action.keycode);
+ if (!key) return;
+ const field = await this.focused();
+ await this.write(`keydown:${comboLabel(action, key)}`, centreOf(field) ?? cursorPoint(), Promise.resolve(field));
}
private commitTyping(): void {
diff --git a/packages/capture-native/Cargo.toml b/packages/capture-native/Cargo.toml
index 1040b9b..eef8b00 100644
--- a/packages/capture-native/Cargo.toml
+++ b/packages/capture-native/Cargo.toml
@@ -16,6 +16,8 @@ windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_System_Com",
"Win32_UI_Accessibility",
+ "Win32_UI_Input_KeyboardAndMouse",
+ "Win32_UI_WindowsAndMessaging",
] }
[build-dependencies]
diff --git a/packages/capture-native/index.d.ts b/packages/capture-native/index.d.ts
index 5b06506..214232a 100644
--- a/packages/capture-native/index.d.ts
+++ b/packages/capture-native/index.d.ts
@@ -22,6 +22,8 @@ export declare function focusedElement(): Promise<UiElement | null>
export declare function isSupported(): boolean
+export declare function keyLabel(keycode: number): string | null
+
export interface UiElement {
role?: string
name?: string
diff --git a/packages/capture-native/index.js b/packages/capture-native/index.js
index 0f8bf0a..530f7dd 100644
--- a/packages/capture-native/index.js
+++ b/packages/capture-native/index.js
@@ -781,3 +781,4 @@ module.exports = nativeBinding
module.exports.elementAtPoint = nativeBinding.elementAtPoint
module.exports.focusedElement = nativeBinding.focusedElement
module.exports.isSupported = nativeBinding.isSupported
+module.exports.keyLabel = nativeBinding.keyLabel
diff --git a/packages/capture-native/src/lib.rs b/packages/capture-native/src/lib.rs
index 8143c15..d5327b0 100644
--- a/packages/capture-native/src/lib.rs
+++ b/packages/capture-native/src/lib.rs
@@ -62,6 +62,17 @@ pub fn focused_element() -> AsyncTask<ElementLookup> {
AsyncTask::new(ElementLookup { at: None })
}
+#[napi]
+pub fn key_label(keycode: u32) -> Option<String> {
+ #[cfg(windows)]
+ return win::key_label(keycode);
+ #[cfg(not(windows))]
+ {
+ let _ = keycode;
+ None
+ }
+}
+
#[napi]
pub fn is_supported() -> bool {
cfg!(windows)
diff --git a/packages/capture-native/src/win.rs b/packages/capture-native/src/win.rs
index acdf9e8..b601717 100644
--- a/packages/capture-native/src/win.rs
+++ b/packages/capture-native/src/win.rs
@@ -7,6 +7,12 @@ use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED,
};
use windows::Win32::UI::Accessibility::*;
+use windows::Win32::UI::Input::KeyboardAndMouse::{
+ GetKeyboardLayout, MapVirtualKeyExW, HKL, MAPVK_VSC_TO_VK_EX, VK_BACK, VK_DELETE, VK_DOWN, VK_END,
+ VK_ESCAPE, VK_F1, VK_F24, VK_HOME, VK_INSERT, VK_LEFT, VK_NEXT, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SPACE,
+ VK_TAB, VK_UP,
+};
+use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
use crate::{ElementRect, UiElement};
@@ -138,3 +144,52 @@ pub fn focused_element() -> Result<Option<UiElement>> {
.map_err(|error| napi::Error::from_reason(error.message()))?;
Ok(Some(describe(&found)))
}
+
+const NAMED_KEYS: &[(u16, &str)] = &[
+ (VK_RETURN.0, "Enter"),
+ (VK_TAB.0, "Tab"),
+ (VK_ESCAPE.0, "Escape"),
+ (VK_BACK.0, "Backspace"),
+ (VK_SPACE.0, "Space"),
+ (VK_DELETE.0, "Delete"),
+ (VK_INSERT.0, "Insert"),
+ (VK_HOME.0, "Home"),
+ (VK_END.0, "End"),
+ (VK_PRIOR.0, "PageUp"),
+ (VK_NEXT.0, "PageDown"),
+ (VK_UP.0, "ArrowUp"),
+ (VK_DOWN.0, "ArrowDown"),
+ (VK_LEFT.0, "ArrowLeft"),
+ (VK_RIGHT.0, "ArrowRight"),
+];
+
+const EXTENDED: u32 = 0xe00;
+
+fn foreground_layout() -> HKL {
+ let window = unsafe { GetForegroundWindow() };
+ let thread = unsafe { GetWindowThreadProcessId(window, None) };
+ unsafe { GetKeyboardLayout(thread) }
+}
+
+pub fn key_label(keycode: u32) -> Option<String> {
+ let extended = keycode >= EXTENDED;
+ let scancode = if extended {
+ 0xe000 | (keycode - EXTENDED)
+ } else {
+ keycode
+ };
+ let vk = unsafe { MapVirtualKeyExW(scancode, MAPVK_VSC_TO_VK_EX, Some(foreground_layout())) } as u16;
+ if vk == 0 {
+ return None;
+ }
+ if let Some((_, name)) = NAMED_KEYS.iter().find(|(key, _)| *key == vk) {
+ return Some((*name).to_string());
+ }
+ if (VK_F1.0..=VK_F24.0).contains(&vk) {
+ return Some(format!("F{}", vk - VK_F1.0 + 1));
+ }
+ if vk < 128 && (vk as u8).is_ascii_alphanumeric() {
+ return Some((vk as u8 as char).to_string());
+ }
+ None
+}