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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use crate::{
any_key::AnyKey,
component::{Component, ComponentHelper, ComponentHelperExt},
mock_terminal_render_loop,
props::AnyProps,
render, terminal_render_loop, Canvas, MockTerminalConfig, Terminal,
};
use crossterm::terminal;
use futures::Stream;
use std::{
fmt::Debug,
future::Future,
hash::Hash,
io::{self, stderr, stdout, IsTerminal, LineWriter, Write},
pin::Pin,
sync::Arc,
};
/// Used by the `element!` macro to extend a collection with elements.
#[doc(hidden)]
pub trait ExtendWithElements<T>: Sized {
fn extend_with_elements<E: Extend<T>>(self, dest: &mut E);
}
impl<'a, T, U> ExtendWithElements<T> for Element<'a, U>
where
U: ElementType + 'a,
T: From<Element<'a, U>>,
{
fn extend_with_elements<E: Extend<T>>(self, dest: &mut E) {
dest.extend([self.into()]);
}
}
impl<'a> ExtendWithElements<AnyElement<'a>> for AnyElement<'a> {
fn extend_with_elements<E: Extend<AnyElement<'a>>>(self, dest: &mut E) {
dest.extend([self]);
}
}
impl<T, U, I> ExtendWithElements<T> for I
where
I: IntoIterator<Item = U>,
U: Into<T>,
{
fn extend_with_elements<E: Extend<T>>(self, dest: &mut E) {
dest.extend(self.into_iter().map(|e| e.into()));
}
}
/// Used by the `element!` macro to extend a collection with elements.
#[doc(hidden)]
pub fn extend_with_elements<T, U, E>(dest: &mut T, elements: U)
where
T: Extend<E>,
U: ExtendWithElements<E>,
{
elements.extend_with_elements(dest);
}
/// Used to identify an element within the scope of its parent. This is used to minimize the number
/// of times components are destroyed and recreated from render-to-render.
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub struct ElementKey(Arc<Box<dyn AnyKey + Send + Sync>>);
impl ElementKey {
/// Constructs a new key.
pub fn new<K: Debug + Hash + Eq + Send + Sync + 'static>(key: K) -> Self {
Self(Arc::new(Box::new(key)))
}
}
/// An element is a description of an uninstantiated component, including its key and properties.
#[derive(Clone)]
pub struct Element<'a, T: ElementType + 'a> {
/// The key of the element.
pub key: ElementKey,
/// The properties of the element.
pub props: T::Props<'a>,
}
/// A trait implemented by all element types to define the properties that can be passed to them.
///
/// This trait is automatically implemented for all types that implement [`Component`].
pub trait ElementType {
/// The type of the properties that can be passed to the element.
type Props<'a>
where
Self: 'a;
}
/// A type-erased element that can be created from any [`Element`].
pub struct AnyElement<'a> {
key: ElementKey,
props: AnyProps<'a>,
helper: Box<dyn ComponentHelperExt>,
}
impl<'a, T> Element<'a, T>
where
T: Component + 'a,
{
/// Converts the element into an [`AnyElement`].
pub fn into_any(self) -> AnyElement<'a> {
self.into()
}
}
impl<'a, T> From<Element<'a, T>> for AnyElement<'a>
where
T: Component + 'a,
{
fn from(e: Element<'a, T>) -> Self {
Self {
key: e.key,
props: AnyProps::owned(e.props),
helper: ComponentHelper::<T>::boxed(),
}
}
}
impl<'a, 'b: 'a, T> From<&'a mut Element<'b, T>> for AnyElement<'a>
where
T: Component,
{
fn from(e: &'a mut Element<'b, T>) -> Self {
Self {
key: e.key.clone(),
props: AnyProps::borrowed(&mut e.props),
helper: ComponentHelper::<T>::boxed(),
}
}
}
impl<'a, 'b: 'a> From<&'a mut AnyElement<'b>> for AnyElement<'b> {
fn from(e: &'a mut AnyElement<'b>) -> Self {
Self {
key: e.key.clone(),
props: e.props.borrow(),
helper: e.helper.copy(),
}
}
}
mod private {
use super::*;
pub trait Sealed {}
impl Sealed for AnyElement<'_> {}
impl Sealed for &mut AnyElement<'_> {}
impl<T> Sealed for Element<'_, T> where T: Component {}
impl<T> Sealed for &mut Element<'_, T> where T: Component {}
}
/// A trait implemented by all element types, providing methods for common operations on them.
pub trait ElementExt: private::Sealed + Sized {
/// Returns the key of the element.
fn key(&self) -> &ElementKey;
#[doc(hidden)]
fn props_mut(&mut self) -> AnyProps<'_>;
#[doc(hidden)]
fn helper(&self) -> Box<dyn ComponentHelperExt>;
/// Renders the element into a canvas.
fn render(&mut self, max_width: Option<usize>) -> Canvas;
/// Renders the element into a string.
///
/// Note that unlike [`std::fmt::Display`] and [`std::string::ToString`], this method requires
/// the element to be mutable, as it's possible for the properties of the element to change
/// during rendering.
fn to_string(&mut self) -> String {
self.render(None).to_string()
}
/// Renders the element and prints it to stdout.
fn print(&mut self) {
self.write_to_is_terminal(stdout()).unwrap();
}
/// Renders the element and prints it to stderr.
fn eprint(&mut self) {
self.write_to_is_terminal(stderr()).unwrap();
}
/// Renders the element and writes it to the given writer.
fn write<W: Write>(&mut self, w: W) -> io::Result<()> {
let canvas = self.render(None);
canvas.write(w)
}
/// Renders the element and writes it to the given raw file descriptor. If the file descriptor
/// is a TTY, the canvas will be rendered based on its size, with ANSI escape codes.
#[cfg(unix)]
fn write_to_raw_fd<F: Write + std::os::fd::AsRawFd>(&mut self, fd: F) -> io::Result<()> {
use crossterm::tty::IsTty;
if fd.is_tty() {
let (width, _) = terminal::size()?;
let canvas = self.render(Some(width as _));
canvas.write_ansi(fd)
} else {
self.write(fd)
}
}
/// Renders the element and writes it to the given writer also implementing
/// [`IsTerminal`](std::io::IsTerminal). If the writer is a terminal, the canvas will be
/// rendered based on its size, with ANSI escape codes.
fn write_to_is_terminal<W: Write + IsTerminal>(&mut self, w: W) -> io::Result<()> {
if w.is_terminal() {
let (width, _) = terminal::size()?;
let canvas = self.render(Some(width as _));
canvas.write_ansi(w)
} else {
self.write(w)
}
}
/// Returns a future which renders the element in a loop, allowing it to be dynamic and
/// interactive.
///
/// This method should only be used when stdio is a TTY terminal. If for example, stdout is a
/// file, this will probably not produce the desired result. You can determine whether stdout
/// is a terminal with [`IsTerminal`](std::io::IsTerminal).
///
/// The behavior of the render loop can be configured via the methods on the returned future
/// before awaiting it.
fn render_loop(&mut self) -> RenderLoopFuture<'_, Self> {
RenderLoopFuture::new(self)
}
/// Renders the element in a loop using a mock terminal, allowing you to simulate terminal
/// events for testing purposes.
///
/// A stream of canvases is returned, allowing you to inspect the output of each render pass.
///
/// # Example
///
/// ```
/// # use iocraft::prelude::*;
/// # use futures::stream::StreamExt;
/// # #[component]
/// # fn MyTextInput() -> impl Into<AnyElement<'static>> {
/// # element!(View)
/// # }
/// async fn test_text_input() {
/// let actual = element!(MyTextInput)
/// .mock_terminal_render_loop(MockTerminalConfig::with_events(futures::stream::iter(
/// vec![
/// TerminalEvent::Key(KeyEvent::new(KeyEventKind::Press, KeyCode::Char('f'))),
/// TerminalEvent::Key(KeyEvent::new(KeyEventKind::Release, KeyCode::Char('f'))),
/// TerminalEvent::Key(KeyEvent::new(KeyEventKind::Press, KeyCode::Char('o'))),
/// TerminalEvent::Key(KeyEvent::new(KeyEventKind::Repeat, KeyCode::Char('o'))),
/// TerminalEvent::Key(KeyEvent::new(KeyEventKind::Release, KeyCode::Char('o'))),
/// ],
/// )))
/// .map(|c| c.to_string())
/// .collect::<Vec<_>>()
/// .await;
/// let expected = vec!["\n", "foo\n"];
/// assert_eq!(actual, expected);
/// }
/// ```
fn mock_terminal_render_loop(
&mut self,
config: MockTerminalConfig,
) -> impl Stream<Item = Canvas> {
mock_terminal_render_loop(self, config)
}
/// Renders the element as fullscreen in a loop, allowing it to be dynamic and interactive.
///
/// This method should only be used when stdio is a TTY terminal. If for example, stdout is a
/// file, this will probably not produce the desired result. You can determine whether stdout
/// is a terminal with [`IsTerminal`](std::io::IsTerminal).
///
/// This is equivalent to `self.render_loop().fullscreen()`.
fn fullscreen(&mut self) -> RenderLoopFuture<'_, Self> {
self.render_loop().fullscreen()
}
}
/// Specifies which handle to render the TUI to.
#[cfg_attr(not(feature = "unstable-output-streams"), doc(hidden))]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-output-streams")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Output {
/// Render to the stdout handle (default).
#[default]
Stdout,
/// Render to the stderr handle.
Stderr,
}
#[derive(Default)]
enum RenderLoopFutureState<'a, E: ElementExt> {
#[default]
Empty,
Init {
fullscreen: bool,
mouse_capture: Option<bool>,
ignore_ctrl_c: bool,
output: Output,
stdout_writer: Option<Box<dyn Write + Send + 'a>>,
stderr_writer: Option<Box<dyn Write + Send + 'a>>,
element: &'a mut E,
},
Running(Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>>),
}
/// A future that renders an element in a loop, allowing it to be dynamic and interactive.
///
/// This is created by the [`ElementExt::render_loop`] method.
///
/// Before awaiting the future, you can use its methods to configure its behavior.
pub struct RenderLoopFuture<'a, E: ElementExt + 'a> {
state: RenderLoopFutureState<'a, E>,
}
impl<'a, E: ElementExt + 'a> RenderLoopFuture<'a, E> {
pub(crate) fn new(element: &'a mut E) -> Self {
Self {
state: RenderLoopFutureState::Init {
fullscreen: false,
mouse_capture: None,
ignore_ctrl_c: false,
output: Output::default(),
stdout_writer: None,
stderr_writer: None,
element,
},
}
}
/// Renders the element as fullscreen in a loop, allowing it to be dynamic and interactive.
///
/// This method should only be used when stdio is a TTY terminal. If for example, stdout is a
/// file, this will probably not produce the desired result. You can determine whether stdout
/// is a terminal with [`IsTerminal`](std::io::IsTerminal).
pub fn fullscreen(mut self) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { fullscreen, .. } => {
*fullscreen = true;
}
_ => panic!("fullscreen() must be called before polling the future"),
}
self
}
/// Enables mouse capture. By default, mouse capture is only enabled in fullscreen mode. Call
/// this method to enable it in inline mode as well.
pub fn enable_mouse_capture(mut self) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { mouse_capture, .. } => {
*mouse_capture = Some(true);
}
_ => panic!("enable_mouse_capture() must be called before polling the future"),
}
self
}
/// Disables mouse capture for fullscreen mode. By default, fullscreen mode enables mouse
/// capture via crossterm's `EnableMouseCapture`. Call this method to opt out.
pub fn disable_mouse_capture(mut self) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { mouse_capture, .. } => {
*mouse_capture = Some(false);
}
_ => panic!("disable_mouse_capture() must be called before polling the future"),
}
self
}
/// If the terminal is in raw mode, Ctrl-C presses will not trigger the usual interrupt
/// signals. By default, if the terminal is in raw mode for any reason, iocraft will listen for
/// Ctrl-C and stop the render loop in response. If you would like to prevent this behavior and
/// implement your own handling for Ctrl-C, you can call this method.
pub fn ignore_ctrl_c(mut self) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { ignore_ctrl_c, .. } => {
*ignore_ctrl_c = true;
}
_ => panic!("ignore_ctrl_c() must be called before polling the future"),
}
self
}
/// Set the stdout handle for hook output and TUI rendering (when output is Stdout).
///
/// See [`output`](Self::output) for known crossterm caveats when mixing streams.
///
/// Default: `std::io::stdout()`
#[cfg(feature = "unstable-output-streams")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-output-streams")))]
pub fn stdout<W: Write + Send + 'a>(mut self, writer: W) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { stdout_writer, .. } => {
*stdout_writer = Some(Box::new(writer));
}
_ => panic!("stdout() must be called before polling the future"),
}
self
}
/// Set the stderr handle for hook output and TUI rendering (when output is Stderr).
///
/// See [`output`](Self::output) for known crossterm caveats when mixing streams.
///
/// Default: `LineWriter::new(std::io::stderr())`
#[cfg(feature = "unstable-output-streams")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-output-streams")))]
pub fn stderr<W: Write + Send + 'a>(mut self, writer: W) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { stderr_writer, .. } => {
*stderr_writer = Some(Box::new(writer));
}
_ => panic!("stderr() must be called before polling the future"),
}
self
}
/// Choose which handle to render the TUI to.
///
/// When set to [`Output::Stderr`], the TUI will be rendered to the stderr handle.
/// This is useful for CLI tools that need to pipe stdout to other programs
/// while still displaying a TUI to the user.
///
/// ## Known crossterm caveats
///
/// Some crossterm operations bypass the provided writer and write directly to
/// stdout, which can cause issues when stdout is piped:
///
/// - Cursor position queries always write to stdout
/// ([#652](https://github.com/crossterm-rs/crossterm/issues/652),
/// [#957](https://github.com/crossterm-rs/crossterm/pull/957)).
/// - Keyboard enhancement queries fall back to stdout on unix
/// ([#1026](https://github.com/crossterm-rs/crossterm/pull/1026)).
///
/// Default: [`Output::Stdout`]
#[cfg(feature = "unstable-output-streams")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-output-streams")))]
pub fn output(mut self, output: Output) -> Self {
match &mut self.state {
RenderLoopFutureState::Init { output: o, .. } => {
*o = output;
}
_ => panic!("output() must be called before polling the future"),
}
self
}
}
impl<'a, E: ElementExt + Send + 'a> Future for RenderLoopFuture<'a, E> {
type Output = io::Result<()>;
fn poll(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
loop {
match &mut self.state {
RenderLoopFutureState::Init { .. } => {
let (
fullscreen,
mouse_capture,
ignore_ctrl_c,
output,
stdout_writer,
stderr_writer,
element,
) = match std::mem::replace(&mut self.state, RenderLoopFutureState::Empty) {
RenderLoopFutureState::Init {
fullscreen,
mouse_capture,
ignore_ctrl_c,
output,
stdout_writer,
stderr_writer,
element,
} => (
fullscreen,
mouse_capture,
ignore_ctrl_c,
output,
stdout_writer,
stderr_writer,
element,
),
_ => unreachable!(),
};
let effective_mouse_capture = mouse_capture.unwrap_or(fullscreen);
let stdout_handle = stdout_writer.unwrap_or_else(|| Box::new(stdout()));
// Unlike stdout, stderr is unbuffered by default in the standard library
let stderr_handle =
stderr_writer.unwrap_or_else(|| Box::new(LineWriter::new(stderr())));
let mut terminal = match Terminal::new(
stdout_handle,
stderr_handle,
output,
fullscreen,
effective_mouse_capture,
) {
Ok(t) => t,
Err(e) => return std::task::Poll::Ready(Err(e)),
};
if effective_mouse_capture && !fullscreen {
if let Err(e) = terminal.enable_mouse_capture() {
return std::task::Poll::Ready(Err(e));
}
}
if ignore_ctrl_c {
terminal.ignore_ctrl_c();
}
let fut = Box::pin(terminal_render_loop(element, terminal));
self.state = RenderLoopFutureState::Running(fut);
}
RenderLoopFutureState::Running(fut) => {
return fut.as_mut().poll(cx);
}
RenderLoopFutureState::Empty => {
panic!("polled after completion");
}
}
}
}
}
impl ElementExt for AnyElement<'_> {
fn key(&self) -> &ElementKey {
&self.key
}
fn props_mut(&mut self) -> AnyProps<'_> {
self.props.borrow()
}
#[doc(hidden)]
fn helper(&self) -> Box<dyn ComponentHelperExt> {
self.helper.copy()
}
fn render(&mut self, max_width: Option<usize>) -> Canvas {
render(self, max_width)
}
}
impl ElementExt for &mut AnyElement<'_> {
fn key(&self) -> &ElementKey {
&self.key
}
fn props_mut(&mut self) -> AnyProps<'_> {
self.props.borrow()
}
#[doc(hidden)]
fn helper(&self) -> Box<dyn ComponentHelperExt> {
self.helper.copy()
}
fn render(&mut self, max_width: Option<usize>) -> Canvas {
render(&mut **self, max_width)
}
}
impl<T> ElementExt for Element<'_, T>
where
T: Component + 'static,
{
fn key(&self) -> &ElementKey {
&self.key
}
fn props_mut(&mut self) -> AnyProps<'_> {
AnyProps::borrowed(&mut self.props)
}
#[doc(hidden)]
fn helper(&self) -> Box<dyn ComponentHelperExt> {
ComponentHelper::<T>::boxed()
}
fn render(&mut self, max_width: Option<usize>) -> Canvas {
render(self, max_width)
}
}
impl<T> ElementExt for &mut Element<'_, T>
where
T: Component + 'static,
{
fn key(&self) -> &ElementKey {
&self.key
}
fn props_mut(&mut self) -> AnyProps<'_> {
AnyProps::borrowed(&mut self.props)
}
#[doc(hidden)]
fn helper(&self) -> Box<dyn ComponentHelperExt> {
ComponentHelper::<T>::boxed()
}
fn render(&mut self, max_width: Option<usize>) -> Canvas {
render(&mut **self, max_width)
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use futures::Future;
#[allow(clippy::unnecessary_mut_passed)]
#[test]
fn test_element() {
let mut view_element = element!(View);
view_element.key();
view_element.print();
view_element.eprint();
(&mut view_element).key();
(&mut view_element).print();
(&mut view_element).eprint();
#[cfg(unix)]
view_element.write_to_raw_fd(std::io::stdout()).unwrap();
let mut any_element: AnyElement<'static> = view_element.into_any();
any_element.key();
any_element.print();
any_element.eprint();
(&mut any_element).key();
(&mut any_element).print();
(&mut any_element).eprint();
let mut view_element = element!(View);
let mut any_element_ref: AnyElement = (&mut view_element).into();
any_element_ref.print();
any_element_ref.eprint();
}
#[test]
fn test_render_loop_future() {
fn assert_send<F: Future + Send>(_f: F) {}
let mut element = element!(View);
let render_loop_future = element.render_loop();
assert_send(render_loop_future);
}
}