lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! A paste into a text input delivers one `PasteEvent` to the input and its
//! ancestors before the text is inserted, and a synthetic Ctrl+V never
//! reads the OS clipboard.

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};

/// A clipboard of the test's own, counting what a paste reads from it.
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");
}

/// The person's clipboard is theirs: a synthetic Ctrl+V (an MCP client's
/// `key` action) is refused instead of reading it, whatever it holds.
#[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(), "");
}

/// `paste_from_os_clipboard` trusts neither its argument nor its caller: a
/// request made while synthetic input is delivered is refused either way.
#[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");
}

/// A person's Ctrl+V reads the clipboard: only its text when no handler
/// looks at the paste, as before paste events, and everything when one does.
#[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]);
}

/// What copies wrote, in place of the OS clipboard.
#[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
  }
}

/// A focused element that is not an input, in a column that hears copies and pastes, with the test's
/// clipboards.
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"
  );
}

/// A copy button of an app's: a press asks the window to put its code on the clipboard.
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() {}")),
    )
  }
}

/// A press puts a text on the clipboard through the window: it is written where a copy shortcut writes, once the
/// press is handled.
#[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() {}"]);
  // Nothing is written twice.
  runtime.pass_headless(&mut app);
  assert_eq!(written.0.lock().unwrap().len(), 1);
}