typechar 1.1.0

Type any Unicode string on macOS, regardless of keyboard layout
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Type any Unicode string on macOS, regardless of keyboard layout.
//!
//! The string is posted directly as a keyboard event via CoreGraphics
//! (`CGEventKeyboardSetUnicodeString`), so the active keyboard layout is
//! never consulted — characters that no key combination can produce still
//! arrive at the frontmost app.
//!
//! ```no_run
//! if !typechar::has_permission() {
//!     typechar::request_permission(); // prompts the user via System Settings
//! }
//! typechar::type_string("¯\\_(ツ)_/¯")?;
//! # Ok::<(), typechar::TypeError>(())
//! ```
//!
//! The calling process needs macOS Accessibility permission (System Settings
//! → Privacy & Security → Accessibility); without it [`type_string`] returns
//! [`TypeError::PermissionDenied`] instead of silently typing nothing.

use core_graphics::event::{CGEvent, CGEventTapLocation};
use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
use std::thread::sleep;
use std::time::Duration;
use thiserror::Error;

/// `CGEventKeyboardSetUnicodeString` silently truncates long strings; 20
/// UTF-16 code units per event is the documented-by-folklore safe limit.
const MAX_UNITS_PER_EVENT: usize = 20;

// Not exposed by the core-graphics crate; resolved from the already-linked
// CoreGraphics framework.
unsafe extern "C" {
    fn CGPreflightPostEventAccess() -> bool;
    fn CGRequestPostEventAccess() -> bool;
}

/// Why typing failed.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum TypeError {
    /// The calling process lacks Accessibility permission. Call
    /// [`request_permission`] to prompt the user, then retry.
    #[error("no permission to post keyboard events")]
    PermissionDenied,
    #[error("failed to create CoreGraphics event source")]
    EventSourceFailed,
    #[error("failed to create keyboard event")]
    EventCreationFailed,
}

/// Whether the calling process may post keyboard events.
pub fn has_permission() -> bool {
    unsafe { CGPreflightPostEventAccess() }
}

/// Ask macOS to prompt the user to grant this process Accessibility
/// permission (opens System Settings). Returns whether permission is held.
pub fn request_permission() -> bool {
    unsafe { CGRequestPostEventAccess() }
}

/// Type `text` into the frontmost application, bypassing the keyboard layout.
pub fn type_string(text: &str) -> Result<(), TypeError> {
    if !has_permission() {
        return Err(TypeError::PermissionDenied);
    }
    let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState)
        .map_err(|_| TypeError::EventSourceFailed)?;
    for chunk in utf16_chunks(text, MAX_UNITS_PER_EVENT) {
        for key_down in [true, false] {
            let event = CGEvent::new_keyboard_event(source.clone(), 0, key_down)
                .map_err(|_| TypeError::EventCreationFailed)?;
            event.set_string_from_utf16_unchecked(&chunk);
            event.post(CGEventTapLocation::HID);
        }
        // Give the WindowServer a beat between chunks so long strings arrive in order.
        sleep(Duration::from_millis(1));
    }
    Ok(())
}

/// What the process should do, decided from argv.
#[derive(Debug, PartialEq, Eq)]
pub enum Action {
    /// Type this text, after waiting `delay_ms` milliseconds.
    Type {
        text: String,
        delay_ms: u64,
    },
    Help,
    Version,
}

/// Parse argv (excluding argv[0]) into an Action.
pub fn parse_args(args: &[String]) -> Result<Action, String> {
    let mut delay_ms: u64 = 0;
    let mut text: Option<String> = None;
    let mut codepoints = String::new();
    let mut literal = false;

    let set_text = |s: &str, text: &mut Option<String>| -> Result<(), String> {
        if text.is_some() {
            return Err("only one text argument is allowed (quote the whole string)".into());
        }
        *text = Some(s.to_string());
        Ok(())
    };

    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if literal {
            set_text(arg, &mut text)?;
            continue;
        }
        match arg.as_str() {
            "--help" | "-h" => return Ok(Action::Help),
            "--version" | "-V" => return Ok(Action::Version),
            "--" => literal = true,
            "--delay" | "-d" => {
                let value = iter
                    .next()
                    .ok_or("--delay requires a value in milliseconds")?;
                delay_ms = value
                    .parse()
                    .map_err(|_| format!("invalid --delay value: {value}"))?;
            }
            "--unicode" | "-u" => {
                let value = iter.next().ok_or("--unicode requires a hex codepoint")?;
                codepoints.push(decode_codepoint(value)?);
            }
            flag if flag.starts_with('-') && flag.len() > 1 => {
                return Err(format!(
                    "unknown option: {flag} (use -- to type it literally)"
                ));
            }
            other => set_text(other, &mut text)?,
        }
    }

    let text = match (text, codepoints.is_empty()) {
        (Some(t), true) => t,
        (None, false) => codepoints,
        (Some(_), false) => return Err("pass either a string or --unicode, not both".into()),
        (None, true) => return Err("nothing to type (pass a string or --unicode <hex>)".into()),
    };

    Ok(Action::Type { text, delay_ms })
}

/// Decode a hex codepoint like "20ac" or "U+20AC" into a char.
pub fn decode_codepoint(hex: &str) -> Result<char, String> {
    let digits = hex
        .strip_prefix("U+")
        .or_else(|| hex.strip_prefix("u+"))
        .unwrap_or(hex);
    let value =
        u32::from_str_radix(digits, 16).map_err(|_| format!("invalid hex codepoint: {hex}"))?;
    char::from_u32(value).ok_or(format!("not a valid Unicode scalar value: {hex}"))
}

/// Split text into UTF-16 chunks of at most `max_units` code units,
/// never splitting a surrogate pair across chunks.
pub fn utf16_chunks(text: &str, max_units: usize) -> Vec<Vec<u16>> {
    let mut chunks: Vec<Vec<u16>> = Vec::new();
    let mut current: Vec<u16> = Vec::new();
    for ch in text.chars() {
        let mut buf = [0u16; 2];
        let units = ch.encode_utf16(&mut buf);
        if current.len() + units.len() > max_units && !current.is_empty() {
            chunks.push(std::mem::take(&mut current));
        }
        current.extend_from_slice(units);
    }
    if !current.is_empty() {
        chunks.push(current);
    }
    chunks
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    // ---- TypeError ----

    #[test]
    fn type_error_is_a_std_error_with_useful_messages() {
        fn assert_error<E: std::error::Error>(_: &E) {}
        let e = TypeError::PermissionDenied;
        assert_error(&e);
        assert_eq!(e.to_string(), "no permission to post keyboard events");
        assert_eq!(
            TypeError::EventSourceFailed.to_string(),
            "failed to create CoreGraphics event source"
        );
        assert_eq!(
            TypeError::EventCreationFailed.to_string(),
            "failed to create keyboard event"
        );
    }

    #[test]
    fn type_string_without_permission_returns_permission_denied() {
        // The test runner is not Accessibility-trusted in CI/sandboxes, so
        // this exercises the real permission check. On a trusted machine the
        // call succeeds — with an empty string it posts zero events either way.
        match type_string("") {
            Ok(()) | Err(TypeError::PermissionDenied) => {}
            Err(other) => panic!("unexpected error: {other}"),
        }
    }

    // ---- parse_args ----

    #[test]
    fn types_a_positional_string() {
        let a = parse_args(&args(&[""])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "".into(),
                delay_ms: 0
            }
        );
    }

    #[test]
    fn types_a_multichar_snippet() {
        let a = parse_args(&args(&["¯\\_(ツ)_/¯"])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "¯\\_(ツ)_/¯".into(),
                delay_ms: 0
            }
        );
    }

    #[test]
    fn delay_flag_sets_delay() {
        let a = parse_args(&args(&["--delay", "150", ""])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "".into(),
                delay_ms: 150
            }
        );
    }

    #[test]
    fn unicode_flag_decodes_hex_codepoint() {
        let a = parse_args(&args(&["--unicode", "20ac"])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "".into(),
                delay_ms: 0
            }
        );
    }

    #[test]
    fn unicode_short_flag_works() {
        let a = parse_args(&args(&["-u", "2713"])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "".into(),
                delay_ms: 0
            }
        );
    }

    #[test]
    fn unicode_flag_accepts_multiple_codepoints() {
        let a = parse_args(&args(&["-u", "20ac", "-u", "2713"])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "€✓".into(),
                delay_ms: 0
            }
        );
    }

    #[test]
    fn double_dash_makes_following_arg_literal() {
        let a = parse_args(&args(&["--", "--delay"])).unwrap();
        assert_eq!(
            a,
            Action::Type {
                text: "--delay".into(),
                delay_ms: 0
            }
        );
    }

    #[test]
    fn no_args_is_an_error() {
        assert!(parse_args(&[]).is_err());
    }

    #[test]
    fn missing_delay_value_is_an_error() {
        assert!(parse_args(&args(&["--delay"])).is_err());
    }

    #[test]
    fn non_numeric_delay_is_an_error() {
        assert!(parse_args(&args(&["--delay", "abc", ""])).is_err());
    }

    #[test]
    fn unknown_flag_is_an_error() {
        assert!(parse_args(&args(&["--frobnicate", ""])).is_err());
    }

    #[test]
    fn two_positional_args_is_an_error() {
        assert!(parse_args(&args(&["", ""])).is_err());
    }

    #[test]
    fn help_flag_wins() {
        assert_eq!(parse_args(&args(&["--help"])).unwrap(), Action::Help);
        assert_eq!(parse_args(&args(&["-h"])).unwrap(), Action::Help);
    }

    #[test]
    fn version_flag_wins() {
        assert_eq!(parse_args(&args(&["--version"])).unwrap(), Action::Version);
        assert_eq!(parse_args(&args(&["-V"])).unwrap(), Action::Version);
    }

    // ---- decode_codepoint ----

    #[test]
    fn decodes_plain_hex() {
        assert_eq!(decode_codepoint("20ac").unwrap(), '');
    }

    #[test]
    fn decodes_uppercase_and_u_plus_prefix() {
        assert_eq!(decode_codepoint("U+20AC").unwrap(), '');
        assert_eq!(decode_codepoint("u+20ac").unwrap(), '');
    }

    #[test]
    fn decodes_astral_plane_codepoint() {
        assert_eq!(decode_codepoint("1F600").unwrap(), '😀');
    }

    #[test]
    fn rejects_invalid_hex() {
        assert!(decode_codepoint("xyz").is_err());
    }

    #[test]
    fn rejects_surrogate_codepoints() {
        assert!(decode_codepoint("D800").is_err());
    }

    #[test]
    fn rejects_out_of_range_codepoints() {
        assert!(decode_codepoint("110000").is_err());
    }

    // ---- utf16_chunks ----

    #[test]
    fn short_text_is_one_chunk() {
        let chunks = utf16_chunks("abc", 20);
        assert_eq!(chunks, vec!["abc".encode_utf16().collect::<Vec<u16>>()]);
    }

    #[test]
    fn long_text_splits_at_max_units() {
        let text = "a".repeat(25);
        let chunks = utf16_chunks(&text, 20);
        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].len(), 20);
        assert_eq!(chunks[1].len(), 5);
    }

    #[test]
    fn never_splits_a_surrogate_pair() {
        // Each emoji is 2 UTF-16 units; max 3 forces a split decision mid-pair.
        let chunks = utf16_chunks("😀😀😀", 3);
        for chunk in &chunks {
            // A chunk must decode cleanly on its own — no lone surrogates.
            assert!(
                String::from_utf16(chunk).is_ok(),
                "chunk split a surrogate pair"
            );
        }
        let total: Vec<u16> = chunks.concat();
        assert_eq!(total, "😀😀😀".encode_utf16().collect::<Vec<u16>>());
    }

    #[test]
    fn empty_text_yields_no_chunks() {
        assert!(utf16_chunks("", 20).is_empty());
    }
}