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 if !text.is_empty() {
143 let mut cmd = Command::new("wtype");
144 cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
145 cmd.arg("--").arg(text);
146 run(cmd)?;
147 }
148 Ok(())
149}
150
151/// Replace a word at a *known position relative to end-of-line*.
152/// `chars_from_end` is the number of Left arrows needed to walk
153/// from end-of-line back to the END of the word to replace;
154/// `word_chars` is the BackSpace count to remove the word once
155/// the cursor is on it.
156///
157/// Anchored at `End` (rather than relative to the user's current
158/// caret) so held-arrow undercount / mouse clicks / any other
159/// way the buffer's caret can drift from the visible cursor
160/// don't cause the emit to land at the wrong spot. The buffer's
161/// *text* tracks what's actually on screen reliably — only the
162/// caret offset is fragile — so counting chars back from
163/// end-of-line is rock solid as long as the focused app's `End`
164/// goes to end-of-line (shells, single-line text inputs, most
165/// terminals do; multi-line editors may not).
166///
167/// Same mod-clear gate runs first.
168///
169/// # Errors
170///
171/// Returns [`EmitError`] if `wtype` is missing or exits non-zero.
172pub fn anchored_replace_with_delay(
173 chars_from_end: usize,
174 word_chars: usize,
175 insert: &str,
176 pause_per_backspace_ms: u32,
177) -> Result<(), EmitError> {
178 let _ = capture::wait_mods_clear(Duration::from_millis(MODS_CLEAR_TIMEOUT_MS));
179
180 // Anchor: jump the cursor to end-of-line.
181 {
182 let mut cmd = Command::new("wtype");
183 cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
184 cmd.args(["-P", "End", "-p", "End"]);
185 run(cmd)?;
186 sleep_ms(pause_per_backspace_ms, 1);
187 }
188 if chars_from_end > 0 {
189 let mut cmd = Command::new("wtype");
190 cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
191 for _ in 0..chars_from_end {
192 cmd.args(["-P", "Left", "-p", "Left"]);
193 }
194 run(cmd)?;
195 sleep_ms(pause_per_backspace_ms, chars_from_end);
196 }
197 if word_chars > 0 {
198 let mut cmd = Command::new("wtype");
199 cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
200 for _ in 0..word_chars {
201 cmd.args(["-P", "BackSpace", "-p", "BackSpace"]);
202 }
203 run(cmd)?;
204 sleep_ms(pause_per_backspace_ms, word_chars);
205 }
206 if !insert.is_empty() {
207 let mut cmd = Command::new("wtype");
208 cmd.args(["-d", &WTYPE_INTER_KEY_DELAY_MS.to_string()]);
209 cmd.arg("--").arg(insert);
210 run(cmd)?;
211 }
212 Ok(())
213}
214
215fn sleep_ms(pause_per_backspace_ms: u32, count: usize) {
216 let total = u64::from(pause_per_backspace_ms).saturating_mul(count as u64);
217 if total > 0 {
218 std::thread::sleep(std::time::Duration::from_millis(total));
219 }
220}
221
222fn run(mut cmd: Command) -> Result<(), EmitError> {
223 let status = cmd.status().map_err(|e| match e.kind() {
224 ErrorKind::NotFound => EmitError::WtypeMissing,
225 _ => EmitError::WtypeFailed,
226 })?;
227 if status.success() {
228 Ok(())
229 } else {
230 Err(EmitError::WtypeFailed)
231 }
232}