Skip to main content

hyprcorrect_platform/linux/
emit.rs

1//! Linux synthetic text input.
2//!
3//! Corrections are applied by shelling out to `wtype`, which drives the
4//! Wayland `virtual-keyboard-v1` protocol. (A native, dependency-free
5//! implementation of that protocol is a later refinement — see
6//! `DESIGN.md`.)
7
8use std::io::ErrorKind;
9use std::process::Command;
10use std::time::Duration;
11
12use super::capture;
13
14/// How long we'll wait for the user to release the chord
15/// (Ctrl/Shift/Alt/Super) before giving up and emitting anyway.
16/// Tuned to feel instant when the user taps-and-releases, but
17/// generous enough to cover a slow release.
18const MODS_CLEAR_TIMEOUT_MS: u64 = 250;
19
20/// An error applying a text replacement.
21#[derive(Debug, thiserror::Error)]
22pub enum EmitError {
23    /// `wtype` is not installed.
24    #[error(
25        "`wtype` is not installed — install it (e.g. `sudo pacman -S wtype`) so hyprcorrect can type corrections"
26    )]
27    WtypeMissing,
28    /// `wtype` ran but exited with a failure.
29    #[error("`wtype` failed to apply the correction")]
30    WtypeFailed,
31}
32
33/// Per-key delay used inside each `wtype` burst. Was 2 ms originally
34/// — large enough to give wtype's protocol a flush point per event,
35/// small enough to feel instant. But terminals (Ghostty, foot, …)
36/// drop the occasional BackSpace under that pressure when the burst
37/// is 5+ keys: the result is leftover characters that escape the
38/// deletion (e.g., `mothr → motherr` instead of `mother`). 8 ms
39/// per key is still imperceptible for normal-length words and is
40/// reliably swallowed by every terminal we've tested.
41const WTYPE_INTER_KEY_DELAY_MS: u32 = 8;
42
43/// Apply an edit at the caret: press Backspace `backspaces` times, then
44/// type `text`. Uses the default per-backspace pause.
45///
46/// # Errors
47///
48/// Returns [`EmitError`] if `wtype` is missing or exits non-zero.
49pub fn replace(backspaces: usize, text: &str) -> Result<(), EmitError> {
50    replace_with_delay(backspaces, text, 8)
51}
52
53/// Like [`replace`], but lets the caller set the pause-per-backspace
54/// in milliseconds. The pause is applied as a single sleep between
55/// the backspace burst and the replacement-text burst, scaled by the
56/// number of backspaces so longer edits wait proportionally longer.
57///
58/// Wayland delivers wtype's events reliably; what this pause covers
59/// is the time the focused app needs to *apply* the backspaces
60/// through its own event loop before our next `wtype` (the typing
61/// burst) starts queueing text events behind the still-processing
62/// deletes.
63///
64/// Backspaces and text are emitted as *two separate* `wtype`
65/// invocations so the focused app has a clean event boundary
66/// between them.
67///
68/// # Errors
69///
70/// Returns [`EmitError`] if `wtype` is missing or exits non-zero.
71pub fn replace_with_delay(
72    backspaces: usize,
73    text: &str,
74    pause_per_backspace_ms: u32,
75) -> Result<(), EmitError> {
76    replace_around_caret_with_delay(backspaces, 0, text, pause_per_backspace_ms)
77}
78
79/// Like [`replace_with_delay`] but also emits Delete keys (right of
80/// the caret) before typing the replacement. Used by fix-word /
81/// fix-sentence when the caret is INSIDE a word or sentence: we
82/// can't backspace away text on the right side of the caret, so we
83/// hand the focused app `BackSpace × N` then `Delete × M` then the
84/// new text.
85///
86/// `pause_per_backspace_ms` scales the drain pause by the total
87/// number of editing keystrokes (backspaces + deletes), since both
88/// kinds of edits queue in the focused app's event loop the same
89/// way.
90///
91/// # Errors
92///
93/// Returns [`EmitError`] if `wtype` is missing or exits non-zero.
94pub fn replace_around_caret_with_delay(
95    backspaces: usize,
96    deletes: usize,
97    text: &str,
98    pause_per_backspace_ms: u32,
99) -> Result<(), EmitError> {
100    // Wait for the user to release the trigger chord before we
101    // type anything. Many Wayland compositors deliver wtype's
102    // synthetic keys ORed with the user's physical modifier
103    // state, so a `BackSpace` while Ctrl is still held arrives at
104    // the focused window as Ctrl+BackSpace (delete-word, in most
105    // terminals). On timeout we fall through and emit anyway —
106    // the user may be holding an unrelated modifier on purpose.
107    let _ = capture::wait_mods_clear(Duration::from_millis(MODS_CLEAR_TIMEOUT_MS));
108
109    // Implementation strategy: "delete N chars to the right of the
110    // caret" is rewritten as "move caret right N, then backspace N
111    // more." Every deletion ends up going through `BackSpace`,
112    // which TUIs and editors handle uniformly. Sending Delete keys
113    // directly worked unreliably — under fast bursts terminals'
114    // input parsers were dropping the trailing keystrokes, leaving
115    // chars on screen.
116    //
117    // Three phases, each its own wtype call with a drain pause:
118    // 1. Right arrow × `deletes` — moves caret to the right edge of
119    //    the region we want gone.
120    // 2. BackSpace × (`backspaces` + `deletes`) — drains the whole
121    //    region left of the now-rightmost caret position.
122    // 3. Type the replacement text.
123    if deletes > 0 {
124        let mut cmd = Command::new("wtype");
125        cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
126        for _ in 0..deletes {
127            cmd.args(["-P", "Right", "-p", "Right"]);
128        }
129        run(cmd)?;
130        sleep_ms(pause_per_backspace_ms, deletes);
131    }
132    let total_backspaces = backspaces + deletes;
133    if total_backspaces > 0 {
134        let mut cmd = Command::new("wtype");
135        cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
136        for _ in 0..total_backspaces {
137            cmd.args(["-P", "BackSpace", "-p", "BackSpace"]);
138        }
139        run(cmd)?;
140        sleep_ms(pause_per_backspace_ms, total_backspaces);
141    }
142    type_text(text)?;
143    Ok(())
144}
145
146/// Replace a word at a *known position relative to end-of-line*.
147/// `chars_from_end` is the number of Left arrows needed to walk
148/// from end-of-line back to the END of the word to replace;
149/// `word_chars` is the BackSpace count to remove the word once
150/// the cursor is on it.
151///
152/// Anchored at `End` (rather than relative to the user's current
153/// caret) so held-arrow undercount / mouse clicks / any other
154/// way the buffer's caret can drift from the visible cursor
155/// don't cause the emit to land at the wrong spot. The buffer's
156/// *text* tracks what's actually on screen reliably — only the
157/// caret offset is fragile — so counting chars back from
158/// end-of-line is rock solid as long as the focused app's `End`
159/// goes to end-of-line (shells, single-line text inputs, most
160/// terminals do; multi-line editors may not).
161///
162/// Same mod-clear gate runs first.
163///
164/// # Errors
165///
166/// Returns [`EmitError`] if `wtype` is missing or exits non-zero.
167pub fn anchored_replace_with_delay(
168    chars_from_end: usize,
169    word_chars: usize,
170    insert: &str,
171    pause_per_backspace_ms: u32,
172) -> Result<(), EmitError> {
173    let _ = capture::wait_mods_clear(Duration::from_millis(MODS_CLEAR_TIMEOUT_MS));
174
175    // Anchor: jump the cursor to end-of-line.
176    {
177        let mut cmd = Command::new("wtype");
178        cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
179        cmd.args(["-P", "End", "-p", "End"]);
180        run(cmd)?;
181        sleep_ms(pause_per_backspace_ms, 1);
182    }
183    if chars_from_end > 0 {
184        let mut cmd = Command::new("wtype");
185        cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
186        for _ in 0..chars_from_end {
187            cmd.args(["-P", "Left", "-p", "Left"]);
188        }
189        run(cmd)?;
190        sleep_ms(pause_per_backspace_ms, chars_from_end);
191    }
192    if word_chars > 0 {
193        let mut cmd = Command::new("wtype");
194        cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
195        for _ in 0..word_chars {
196            cmd.args(["-P", "BackSpace", "-p", "BackSpace"]);
197        }
198        run(cmd)?;
199        sleep_ms(pause_per_backspace_ms, word_chars);
200    }
201    type_text(insert)?;
202    Ok(())
203}
204
205/// Type `text` as a `wtype` burst, emitting embedded newlines as
206/// Shift+Enter rather than a bare Return. A plain Return submits
207/// chat-style inputs (the Claude Code prompt, Slack, Discord, …);
208/// Shift+Enter inserts a line break instead, so applying a multi-line
209/// correction never sends the message. Each line is its own text burst
210/// with a Shift+Enter key event between them; a string with no newline
211/// is a single burst, identical to the old behavior. Empty input is a
212/// no-op.
213fn type_text(text: &str) -> Result<(), EmitError> {
214    let mut first = true;
215    for line in text.split('\n') {
216        if !first {
217            let mut cmd = Command::new("wtype");
218            cmd.args(["-M", "shift", "-k", "Return", "-m", "shift"]);
219            run(cmd)?;
220        }
221        first = false;
222        if !line.is_empty() {
223            let mut cmd = Command::new("wtype");
224            cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
225            cmd.arg("--").arg(line);
226            run(cmd)?;
227        }
228    }
229    Ok(())
230}
231
232fn sleep_ms(pause_per_backspace_ms: u32, count: usize) {
233    let total = u64::from(pause_per_backspace_ms).saturating_mul(count as u64);
234    if total > 0 {
235        std::thread::sleep(std::time::Duration::from_millis(total));
236    }
237}
238
239fn run(mut cmd: Command) -> Result<(), EmitError> {
240    let status = cmd.status().map_err(|e| match e.kind() {
241        ErrorKind::NotFound => EmitError::WtypeMissing,
242        _ => EmitError::WtypeFailed,
243    })?;
244    if status.success() {
245        Ok(())
246    } else {
247        Err(EmitError::WtypeFailed)
248    }
249}