Files
hex/src/paste.rs
T

1116 lines
38 KiB
Rust

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,
}
struct PreparedClipboard {
change_count: isize,
snapshot: ClipboardSnapshot,
capture_ms: u128,
}
struct Continuation {
revision: u64,
inserted: String,
}
#[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
}
}
#[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;
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"),
}
}
/// Commit only after clipboard preparation, immediately before the first write.
/// A rejected commit leaves both the clipboard and continuation unchanged.
pub fn paste(
&mut self,
text: &str,
mode: PasteMode,
commit: impl FnOnce() -> bool,
) -> Result<()> {
self.paste_text(text, mode, commit)
}
fn paste_text(
&mut self,
text: &str,
mode: PasteMode,
commit: impl FnOnce() -> bool,
) -> Result<()> {
let revision = self.activity.revision();
let text = self
.continuation
.as_ref()
.filter(|continuation| {
!matches!(mode, PasteMode::Standalone) && continuation.revision == revision
})
.map_or_else(
|| text.to_string(),
|continuation| join(&continuation.inserted, text),
);
if crate::context::frontmost_bundle_path().is_some_and(|bundle| has_clipboard_race(&bundle))
{
commit_prepared_paste(
|| Ok(()),
commit,
|()| {
if matches!(mode, PasteMode::Standalone) {
self.continuation = None;
}
tracing::debug!("typing instead of pasting into Chromium 155 or 156");
keyboard::type_text(&text)
},
)?;
} else {
self.paste_through_clipboard(&text, mode, commit)?;
}
self.continuation = (!matches!(mode, PasteMode::Standalone)).then_some(Continuation {
revision,
inserted: text,
});
Ok(())
}
fn paste_through_clipboard(
&mut self,
text: &str,
mode: PasteMode,
commit: impl FnOnce() -> bool,
) -> Result<()> {
let generation = commit_prepared_paste(
|| {
let 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"));
}
Ok((restore, previous, previous_change_count))
},
commit,
|(mut restore, previous, previous_change_count)| {
if matches!(mode, PasteMode::Standalone) {
self.continuation = None;
}
if let Err(error) = write_clipboard_text(&self.clipboard, text) {
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);
}
let inserted_change_count = self.clipboard.changeCount();
Ok(restore.register(previous, previous_change_count, inserted_change_count))
},
)?;
let clipboard_restore = self.clipboard_restore.clone();
complete_paste(
|| keyboard::post_command('v'),
move || {
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,
)
}
}
pub(crate) fn commit_prepared_paste<P, T>(
prepare: impl FnOnce() -> Result<P>,
commit: impl FnOnce() -> bool,
paste: impl FnOnce(P) -> Result<T>,
) -> Result<T> {
let prepared = prepare()?;
// Waiting for restoration and materializing promised clipboard data remain cancellable.
// Once committed, even a failed first write may have changed the clipboard.
if !commit() {
return Err(eyre!("paste was cancelled"));
}
paste(prepared)
}
/// 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.
const CLIPBOARD_MANAGER_MARKERS: [&str; 2] = [
"org.nspasteboard.TransientType",
"org.nspasteboard.AutoGeneratedType",
];
fn write_clipboard_text(clipboard: &NSPasteboard, text: &str) -> 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 = 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
}
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 rejected_commit_does_not_write_paste_or_restore() {
let steps = RefCell::new(Vec::new());
let result = commit_prepared_paste(
|| {
steps.borrow_mut().push("prepare");
Ok(())
},
|| {
steps.borrow_mut().push("commit");
false
},
|()| {
steps.borrow_mut().push("write");
complete_paste(
|| {
steps.borrow_mut().push("post");
Ok(())
},
|| steps.borrow_mut().push("restore"),
|_| steps.borrow_mut().push("settle"),
)
},
);
assert_eq!(result.unwrap_err().to_string(), "paste was cancelled");
assert_eq!(steps.into_inner(), ["prepare", "commit"]);
}
#[test]
fn failed_preparation_does_not_commit_or_write() {
let result = commit_prepared_paste(
|| Err::<(), _>(eyre!("snapshot failed")),
|| panic!("failed preparation must remain cancellable"),
|()| -> Result<()> { panic!("failed preparation must not mutate the clipboard") },
);
assert_eq!(result.unwrap_err().to_string(), "snapshot failed");
}
#[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"]);
}
#[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 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 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").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);
}
}