GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
//! The system clipboard is checked for Paste off the UI thread where the host installs a probe
//! (Linux): an X11 clipboard owner that never answers used to block the frame loop for seconds, so
//! the window stopped drawing and could not even be closed. The in-line check (no probe: the web,
//! Windows, macOS) is covered by `tests_clipboard` and `tests_sysclip`.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::clipboard::Flavour;

use crate::tests_sysclip::{copy_rect, run};
use crate::{Services, SystemClipboard, VectorcraftApp, clipboard_probe, menus};

/// What the clipboard handles saw: the thread each `has()` ran on, how many handles are alive, and
/// the thread each handle was dropped on, in order.
#[derive(Default)]
struct Recorder {
    threads: Mutex<Vec<Option<String>>>,
    alive: AtomicUsize,
    drops: Mutex<Vec<Option<String>>>,
}

impl Recorder {
    fn looks(&self) -> usize {
        self.threads.lock().unwrap().len()
    }
}

/// A system clipboard whose `has()` takes `delay` (an owner slow to answer) and answers `verdict`,
/// or panics without one (a bug in the platform code).
struct Slow {
    rec: Arc<Recorder>,
    delay: Duration,
    verdict: Option<bool>,
}

impl Slow {
    fn boxed(rec: &Arc<Recorder>, delay: Duration, verdict: Option<bool>) -> Box<dyn SystemClipboard> {
        rec.alive.fetch_add(1, Ordering::SeqCst);
        Box::new(Self { rec: Arc::clone(rec), delay, verdict })
    }
}

impl Drop for Slow {
    fn drop(&mut self) {
        self.rec.drops.lock().unwrap().push(std::thread::current().name().map(str::to_owned));
        self.rec.alive.fetch_sub(1, Ordering::SeqCst);
    }
}

/// The probe's clipboard: its `has()` tells `looking` it started, then waits until `answer` sends
/// (an owner that answers only once the app is quitting).
struct Held {
    rec: Arc<Recorder>,
    looking: std::sync::mpsc::Sender<()>,
    answer: std::sync::mpsc::Receiver<()>,
}

impl Drop for Held {
    fn drop(&mut self) {
        self.rec.drops.lock().unwrap().push(std::thread::current().name().map(str::to_owned));
    }
}

impl SystemClipboard for Held {
    fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> {
        Ok(())
    }
    fn holds_ours(&mut self) -> bool {
        false
    }
    fn read(&mut self, _mimes: &[&'static str]) -> Option<Flavour> {
        None
    }
    fn has(&mut self, _mimes: &[&'static str]) -> bool {
        let _ = self.looking.send(());
        let _ = self.answer.recv();
        false
    }
}

impl SystemClipboard for Slow {
    fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> {
        Ok(())
    }
    fn holds_ours(&mut self) -> bool {
        false
    }
    fn read(&mut self, _mimes: &[&'static str]) -> Option<Flavour> {
        None
    }
    fn has(&mut self, _mimes: &[&'static str]) -> bool {
        self.rec.threads.lock().unwrap().push(std::thread::current().name().map(str::to_owned));
        std::thread::sleep(self.delay);
        self.verdict.expect("the clipboard failed")
    }
}

/// An app whose two clipboard handles record into `rec`: the UI's says `inline`, the probe's
/// `probe`, each after `delay`.
fn app(rec: &Arc<Recorder>, delay: Duration, inline: bool, probe: Option<bool>) -> VectorcraftApp {
    let make = {
        let rec = Arc::clone(rec);
        move || Slow::boxed(&rec, delay, probe)
    };
    let services =
        Services { system_clipboard: Some(Slow::boxed(rec, delay, Some(inline))), clipboard_probe: Some(Box::new(make)), ..Default::default() };
    VectorcraftApp::new(Session::new(), services)
}

/// One headless frame of app logic in the test's one context (a new one would restart the fonts),
/// half a second after the last: past the in-line check's throttle, so it would run every frame.
fn frame(app: &mut VectorcraftApp) {
    thread_local! {
        static CTX: egui::Context = egui::Context::default();
        static NOW: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
    }
    let time = NOW.with(|t| {
        t.set(t.get() + 0.5);
        t.get()
    });
    let input = egui::RawInput { time: Some(time), ..Default::default() };
    CTX.with(|ctx| ctx.run_ui(input, |ui| app.logic(ui.ctx())).textures_delta.clear());
}

/// Frames for `wait`, or until `done` holds; whether it does.
fn frames_until(app: &mut VectorcraftApp, wait: Duration, done: impl Fn(&VectorcraftApp) -> bool) -> bool {
    let end = Instant::now() + wait;
    loop {
        frame(app);
        if done(app) || Instant::now() > end {
            return done(app);
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

#[test]
fn a_slow_clipboard_is_read_off_the_ui_thread() {
    let rec = Arc::new(Recorder::default());
    let mut app = app(&rec, Duration::from_secs(1), false, Some(true));
    // The first frames install the UI fonts. Without a document Paste is off whatever the clipboard
    // holds: nobody looks.
    assert!(!frames_until(&mut app, Duration::from_millis(100), |_| rec.looks() > 0));
    run(&mut app, "file.new", json!({"width": 100, "height": 100}));
    frame(&mut app);
    let t0 = Instant::now();
    frame(&mut app);
    assert!(t0.elapsed() < Duration::from_millis(300), "the frame waited on the clipboard: {:?}", t0.elapsed());
    // The probe's verdict (the UI's own handle would say no) enables Paste once it arrives.
    assert!(frames_until(&mut app, Duration::from_secs(60), |app| app.system_paste), "the probe's verdict never arrived");
    assert!(menus::enabled(&app, "edit.paste"));
    let threads = rec.threads.lock().unwrap().clone();
    assert!(threads.iter().all(|n| n.as_deref() == Some("vectorcraft-clip")), "checked on: {threads:?}");
}

#[test]
fn the_probe_rests_after_a_copy_and_stops_with_the_app() {
    let rec = Arc::new(Recorder::default());
    let mut app = app(&rec, Duration::ZERO, false, Some(true));
    run(&mut app, "file.new", json!({"width": 100, "height": 100}));
    assert!(frames_until(&mut app, Duration::from_secs(60), |app| app.system_paste));
    // Something copied in the app enables Paste alone: the clipboard isn't read any more.
    copy_rect(&mut app);
    frames_until(&mut app, Duration::from_millis(50), |_| false);
    let looks = rec.looks();
    frames_until(&mut app, Duration::from_millis(600), |_| false);
    assert_eq!(rec.looks(), looks);
    assert!(!app.system_paste && menus::enabled(&app, "edit.paste"));
    // Quitting waits until the probe's thread has let go of its handle: on X11 the last handle
    // alive hands what the app copied to the clipboard manager.
    assert_eq!(rec.alive.load(Ordering::SeqCst), 2);
    drop(app);
    assert_eq!(rec.alive.load(Ordering::SeqCst), 0, "the probe's thread kept its clipboard");
}

#[test]
fn quitting_drops_the_probes_clipboard_before_the_apps() {
    let rec = Arc::new(Recorder::default());
    let (looking, looked) = std::sync::mpsc::channel();
    let (answer, answered) = std::sync::mpsc::channel::<()>();
    let make = {
        let rec = Arc::clone(&rec);
        move || -> Box<dyn SystemClipboard> { Box::new(Held { rec, looking, answer: answered }) }
    };
    let services = Services {
        system_clipboard: Some(Slow::boxed(&rec, Duration::ZERO, Some(false))),
        clipboard_probe: Some(Box::new(make)),
        ..Default::default()
    };
    let mut app = VectorcraftApp::new(Session::new(), services);
    run(&mut app, "file.new", json!({"width": 100, "height": 100}));
    frame(&mut app);
    frame(&mut app);
    // The probe's thread is waiting on the clipboard's owner when the user quits.
    looked.recv_timeout(Duration::from_secs(60)).expect("the probe never looked");
    drop(answer);
    drop(app);
    // On X11 the last handle dropped hands what the app copied to the clipboard manager: it must be
    // the app's own, dropped on the UI thread before the process exits.
    let drops = rec.drops.lock().unwrap().clone();
    let ui = std::thread::current().name().map(str::to_owned);
    assert_eq!(drops, vec![Some("vectorcraft-clip".to_owned()), ui], "handles dropped on: {drops:?}");
}

/// The probe's clipboard: dropping it tells `dropping` it started, then waits until `release` sends
/// (a handle that lets go only once an unanswered read ends), and tells `dropped` once it is gone.
struct Releasing {
    rec: Arc<Recorder>,
    dropping: std::sync::mpsc::Sender<()>,
    release: std::sync::mpsc::Receiver<()>,
    dropped: std::sync::mpsc::Sender<()>,
}

impl Drop for Releasing {
    fn drop(&mut self) {
        let _ = self.dropping.send(());
        let _ = self.release.recv();
        self.rec.drops.lock().unwrap().push(std::thread::current().name().map(str::to_owned));
        let _ = self.dropped.send(());
    }
}

impl SystemClipboard for Releasing {
    fn write(&mut self, _flavours: &[Flavour]) -> Result<(), String> {
        Ok(())
    }
    fn holds_ours(&mut self) -> bool {
        false
    }
    fn read(&mut self, _mimes: &[&'static str]) -> Option<Flavour> {
        None
    }
    fn has(&mut self, _mimes: &[&'static str]) -> bool {
        false
    }
}

#[test]
fn quitting_waits_while_the_probes_clipboard_is_still_letting_go() {
    let rec = Arc::new(Recorder::default());
    let (dropping, dropping_seen) = std::sync::mpsc::channel();
    let (release, released) = std::sync::mpsc::channel();
    let (dropped, dropped_seen) = std::sync::mpsc::channel();
    let make = {
        let rec = Arc::clone(&rec);
        move || -> Box<dyn SystemClipboard> { Box::new(Releasing { rec, dropping, release: released, dropped }) }
    };
    let services = Services {
        system_clipboard: Some(Slow::boxed(&rec, Duration::ZERO, Some(false))),
        clipboard_probe: Some(Box::new(make)),
        ..Default::default()
    };
    let mut app = VectorcraftApp::new(Session::new(), services);
    frame(&mut app);
    // A controllable clock: the probe's handle lets go 26 s after the quit (a text read unanswered
    // just before it, and the worker's teardown). The wait sees the handle start to drop, then
    // either reaches that time and waits for the worker, or ends at its deadline first.
    let lets_go = Duration::from_secs(26);
    let release_at_deadline = release.clone();
    app.clipboard_probe.as_mut().expect("the probe started").stop = Box::new(move |verdicts, quit, end| {
        dropping_seen.recv().expect("the probe's handle was never dropped");
        if end >= quit + lets_go {
            let _ = release_at_deadline.send(());
            while verdicts.recv().is_ok() {}
        }
    });
    drop(app);
    // A wait that ended first left the handle dropping: let it finish to read the order.
    let _ = release.send(());
    dropped_seen.recv().expect("the probe's handle was never dropped");
    let drops = rec.drops.lock().unwrap().clone();
    let ui = std::thread::current().name().map(str::to_owned);
    assert_eq!(drops, vec![Some("vectorcraft-clip".to_owned()), ui], "handles dropped on: {drops:?}");
}

#[test]
fn quitting_waits_out_an_unanswered_x11_read_and_its_teardown() {
    let quit = Instant::now();
    // A look whose text read went unanswered just before the quit: the Linux host's worker holds its
    // handle until 25 s after the read was sent, and an idle worker's teardown takes 2 s at most.
    assert!(clipboard_probe::stop_by(quit) >= quit + Duration::from_secs(25) + Duration::from_secs(2));
    // A handle that never lets go still lets the app quit.
    assert_eq!(clipboard_probe::stop_by(quit), quit + Duration::from_secs(27));
}

#[test]
fn without_its_thread_the_check_runs_in_line_again() {
    let rec = Arc::new(Recorder::default());
    // The probe's clipboard panics: its thread ends.
    let mut app = app(&rec, Duration::ZERO, true, None);
    run(&mut app, "file.new", json!({"width": 100, "height": 100}));
    assert!(frames_until(&mut app, Duration::from_secs(60), |app| app.system_paste), "no fallback");
    assert!(app.clipboard_probe.is_none());
    let threads = rec.threads.lock().unwrap().clone();
    assert_eq!(threads.first().cloned().flatten().as_deref(), Some("vectorcraft-clip"), "{threads:?}");
}