From b460af26256057b4e0dba4d46f8e3ac54d3de57f Mon Sep 17 00:00:00 2001 From: pentamassiv Date: Mon, 5 Feb 2024 19:45:59 -0500 Subject: [PATCH] macOS: Added workaround for entering text that starts with newline characters Fixes https://github.com/enigo-rs/enigo/issues/260 --- CHANGES.md | 1 + src/macos/macos_impl.rs | 16 +++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d592b279..532eee39 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -33,6 +33,7 @@ - linux: You can enter `Key::ScrollLock` now - win: No more sleeps! Simulating input is done in 1 ms instead of 40+ ms. This is most obvious when entering long strings - macOS: Added keys to control media, brightness, contrast, illumination and more +- macOS: Fix entering text that starts with newline characters # 0.1.3 diff --git a/src/macos/macos_impl.rs b/src/macos/macos_impl.rs index 71e28ff6..38c9f1af 100644 --- a/src/macos/macos_impl.rs +++ b/src/macos/macos_impl.rs @@ -309,9 +309,7 @@ impl Keyboard for Enigo { let mut indices = s.char_indices().map(|(idx, _)| idx).peekable(); std::iter::from_fn(move || { - let Some(start_idx) = indices.next() else { - return None; - }; + let start_idx = indices.next()?; for _ in 0..len - 1 { indices.next(); } @@ -324,15 +322,23 @@ impl Keyboard for Enigo { } debug!("\x1b[93mfast_text(text: {text})\x1b[0m"); - // NOTE(dustin): This is a fix for issue https://github.com/enigo-rs/enigo/issues/68 + // WORKAROUND: This is a fix for issue https://github.com/enigo-rs/enigo/issues/68 // The CGEventKeyboardSetUnicodeString function (used inside of // event.set_string(chunk)) truncates strings down to 20 characters - for chunk in chunks(text, 20) { + for mut chunk in chunks(text, 20) { let Ok(event) = CGEvent::new_keyboard_event(self.event_source.clone(), 0, true) else { return Err(InputError::Simulate( "failed creating event to enter the text", )); }; + // WORKAROUND: This is a fix for issue https://github.com/enigo-rs/enigo/issues/260 + // This is needed to get rid of all leading newline characters. + // event.set_string(chunk)) silently fails if the chunk starts with a newline + // character + while chunk.starts_with('\n') { + self.key(Key::Return, Direction::Click)?; + chunk = &chunk[1..]; + } event.set_string(chunk); event.post(CGEventTapLocation::HID);