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
//! FileProxy: Redirect writes to a Console.
//!
//! Port of Python Rich's `rich/file_proxy.py`.
//!
//! FileProxy wraps a writer (e.g., stdout) and redirects writes to a Console,
//! using AnsiDecoder to parse ANSI sequences from input. It implements line
//! buffering - accumulating input until a newline, then printing via Console.
use std::io::{self, Stdout, Write};
use crate::ansi::AnsiDecoder;
use crate::text::Text;
use crate::{Console, ConsoleOptions};
/// Wraps a writer (e.g., stdout) and redirects writes to a Console.
///
/// FileProxy buffers input until a newline is encountered, then decodes
/// ANSI escape sequences and prints the result via the Console.
///
/// # Type Parameters
///
/// * `C` - The writer type for the Console (e.g., `Stdout` or `Vec<u8>`).
/// * `W` - The inner writer type to wrap.
///
/// # Example
///
/// ```no_run
/// use rich_rs::{Console, ConsoleOptions};
/// use rich_rs::file_proxy::FileProxy;
/// use std::io::Write;
///
/// let console = Console::new();
/// let mut proxy = FileProxy::new(console, std::io::stdout());
///
/// // Writes are buffered until newline
/// write!(proxy, "Hello, ").unwrap();
/// writeln!(proxy, "World!").unwrap(); // Prints "Hello, World!" via Console
/// ```
pub struct FileProxy<C: Write, W: Write> {
/// The Console to redirect output to.
console: Console<C>,
/// The inner writer (for passthrough operations like fileno).
inner: W,
/// Line buffer - accumulates text until newline.
buffer: String,
/// ANSI decoder for parsing escape sequences.
decoder: AnsiDecoder,
}
impl<W: Write> FileProxy<Stdout, W> {
/// Create a new FileProxy with a stdout Console.
///
/// # Arguments
///
/// * `console` - The Console to redirect output to.
/// * `inner` - The inner writer to wrap.
pub fn new(console: Console<Stdout>, inner: W) -> Self {
Self {
console,
inner,
buffer: String::new(),
decoder: AnsiDecoder::new(),
}
}
/// Create a new FileProxy with custom console options.
pub fn with_options(options: ConsoleOptions, inner: W) -> Self {
Self {
console: Console::with_options(options),
inner,
buffer: String::new(),
decoder: AnsiDecoder::new(),
}
}
}
impl<C: Write, W: Write> FileProxy<C, W> {
/// Create a new FileProxy with a generic Console.
///
/// # Arguments
///
/// * `console` - The Console to redirect output to.
/// * `inner` - The inner writer to wrap.
pub fn with_console(console: Console<C>, inner: W) -> Self {
Self {
console,
inner,
buffer: String::new(),
decoder: AnsiDecoder::new(),
}
}
/// Get a reference to the inner writer.
pub fn inner(&self) -> &W {
&self.inner
}
/// Get a mutable reference to the inner writer.
pub fn inner_mut(&mut self) -> &mut W {
&mut self.inner
}
/// Get a reference to the console.
pub fn console(&self) -> &Console<C> {
&self.console
}
/// Get a mutable reference to the console.
pub fn console_mut(&mut self) -> &mut Console<C> {
&mut self.console
}
/// Consume the FileProxy and return the inner writer.
pub fn into_inner(self) -> W {
self.inner
}
/// Process buffered content and print complete lines.
fn process_text(&mut self, text: &str) -> io::Result<()> {
let mut remaining = text;
let mut lines: Vec<String> = Vec::new();
while !remaining.is_empty() {
if let Some(newline_pos) = remaining.find('\n') {
// Found a newline - complete the current line
let line_part = &remaining[..newline_pos];
let complete_line = if self.buffer.is_empty() {
line_part.to_string()
} else {
let mut line = std::mem::take(&mut self.buffer);
line.push_str(line_part);
line
};
lines.push(complete_line);
remaining = &remaining[newline_pos + 1..];
} else {
// No newline - buffer the remaining text
self.buffer.push_str(remaining);
break;
}
}
// Print complete lines via Console
if !lines.is_empty() {
// Decode ANSI sequences and join with newlines
let decoded_texts: Vec<Text> = lines
.iter()
.map(|line| self.decoder.decode_line(line))
.collect();
// Join texts with newlines
let mut output = Text::new();
for (i, text) in decoded_texts.into_iter().enumerate() {
if i > 0 {
output.append("\n".to_string(), None);
}
output.append_text(&text);
}
self.console
.print(&output, None, None, None, false, "\n")
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
}
Ok(())
}
}
impl<C: Write, W: Write> Write for FileProxy<C, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Convert bytes to string (lossy for non-UTF8)
let text = String::from_utf8_lossy(buf);
self.process_text(&text)?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
// Flush any remaining buffered content
if !self.buffer.is_empty() {
let buffered = std::mem::take(&mut self.buffer);
let decoded = self.decoder.decode_line(&buffered);
self.console
.print(&decoded, None, None, None, false, "\n")
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn test_file_proxy_basic_write() {
let console = Console::capture();
let inner = Vec::<u8>::new();
let mut proxy = FileProxy::with_console(console, inner);
writeln!(proxy, "Hello, World!").unwrap();
proxy.flush().unwrap();
// The output goes to console, not inner
let console_output = proxy.console().get_captured();
assert!(console_output.contains("Hello"));
assert!(console_output.contains("World"));
}
#[test]
fn test_file_proxy_line_buffering() {
let console = Console::capture();
let inner = Vec::<u8>::new();
let mut proxy = FileProxy::with_console(console, inner);
// Write without newline - should buffer
write!(proxy, "Hello, ").unwrap();
assert!(proxy.console().get_captured().is_empty());
// Write with newline - should flush buffer
writeln!(proxy, "World!").unwrap();
let output = proxy.console().get_captured();
assert!(output.contains("Hello"));
assert!(output.contains("World"));
}
#[test]
fn test_file_proxy_ansi_decoding() {
let console = Console::capture();
let inner = Vec::<u8>::new();
let mut proxy = FileProxy::with_console(console, inner);
// Write text with ANSI bold
writeln!(proxy, "\x1b[1mBold\x1b[0m Normal").unwrap();
let output = proxy.console().get_captured();
assert!(output.contains("Bold"));
assert!(output.contains("Normal"));
}
#[test]
fn test_file_proxy_multiple_lines() {
let console = Console::capture();
let inner = Vec::<u8>::new();
let mut proxy = FileProxy::with_console(console, inner);
writeln!(proxy, "Line 1").unwrap();
writeln!(proxy, "Line 2").unwrap();
writeln!(proxy, "Line 3").unwrap();
let output = proxy.console().get_captured();
assert!(output.contains("Line 1"));
assert!(output.contains("Line 2"));
assert!(output.contains("Line 3"));
}
#[test]
fn test_file_proxy_flush_partial_line() {
let console = Console::capture();
let inner = Vec::<u8>::new();
let mut proxy = FileProxy::with_console(console, inner);
// Write without newline
write!(proxy, "Partial").unwrap();
assert!(proxy.console().get_captured().is_empty());
// Explicit flush should print the partial line
proxy.flush().unwrap();
let output = proxy.console().get_captured();
assert!(output.contains("Partial"));
}
#[test]
fn test_file_proxy_inner_access() {
let console = Console::capture();
let inner = Vec::<u8>::new();
let mut proxy = FileProxy::with_console(console, inner);
// Inner should be accessible
assert!(proxy.inner().is_empty());
proxy.inner_mut().push(42);
assert_eq!(proxy.inner().len(), 1);
let inner = proxy.into_inner();
assert_eq!(inner, vec![42]);
}
}