Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

7.9 KB
Raw Blame
use crate::protocol::{ErrorCode, Failure, PasteFormat};
use crate::text;
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_app_kit::{NSPasteboard, NSPasteboardItem, NSPasteboardTypeHTML, NSPasteboardTypeString, NSPasteboardWriting};
use objc2_foundation::{NSArray, NSData, NSString};
use std::time::{Duration, Instant};

const MARKERS: &[&str] = &["org.nspasteboard.TransientType", "org.nspasteboard.AutoGeneratedType"];
const CONCEALED: &[&str] = &["org.nspasteboard.ConcealedType"];
const SHOW_TIMEOUT: Duration = Duration::from_secs(3);

type Saved = Vec<Vec<(Retained<NSString>, Retained<NSData>)>>;

fn fail(code: ErrorCode, m: &str) -> Failure {
    Failure::new(code, m)
}

fn snapshot(board: &NSPasteboard) -> Result<(Saved, isize), Failure> {
    let before = board.changeCount();
    let mut saved = vec![];
    for item in board.pasteboardItems().iter().flat_map(|items| items.iter()) {
        let mut types = vec![];
        for t in item.types() {
            if CONCEALED.contains(&t.to_string().as_str()) {
                return Err(fail(
                    ErrorCode::ActionFailed,
                    "The clipboard holds a concealed item, such as a password, so desk did not paste. Use typeText instead.",
                ));
            }
            let d = item
                .dataForType(&t)
                .ok_or_else(|| fail(ErrorCode::ActionFailed, "Could not preserve the current clipboard; paste was not attempted."))?;
            types.push((t, d));
        }
        saved.push(types);
    }
    if board.changeCount() != before {
        return Err(fail(ErrorCode::PasteConflict, "The clipboard changed while being saved; paste was not attempted."));
    }
    Ok((saved, before))
}

fn write(board: &NSPasteboard, items: Vec<Retained<NSPasteboardItem>>, expected: isize) -> Result<(bool, isize), Failure> {
    let objects: Vec<Retained<ProtocolObject<dyn NSPasteboardWriting>>> = items.into_iter().map(ProtocolObject::from_retained).collect();
    let objects = NSArray::from_retained_slice(&objects);
    if board.changeCount() != expected {
        return Err(fail(ErrorCode::PasteConflict, CONFLICT));
    }
    let cleared = board.clearContents();
    if board.changeCount() != cleared {
        return Err(fail(ErrorCode::PasteConflict, CONFLICT));
    }
    Ok((objects.is_empty() || board.writeObjects(&objects), cleared))
}

fn restore(board: &NSPasteboard, saved: &Saved, expected: isize) -> bool {
    let mut items = Vec::with_capacity(saved.len());
    for types in saved {
        let item = NSPasteboardItem::new();
        for (kind, data) in types {
            if !item.setData_forType(data, kind) {
                return false;
            }
        }
        items.push(item);
    }
    write(board, items, expected).is_ok_and(|(written, _)| written)
}

pub enum Check {
    Landed,
    NotYet,
    Unreadable,
}

const CONFLICT: &str = "The clipboard changed during the paste, probably because the user copied something. \
The app may have pasted that instead of your text. Observe the app and check what was pasted before continuing.";

fn uncertain(board: &NSPasteboard, ours: isize, why: &str) -> Failure {
    if board.changeCount() != ours {
        return fail(ErrorCode::PasteConflict, &format!("{why}. {CONFLICT}"));
    }
    fail(
        ErrorCode::ActionFailed,
        &format!(
            "desk could not confirm that the app pasted the text: {why}. The pasted text is still on the clipboard, and the user's previous clipboard was not restored, \
because restoring it now could let the app paste that instead. Observe the field to check what was pasted before continuing."
        ),
    )
}

pub fn paste(
    text: &str,
    format: PasteFormat,
    keystroke: impl FnOnce() -> Result<(), Failure>,
    check: &mut dyn FnMut() -> Check,
    interrupted: &dyn Fn() -> Result<(), Failure>,
) -> Result<(), Failure> {
    let (plain, html) = text::payload(text, format);
    let mut data = vec![(unsafe { NSPasteboardTypeString }.to_string(), plain.into_bytes())];
    if let Some(html) = html {
        data.push((unsafe { NSPasteboardTypeHTML }.to_string(), html.into_bytes()));
    }
    data.extend(MARKERS.iter().map(|marker| (marker.to_string(), vec![])));
    let item = NSPasteboardItem::new();
    for (kind, bytes) in data {
        if !item.setData_forType(&NSData::with_bytes(&bytes), &NSString::from_str(&kind)) {
            return Err(fail(ErrorCode::ActionFailed, "Could not put the text on the clipboard."));
        }
    }

    let board = NSPasteboard::generalPasteboard();
    let (saved, previous) = snapshot(&board)?;
    interrupted()?;
    let (written, cleared) = write(&board, vec![item], previous)?;
    if !written {
        return Err(fail(
            ErrorCode::ActionFailed,
            if restore(&board, &saved, cleared) {
                "Could not put the text on the clipboard."
            } else {
                "Could not put the text on the clipboard, and the previous clipboard could not be restored."
            },
        ));
    }
    let ours = board.changeCount();
    if let Err(e) = keystroke() {
        return Err(uncertain(&board, ours, &format!("sending Cmd+V failed ({})", e.message)));
    }

    let start = Instant::now();
    loop {
        crate::cancellation::wait(Duration::from_millis(100));
        if board.changeCount() != ours {
            return Err(fail(ErrorCode::PasteConflict, CONFLICT));
        }
        if let Err(e) = interrupted() {
            return Err(uncertain(&board, ours, &format!("the paste was interrupted after Cmd+V was sent ({})", e.message)));
        }
        match check() {
            Check::Landed => break,
            Check::Unreadable => return Err(uncertain(&board, ours, "desk cannot read the text of the app's focused field")),
            Check::NotYet if start.elapsed() >= SHOW_TIMEOUT => {
                return Err(uncertain(&board, ours, "the focused field does not show the pasted text"));
            }
            Check::NotYet => {}
        }
    }
    if !restore(&board, &saved, ours) {
        return Err(fail(
            ErrorCode::ActionFailed,
            "The text was pasted, but the previous clipboard could not be restored. Check the clipboard before continuing.",
        ));
    }
    Ok(())
}

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

    fn item(types: &[(&str, &[u8])]) -> Retained<NSPasteboardItem> {
        let item = NSPasteboardItem::new();
        for (kind, bytes) in types {
            assert!(item.setData_forType(&NSData::with_bytes(bytes), &NSString::from_str(kind)));
        }
        item
    }

    #[test]
    fn restores_every_item_and_type_without_overwriting_a_new_owner() {
        let board = NSPasteboard::pasteboardWithUniqueName();
        let original = vec![
            item(&[("public.utf8-plain-text", b"saved"), ("test.qm.binary", &[0, 255, 4])]),
            item(&[("public.html", b"<b>second</b>")]),
        ];
        assert!(write(&board, original, board.changeCount()).unwrap().0);
        let (saved, previous) = snapshot(&board).unwrap();
        assert!(write(&board, vec![item(&[("public.utf8-plain-text", b"temporary")])], previous).unwrap().0);
        assert!(restore(&board, &saved, board.changeCount()));
        let items = board.pasteboardItems().unwrap();
        assert_eq!(items.len(), 2);
        assert_eq!(items.objectAtIndex(0).dataForType(&NSString::from_str("test.qm.binary")).unwrap().to_vec(), vec![0, 255, 4]);
        assert_eq!(items.objectAtIndex(0).dataForType(&NSString::from_str("public.utf8-plain-text")).unwrap().to_vec(), b"saved");
        assert_eq!(items.objectAtIndex(1).dataForType(&NSString::from_str("public.html")).unwrap().to_vec(), b"<b>second</b>");
        let before_copy = board.changeCount();
        assert!(write(&board, vec![item(&[("public.utf8-plain-text", b"new owner")])], before_copy).unwrap().0);
        assert!(!restore(&board, &saved, before_copy));
        assert_eq!(board.dataForType(&NSString::from_str("public.utf8-plain-text")).unwrap().to_vec(), b"new owner");
        board.clearContents();
    }
}