Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_core/src/term/line.rs

20.8 KiB, 181 runs

created by r1870400018:77040, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Lines typed at a terminal, read beside other work, with output printed above the prompt.
2//!
3//! The terminal stays in its ordinary cooked mode, so its own line editing (erase, word erase,
4//! kill, reprint) works and nothing need be restored if the program dies. The cost is that the
5//! text of a line is the terminal's until Enter is pressed: [`LineReader::print`] clears the
6//! prompt line, writes its text and draws the prompt again, but cannot draw again what was
7//! partly typed. That text is still held by the terminal, Enter still sends it, and the
8//! terminal's reprint key (Ctrl-R, where `stty` has `rprnt` set) shows it once more.
9//!
10//! The lines are read by a thread of their own, which blocks on its input, and handed over a
11//! bounded flume channel, so an asynchronous caller awaits [`LineReader::next`] under any
12//! executor, in `select!` beside its other work, a runtime that ends need not wait for the read,
13//! and input the caller has not taken stays where it came from once [`LineLimits`] is reached.
14//! Ctrl-C is heard, when asked for, through tokio's `signal` module on one more thread for the
15//! whole process, with a runtime of its own, as `stop.rs` hears it, so the caller's runtime needs
16//! no signal driver and this crate keeps `#![forbid(unsafe_code)]`. It reaches a reader on a
17//! channel apart from the lines, and is given before any line that waits.
18
19use crate::{
20 prelude::*,
21 channels::{
22 bounded,
23 Receiver,
24 Sender,
25 },
26};
27
28use std::{
29 future::Future,
30 io::{
31 BufRead,
32 IsTerminal,
33 Read,
34 Stdout,
35 Write,
36 },
37 pin::Pin,
38 sync::{
39 atomic::{
40 AtomicUsize,
41 Ordering,
42 },
43 mpsc,
44 Arc,
45 Mutex,
46 },
47 task::Poll,
48 thread,
49};
50
51const CLEAR_LINE: &str = "\r\x1b[K"; // fixed: ECMA-48 carriage return, then erase in line
52
53// What a process ended by Ctrl-C leaves behind it.
54#[cfg(windows)]
55const INT_EXIT: i32 = 0xC000_013A_u32 as i32; // fixed: STATUS_CONTROL_C_EXIT
56#[cfg(not(windows))]
57const INT_EXIT: i32 = 130; // fixed: 128 + SIGINT, as a shell reports it
58
59// The readers hearing interrupts, `None` until the one listener of the process is in place.
60static HEARERS: Mutex<Option<Vec<Hearer>>> = Mutex::new(None);
61
62/// What the person at the terminal did.
63#[derive(Clone, Debug, Eq, PartialEq)]
64pub enum LineEvent {
65 Line(String), // an entry, its continuation lines joined by '\n'
66 Interrupt, // Ctrl-C, which the terminal answers by discarding what was typed
67 End, // end of input, Ctrl-D on an empty line at a terminal
68}
69
70/// How much input a reader may hold, which the caller takes from its configuration.
71#[derive(Clone, Copy, Debug, Eq, PartialEq)]
72pub struct LineLimits {
73 pub ahead: usize, // lines held before the caller takes one, and one more the thread waits to send
74 pub len: usize, // bytes in one line without its ending; a longer one fails the read
75}
76
77/// What a reader hears, a line or the end from the reading thread, or an interrupt.
78enum Heard {
79 Line(String, bool), // and whether the line was ended, as Enter ends it
80 End,
81 Interrupt,
82 Failed(Error<ErrTag>),
83}
84
85/// How far the input had been read when Ctrl-C came, so that the entry it discards is the one
86/// being made then and not one made since.
87#[derive(Default)]
88struct Mark {
89 read: AtomicUsize, // lines taken from the input
90 cut: AtomicUsize, // of those, the lines taken before the last interrupt
91}
92
93/// A reader's place in [`HEARERS`].
94struct Hearer {
95 tx: Sender<()>,
96 mark: Arc<Mark>,
97}
98
99/// Reads entries from a terminal, or any line input, without holding up an asynchronous caller.
100///
101/// A line ending in a backslash continues the entry on the next line; the backslash is dropped
102/// and the lines are joined by '\n', so an entry cannot itself end in a backslash. Input ending
103/// part way through an entry gives the entry as it stands, then the end.
104pub struct LineReader<W: Write> {
105 rx: Receiver<Heard>,
106 ints: Option<Receiver<()>>, // interrupts, once they are heard
107 mark: Arc<Mark>,
108 out: W,
109 prompt: String,
110 cont: String, // the prompt for a continuation line
111 prompting: bool, // are prompts drawn at all?
112 echo: bool, // a terminal shows on `out` what is typed
113 up: bool, // the caller has the prompt up
114 drawn: bool, // the current line holds the prompt, or the terminal's ^C
115 midline: bool, // the current line holds output, or an echo, that has not ended
116 partial: String, // an entry continued with a trailing backslash
117 seen: usize, // lines taken from the channel
118 cut: usize, // the line count at which an interrupted entry ends
119 ended: bool, // the input has ended
120 told: bool, // the end has been given to the caller
121}
122
123impl LineReader<Stdout> {
124
125 /// Reads standard input and writes to standard output, hearing Ctrl-C as
126 /// [`LineEvent::Interrupt`] rather than as the end of the process. Prompts are drawn only
127 /// when both are a terminal, so piped input reads the same way unprompted. The prompt is
128 /// written as given, so styling codes in it work. The reading thread holds the lock on
129 /// standard input for the life of the process.
130 pub fn stdio(prompt: &str, limits: LineLimits) -> Outcome<Self> {
131 let tty = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
132 let r = res!(Self::start(|| std::io::stdin().lock(), std::io::stdout(), prompt, limits,
133 tty, tty));
134 r.hear_interrupts()
135 }
136}
137
138impl<W: Write> LineReader<W> {
139
140 /// Reads `input` on a thread of its own and draws prompts and output on `out`. The prompt is
141 /// written as given, so styling codes in it work. Nothing is taken to echo the input onto
142 /// `out`, so an entry leaves the prompt where it stood.
143 pub fn new<R: BufRead + Send + 'static>(
144 input: R,
145 out: W,
146 prompt: &str,
147 limits: LineLimits,
148 )
149 -> Outcome<Self>
150 {
151 Self::start(move || input, out, prompt, limits, true, false)
152 }
153
154 /// `open` gives the input inside the reading thread, since a lock on standard input cannot
155 /// be sent to it.
156 fn start<R, F>(
157 open: F,
158 out: W,
159 prompt: &str,
160 limits: LineLimits,
161 prompting: bool,
162 echo: bool,
163 )
164 -> Outcome<Self>
165 where
166 R: BufRead,
167 F: FnOnce() -> R + Send + 'static,
168 {
169 let (tx, rx) = bounded(limits.ahead);
170 let mark = Arc::new(Mark::default());
171 let mark2 = mark.clone();
172 let _reader = res!(thread::Builder::new()
173 .name("fe2o3-line".to_string())
174 .spawn(move || read(open(), tx, mark2, limits.len)), Thread, Init);
175 Ok(Self {
176 rx,
177 ints: None,
178 mark,
179 out,
180 prompt: prompt.to_string(),
181 cont: String::new(),
182 prompting,
183 echo,
184 up: false,
185 drawn: false,
186 midline: false,
187 partial: String::new(),
188 seen: 0,
189 cut: 0,
190 ended: false,
191 told: false,
192 })
193 }
194
195 /// Sets the prompt drawn for a continuation line, by default none.
196 pub fn continuation(mut self, prompt: &str) -> Self {
197 self.cont = prompt.to_string();
198 self
199 }
200
201 /// Hears Ctrl-C (`SIGINT`) as [`LineEvent::Interrupt`] for as long as the reader lives. The
202 /// listener is in place when this returns, one to a process however many readers hear.
203 /// Presses not yet taken count as one. A signal handler cannot be taken back without
204 /// `unsafe`, so when Ctrl-C comes and no hearing reader is left the listener ends the process
205 /// itself with the status a shell reports for the default action (130), unless a
206 /// [`crate::stop::on_stop_request`] listener is installed, which then answers it alone.
207 pub fn hear_interrupts(mut self) -> Outcome<Self> {
208 if self.ints.is_some() {
209 return Ok(self);
210 }
211 let (tx, rx) = bounded(1); // fixed: an interrupt is pending or it is not
212 let mut hearers = lock_mutex!(HEARERS);
213 let mut list = match hearers.take() {
214 Some(list) => list,
215 None => {
216 res!(start_listener());
217 Vec::new()
218 },
219 };
220 list.retain(|h| !h.tx.is_disconnected());
221 list.push(Hearer { tx, mark: self.mark.clone() });
222 *hearers = Some(list);
223 self.ints = Some(rx);
224 Ok(self)
225 }
226
227 /// Waits for the next entry, interrupt or end of input, an interrupt before any entry that
228 /// waits. Cancel-safe: a call dropped part way, as a `select!` arm not taken is, loses
229 /// nothing. After the end, or a failed read, a further call gives the end again, or waits
230 /// for an interrupt while interrupts are heard.
231 pub async fn next(&mut self) -> Outcome<LineEvent> {
232 loop {
233 if self.ended && (!self.told || self.ints.is_none()) {
234 self.told = true;
235 return Ok(LineEvent::End);
236 }
237 match self.hear().await {
238 Heard::Line(line, entered) => {
239 self.seen = self.seen.wrapping_add(1);
240 if self.echo {
241 // Enter has taken the terminal to a fresh line; input ending part way
242 // along one has left it there.
243 self.drawn = false;
244 self.midline = !entered;
245 }
246 let entry = match line.strip_suffix('\\') {
247 Some(head) => {
248 self.partial.push_str(head);
249 self.partial.push('\n');
250 None
251 },
252 None => {
253 let mut entry = std::mem::take(&mut self.partial);
254 entry.push_str(&line);
255 Some(entry)
256 },
257 };
258 if self.seen == self.cut {
259 // What is still being made was begun before the interrupt.
260 self.partial.clear();
261 }
262 match entry {
263 Some(entry) => {
264 self.up = false;
265 return Ok(LineEvent::Line(entry));
266 },
267 None => if self.up {
268 res!(self.draw());
269 },
270 }
271 },
272 Heard::Interrupt => {
273 self.interrupted();
274 return Ok(LineEvent::Interrupt);
275 },
276 Heard::End => {
277 self.ended = true;
278 self.up = false;
279 if !self.partial.is_empty() {
280 let mut entry = std::mem::take(&mut self.partial);
281 entry.pop();
282 return Ok(LineEvent::Line(entry));
283 }
284 },
285 Heard::Failed(e) => {
286 self.ended = true;
287 self.up = false;
288 return Err(e);
289 },
290 }
291 }
292 }
293
294 /// Waits for Ctrl-C alone, so a caller can hold its input and still be interrupted. Lines
295 /// typed meanwhile are kept for [`Self::next`] up to one more than [`LineLimits::ahead`];
296 /// the rest wait unread at the terminal, which discards them on Ctrl-C.
297 pub async fn interrupt(&mut self) -> Outcome<()> {
298 let got = match &self.ints {
299 Some(rx) => rx.recv_async().await,
300 None => return Err(err!(
301 "This reader does not hear interrupts: call hear_interrupts first.";
302 Missing, Init)),
303 };
304 res!(got, Channel, Read);
305 self.interrupted();
306 Ok(())
307 }
308
309 /// Puts the prompt up, on a line of its own, until an entry is made or [`Self::hide`].
310 pub fn prompt(&mut self) -> Outcome<()> {
311 if self.up && self.drawn {
312 return Ok(());
313 }
314 self.up = true;
315 self.draw()
316 }
317
318 /// Changes the prompt, drawing the new one in place of one that is up. A continuation
319 /// line keeps its own prompt.
320 pub fn set_prompt(&mut self, prompt: &str) -> Outcome<()> {
321 if self.prompt == prompt {
322 return Ok(());
323 }
324 self.prompt = prompt.to_string();
325 if self.up && self.drawn && self.partial.is_empty() {
326 return self.draw();
327 }
328 Ok(())
329 }
330
331 /// Takes the prompt down, clearing its line.
332 pub fn hide(&mut self) -> Outcome<()> {
333 self.up = false;
334 if self.drawn {
335 self.drawn = false;
336 res!(self.out.write_all(CLEAR_LINE.as_bytes()), IO, Output, Write);
337 res!(self.out.flush(), IO, Output, Write);
338 }
339 Ok(())
340 }
341
342 /// Writes `text` above the prompt, which is drawn again below it once the text ends its
343 /// line. Text that does not end its line, as streamed output may not, is continued by the
344 /// next call.
345 pub fn print(&mut self, text: &str) -> Outcome<()> {
346 self.write(text, false)
347 }
348
349 /// As [`Self::print`], but on a fresh line: a line left part way along is ended first. With
350 /// no text it does only that.
351 pub fn print_fresh(&mut self, text: &str) -> Outcome<()> {
352 self.write(text, true)
353 }
354
355 /// Does the current line hold output, or an echoed entry, that has not ended?
356 pub fn midline(&self) -> bool {
357 self.midline
358 }
359
360 fn write(&mut self, text: &str, fresh: bool) -> Outcome<()> {
361 let end = fresh && self.midline;
362 if text.is_empty() && !end {
363 return Ok(());
364 }
365 if self.drawn {
366 self.drawn = false;
367 res!(self.out.write_all(CLEAR_LINE.as_bytes()), IO, Output, Write);
368 }
369 if end {
370 res!(self.out.write_all(b"\n"), IO, Output, Write);
371 self.midline = false;
372 }
373 if !text.is_empty() {
374 res!(self.out.write_all(text.as_bytes()), IO, Output, Write);
375 self.midline = !text.ends_with('\n');
376 }
377 if self.up && !self.midline {
378 return self.draw();
379 }
380 res!(self.out.flush(), IO, Output, Write);
381 Ok(())
382 }
383
384 /// Draws the prompt, or the continuation prompt part way through an entry.
385 fn draw(&mut self) -> Outcome<()> {
386 if !self.prompting {
387 return Ok(());
388 }
389 if self.drawn {
390 res!(self.out.write_all(CLEAR_LINE.as_bytes()), IO, Output, Write);
391 }
392 if self.midline {
393 res!(self.out.write_all(b"\n"), IO, Output, Write);
394 self.midline = false;
395 }
396 let p = if self.partial.is_empty() { &self.prompt } else { &self.cont };
397 res!(self.out.write_all(p.as_bytes()), IO, Output, Write);
398 res!(self.out.flush(), IO, Output, Write);
399 self.drawn = true;
400 Ok(())
401 }
402
403 /// The next thing heard, an interrupt before a line however many lines wait.
404 async fn hear(&mut self) -> Heard {
405 let mut int = self.ints.as_ref().map(|rx| rx.recv_async());
406 let mut line = if self.ended { None } else { Some(self.rx.recv_async()) };
407 std::future::poll_fn(|cx| {
408 match int.as_mut().map(|f| Pin::new(f).poll(cx)) {
409 Some(Poll::Ready(Ok(()))) => return Poll::Ready(Heard::Interrupt),
410 Some(Poll::Ready(Err(_))) => int = None,
411 Some(Poll::Pending) | None => (),
412 }
413 match line.as_mut() {
414 // The thread says when it ends, so a channel closed without a word is its panic.
415 Some(f) => Pin::new(f).poll(cx).map(|h| h.unwrap_or(Heard::End)),
416 None => Poll::Pending,
417 }
418 }).await
419 }
420
421 fn interrupted(&mut self) {
422 self.cut = self.mark.cut.load(Ordering::SeqCst);
423 // With lines read before the interrupt still waiting, the entry it discards may have been
424 // finished by them; reaching `cut` in next() settles it. The counts wrap, as `seen` does.
425 if (self.cut.wrapping_sub(self.seen) as isize) <= 0 {
426 self.partial.clear();
427 }
428 self.up = false;
429 // The terminal has written ^C where the cursor was.
430 self.drawn = self.prompting && !self.midline;
431 }
432}
433
434/// The reading thread's whole life: a line at a time until the input ends or nobody listens,
435/// waiting whenever the caller is `LineLimits::ahead` lines behind.
436fn read<R: BufRead>(mut input: R, tx: Sender<Heard>, mark: Arc<Mark>, max: usize) {
437 loop {
438 let heard = match read_line(&mut input, max) {
439 Ok(Some((line, entered))) => {
440 mark.read.fetch_add(1, Ordering::SeqCst);
441 Heard::Line(line, entered)
442 },
443 Ok(None) => Heard::End,
444 Err(e) => Heard::Failed(e),
445 };
446 let last = !matches!(heard, Heard::Line(..));
447 if tx.send(heard).is_err() || last {
448 return;
449 }
450 }
451}
452
453/// One line without its ending, and whether it had one, or `None` at the end of input. Bytes
454/// that are not UTF-8 are replaced rather than refused, so one stray byte does not end the input.
455fn read_line<R: BufRead>(input: &mut R, max: usize) -> Outcome<Option<(String, bool)>> {
456 let mut buf = Vec::new();
457 let most = (max as u64).saturating_add(2); // fixed: room for "\r\n"
458 if res!(input.take(most).read_until(b'\n', &mut buf), IO, Read) == 0 {
459 return Ok(None);
460 }
461 let entered = buf.last() == Some(&b'\n');
462 if entered {
463 buf.pop();
464 if buf.last() == Some(&b'\r') {
465 buf.pop();
466 }
467 }
468 if buf.len() > max {
469 return Err(err!("A line of input is longer than the {} bytes allowed.", max;
470 Input, TooBig));
471 }
472 Ok(Some((String::from_utf8_lossy(&buf).into_owned(), entered)))
473}
474
475/// Starts the interrupt listener and waits until it is in place.
476fn start_listener() -> Outcome<()> {
477 let (ready_tx, ready_rx) = mpsc::channel();
478 let _listener = res!(thread::Builder::new()
479 .name("fe2o3-line-int".to_string())
480 .spawn(move || listen(ready_tx)), Thread, Init);
481 match ready_rx.recv() {
482 Ok(ready) => ready,
483 Err(e) => Err(err!(e,
484 "The interrupt listener ended before it was in place."; Thread, Init)),
485 }
486}
487
488/// Tells every reader still hearing. With none left the process ends here, as the default
489/// action would have ended it, unless the stop listener is there to answer.
490fn tell() {
491 let mut hearers = lock_mutex_or_recover!(HEARERS);
492 let list = hearers.get_or_insert_with(Vec::new);
493 list.retain(|h| !h.tx.is_disconnected());
494 if list.is_empty() {
495 if crate::stop::listening() {
496 return;
497 }
498 std::process::exit(INT_EXIT);
499 }
500 for h in list.iter() {
501 h.mark.cut.store(h.mark.read.load(Ordering::SeqCst), Ordering::SeqCst);
502 let _ = h.tx.try_send(());
503 }
504}
505
506/// The interrupt listener's whole life, on a runtime of its own, saying when it is in place.
507fn listen(ready: mpsc::Sender<Outcome<()>>) {
508 let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
509 Ok(rt) => rt,
510 Err(e) => {
511 let _ = ready.send(Err(err!(e,
512 "Building the interrupt listener's runtime."; Init, System)));
513 return;
514 },
515 };
516 rt.block_on(interrupts(ready));
517}
518
519#[cfg(unix)]
520async fn interrupts(ready: mpsc::Sender<Outcome<()>>) {
521 use tokio::signal::unix::{
522 signal,
523 SignalKind,
524 };
525 let mut int = match signal(SignalKind::interrupt()) {
526 Ok(s) => s,
527 Err(e) => {
528 let _ = ready.send(Err(err!(e, "Listening for SIGINT."; Init, System)));
529 return;
530 },
531 };
532 let _ = ready.send(Ok(()));
533 while int.recv().await.is_some() {
534 tell();
535 }
536}
537
538#[cfg(windows)]
539async fn interrupts(ready: mpsc::Sender<Outcome<()>>) {
540 let mut int = match tokio::signal::windows::ctrl_c() {
541 Ok(s) => s,
542 Err(e) => {
543 let _ = ready.send(Err(err!(e, "Listening for Ctrl-C."; Init, System)));
544 return;
545 },
546 };
547 let _ = ready.send(Ok(()));
548 while int.recv().await.is_some() {
549 tell();
550 }
551}
552
553#[cfg(not(any(unix, windows)))]
554async fn interrupts(ready: mpsc::Sender<Outcome<()>>) {
555 let _ = ready.send(Ok(()));
556 while tokio::signal::ctrl_c().await.is_ok() {
557 tell();
558 }
559}