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
use crate::cmd::{Cmd, CmdResult};
use crate::event::Event;
use crate::model::Model;
use crate::renderer::Renderer;
use crate::terminal::{Terminal, TerminalOptions};
use crossterm::event::EventStream;
use futures_util::StreamExt;
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::mpsc;
pub struct ProgramBuilder<M: Model> {
model: M,
alt_screen: bool,
mouse_support: bool,
fps: u32,
}
impl<M: Model> ProgramBuilder<M>
where
M::Msg: From<Event>,
{
pub fn new(model: M) -> Self {
Self {
model,
alt_screen: true,
mouse_support: false,
fps: 60,
}
}
pub fn with_alt_screen(mut self) -> Self {
self.alt_screen = true;
self
}
pub fn without_alt_screen(mut self) -> Self {
self.alt_screen = false;
self
}
pub fn with_mouse_support(mut self) -> Self {
self.mouse_support = true;
self
}
pub fn with_fps(mut self, fps: u32) -> Self {
self.fps = fps.clamp(1, 120);
self
}
pub async fn run(self) -> io::Result<()> {
Program::run_inner(
self.model,
TerminalOptions {
alt_screen: self.alt_screen,
mouse_support: self.mouse_support,
raw_mode: true,
},
self.fps,
)
.await
}
}
pub struct Program;
impl Program {
pub async fn run<M: Model>(model: M) -> io::Result<()>
where
M::Msg: From<Event>,
{
Self::run_inner(model, TerminalOptions::default(), 60).await
}
async fn run_inner<M: Model>(mut model: M, options: TerminalOptions, fps: u32) -> io::Result<()>
where
M::Msg: From<Event>,
{
let mut terminal = Terminal::new(&options)?;
terminal.enter()?;
let (msg_tx, mut msg_rx) = mpsc::unbounded_channel::<M::Msg>();
let quit_flag = Arc::new(AtomicBool::new(false));
if let Some(cmd) = model.init() {
Self::dispatch_cmd(cmd, msg_tx.clone(), quit_flag.clone());
}
let mut event_stream = EventStream::new();
let mut renderer = Renderer::new(fps);
let view = model.view();
renderer.render(&mut terminal, &view)?;
// Place the cursor on the first frame too, so the input is focused
// immediately (not only after the first key event).
match model.cursor() {
Some((col, row)) => terminal.show_cursor_at(col, row)?,
None => terminal.hide_cursor()?,
}
loop {
if quit_flag.load(Ordering::Relaxed) {
break;
}
// Terminal events (keystrokes) render immediately for responsive
// input echo; internal messages (e.g. streaming deltas) stay
// frame-throttled to avoid flicker.
let mut immediate = false;
tokio::select! {
event = event_stream.next() => {
match event {
Some(Ok(ct_event)) => {
immediate = true;
// A resize shifts every row — force a full clear+redraw.
if matches!(ct_event, crossterm::event::Event::Resize(_, _)) {
renderer.invalidate();
}
let ev: Event = ct_event.into();
let msg: M::Msg = ev.into();
if let Some(cmd) = model.update(msg) {
Self::dispatch_cmd(cmd, msg_tx.clone(), quit_flag.clone());
}
}
Some(Err(_)) => break,
None => break,
}
}
Some(msg) = msg_rx.recv() => {
if let Some(cmd) = model.update(msg) {
Self::dispatch_cmd(cmd, msg_tx.clone(), quit_flag.clone());
}
}
}
if quit_flag.load(Ordering::Relaxed) {
break;
}
let view = model.view();
if immediate {
renderer.render(&mut terminal, &view)?;
} else {
renderer.render_if_changed(&mut terminal, &view)?;
}
// Place the real terminal cursor at the model's insertion point (or
// hide it). Done after rendering so it sits on top of the content.
match model.cursor() {
Some((col, row)) => terminal.show_cursor_at(col, row)?,
None => terminal.hide_cursor()?,
}
}
terminal.exit()?;
std::mem::forget(terminal);
Ok(())
}
fn dispatch_cmd<M: Send + 'static>(
cmd: Cmd<M>,
tx: mpsc::UnboundedSender<M>,
quit: Arc<AtomicBool>,
) {
tokio::spawn(async move {
let result = cmd.await;
match result {
CmdResult::Quit => {
quit.store(true, Ordering::Relaxed);
}
CmdResult::Msg(m) => {
let _ = tx.send(m);
}
CmdResult::Batch(cmds) => {
for c in cmds {
let tx2 = tx.clone();
let quit2 = quit.clone();
tokio::spawn(async move {
let r = c.await;
match r {
CmdResult::Quit => {
quit2.store(true, Ordering::Relaxed);
}
CmdResult::Msg(m) => {
let _ = tx2.send(m);
}
CmdResult::Batch(inner_cmds) => {
for ic in inner_cmds {
let tx3 = tx2.clone();
let quit3 = quit2.clone();
tokio::spawn(async move {
let r = ic.await;
match r {
CmdResult::Quit => {
quit3.store(true, Ordering::Relaxed);
}
CmdResult::Msg(m) => {
let _ = tx3.send(m);
}
_ => {}
}
});
}
}
CmdResult::None => {}
}
});
}
}
CmdResult::None => {}
}
});
}
}