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
//! In-place live rendering.
//!
//! Port of `rich/live_render.py`. A [`LiveRender`] wraps a renderable, remembers
//! the shape (width × height) of its last render, and produces the terminal
//! control sequences to move the cursor back over that render — the mechanism a
//! `Live` display uses to redraw in place. The full `Live` loop (threading,
//! timing, stdout management) is deferred; this is its byte-parity-testable core.
//!
//! Content taller than the screen is cropped, ended with an ellipsis line
//! (the default) or left visible, per [`VerticalOverflow`].
use std::cell::Cell;
use crate::console::{Console, ConsoleOptions, Justify, Overflow};
use crate::control::{Control, ControlType};
use crate::protocol::Renderable;
use crate::segment::Segment;
use crate::style::Style;
use crate::text::Text;
/// What a live render does with content taller than the screen. Mirrors
/// upstream's `VerticalOverflowMethod`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalOverflow {
/// Keep only the lines that fit.
Crop,
/// Keep all but the last line that fits, then a centred `...` line in
/// `live.ellipsis` (upstream's default).
#[default]
Ellipsis,
/// Render every line.
Visible,
}
/// Wraps a renderable for repeated in-place redraws. Mirrors
/// `rich.live_render.LiveRender`.
pub struct LiveRender {
renderable: Box<dyn Renderable>,
style: Option<Style>,
vertical_overflow: VerticalOverflow,
/// `(width, height)` of the last render, or `None` before the first.
shape: Cell<Option<(usize, usize)>>,
}
impl LiveRender {
pub fn new(renderable: Box<dyn Renderable>) -> Self {
LiveRender {
renderable,
style: None,
vertical_overflow: VerticalOverflow::Ellipsis,
shape: Cell::new(None),
}
}
/// Apply a style across the whole live render.
pub fn style(mut self, style: Style) -> Self {
self.style = Some(style);
self
}
/// What to do with content taller than the screen (upstream
/// `vertical_overflow`, default [`VerticalOverflow::Ellipsis`]).
pub fn vertical_overflow(mut self, vertical_overflow: VerticalOverflow) -> Self {
self.vertical_overflow = vertical_overflow;
self
}
/// Set [`vertical_overflow`](Self::vertical_overflow) in place.
pub fn set_vertical_overflow(&mut self, vertical_overflow: VerticalOverflow) {
self.vertical_overflow = vertical_overflow;
}
/// Replace the wrapped renderable (the shape carries over until the next
/// render). Port of `LiveRender.set_renderable`.
pub fn set_renderable(&mut self, renderable: Box<dyn Renderable>) {
self.renderable = renderable;
}
/// The height of the last render, `0` before any. Port of
/// `LiveRender.last_render_height`.
pub fn last_render_height(&self) -> usize {
self.shape.get().map_or(0, |(_, height)| height)
}
/// Control codes to move the cursor to the start of the previous render,
/// erasing each line. Port of `LiveRender.position_cursor`.
pub fn position_cursor(&self) -> Control {
match self.shape.get() {
Some((_, height)) => {
let mut codes = vec![ControlType::CarriageReturn, ControlType::EraseInLine(2)];
for _ in 0..height.saturating_sub(1) {
codes.push(ControlType::CursorUp(1));
codes.push(ControlType::EraseInLine(2));
}
Control::new(&codes)
}
None => Control::new(&[]),
}
}
/// Control codes to clear the render and restore the cursor to where it was
/// before it. Port of `LiveRender.restore_cursor`.
pub fn restore_cursor(&self) -> Control {
match self.shape.get() {
Some((_, height)) => {
let mut codes = vec![ControlType::CarriageReturn];
for _ in 0..height {
codes.push(ControlType::CursorUp(1));
codes.push(ControlType::EraseInLine(2));
}
Control::new(&codes)
}
None => Control::new(&[]),
}
}
}
impl Renderable for LiveRender {
fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
// Render unpadded lines (`pad=False`), applying the live style if set.
let mut lines = console.render_lines(self.renderable.as_ref(), options, false);
if let Some(style) = &self.style {
for line in &mut lines {
*line = Segment::apply_style(line, style);
}
}
// Content taller than the screen (`options.size.height`).
let screen_height = options.size.height;
if lines.len() > screen_height {
match self.vertical_overflow {
VerticalOverflow::Crop => lines.truncate(screen_height),
VerticalOverflow::Ellipsis => {
// `lines[: height - 1]`: at height 0 that is Python's
// `lines[:-1]`, every line but the last.
let keep = screen_height
.checked_sub(1)
.unwrap_or_else(|| lines.len() - 1);
lines.truncate(keep);
let overflow_text = Text::styled("...", "live.ellipsis")
.overflow(Overflow::Crop)
.justify(Justify::Center);
lines.push(console.render(&overflow_text, None));
}
VerticalOverflow::Visible => {}
}
}
// Remember the shape for the next `position_cursor`/`restore_cursor`.
let height = lines.len();
let width = lines
.iter()
.map(|line| line.iter().map(Segment::cell_length).sum::<usize>())
.max()
.unwrap_or(0);
self.shape.set(Some((width, height)));
let mut segments = Vec::new();
let last = height.saturating_sub(1);
for (index, line) in lines.into_iter().enumerate() {
segments.extend(line);
if index != last {
segments.push(Segment::line());
}
}
segments
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::color::ColorSystem;
use crate::text::Text;
fn console() -> Console {
Console::builder()
.force_terminal(true)
.color_system(Some(ColorSystem::Truecolor))
.width(20)
.no_color(false)
.build()
}
#[test]
fn renders_content_and_control_codes() {
let live = LiveRender::new(Box::new(Text::new("line one\nline two\nline three")));
let console = console();
// Rendering sets the shape.
assert_eq!(
console.render_to_string(&live),
"line one\nline two\nline three"
);
// Captured from real rich 15.0.0 (height 3).
assert_eq!(
live.position_cursor().as_str(),
"\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K"
);
assert_eq!(
live.restore_cursor().as_str(),
"\r\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K"
);
}
#[test]
fn single_line_shape() {
let live = LiveRender::new(Box::new(Text::new("solo")));
let console = console();
assert_eq!(console.render_to_string(&live), "solo");
assert_eq!(live.position_cursor().as_str(), "\r\x1b[2K");
assert_eq!(live.restore_cursor().as_str(), "\r\x1b[1A\x1b[2K");
}
#[test]
fn no_control_before_first_render() {
let live = LiveRender::new(Box::new(Text::new("x")));
assert_eq!(live.position_cursor().as_str(), "");
assert_eq!(live.restore_cursor().as_str(), "");
}
}