use std::{
path::PathBuf,
sync::{Arc, Mutex},
};
use lurq::{
app::{
Tree,
events::{ClipboardContent, ClipboardImage, MouseButton, PasteEvent, is_synthetic_input},
synthetic_input::{self, SyntheticInput, SyntheticModifiers},
},
components::{Column, TextInput},
core::Signal,
};
use crate::support::{pointer_click, run_pass};
struct TestClipboard {
text_reads: Mutex<usize>,
full_reads: Mutex<usize>,
}
impl TestClipboard {
fn install(runtime: &mut Tree) -> Arc<Self> {
let clipboard = Arc::new(Self {
text_reads: Mutex::new(0),
full_reads: Mutex::new(0),
});
runtime.set_clipboard_reader(Some(clipboard.clone()));
clipboard
}
fn reads(&self) -> (usize, usize) {
(*self.text_reads.lock().unwrap(), *self.full_reads.lock().unwrap())
}
}
impl lurq::app::ClipboardReader for TestClipboard {
fn read_text(&self) -> Option<String> {
*self.text_reads.lock().unwrap() += 1;
Some("secret".to_owned())
}
fn read(&self) -> Option<ClipboardContent> {
*self.full_reads.lock().unwrap() += 1;
Some(ClipboardContent::text("secret").with_files([PathBuf::from("C:/shots/a.png")]))
}
}
fn focused_input(value: &Signal<String>) -> Tree {
let mut runtime = Tree::new();
runtime.set_root(TextInput::new(value.clone()).id("input"));
focus(runtime)
}
fn focus(mut runtime: Tree) -> Tree {
run_pass(&mut runtime);
let (x, y) = runtime
.get_element_by_id_mut("input")
.expect("input")
.bounds()
.expect("laid out")
.center();
pointer_click(&mut runtime, x, y, MouseButton::Left);
runtime
}
#[test]
fn a_paste_inserts_the_text_at_the_caret() {
let value = Signal::new("ab".to_owned());
let mut runtime = focused_input(&value);
runtime.key_down("End".into(), "End".into(), false, false, false);
assert!(runtime.paste(ClipboardContent::text("cd")));
assert_eq!(value.get(), "abcd");
}
#[test]
fn the_paste_event_runs_before_the_insertion() {
let value = Signal::new("old".to_owned());
let seen = Arc::new(Mutex::new(Vec::new()));
let mut runtime = Tree::new();
let log = seen.clone();
let observed = value.clone();
runtime.set_root(
TextInput::new(value.clone())
.id("input")
.on_paste(move |event: PasteEvent| {
log
.lock()
.unwrap()
.push((observed.get(), event.text().map(str::to_owned)));
}),
);
let mut runtime = focus(runtime);
runtime.key_down("End".into(), "End".into(), false, false, false);
runtime.paste(ClipboardContent::text("new"));
assert_eq!(
seen.lock().unwrap().as_slice(),
&[("old".to_owned(), Some("new".to_owned()))],
"the handler sees the value before the paste"
);
assert_eq!(value.get(), "oldnew");
}
#[test]
fn prevent_default_keeps_the_text_out_of_the_input() {
let value = Signal::new(String::new());
let mut runtime = Tree::new();
runtime.set_root(
TextInput::new(value.clone())
.id("input")
.on_paste(|event: PasteEvent| event.prevent_default()),
);
let mut runtime = focus(runtime);
assert!(
runtime.paste(ClipboardContent::text("kept out")),
"a prevented paste is handled"
);
assert_eq!(value.get(), "");
}
#[test]
fn an_image_and_files_reach_the_handler_and_insert_nothing() {
let value = Signal::new(String::new());
let seen = Arc::new(Mutex::new(None));
let mut runtime = Tree::new();
let log = seen.clone();
runtime.set_root(
TextInput::new(value.clone())
.id("input")
.on_paste(move |event: PasteEvent| {
let image = event.image().map(|image| (image.width(), image.height()));
*log.lock().unwrap() = Some((event.kinds(), image, event.files().to_vec()));
event.prevent_default();
}),
);
let mut runtime = focus(runtime);
let image = ClipboardImage::from_rgba(2, 1, vec![255; 8]).expect("2x1 RGBA");
let content = ClipboardContent::image(image).with_files([PathBuf::from("C:/shots/a.png")]);
runtime.paste(content);
let (kinds, image, files) = seen.lock().unwrap().clone().expect("the handler ran");
assert!(kinds.image && kinds.files && !kinds.text);
assert_eq!(image, Some((2, 1)));
assert_eq!(files, vec![PathBuf::from("C:/shots/a.png")]);
assert_eq!(value.get(), "");
}
#[test]
fn a_paste_without_text_or_handler_is_not_handled() {
let value = Signal::new(String::new());
let mut runtime = focused_input(&value);
assert!(!runtime.paste(ClipboardContent::files([PathBuf::from("a.txt")])));
assert!(!runtime.paste(ClipboardContent::text("")));
assert_eq!(value.get(), "");
}
#[test]
fn the_paste_event_bubbles_from_the_input_to_its_ancestors() {
let value = Signal::new(String::new());
let order = Arc::new(Mutex::new(Vec::new()));
let mut runtime = Tree::new();
let (outer, inner) = (order.clone(), order.clone());
runtime.set_root(
Column::new()
.on_paste(move |event: PasteEvent| {
outer
.lock()
.unwrap()
.push(("column", event.target_id == event.input_id));
})
.child(
TextInput::new(value.clone())
.id("input")
.on_paste(move |event: PasteEvent| {
inner.lock().unwrap().push(("input", event.target_id == event.input_id));
}),
),
);
let mut runtime = focus(runtime);
runtime.paste(ClipboardContent::text("x"));
assert_eq!(order.lock().unwrap().as_slice(), &[("input", true), ("column", false)]);
assert_eq!(value.get(), "x");
}
#[test]
fn stop_propagation_keeps_the_paste_from_the_ancestors() {
let value = Signal::new(String::new());
let column_saw = Arc::new(Mutex::new(false));
let mut runtime = Tree::new();
let flag = column_saw.clone();
runtime.set_root(
Column::new()
.on_paste(move |_: PasteEvent| *flag.lock().unwrap() = true)
.child(
TextInput::new(value.clone())
.id("input")
.on_paste(|event: PasteEvent| event.stop_propagation()),
),
);
let mut runtime = focus(runtime);
runtime.paste(ClipboardContent::text("x"));
assert!(!*column_saw.lock().unwrap());
assert_eq!(value.get(), "x", "stopping the propagation keeps the default");
}
#[test]
fn a_paste_without_a_focused_input_does_nothing() {
let value = Signal::new(String::new());
let mut runtime = Tree::new();
runtime.set_root(TextInput::new(value.clone()).id("input"));
run_pass(&mut runtime);
assert!(!runtime.paste(ClipboardContent::text("nowhere")));
assert_eq!(value.get(), "");
}
#[test]
fn a_synthetic_paste_carries_its_content_and_is_marked_synthetic() {
let value = Signal::new(String::new());
let synthetic = Arc::new(Mutex::new(None));
let mut runtime = Tree::new();
let flag = synthetic.clone();
runtime.set_root(
TextInput::new(value.clone())
.id("input")
.on_paste(move |_: PasteEvent| {
*flag.lock().unwrap() = Some(is_synthetic_input());
}),
);
let mut runtime = focus(runtime);
synthetic_input::apply(&mut runtime, &SyntheticInput::paste(ClipboardContent::text("agent")));
assert_eq!(*synthetic.lock().unwrap(), Some(true));
assert_eq!(value.get(), "agent");
}
#[test]
fn a_synthetic_ctrl_v_does_not_read_the_clipboard() {
let value = Signal::new(String::new());
let seen = Arc::new(Mutex::new(0));
let mut runtime = Tree::new();
let clipboard = TestClipboard::install(&mut runtime);
let count = seen.clone();
runtime.set_root(
TextInput::new(value.clone())
.id("input")
.on_paste(move |_: PasteEvent| {
*count.lock().unwrap() += 1;
}),
);
let mut runtime = focus(runtime);
let ctrl = SyntheticModifiers::default().ctrl();
let meta = SyntheticModifiers::default().meta();
let shift = SyntheticModifiers::default().shift();
for input in [
SyntheticInput::key_down("v").with_modifiers(ctrl),
SyntheticInput::key_down("v").with_modifiers(meta),
SyntheticInput::key_down("Insert").with_modifiers(shift),
] {
synthetic_input::apply(&mut runtime, &input);
}
assert_eq!(clipboard.reads(), (0, 0), "the clipboard was never read");
assert_eq!(*seen.lock().unwrap(), 0, "no paste event without content");
assert_eq!(value.get(), "");
}
#[test]
fn a_paste_request_under_synthetic_input_is_refused_whatever_its_argument_says() {
let value = Signal::new(String::new());
let mut runtime = Tree::new();
let clipboard = TestClipboard::install(&mut runtime);
runtime.set_root(TextInput::new(value.clone()).id("input"));
let mut runtime = focus(runtime);
assert!(!runtime.paste_from_os_clipboard(true));
assert!(!lurq::app::events::with_synthetic_input(
|| runtime.paste_from_os_clipboard(false)
));
assert_eq!(clipboard.reads(), (0, 0));
assert_eq!(value.get(), "");
assert!(runtime.paste_from_os_clipboard(false));
assert_eq!(value.get(), "secret");
}
#[test]
fn a_ctrl_v_from_the_os_reads_as_much_of_the_clipboard_as_the_paste_needs() {
let value = Signal::new(String::new());
let mut runtime = Tree::new();
let clipboard = TestClipboard::install(&mut runtime);
runtime.set_root(TextInput::new(value.clone()).id("input"));
let mut runtime = focus(runtime);
let shortcut = if cfg!(target_vendor = "apple") {
(false, true)
} else {
(true, false)
};
runtime.key_down_with_meta("v".into(), "KeyV".into(), false, shortcut.0, false, shortcut.1);
assert_eq!(value.get(), "secret");
assert_eq!(clipboard.reads(), (1, 0), "text only: nothing looks at the paste");
let seen = Arc::new(Mutex::new(Vec::new()));
let mut runtime = Tree::new();
let clipboard = TestClipboard::install(&mut runtime);
let log = seen.clone();
runtime.set_root(
Column::new()
.on_paste(move |event: PasteEvent| log.lock().unwrap().push(event.files().len()))
.child(TextInput::new(value.clone()).id("input")),
);
let mut runtime = focus(runtime);
runtime.key_down("Insert".into(), "Insert".into(), true, false, false);
assert_eq!(
clipboard.reads(),
(0, 1),
"everything: an ancestor's handler looks at the paste"
);
assert_eq!(seen.lock().unwrap().as_slice(), &[1]);
}
#[derive(Default)]
struct Written(Mutex<Vec<String>>);
impl lurq::app::ClipboardWriter for Written {
fn write_text(&self, text: &str) -> bool {
self.0.lock().unwrap().push(text.to_owned());
true
}
}
fn focused_cell(heard: Arc<Mutex<Vec<String>>>) -> (Tree, Arc<Written>) {
let mut runtime = Tree::new();
let (copies, pastes) = (heard.clone(), heard);
runtime.set_root(
Column::new()
.on_copy(move |event: lurq::app::events::CopyEvent| {
copies.lock().unwrap().push(format!("copy cut={}", event.is_cut()));
event.set_text("a\tb\nc\td");
})
.on_paste(move |event: PasteEvent| {
pastes
.lock()
.unwrap()
.push(format!("paste {}", event.text().unwrap_or_default()));
})
.child(lurq::components::Row::new().size(80.0, 30.0).tab_index(0).id("input")),
);
let mut runtime = focus(runtime);
TestClipboard::install(&mut runtime);
let written = Arc::new(Written::default());
runtime.set_clipboard_writer(Some(written.clone()));
(runtime, written)
}
#[test]
fn ctrl_c_on_a_focused_element_that_is_not_an_input_writes_what_its_handler_says() {
let heard = Arc::new(Mutex::new(Vec::new()));
let (mut runtime, written) = focused_cell(heard.clone());
crate::support::shortcut(&mut runtime, "c", "KeyC", false);
crate::support::shortcut(&mut runtime, "x", "KeyX", false);
assert_eq!(*heard.lock().unwrap(), ["copy cut=false", "copy cut=true"]);
assert_eq!(*written.0.lock().unwrap(), ["a\tb\nc\td", "a\tb\nc\td"]);
}
#[test]
fn ctrl_v_on_a_focused_element_that_is_not_an_input_reaches_its_handlers_with_the_clipboard() {
let heard = Arc::new(Mutex::new(Vec::new()));
let (mut runtime, _) = focused_cell(heard.clone());
crate::support::shortcut(&mut runtime, "v", "KeyV", false);
assert_eq!(*heard.lock().unwrap(), ["paste secret"]);
assert!(
runtime.paste(ClipboardContent::text("given")),
"a paste of given content too"
);
assert_eq!(heard.lock().unwrap().last().map(String::as_str), Some("paste given"));
}
#[test]
fn a_copy_nothing_hears_writes_nothing() {
let mut runtime = Tree::new();
runtime.set_root(lurq::components::Row::new().size(80.0, 30.0).tab_index(0).id("input"));
let mut runtime = focus(runtime);
let written = Arc::new(Written::default());
runtime.set_clipboard_writer(Some(written.clone()));
crate::support::shortcut(&mut runtime, "c", "KeyC", false);
assert!(written.0.lock().unwrap().is_empty());
assert!(
!runtime.paste(ClipboardContent::text("given")),
"no handler takes a paste"
);
}
struct CopyButton;
impl lurq::app::component::Component for CopyButton {
type Props = ();
fn create(_ctx: &mut lurq::app::ctx::Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut lurq::app::ctx::Ctx) -> impl Into<lurq::node::Element> {
let window = ctx.window();
Column::new().child(
lurq::components::Rect::new(80.0, 30.0)
.id("copy")
.on_click(move |_: lurq::app::events::MouseEvent| window.copy_to_clipboard("fn main() {}")),
)
}
}
#[test]
fn a_press_puts_a_text_on_the_clipboard_through_the_window() {
let mut app = lurq::app::App::new();
let mut runtime = Tree::new();
runtime.mount_root::<CopyButton>(&mut app, ());
let written = Arc::new(Written::default());
runtime.set_clipboard_writer(Some(written.clone()));
runtime.pass_headless(&mut app);
pointer_click(&mut runtime, 10.0, 10.0, MouseButton::Left);
assert_eq!(*written.0.lock().unwrap(), ["fn main() {}"]);
runtime.pass_headless(&mut app);
assert_eq!(written.0.lock().unwrap().len(), 1);
}