summaryrefslogtreecommitdiffstats
path: root/src/ui.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/ui.rs75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/ui.rs b/src/ui.rs
new file mode 100644
index 0000000..13440b2
--- /dev/null
+++ b/src/ui.rs
@@ -0,0 +1,75 @@
1use std::io::{IsTerminal, Write};
2use std::time::Duration;
3
4use crate::provider::{Outcome, Sink};
5
6pub fn stdout_is_tty() -> bool {
7 std::io::stdout().is_terminal()
8}
9
10/// Streams to stdout. Colour is used only when stdout is a terminal, so piping
11/// the output somewhere gives clean text.
12pub struct Renderer {
13 color: bool,
14 dimmed: bool,
15 wrote_text: bool,
16}
17
18impl Renderer {
19 pub fn new(color: bool) -> Self {
20 Self {
21 color,
22 dimmed: false,
23 wrote_text: false,
24 }
25 }
26
27 fn undim(&mut self) {
28 if self.dimmed {
29 print!("\x1b[0m");
30 self.dimmed = false;
31 }
32 }
33}
34
35impl Sink for Renderer {
36 fn text(&mut self, s: &str) {
37 self.undim();
38 print!("{s}");
39 let _ = std::io::stdout().flush();
40 self.wrote_text = true;
41 }
42
43 fn reasoning(&mut self, s: &str) {
44 if !self.color {
45 return;
46 }
47 if !self.dimmed {
48 print!("\x1b[2m");
49 self.dimmed = true;
50 }
51 print!("{s}");
52 let _ = std::io::stdout().flush();
53 }
54
55 fn done(&mut self, outcome: &Outcome, elapsed: Duration) {
56 self.undim();
57 if self.wrote_text {
58 println!();
59 }
60 let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())];
61 if let Some(usage) = &outcome.usage {
62 let input = usage.get("prompt_tokens").and_then(|v| v.as_u64());
63 let output = usage.get("completion_tokens").and_then(|v| v.as_u64());
64 if let (Some(i), Some(o)) = (input, output) {
65 parts.push(format!("{i} in · {o} out"));
66 }
67 }
68 let line = format!("─ {}", parts.join(" · "));
69 if self.color {
70 println!("\x1b[2m{line}\x1b[0m");
71 } else {
72 println!("{line}");
73 }
74 }
75}