hex/src/paste.rs
Dax 0c0faf273f
fix(macos): type dictation into Windows App instead of pasting (#1878)
* fix(macos): type dictation into Windows App instead of pasting (#1048)

* fix(macos): stop paced dictation when another app comes in front (#1048)

* test(macos): keep the paced typing tests within clippy's types (#1048)
2026-11-15 23:43:13 -05:00

1326 lines
47 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

pub(crate) mod return_to_app;
use std::ffi::{c_char, c_void};
use std::fs;
use std::ops::RangeInclusive;
use std::path::Path;
use std::ptr;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use std::time::Instant;
use color_eyre::eyre::{Result, eyre};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_app_kit::{NSPasteboard, NSPasteboardItem, NSPasteboardTypeString, NSPasteboardWriting};
use objc2_foundation::{NSArray, NSData, NSString};
use crate::keyboard;
use crate::suppression::InputActivity;
pub struct Paster {
clipboard: Retained<NSPasteboard>,
activity: InputActivity,
continuation: Option<Continuation>,
clipboard_restore: Arc<Mutex<ClipboardRestore>>,
prepared_clipboard: Option<PreparedClipboard>,
}
#[derive(Clone, Copy)]
pub enum PasteMode {
Continue,
Standalone,
/// Labs › Copy dictation only: the text goes to the clipboard as an
/// ordinary entry and nothing is pasted, typed, or restored.
CopyOnly,
/// Labs › YOLO mode: pastes as `Continue` does, but what may be sent
/// can't be continued. `Return` sends it.
Send,
/// Labs › YOLO mode: presses Return after a `Send` paste; the text is
/// ignored.
Return,
}
struct PreparedClipboard {
change_count: isize,
snapshot: ClipboardSnapshot,
capture_ms: u128,
}
struct Continuation {
revision: u64,
inserted: String,
}
/// How Hex inserts a dictation into an app that can't take a paste.
enum Typing {
/// Type the text as fast as its events post: Chromium 155 and 156 can drop
/// a ⌘V that races their own pasteboard change notification.
Burst,
/// Type one character at a time, paced: Microsoft's Windows App reads a
/// synthetic shortcut as its bare key (#1048), so it gets typed text.
Paced,
}
#[derive(Default)]
struct ClipboardRestore {
generation: u64,
original: Option<ClipboardSnapshot>,
last_change_count: Option<isize>,
}
impl ClipboardRestore {
fn register(
&mut self,
previous: ClipboardSnapshot,
previous_change_count: isize,
inserted_change_count: isize,
) -> u64 {
self.generation = self.generation.wrapping_add(1);
if self.last_change_count != Some(previous_change_count) {
self.original = Some(previous);
}
self.last_change_count = Some(inserted_change_count);
self.generation
}
/// Labs › Keep dictation on clipboard: the paste stays on the clipboard,
/// so no earlier snapshot may come back and any pending restore stands
/// down.
fn keep(&mut self) {
self.generation = self.generation.wrapping_add(1);
self.original = None;
self.last_change_count = None;
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ClipboardSnapshot {
items: Vec<Vec<ClipboardFlavor>>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct ClipboardFlavor {
data_type: String,
data: Vec<u8>,
flags: u32,
}
type PasteboardRef = *const c_void;
type PasteboardItemId = *mut c_void;
type CfTypeRef = *const c_void;
type CfStringRef = *const c_void;
type CfArrayRef = *const c_void;
type CfDataRef = *const c_void;
const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
const BAD_PASTEBOARD_FLAVOR: i32 = -25133;
const DUPLICATE_PASTEBOARD_FLAVOR: i32 = -25134;
const PASTE_SETTLE_DELAY: Duration = Duration::from_millis(100);
// Chromium 155 and 156 on macOS can drop a ⌘V that races its own pasteboard
// change notification, however long Hex waits first (#136, #212). The bug
// arrived with Chromium CL 8217390 and is fixed by CL 8503629 in 157.
const CLIPBOARD_RACE_CHROMIUM: RangeInclusive<u32> = 155..=156;
// Microsoft's Windows App (formerly Microsoft Remote Desktop) reads Hex's
// synthetic ⌘V as a bare "v" (#1048), so Hex types its dictation instead,
// one paced key at a time.
const REMOTE_DESKTOP_CLIENTS: &[&str] = &["com.microsoft.rdc.macos", "com.microsoft.windowsapp"];
const SYSTEM_TRANSLATED_FLAVOR: u32 = 1 << 8;
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn PasteboardCreate(name: CfStringRef, pasteboard: *mut PasteboardRef) -> i32;
fn PasteboardSynchronize(pasteboard: PasteboardRef) -> u32;
fn PasteboardClear(pasteboard: PasteboardRef) -> i32;
fn PasteboardGetItemCount(pasteboard: PasteboardRef, count: *mut usize) -> i32;
fn PasteboardGetItemIdentifier(
pasteboard: PasteboardRef,
index: isize,
item: *mut PasteboardItemId,
) -> i32;
fn PasteboardCopyItemFlavors(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavors: *mut CfArrayRef,
) -> i32;
fn PasteboardGetItemFlavorFlags(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavor: CfStringRef,
flags: *mut u32,
) -> i32;
fn PasteboardCopyItemFlavorData(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavor: CfStringRef,
data: *mut CfDataRef,
) -> i32;
fn PasteboardPutItemFlavor(
pasteboard: PasteboardRef,
item: PasteboardItemId,
flavor: CfStringRef,
data: CfDataRef,
flags: u32,
) -> i32;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFArrayGetCount(array: CfArrayRef) -> isize;
fn CFArrayGetValueAtIndex(array: CfArrayRef, index: isize) -> *const c_void;
fn CFDataCreate(allocator: *const c_void, bytes: *const u8, length: isize) -> CfDataRef;
fn CFDataGetBytePtr(data: CfDataRef) -> *const u8;
fn CFDataGetLength(data: CfDataRef) -> isize;
fn CFStringGetLength(value: CfStringRef) -> isize;
fn CFStringGetMaximumSizeForEncoding(length: isize, encoding: u32) -> isize;
fn CFStringGetCString(
value: CfStringRef,
buffer: *mut c_char,
buffer_size: isize,
encoding: u32,
) -> bool;
fn CFStringCreateWithBytes(
allocator: *const c_void,
bytes: *const u8,
length: isize,
encoding: u32,
is_external_representation: u8,
) -> CfStringRef;
fn CFRelease(value: CfTypeRef);
}
struct PasteboardHandle(PasteboardRef);
impl Drop for PasteboardHandle {
fn drop(&mut self) {
unsafe { CFRelease(self.0) };
}
}
impl Paster {
pub fn new(activity: InputActivity) -> Self {
Self {
clipboard: NSPasteboard::generalPasteboard(),
activity,
continuation: None,
clipboard_restore: Arc::new(Mutex::new(ClipboardRestore::default())),
prepared_clipboard: None,
}
}
pub fn prepare(&mut self) {
let change_count = self.clipboard.changeCount();
if self
.prepared_clipboard
.as_ref()
.is_some_and(|prepared| prepared.change_count == change_count)
{
return;
}
self.prepared_clipboard = None;
let _restore = self
.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner());
let started = Instant::now();
match capture_clipboard(&self.clipboard) {
Ok(snapshot) => {
self.prepared_clipboard = Some(PreparedClipboard {
change_count,
snapshot,
capture_ms: started.elapsed().as_millis(),
});
}
Err(error) => tracing::debug!(%error, "eager clipboard capture failed"),
}
}
pub fn paste(&mut self, text: &str, mode: PasteMode) -> Result<()> {
if matches!(mode, PasteMode::CopyOnly) {
return self.copy_only(text);
}
if matches!(mode, PasteMode::Send) {
self.paste(text, PasteMode::Continue)?;
self.continuation = None;
return Ok(());
}
if matches!(mode, PasteMode::Return) {
return keyboard::post_return();
}
let revision = self.activity.revision();
let continuation = self.continuation.as_ref().filter(|continuation| {
!matches!(mode, PasteMode::Standalone) && continuation.revision == revision
});
let text = match continuation {
Some(continuation) => join(&continuation.inserted, text),
// Read as the paste commits, so the toggle applies at once.
None if crate::labs::smart_spacing() => with_smart_spacing(text),
None => text.to_string(),
};
match typing_for_frontmost() {
Some(typing) => self.type_into_frontmost(&text, mode, typing)?,
None => self.paste_through_clipboard(&text, mode)?,
}
self.continuation = (!matches!(mode, PasteMode::Standalone)).then_some(Continuation {
revision,
inserted: text,
});
Ok(())
}
/// Inserts `text` as synthesized key events instead of a clipboard paste,
/// for the apps [`typing_for_frontmost`] names. Nothing is captured for a
/// restore; Labs › Keep dictation on clipboard still leaves the text on
/// the clipboard after typing.
fn type_into_frontmost(&mut self, text: &str, mode: PasteMode, typing: Typing) -> Result<()> {
if matches!(mode, PasteMode::Standalone) {
self.continuation = None;
}
match typing {
Typing::Burst => {
tracing::debug!("typing instead of pasting into Chromium 155 or 156");
keyboard::type_text(text)?;
}
Typing::Paced => {
tracing::debug!("typing instead of pasting into Windows App");
// Typing a transcript takes seconds, so the app in front is
// watched at each character: keys the user meant for another
// app never land there, and stopping keeps the text for Paste
// last dictation instead of pasting it a second time.
keyboard::type_text_paced(text, || {
let in_front = remote_desktop_client_in_front();
if !in_front {
tracing::warn!("stopped typing into Windows App: another app is in front");
}
in_front
})?;
}
}
if crate::labs::keep_on_clipboard() {
self.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner())
.keep();
if let Err(error) = write_clipboard_text(&self.clipboard, text, false) {
tracing::warn!(%error, "could not leave the dictation on the clipboard");
}
}
Ok(())
}
/// Leaves `text` on the clipboard for the user to paste: no ⌘V, no typed
/// text, and no restore. A pending restore stands down and no earlier
/// snapshot comes back, and the next paste starts a new continuation.
fn copy_only(&mut self, text: &str) -> Result<()> {
self.continuation = None;
self.prepared_clipboard = None;
self.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner())
.keep();
write_clipboard_text(&self.clipboard, text, false)
}
fn paste_through_clipboard(&mut self, text: &str, mode: PasteMode) -> Result<()> {
let generation = {
let mut restore = self
.clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner());
let previous_change_count = self.clipboard.changeCount();
let prepared = self.prepared_clipboard.take();
let previous = if let Some(prepared) = prepared
&& prepared.change_count == previous_change_count
{
tracing::debug!(
clipboard_capture_ms = prepared.capture_ms,
"used eagerly captured clipboard"
);
prepared.snapshot
} else {
let started = Instant::now();
let snapshot = capture_clipboard(&self.clipboard)?;
tracing::debug!(
clipboard_capture_ms = started.elapsed().as_millis(),
"captured clipboard at paste time"
);
snapshot
};
if self.clipboard.changeCount() != previous_change_count {
return Err(eyre!("clipboard changed while Hex was preserving it"));
}
if matches!(mode, PasteMode::Standalone) {
self.continuation = None;
}
// Read as the paste commits, so the toggle applies at once.
let keep = crate::labs::keep_on_clipboard();
if let Err(error) = write_clipboard_text(&self.clipboard, text, !keep) {
if let Err(restore_error) = restore_clipboard(&self.clipboard, &previous) {
tracing::error!(%restore_error, "could not recover the clipboard after a failed write");
}
return Err(error);
}
if keep {
restore.keep();
None
} else {
let inserted_change_count = self.clipboard.changeCount();
Some(restore.register(previous, previous_change_count, inserted_change_count))
}
};
let clipboard_restore = self.clipboard_restore.clone();
complete_paste(
|| keyboard::post_command('v'),
move || {
let Some(generation) = generation else {
return;
};
thread::spawn(move || {
thread::sleep(Duration::from_millis(500));
let mut restore = clipboard_restore
.lock()
.unwrap_or_else(|error| error.into_inner());
if restore.generation != generation {
return;
}
let clipboard = NSPasteboard::generalPasteboard();
if restore.last_change_count != Some(clipboard.changeCount()) {
restore.original = None;
restore.last_change_count = None;
return;
}
let Some(previous) = restore.original.take() else {
return;
};
let result = restore_clipboard(&clipboard, &previous);
restore.last_change_count = None;
if let Err(error) = result {
tracing::warn!(%error, "could not restore clipboard after paste");
}
});
},
thread::sleep,
)
}
}
/// How this paste inserts the text, or `None` for a clipboard paste. The
/// bundle identifier decides first, so a remote desktop client never pays for
/// the Chromium check; every other app keeps it.
fn typing_for_frontmost() -> Option<Typing> {
if remote_desktop_client_in_front() {
return Some(Typing::Paced);
}
let bundle = crate::dictation::context::frontmost_bundle_path()?;
has_clipboard_race(&bundle).then_some(Typing::Burst)
}
/// Whether the app in front is a remote desktop client that gets typed text.
fn remote_desktop_client_in_front() -> bool {
crate::dictation::context::frontmost_bundle_id()
.as_deref()
.is_some_and(is_remote_desktop_client)
}
fn is_remote_desktop_client(bundle_id: &str) -> bool {
REMOTE_DESKTOP_CLIENTS
.iter()
.any(|client| client.eq_ignore_ascii_case(bundle_id))
}
/// Whether the app at `bundle` embeds a Chromium 155 or 156 framework. Every
/// version found counts, so a browser that has staged an update before
/// relaunching is covered whichever version is running; typing works in any
/// version, so the wrong guess there costs nothing.
fn has_clipboard_race(bundle: &Path) -> bool {
chromium_major_versions(bundle).any(|major| CLIPBOARD_RACE_CHROMIUM.contains(&major))
}
/// Chromium browsers (Chrome, Helium, Brave, Edge, Chromium itself and
/// most forks) ship `Contents/Frameworks/<Name> Framework.framework/Versions/
/// <major>.<minor>.<build>.<patch>/`. Electron's `Versions/A` has no version.
fn chromium_major_versions(bundle: &Path) -> impl Iterator<Item = u32> {
fs::read_dir(bundle.join("Contents/Frameworks"))
.into_iter()
.flatten()
.flatten()
.filter(|framework| {
framework
.file_name()
.to_str()
.is_some_and(|name| name.ends_with("Framework.framework"))
})
.flat_map(|framework| fs::read_dir(framework.path().join("Versions")).into_iter())
.flatten()
.flatten()
.filter_map(|version| chromium_major_version(version.file_name().to_str()?))
}
fn chromium_major_version(version: &str) -> Option<u32> {
let components = version
.split('.')
.map(str::parse::<u32>)
.collect::<Result<Vec<_>, _>>()
.ok()?;
match components[..] {
[major, _, _, _] => Some(major),
_ => None,
}
}
fn complete_paste(
post_paste: impl FnOnce() -> Result<()>,
schedule_restore: impl FnOnce(),
mut wait: impl FnMut(Duration),
) -> Result<()> {
let posted = post_paste();
schedule_restore();
posted?;
// Keep the clipboard stable for the target's 100 ms consumption window.
// This is not an acknowledgment; longer OS or application stalls can still lose a paste.
wait(PASTE_SETTLE_DELAY);
Ok(())
}
fn capture_clipboard(clipboard: &NSPasteboard) -> Result<ClipboardSnapshot> {
let capture_started = Instant::now();
let pasteboard = create_pasteboard(&clipboard.name())?;
unsafe { PasteboardSynchronize(pasteboard.0) };
let mut item_count = 0;
check_status(
unsafe { PasteboardGetItemCount(pasteboard.0, &mut item_count) },
"count clipboard items",
)?;
let mut items = Vec::with_capacity(item_count);
for index in 1..=item_count {
let mut item = ptr::null_mut();
check_status(
unsafe { PasteboardGetItemIdentifier(pasteboard.0, index as isize, &mut item) },
"identify a clipboard item",
)?;
let mut flavors = ptr::null();
check_status(
unsafe { PasteboardCopyItemFlavors(pasteboard.0, item, &mut flavors) },
"list clipboard formats",
)?;
if flavors.is_null() {
return Err(eyre!("could not list clipboard formats"));
}
let flavor_count = unsafe { CFArrayGetCount(flavors) };
let result = (0..flavor_count)
.map(|flavor_index| {
let flavor = unsafe { CFArrayGetValueAtIndex(flavors, flavor_index) };
if flavor.is_null() {
return Err(eyre!("clipboard format was unavailable"));
}
let mut flags = 0;
check_status(
unsafe { PasteboardGetItemFlavorFlags(pasteboard.0, item, flavor, &mut flags) },
"inspect clipboard format",
)?;
Ok((flavor, flags))
})
.collect::<Result<Vec<_>>>()
.and_then(|flavor_entries| {
let has_authoritative_flavor = flavor_entries
.iter()
.any(|&(_, flags)| flags & SYSTEM_TRANSLATED_FLAVOR == 0);
flavor_entries
.into_iter()
.map(|(flavor, flags)| {
let data_type = cf_string(flavor)?;
if !should_preserve_flavor(flags, has_authoritative_flavor) {
tracing::debug!(%data_type, "skipping synthesized clipboard format");
return Ok(None);
}
let mut data = ptr::null();
let flavor_started = Instant::now();
let status = unsafe {
PasteboardCopyItemFlavorData(pasteboard.0, item, flavor, &mut data)
};
let flavor_ms = flavor_started.elapsed().as_millis();
if flavor_ms >= 100 {
tracing::warn!(
%data_type,
flavor_ms,
"clipboard format was slow to materialize"
);
}
if status == BAD_PASTEBOARD_FLAVOR {
tracing::debug!(%data_type, "skipping unavailable clipboard format");
return Ok(None);
}
check_status(status, "preserve clipboard format")?;
if data.is_null() {
return Err(eyre!("clipboard format data was unavailable"));
}
let bytes = cf_data(data);
unsafe { CFRelease(data) };
Ok(Some(ClipboardFlavor {
data_type,
data: bytes?,
flags: flags & 0x0f,
}))
})
.collect::<Result<Vec<_>>>()
});
unsafe { CFRelease(flavors) };
items.push(result?.into_iter().flatten().collect());
}
let capture_ms = capture_started.elapsed().as_millis();
if capture_ms >= 100 {
tracing::warn!(capture_ms, item_count, "clipboard snapshot was slow");
}
Ok(ClipboardSnapshot { items })
}
fn should_preserve_flavor(flags: u32, has_authoritative_flavor: bool) -> bool {
!has_authoritative_flavor || flags & SYSTEM_TRANSLATED_FLAVOR == 0
}
/// nspasteboard.org markers asking clipboard managers not to record a write.
/// The transcript is only on the clipboard for the duration of the paste,
/// unless Labs › Keep dictation on clipboard leaves it there (`transient`
/// false), when it is an ordinary clipboard entry.
const CLIPBOARD_MANAGER_MARKERS: [&str; 2] = [
"org.nspasteboard.TransientType",
"org.nspasteboard.AutoGeneratedType",
];
fn write_clipboard_text(clipboard: &NSPasteboard, text: &str, transient: bool) -> Result<()> {
// One item carrying the text and its markers, published by a single write,
// so a polling clipboard manager never observes the text without them.
let item = NSPasteboardItem::new();
let marker_data = NSData::new();
let markers_written = !transient
|| CLIPBOARD_MANAGER_MARKERS
.iter()
.all(|marker| item.setData_forType(&marker_data, &NSString::from_str(marker)));
let text_written =
item.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString });
if !(markers_written && text_written) {
return Err(eyre!("could not prepare the transcript for the clipboard"));
}
clipboard.clearContents();
write_items(clipboard, &[item])
}
fn restore_clipboard(clipboard: &NSPasteboard, snapshot: &ClipboardSnapshot) -> Result<()> {
let pasteboard = create_pasteboard(&clipboard.name())?;
unsafe { PasteboardSynchronize(pasteboard.0) };
check_status(
unsafe { PasteboardClear(pasteboard.0) },
"clear the clipboard",
)?;
for (item_index, item) in snapshot.items.iter().enumerate() {
let item_id = (item_index + 1) as PasteboardItemId;
for flavor in item {
let data_type = cf_string_create(&flavor.data_type)?;
let data = unsafe {
CFDataCreate(
ptr::null(),
flavor.data.as_ptr(),
flavor.data.len() as isize,
)
};
if data.is_null() {
unsafe { CFRelease(data_type) };
return Err(eyre!("could not encode a clipboard format"));
}
let status = unsafe {
PasteboardPutItemFlavor(pasteboard.0, item_id, data_type, data, flavor.flags)
};
unsafe {
CFRelease(data);
CFRelease(data_type);
}
if status == DUPLICATE_PASTEBOARD_FLAVOR {
tracing::debug!(data_type = %flavor.data_type, "skipping synthesized clipboard format");
continue;
}
check_status(status, "restore clipboard format")?;
}
}
Ok(())
}
fn write_items(clipboard: &NSPasteboard, items: &[Retained<NSPasteboardItem>]) -> Result<()> {
let objects = items
.iter()
.map(|item| ProtocolObject::from_ref(&**item))
.collect::<Vec<&ProtocolObject<dyn NSPasteboardWriting>>>();
let objects = NSArray::from_slice(&objects);
clipboard
.writeObjects(&objects)
.then_some(())
.ok_or_else(|| eyre!("could not write the clipboard"))
}
fn create_pasteboard(name: &NSString) -> Result<PasteboardHandle> {
let mut pasteboard = ptr::null();
check_status(
unsafe { PasteboardCreate((name as *const NSString).cast(), &mut pasteboard) },
"open the clipboard",
)?;
(!pasteboard.is_null())
.then_some(PasteboardHandle(pasteboard))
.ok_or_else(|| eyre!("could not open the clipboard"))
}
fn check_status(status: i32, action: &str) -> Result<()> {
(status == 0)
.then_some(())
.ok_or_else(|| eyre!("could not {action} (status {status})"))
}
fn cf_string_create(value: &str) -> Result<CfStringRef> {
let value = unsafe {
CFStringCreateWithBytes(
ptr::null(),
value.as_ptr(),
value.len() as isize,
CF_STRING_ENCODING_UTF8,
0,
)
};
(!value.is_null())
.then_some(value)
.ok_or_else(|| eyre!("could not encode a clipboard format name"))
}
fn cf_string(value: CfStringRef) -> Result<String> {
let length = unsafe { CFStringGetLength(value) };
let capacity = unsafe { CFStringGetMaximumSizeForEncoding(length, CF_STRING_ENCODING_UTF8) }
.saturating_add(1);
let mut bytes = vec![0; capacity as usize];
if !unsafe {
CFStringGetCString(
value,
bytes.as_mut_ptr().cast(),
capacity,
CF_STRING_ENCODING_UTF8,
)
} {
return Err(eyre!("could not decode a clipboard format name"));
}
let length = bytes
.iter()
.position(|byte| *byte == 0)
.unwrap_or(bytes.len());
bytes.truncate(length);
String::from_utf8(bytes).map_err(Into::into)
}
fn cf_data(value: CfDataRef) -> Result<Vec<u8>> {
let length = unsafe { CFDataGetLength(value) };
if length < 0 {
return Err(eyre!("clipboard format had an invalid length"));
}
if length == 0 {
return Ok(Vec::new());
}
let bytes = unsafe { CFDataGetBytePtr(value) };
if bytes.is_null() {
return Err(eyre!("clipboard format data was unavailable"));
}
Ok(unsafe { std::slice::from_raw_parts(bytes, length as usize) }.to_vec())
}
fn join(previous: &str, next: &str) -> String {
let sentence_start = ends_sentence(previous);
let mut next = set_initial_case(next, sentence_start);
let needs_space = previous
.chars()
.next_back()
.is_some_and(|character| !character.is_whitespace() && !is_opening(character))
&& next
.chars()
.next()
.is_some_and(|character| !character.is_whitespace() && !is_closing(character));
if needs_space {
next.insert(0, ' ');
}
next
}
/// Labs › Smart spacing: one leading space when the character before the
/// focused app's cursor asks for it. A selection, or a cursor the app
/// doesn't expose through Accessibility, leaves the text unchanged.
fn with_smart_spacing(text: &str) -> String {
let previous = crate::dictation::context::frontmost_pid()
.and_then(crate::accessibility::char_before_caret);
match previous {
Some(previous) if needs_leading_space(previous, text) => format!(" {text}"),
_ => text.to_string(),
}
}
/// Whether `text` pasted right after `previous` needs a space between:
/// after a letter, digit, sentence punctuation, or closing bracket or
/// quote, never after whitespace, opening punctuation, or symbols such as
/// `@` and `$`, and never before text that starts with whitespace or
/// closing punctuation.
fn needs_leading_space(previous: char, text: &str) -> bool {
let Some(first) = text.chars().next() else {
return false;
};
if first.is_whitespace() || is_closing(first) {
return false;
}
previous.is_alphanumeric()
|| matches!(
previous,
'.' | ',' | ';' | ':' | '!' | '?' | '…' | ')' | ']' | '}' | '”' | '’' | '»'
)
}
fn ends_sentence(text: &str) -> bool {
text.trim_end()
.trim_end_matches(['\'', '"', ')', ']', '}'])
.ends_with(['.', '?', '!'])
}
fn is_opening(character: char) -> bool {
matches!(character, '(' | '[' | '{')
}
fn is_closing(character: char) -> bool {
matches!(
character,
',' | '.' | '?' | '!' | ';' | ':' | ')' | ']' | '}'
)
}
fn set_initial_case(text: &str, uppercase: bool) -> String {
let Some((index, character)) = text
.char_indices()
.find(|(_, character)| character.is_alphabetic())
else {
return text.to_string();
};
if uppercase && character.is_lowercase() {
return replace_character(text, index, character.to_uppercase());
}
if !uppercase && character.is_uppercase() && sentence_initial_word(text, index) {
return replace_character(text, index, character.to_lowercase());
}
text.to_string()
}
fn sentence_initial_word(text: &str, start: usize) -> bool {
let word = text[start..]
.split(|character: char| !character.is_alphabetic() && character != '\'')
.next()
.unwrap_or_default();
matches!(
word.to_ascii_lowercase().as_str(),
"a" | "an"
| "and"
| "as"
| "because"
| "but"
| "for"
| "if"
| "nor"
| "or"
| "so"
| "the"
| "then"
| "though"
| "to"
| "when"
| "while"
| "yet"
)
}
fn replace_character(text: &str, index: usize, replacement: impl Iterator<Item = char>) -> String {
let character_length = text[index..].chars().next().unwrap().len_utf8();
let mut output = String::with_capacity(text.len());
output.push_str(&text[..index]);
output.extend(replacement);
output.push_str(&text[index + character_length..]);
output
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use super::*;
static PASTEBOARD_TEST: Mutex<()> = Mutex::new(());
#[test]
fn sequential_pastes_settle_before_overwrite() {
let clipboard = Cell::new("");
let pending = Cell::new(false);
let consumed = RefCell::new(Vec::new());
let steps = RefCell::new(Vec::new());
let paste = |text| {
clipboard.set(text);
complete_paste(
|| {
pending.set(true);
steps.borrow_mut().push("post");
Ok(())
},
|| steps.borrow_mut().push("restore"),
|delay| {
assert_eq!(delay, PASTE_SETTLE_DELAY);
assert!(pending.replace(false));
consumed.borrow_mut().push(clipboard.get());
steps.borrow_mut().push("settle");
},
)
};
paste("first").unwrap();
assert_eq!(*consumed.borrow(), ["first"]);
paste("second").unwrap();
assert_eq!(*consumed.borrow(), ["first", "second"]);
assert_eq!(
steps.into_inner(),
["post", "restore", "settle", "post", "restore", "settle"]
);
}
#[test]
fn restoration_is_scheduled_after_a_stalled_post_completes() {
let elapsed = Cell::new(Duration::ZERO);
let restore_scheduled_at = Cell::new(None);
complete_paste(
|| {
elapsed.set(Duration::from_secs(1));
assert_eq!(restore_scheduled_at.get(), None);
Ok(())
},
|| restore_scheduled_at.set(Some(elapsed.get())),
|delay| elapsed.set(elapsed.get() + delay),
)
.unwrap();
assert_eq!(restore_scheduled_at.get(), Some(Duration::from_secs(1)));
assert_eq!(elapsed.get(), Duration::from_secs(1) + PASTE_SETTLE_DELAY);
}
#[test]
fn failed_paste_still_schedules_restore_without_settling() {
let steps = RefCell::new(Vec::new());
let result = complete_paste(
|| {
steps.borrow_mut().push("post");
Err(eyre!("post failed"))
},
|| steps.borrow_mut().push("restore"),
|_| steps.borrow_mut().push("settle"),
);
assert_eq!(result.unwrap_err().to_string(), "post failed");
assert_eq!(steps.into_inner(), ["post", "restore"]);
}
/// Microsoft's Windows App and the Remote Desktop client it replaced are
/// the apps whose dictation is typed instead of pasted (#1048).
#[test]
fn recognises_the_remote_desktop_clients_by_bundle_identifier() {
assert!(is_remote_desktop_client("com.microsoft.rdc.macos"));
assert!(is_remote_desktop_client("com.microsoft.windowsapp"));
assert!(is_remote_desktop_client("COM.MICROSOFT.WINDOWSAPP"));
for other in [
"com.apple.Safari",
"com.microsoft.Word",
"com.microsoft.rdc.macos.beta",
] {
assert!(!is_remote_desktop_client(other), "{other}");
}
}
#[test]
fn detects_the_chromium_major_version_from_the_bundle_framework() {
let root = std::env::temp_dir().join(format!("hex-chromium-{}", std::process::id()));
let bundle = |name: &str, frameworks: &[(&str, &[&str])]| {
let bundle = root.join(name);
for (framework, versions) in frameworks {
for version in *versions {
fs::create_dir_all(
bundle
.join("Contents/Frameworks")
.join(framework)
.join("Versions")
.join(version),
)
.unwrap();
}
}
fs::create_dir_all(bundle.join("Contents")).unwrap();
bundle
};
let chrome = bundle(
"Google Chrome.app",
&[("Google Chrome Framework.framework", &["155.0.8059.40"])],
);
let helium = bundle(
"Helium.app",
&[("Helium Framework.framework", &["156.0.8078.48"])],
);
let staged = bundle(
"Brave Browser.app",
&[(
"Brave Browser Framework.framework",
&["156.1.88.10", "157.1.89.2"],
)],
);
let fixed = bundle(
"Microsoft Edge.app",
&[("Microsoft Edge Framework.framework", &["157.0.8103.15"])],
);
let older = bundle(
"Chromium.app",
&[("Chromium Framework.framework", &["154.0.7999.1"])],
);
let electron = bundle(
"Slack.app",
&[
("Electron Framework.framework", &["A", "Current"]),
("Squirrel.framework", &["155.0.0.0"]),
],
);
let safari = bundle("Safari.app", &[]);
assert_eq!(chromium_major_versions(&chrome).collect::<Vec<_>>(), [155]);
let mut staged_versions = chromium_major_versions(&staged).collect::<Vec<_>>();
staged_versions.sort_unstable();
assert_eq!(staged_versions, [156, 157]);
for affected in [&chrome, &helium, &staged] {
assert!(has_clipboard_race(affected), "{}", affected.display());
}
for unaffected in [
&fixed,
&older,
&electron,
&safari,
&root.join("Missing.app"),
] {
assert!(!has_clipboard_race(unaffected), "{}", unaffected.display());
}
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn chromium_versions_need_four_numeric_components() {
assert_eq!(chromium_major_version("155.0.8059.84"), Some(155));
assert_eq!(chromium_major_version("156.1.88.10"), Some(156));
for version in [
"A",
"Current",
"155",
"155.0.8059",
"155.0.8059.84.1",
"155.0.x.1",
] {
assert_eq!(chromium_major_version(version), None, "{version}");
}
}
#[test]
fn joins_contiguous_dictation_with_sentence_aware_spacing() {
assert_eq!(
join("Because if I don't do that,", "And if you see it."),
" and if you see it."
);
assert_eq!(
join("And if you see it.", "well, that works."),
" Well, that works."
);
assert_eq!(join("Already spaced. ", "Next sentence."), "Next sentence.");
assert_eq!(join("Hello", ", world."), ", world.");
}
#[test]
fn smart_spacing_adds_a_space_only_where_one_belongs() {
for previous in ['a', 'Z', '7', '.', '?', ')', '”'] {
assert!(needs_leading_space(previous, "in progress"), "{previous:?}");
}
for previous in ['@', '$', '#', '/', '-', '(', '“', ' ', '\n', '\t'] {
assert!(
!needs_leading_space(previous, "in progress"),
"{previous:?}"
);
}
assert!(!needs_leading_space('a', ""));
assert!(!needs_leading_space('a', " already spaced"));
assert!(!needs_leading_space('a', ", then more"));
}
#[test]
fn preserves_likely_proper_nouns_mid_sentence() {
assert_eq!(join("Open", "GitHub next."), " GitHub next.");
assert_eq!(join("Message", "Slack now."), " Slack now.");
}
#[test]
fn rapid_pastes_keep_the_original_clipboard_for_the_latest_restore() {
let mut restore = ClipboardRestore::default();
let original = ClipboardSnapshot {
items: vec![vec![ClipboardFlavor {
data_type: "public.png".into(),
data: vec![1, 2, 3],
flags: 0,
}]],
};
let first_insert = ClipboardSnapshot {
items: vec![vec![ClipboardFlavor {
data_type: "public.utf8-plain-text".into(),
data: b"first".to_vec(),
flags: 0,
}]],
};
let first = restore.register(original.clone(), 10, 12);
let second = restore.register(first_insert, 12, 14);
assert_ne!(first, second);
assert_eq!(restore.original, Some(original));
assert_eq!(restore.last_change_count, Some(14));
}
#[test]
fn a_kept_paste_leaves_nothing_to_restore() {
let mut restore = ClipboardRestore::default();
let original = ClipboardSnapshot {
items: vec![vec![ClipboardFlavor {
data_type: "public.utf8-plain-text".into(),
data: b"before".to_vec(),
flags: 0,
}]],
};
let pending = restore.register(original.clone(), 10, 12);
restore.keep();
assert_ne!(
restore.generation, pending,
"the pending restore stands down"
);
assert_eq!(restore.original, None);
assert_eq!(restore.last_change_count, None);
// A later restoring paste snapshots what is there now, not `original`.
let now = ClipboardSnapshot {
items: vec![vec![ClipboardFlavor {
data_type: "public.utf8-plain-text".into(),
data: b"kept dictation".to_vec(),
flags: 0,
}]],
};
restore.register(now.clone(), 12, 14);
assert_eq!(restore.original, Some(now));
}
#[test]
fn a_kept_transcript_is_an_ordinary_clipboard_entry() {
let _test = PASTEBOARD_TEST.lock().unwrap();
let clipboard = NSPasteboard::pasteboardWithUniqueName();
write_clipboard_text(&clipboard, "kept text", false).unwrap();
let snapshot = capture_clipboard(&clipboard).unwrap();
let types = snapshot.items[0]
.iter()
.map(|flavor| flavor.data_type.as_str())
.collect::<Vec<_>>();
for marker in CLIPBOARD_MANAGER_MARKERS {
assert!(!types.contains(&marker), "{marker} in {types:?}");
}
assert_eq!(
clipboard
.stringForType(unsafe { NSPasteboardTypeString })
.unwrap()
.to_string(),
"kept text"
);
}
#[test]
fn a_copy_only_dictation_is_left_on_the_clipboard_with_nothing_to_restore() {
let _test = PASTEBOARD_TEST.lock().unwrap();
let clipboard = NSPasteboard::pasteboardWithUniqueName();
write_clipboard_text(&clipboard, "before", false).unwrap();
let mut paster = Paster {
clipboard: clipboard.clone(),
activity: InputActivity::default(),
continuation: Some(Continuation {
revision: 0,
inserted: "earlier".into(),
}),
clipboard_restore: Arc::new(Mutex::new(ClipboardRestore::default())),
prepared_clipboard: None,
};
let pending = paster.clipboard_restore.lock().unwrap().register(
capture_clipboard(&clipboard).unwrap(),
1,
2,
);
// Returns without posting ⌘V or typing: only the clipboard changes.
paster.paste("dictated text", PasteMode::CopyOnly).unwrap();
assert_eq!(
clipboard
.stringForType(unsafe { NSPasteboardTypeString })
.unwrap()
.to_string(),
"dictated text",
"the transcript is not joined to an earlier paste"
);
let snapshot = capture_clipboard(&clipboard).unwrap();
let types = snapshot.items[0]
.iter()
.map(|flavor| flavor.data_type.as_str())
.collect::<Vec<_>>();
for marker in CLIPBOARD_MANAGER_MARKERS {
assert!(!types.contains(&marker), "{marker} in {types:?}");
}
let restore = paster.clipboard_restore.lock().unwrap();
assert_ne!(
restore.generation, pending,
"the pending restore stands down"
);
assert_eq!(restore.original, None);
assert_eq!(restore.last_change_count, None);
drop(restore);
assert!(paster.continuation.is_none());
}
#[test]
fn clipboard_snapshot_preserves_multiple_items_and_formats() {
let _test = PASTEBOARD_TEST.lock().unwrap();
let clipboard = NSPasteboard::pasteboardWithUniqueName();
let expected = [
vec![
("com.hex.fixture.text", b"text".to_vec()),
("com.hex.fixture.rich", b"rich text".to_vec()),
],
vec![("com.hex.fixture.image", vec![1, 2, 3, 4])],
];
let items = expected
.iter()
.map(|types| {
let item = NSPasteboardItem::new();
for (data_type, bytes) in types {
assert!(item.setData_forType(
&NSData::with_bytes(bytes),
&NSString::from_str(data_type)
));
}
item
})
.collect::<Vec<_>>();
write_items(&clipboard, &items).unwrap();
let snapshot = capture_clipboard(&clipboard).unwrap();
clipboard.clearContents();
restore_clipboard(&clipboard, &snapshot).unwrap();
assert_eq!(capture_clipboard(&clipboard).unwrap(), snapshot);
}
#[test]
fn eager_clipboard_capture_refreshes_a_stale_snapshot() {
let _test = PASTEBOARD_TEST.lock().unwrap();
let clipboard = NSPasteboard::pasteboardWithUniqueName();
let item = NSPasteboardItem::new();
assert!(item.setData_forType(
&NSData::with_bytes(b"first"),
&NSString::from_str("com.hex.fixture.first")
));
clipboard.clearContents();
write_items(&clipboard, &[item]).unwrap();
let mut paster = Paster {
clipboard: clipboard.clone(),
activity: InputActivity::default(),
continuation: None,
clipboard_restore: Arc::new(Mutex::new(ClipboardRestore::default())),
prepared_clipboard: None,
};
paster.prepare();
let first_change_count = paster.prepared_clipboard.as_ref().unwrap().change_count;
let item = NSPasteboardItem::new();
assert!(item.setData_forType(
&NSData::with_bytes(b"second"),
&NSString::from_str("com.hex.fixture.second")
));
clipboard.clearContents();
write_items(&clipboard, &[item]).unwrap();
paster.prepare();
let prepared = paster.prepared_clipboard.as_ref().unwrap();
assert_ne!(prepared.change_count, first_change_count);
assert_eq!(prepared.snapshot, capture_clipboard(&clipboard).unwrap());
}
#[test]
fn transcript_write_is_marked_for_clipboard_managers() {
let _test = PASTEBOARD_TEST.lock().unwrap();
let clipboard = NSPasteboard::pasteboardWithUniqueName();
write_clipboard_text(&clipboard, "dictated text", true).unwrap();
let snapshot = capture_clipboard(&clipboard).unwrap();
assert_eq!(snapshot.items.len(), 1);
let types = snapshot.items[0]
.iter()
.map(|flavor| flavor.data_type.as_str())
.collect::<Vec<_>>();
for marker in CLIPBOARD_MANAGER_MARKERS {
assert!(types.contains(&marker), "{marker} missing from {types:?}");
}
assert_eq!(
clipboard
.stringForType(unsafe { NSPasteboardTypeString })
.unwrap()
.to_string(),
"dictated text"
);
}
#[test]
fn skips_regenerable_system_translations() {
assert!(!should_preserve_flavor(SYSTEM_TRANSLATED_FLAVOR, true));
assert!(should_preserve_flavor(0, true));
assert!(should_preserve_flavor(SYSTEM_TRANSLATED_FLAVOR, false));
}
#[test]
fn image_snapshot_keeps_its_authoritative_format() {
let _test = PASTEBOARD_TEST.lock().unwrap();
let clipboard = NSPasteboard::pasteboardWithUniqueName();
let item = NSPasteboardItem::new();
assert!(item.setData_forType(
&NSData::with_bytes(include_bytes!("../app/AppIcon.icon/Assets/Image.png")),
&NSString::from_str("public.png")
));
clipboard.clearContents();
write_items(&clipboard, &[item]).unwrap();
let snapshot = capture_clipboard(&clipboard).unwrap();
assert_eq!(
snapshot
.items
.iter()
.flatten()
.map(|flavor| flavor.data_type.as_str())
.collect::<Vec<_>>(),
vec!["public.png"]
);
clipboard.clearContents();
restore_clipboard(&clipboard, &snapshot).unwrap();
assert_eq!(capture_clipboard(&clipboard).unwrap(), snapshot);
}
}