Skip to main content

rich/
protocol.rs

1//! Rendering & extension protocols.
2//!
3//! Port of upstream `rich/protocol.py` + `rich/abc.py` + the highlighter
4//! interface. **These traits are the sanctioned extension points of the port.**
5//! Extensions in `rich-ext` (and, later, third-party plugins) implement them;
6//! the faithful core only ever ships upstream's built-in implementations. See
7//! docs/PLUGINS.md.
8
9use crate::console::{Console, ConsoleOptions};
10use crate::measure::Measurement;
11use crate::segment::Segment;
12use crate::text::Text;
13
14/// Anything that can be rendered to a stream of [`Segment`]s within a width.
15///
16/// The Rust equivalent of upstream's `__rich_console__(console, options)`
17/// protocol. Implement it to make a custom type printable by [`Console`]. The
18/// `options` carry the available width (and, later, height/justify) the
19/// renderable must fit into. Newlines between lines are emitted as ordinary
20/// segments containing `\n`.
21pub trait Renderable {
22    fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment>;
23
24    /// The `(minimum, maximum)` cell width this renderable wants. The default
25    /// assumes the renderable fills the available width (e.g. `Panel`, `Table`);
26    /// `Text` overrides it with its content width so the top-level print path can
27    /// shrink to fit. Port of `__rich_measure__` / `Measurement.get`.
28    fn measure(&self, _console: &Console, options: &ConsoleOptions) -> Measurement {
29        Measurement::new(options.max_width, options.max_width)
30    }
31
32    /// Whether a top-level `Console::print` shrinks this renderable to its
33    /// measured width. The shrink stands in for upstream's
34    /// `_collect_renderables`, which joins printed `str`/`Text` values; other
35    /// upstream renderables render at the full width, so one whose output pads
36    /// to the width it is given (`Syntax`'s background) returns `false`.
37    fn fit_to_measurement(&self) -> bool {
38        true
39    }
40}
41
42/// Optional line-streaming extension point for renderables.
43///
44/// Mirrors the incremental consumption of upstream's rendering generators.
45/// Consumers can write each visual line immediately instead of collecting the
46/// complete segment stream. Implementations may still retain source data for
47/// measurement. This trait keeps streaming hooks out of inherent core APIs.
48pub trait LineRenderable: Renderable {
49    /// Emit styled visual lines without trailing newlines, stopping immediately
50    /// on the callback's first error. An empty segment represents a blank line;
51    /// calling the callback zero times represents no output.
52    fn try_for_each_line<E>(
53        &self,
54        console: &Console,
55        options: &ConsoleOptions,
56        emit: impl FnMut(Vec<Segment>) -> Result<(), E>,
57    ) -> Result<(), E>;
58}
59
60/// Transfer already-owned table rows without cloning every cell string.
61///
62/// This extension point changes ownership only. Column definitions, measurement
63/// and rendering follow the table's existing rules, including missing/extra cells.
64/// Producers that parse into owned strings can release their row collection as
65/// they populate a table instead of retaining a second complete copy.
66pub trait OwnedTableRows {
67    fn extend_owned_rows(&mut self, rows: Vec<Vec<String>>) -> &mut Self;
68}
69
70/// A transformer that adds style spans to [`Text`] (e.g. syntax/number/URL
71/// highlighting). The Rust equivalent of upstream's `Highlighter` ABC.
72///
73/// This is the primary *plugin* seam for the first slice: `rich-ext` registers
74/// [`Highlighter`]s onto a [`Console`] without the core knowing they exist.
75pub trait Highlighter {
76    /// Inspect `text` and apply any style spans in place.
77    fn highlight(&self, text: &mut Text);
78}
79
80/// Evidence for an optional output protocol; inference is not confirmation.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum Support {
83    Unsupported,
84    Inferred,
85    Confirmed,
86}
87
88/// Immutable destination capabilities supplied by an extension. No detection or I/O.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct TargetCapabilities {
91    pub width: usize,
92    pub height: usize,
93    pub color_system: Option<crate::color::ColorSystem>,
94    pub interactive: bool,
95    pub unicode: bool,
96    pub hyperlinks: bool,
97    pub sixel: Support,
98}
99
100/// Optional context shared by nested renderables without changing their protocol.
101pub trait RenderEnvironment: Send + Sync {
102    fn capabilities(&self) -> TargetCapabilities;
103}
104
105/// Attach/query a per-console immutable extension environment.
106pub trait ConsoleEnvironment {
107    fn set_render_environment(&mut self, value: Option<std::sync::Arc<dyn RenderEnvironment>>);
108    fn render_environment(&self) -> Option<&dyn RenderEnvironment>;
109}