Base: codex-main originale (prima del fork aKode)
This commit is contained in:
71
codex-rs/tui/src/ui_tree/decode.rs
Normal file
71
codex-rs/tui/src/ui_tree/decode.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
//! Enforce the input byte limit before parsing and the UI tree limits after deserialization.
|
||||
|
||||
use super::MAX_GAP;
|
||||
use super::MAX_TEXT_BYTES;
|
||||
use super::UiNode;
|
||||
use super::UiTree;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::de::Error;
|
||||
use serde::de::IntoDeserializer;
|
||||
|
||||
impl std::str::FromStr for UiTree {
|
||||
type Err = serde_json::Error;
|
||||
|
||||
fn from_str(text: &str) -> Result<Self, Self::Err> {
|
||||
if text.len() > 64 * 1024 {
|
||||
return Err(Self::Err::custom("UI tree JSON exceeds 64 KiB"));
|
||||
}
|
||||
let root: Option<UiNode> = serde_json::from_str(text)?;
|
||||
let mut pending: Vec<_> = root.iter().map(|node| (node, 0)).collect();
|
||||
let mut nodes = 0;
|
||||
let mut text_bytes = 0;
|
||||
while let Some((node, depth)) = pending.pop() {
|
||||
if depth > 16 {
|
||||
return Err(Self::Err::custom("UI tree exceeds maximum depth 16"));
|
||||
}
|
||||
nodes += 1;
|
||||
if nodes > 256 {
|
||||
return Err(Self::Err::custom("UI tree exceeds 256 non-null nodes"));
|
||||
}
|
||||
match node {
|
||||
UiNode::String(text) => {
|
||||
text_bytes += text.len();
|
||||
if text_bytes > MAX_TEXT_BYTES {
|
||||
return Err(Self::Err::custom("UI tree exceeds 16 KiB of text"));
|
||||
}
|
||||
}
|
||||
UiNode::Text { children, .. }
|
||||
| UiNode::Bold { children }
|
||||
| UiNode::Italic { children }
|
||||
| UiNode::Underline { children }
|
||||
| UiNode::Link { children, .. }
|
||||
| UiNode::Row { children, .. } => {
|
||||
pending.extend(children.iter().flatten().map(|child| (child, depth + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self(root))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn optional_token<'de, D: Deserializer<'de>, T: DeserializeOwned>(
|
||||
d: D,
|
||||
) -> Result<Option<T>, D::Error> {
|
||||
Option::<String>::deserialize(d)?
|
||||
.map(|s| T::deserialize(s.into_deserializer()))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn token<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<T, D::Error> {
|
||||
T::deserialize(String::deserialize(d)?.into_deserializer())
|
||||
}
|
||||
|
||||
pub(super) fn gap<'de, D: Deserializer<'de>>(de: D) -> Result<u64, D::Error> {
|
||||
let gap = u64::deserialize(de)?;
|
||||
if gap > MAX_GAP {
|
||||
return Err(D::Error::custom("gap exceeds the maximum safe integer"));
|
||||
}
|
||||
Ok(gap)
|
||||
}
|
||||
352
codex-rs/tui/src/ui_tree/render.rs
Normal file
352
codex-rs/tui/src/ui_tree/render.rs
Normal file
@@ -0,0 +1,352 @@
|
||||
//! Lay out prepared text and nested rows within a terminal viewport.
|
||||
|
||||
mod prepare;
|
||||
mod text;
|
||||
|
||||
use self::prepare::NodeKind;
|
||||
use self::prepare::PreparedNode;
|
||||
use self::text::Chunk;
|
||||
use self::text::Paint;
|
||||
use self::text::visit_chunks;
|
||||
use super::MAX_TEXT_BYTES;
|
||||
use super::RowWrap;
|
||||
use super::TextProps;
|
||||
use super::TextWeight;
|
||||
use super::UiTree;
|
||||
use super::theme::RenderTheme;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::TerminalHyperlink;
|
||||
use crate::terminal_hyperlinks::mark_hyperlink_cells;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::layout::Size;
|
||||
use ratatui::style::Modifier;
|
||||
use ratatui::text::Span;
|
||||
use std::ops::Range;
|
||||
use syntect::highlighting::Theme;
|
||||
use vtparse::CollectingVTActor;
|
||||
use vtparse::VTAction;
|
||||
use vtparse::VTParser;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct PreparedUiTree(Option<PreparedNode>);
|
||||
|
||||
impl UiTree {
|
||||
pub(crate) fn prepare(self) -> PreparedUiTree {
|
||||
PreparedUiTree(
|
||||
self.0
|
||||
.and_then(|node| PreparedNode::from_node(node, Paint::default())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PreparedUiTree {
|
||||
pub(crate) fn measure_natural(&self) -> Size {
|
||||
self.0.as_ref().map_or_else(Size::default, |node| {
|
||||
let width = u16::try_from(node.widths.preferred).unwrap_or(u16::MAX);
|
||||
Size::new(width, node.natural_height)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn measure(&self, bounds: Size) -> Size {
|
||||
layout(self.0.as_ref(), bounds, /*draw*/ None)
|
||||
}
|
||||
|
||||
pub(crate) fn render(&self, area: Rect, theme: &Theme, buf: &mut Buffer) {
|
||||
let area = area.intersection(buf.area);
|
||||
let mut theme = RenderTheme::new(theme);
|
||||
layout(
|
||||
self.0.as_ref(),
|
||||
area.as_size(),
|
||||
Some(&mut |row, col, text, cells, paint| {
|
||||
let x = area.x + col as u16;
|
||||
let y = area.y + row as u16;
|
||||
buf.set_string(x, y, text, paint.style(&mut theme));
|
||||
if let Some(href) = &paint.href {
|
||||
mark_hyperlink_cells(buf, Rect::new(x, y, cells as u16, 1), href);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn render_line(&self, width: u16, theme: &Theme) -> HyperlinkLine {
|
||||
let natural = self.measure_natural();
|
||||
if width == 1 && (natural.width > 1 || natural.height > 1) {
|
||||
return ratatui::text::Line::from("…").into();
|
||||
}
|
||||
let mut line = HyperlinkLine::default();
|
||||
let mut theme = RenderTheme::new(theme);
|
||||
layout(
|
||||
self.0.as_ref(),
|
||||
Size::new(width, /*height*/ 1),
|
||||
Some(&mut |_, col, text, cells, paint| {
|
||||
line.line
|
||||
.push_span(Span::styled(text.to_owned(), paint.style(&mut theme)));
|
||||
if cells > 0
|
||||
&& let Some(href) = &paint.href
|
||||
{
|
||||
push_link(&mut line, col..col + cells, href);
|
||||
}
|
||||
}),
|
||||
);
|
||||
line
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Fragment<'a> {
|
||||
Text(&'a [Chunk], usize),
|
||||
Gap(usize, &'a Paint),
|
||||
}
|
||||
|
||||
impl<'a> Fragment<'a> {
|
||||
fn width(self) -> usize {
|
||||
match self {
|
||||
Self::Text(_, width) | Self::Gap(width, _) => width,
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(self, limit: usize, mut draw: impl FnMut(usize, &str, usize, &'a Paint)) -> usize {
|
||||
match self {
|
||||
Self::Text(chunks, _) => visit_chunks(chunks, limit, draw),
|
||||
Self::Gap(width, paint) => {
|
||||
const SPACES: &str = " ";
|
||||
let end = width.min(limit);
|
||||
for start in (0..end).step_by(SPACES.len()) {
|
||||
let n = (end - start).min(SPACES.len());
|
||||
draw(start, &SPACES[..n], n, paint);
|
||||
}
|
||||
end
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Visit<'a, 'b> = dyn FnMut(usize, Fragment<'a>) + 'b;
|
||||
|
||||
/// Only the fragment that reaches the right edge must wait until overflow is known.
|
||||
#[derive(Default)]
|
||||
struct Row<'a> {
|
||||
width: usize,
|
||||
edge: Option<(usize, Fragment<'a>)>,
|
||||
last_paint: Option<&'a Paint>,
|
||||
}
|
||||
|
||||
type Draw<'a> = dyn FnMut(usize, usize, &str, usize, &Paint) + 'a;
|
||||
|
||||
fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<'_>>) -> Size {
|
||||
let Some(root) = root else {
|
||||
return Size::default();
|
||||
};
|
||||
let width = usize::from(bounds.width);
|
||||
let height = usize::from(bounds.height);
|
||||
if width == 0 || height == 0 {
|
||||
return Size::default();
|
||||
}
|
||||
let mut rows = Vec::<Row>::new();
|
||||
let total = layout_node(root, width, height + 1, &mut |y, fragment| {
|
||||
if y >= height {
|
||||
return;
|
||||
}
|
||||
if rows.len() <= y {
|
||||
rows.resize_with(y + 1, Row::default);
|
||||
}
|
||||
let row = &mut rows[y];
|
||||
let start = row.width;
|
||||
row.width += fragment.width();
|
||||
if start < width {
|
||||
if row.width >= width {
|
||||
row.edge = Some((start, fragment));
|
||||
} else if let Some(draw) = draw.as_deref_mut() {
|
||||
fragment.visit(usize::MAX, |offset, text, cells, paint| {
|
||||
draw(y, start + offset, text, cells, paint);
|
||||
row.last_paint = Some(paint);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut measured = Size::new(0, total.min(height) as u16);
|
||||
for (y, row) in rows.into_iter().enumerate() {
|
||||
let clipped = row.width > width || (y + 1 == height && total > height);
|
||||
let mut end = row.width;
|
||||
let mut last_paint = row.last_paint;
|
||||
if clipped && width == 1 {
|
||||
end = 0;
|
||||
last_paint = None;
|
||||
} else if let Some((start, edge)) = row.edge
|
||||
&& (clipped || draw.is_some())
|
||||
{
|
||||
let limit = width - usize::from(clipped) - start;
|
||||
end = start
|
||||
+ edge.visit(limit, |offset, text, cells, paint| {
|
||||
if let Some(draw) = draw.as_deref_mut() {
|
||||
draw(y, start + offset, text, cells, paint);
|
||||
}
|
||||
last_paint = Some(paint);
|
||||
});
|
||||
}
|
||||
if clipped {
|
||||
if let Some(draw) = draw.as_deref_mut() {
|
||||
let mut paint = last_paint.cloned().unwrap_or_default();
|
||||
paint.href = None;
|
||||
draw(y, end, "…", 1, &paint);
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
measured.width = measured.width.max(end as u16);
|
||||
}
|
||||
measured
|
||||
}
|
||||
|
||||
fn layout_node<'a>(
|
||||
node: &'a PreparedNode,
|
||||
width: usize,
|
||||
limit: usize,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
match &node.kind {
|
||||
NodeKind::Text(text) => text.layout(width, limit, visit),
|
||||
NodeKind::Row {
|
||||
children,
|
||||
gap,
|
||||
wrap,
|
||||
paint,
|
||||
} => {
|
||||
let gap = (*gap).min((width + 1) as u64) as usize;
|
||||
let mut y = 0;
|
||||
let mut start = 0;
|
||||
let mut used = 0;
|
||||
for (i, child) in children.iter().enumerate() {
|
||||
let preferred = child.widths.preferred.min((width + 1) as u64) as usize;
|
||||
if *wrap == RowWrap::Wrap && i > start && used + gap + preferred > width {
|
||||
y += layout_band(
|
||||
&children[start..i],
|
||||
width,
|
||||
limit - y,
|
||||
gap,
|
||||
paint,
|
||||
&mut |row, part| visit(y + row, part),
|
||||
);
|
||||
if y == limit {
|
||||
return y;
|
||||
}
|
||||
start = i;
|
||||
used = 0;
|
||||
}
|
||||
if i > start {
|
||||
used += gap;
|
||||
}
|
||||
used += preferred;
|
||||
}
|
||||
y + layout_band(
|
||||
&children[start..],
|
||||
width,
|
||||
limit - y,
|
||||
gap,
|
||||
paint,
|
||||
&mut |row, part| visit(y + row, part),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn layout_band<'a>(
|
||||
children: &'a [PreparedNode],
|
||||
width: usize,
|
||||
limit: usize,
|
||||
gap: usize,
|
||||
paint: &'a Paint,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
let bounded = |cells: u64| cells.min((width + 1) as u64) as usize;
|
||||
let mut reserved = children
|
||||
.iter()
|
||||
.map(|c| bounded(c.widths.minimum))
|
||||
.sum::<usize>()
|
||||
+ gap * children.len().saturating_sub(1);
|
||||
let mut offset = 0usize;
|
||||
let mut ends = Vec::new();
|
||||
for child in children {
|
||||
let minimum = bounded(child.widths.minimum);
|
||||
reserved -= minimum;
|
||||
let available = bounded(child.widths.preferred)
|
||||
.min(width.saturating_sub(offset + reserved))
|
||||
.max(minimum);
|
||||
layout_node(child, available.clamp(1, width), limit, &mut |y, part| {
|
||||
if y >= ends.len() {
|
||||
ends.resize(y + 1, 0);
|
||||
}
|
||||
let end = &mut ends[y];
|
||||
let start = offset.min(width + 1);
|
||||
if start > *end {
|
||||
visit(y, Fragment::Gap(start - *end, paint));
|
||||
*end = start;
|
||||
}
|
||||
if offset <= width {
|
||||
visit(y, part);
|
||||
*end += part.width();
|
||||
}
|
||||
});
|
||||
offset += available + gap;
|
||||
reserved = reserved.saturating_sub(gap);
|
||||
}
|
||||
ends.len()
|
||||
}
|
||||
|
||||
fn sanitize_leaf(mut raw: String) -> String {
|
||||
// Directly constructed trees can bypass the wire decoder's text limit.
|
||||
if raw.len() > MAX_TEXT_BYTES {
|
||||
raw.truncate(raw.floor_char_boundary(MAX_TEXT_BYTES));
|
||||
raw.shrink_to_fit();
|
||||
}
|
||||
if raw
|
||||
.chars()
|
||||
.all(|ch| !ch.is_control() || matches!(ch, '\n' | '\t'))
|
||||
{
|
||||
return raw;
|
||||
}
|
||||
let mut actions = CollectingVTActor::default();
|
||||
VTParser::new().parse(raw.as_bytes(), &mut actions);
|
||||
actions
|
||||
.into_iter()
|
||||
.filter_map(|action| match action {
|
||||
VTAction::Print(ch) if !ch.is_control() => Some(ch),
|
||||
VTAction::ExecuteC0orC1(ch @ (b'\n' | b'\t')) => Some(char::from(ch)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_link(line: &mut HyperlinkLine, columns: Range<usize>, href: &str) {
|
||||
if let Some(last) = line.hyperlinks.last_mut()
|
||||
&& last.columns.end == columns.start
|
||||
&& last.destination == href
|
||||
{
|
||||
last.columns.end = columns.end;
|
||||
} else {
|
||||
line.hyperlinks
|
||||
.push(TerminalHyperlink::web(columns, href.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
impl TextProps {
|
||||
fn apply_to(&self, paint: &mut Paint) {
|
||||
if let Some(color) = self.color {
|
||||
paint.foreground = Some(color);
|
||||
}
|
||||
for (enabled, modifier) in [
|
||||
(
|
||||
self.weight.map(|weight| weight == TextWeight::Bold),
|
||||
Modifier::BOLD,
|
||||
),
|
||||
(self.italic, Modifier::ITALIC),
|
||||
(self.underline, Modifier::UNDERLINED),
|
||||
] {
|
||||
match enabled {
|
||||
Some(true) => paint.modifiers = paint.modifiers.add_modifier(modifier),
|
||||
Some(false) => paint.modifiers = paint.modifiers.remove_modifier(modifier),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
168
codex-rs/tui/src/ui_tree/render/prepare.rs
Normal file
168
codex-rs/tui/src/ui_tree/render/prepare.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
//! Prepare inline content and measure each row child before viewport layout.
|
||||
|
||||
use super::text::InlineText;
|
||||
use super::text::Paint;
|
||||
use super::text::PreparedText;
|
||||
use crate::ui_tree::RowWrap;
|
||||
use crate::ui_tree::UiNode;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct PreparedNode {
|
||||
pub(super) kind: NodeKind,
|
||||
pub(super) widths: Widths,
|
||||
pub(super) natural_height: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct Widths {
|
||||
pub(super) minimum: u64,
|
||||
pub(super) preferred: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) enum NodeKind {
|
||||
Text(PreparedText),
|
||||
Row {
|
||||
children: Vec<PreparedNode>,
|
||||
gap: u64,
|
||||
wrap: RowWrap,
|
||||
paint: Paint,
|
||||
},
|
||||
}
|
||||
|
||||
impl PreparedNode {
|
||||
pub(super) fn from_node(node: UiNode, paint: Paint) -> Option<Self> {
|
||||
let mut items = Vec::new();
|
||||
let mut inline = InlineText::default();
|
||||
Self::collect_inline(&mut items, &mut inline, node, paint.clone());
|
||||
items.extend(Self::text(inline));
|
||||
if items.len() <= 1 {
|
||||
items.pop()
|
||||
} else {
|
||||
Self::row(items, /*gap*/ 0, RowWrap::Nowrap, paint)
|
||||
}
|
||||
}
|
||||
|
||||
fn text(inline: InlineText) -> Option<Self> {
|
||||
let text = inline.finish();
|
||||
if text.lines.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut widths = Widths {
|
||||
minimum: 0,
|
||||
preferred: 0,
|
||||
};
|
||||
for line in &text.lines {
|
||||
let mut width = 0;
|
||||
for chunk in line {
|
||||
let cells = chunk.width_cells as u64;
|
||||
widths.minimum = widths.minimum.max(cells);
|
||||
width += cells + u64::from(chunk.trailing_space.is_some());
|
||||
}
|
||||
widths.preferred = widths.preferred.max(width);
|
||||
}
|
||||
Some(Self {
|
||||
natural_height: u16::try_from(text.lines.len()).unwrap_or(u16::MAX),
|
||||
kind: NodeKind::Text(text),
|
||||
widths,
|
||||
})
|
||||
}
|
||||
|
||||
fn row(mut children: Vec<Self>, gap: u64, wrap: RowWrap, paint: Paint) -> Option<Self> {
|
||||
children.retain(|child| {
|
||||
child.widths.preferred > 0
|
||||
|| match &child.kind {
|
||||
NodeKind::Row { .. } => true,
|
||||
NodeKind::Text(text) => text.has_authored_break,
|
||||
}
|
||||
});
|
||||
if children.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let gaps = gap.saturating_mul(children.len() as u64 - 1);
|
||||
let widths = Widths {
|
||||
minimum: match wrap {
|
||||
RowWrap::Nowrap => children
|
||||
.iter()
|
||||
.fold(gaps, |w, c| w.saturating_add(c.widths.minimum)),
|
||||
RowWrap::Wrap => children
|
||||
.iter()
|
||||
.map(|c| c.widths.minimum)
|
||||
.max()
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
preferred: children
|
||||
.iter()
|
||||
.fold(gaps, |w, c| w.saturating_add(c.widths.preferred)),
|
||||
};
|
||||
Some(Self {
|
||||
widths,
|
||||
natural_height: children
|
||||
.iter()
|
||||
.map(|child| child.natural_height)
|
||||
.max()
|
||||
.unwrap_or_default(),
|
||||
kind: NodeKind::Row {
|
||||
children,
|
||||
gap,
|
||||
wrap,
|
||||
paint,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_inline(
|
||||
items: &mut Vec<Self>,
|
||||
inline: &mut InlineText,
|
||||
node: UiNode,
|
||||
mut paint: Paint,
|
||||
) {
|
||||
let children = match node {
|
||||
UiNode::String(raw) => {
|
||||
inline.push_leaf(raw, paint);
|
||||
return;
|
||||
}
|
||||
UiNode::Row { props, children } => {
|
||||
items.extend(Self::text(std::mem::take(inline)));
|
||||
if let Some(color) = props.background {
|
||||
paint.background = Some(color);
|
||||
}
|
||||
let children = children
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|node| Self::from_node(node, paint.clone()))
|
||||
.collect();
|
||||
items.extend(Self::row(children, props.gap, props.wrap, paint));
|
||||
return;
|
||||
}
|
||||
UiNode::Text { props, children } => {
|
||||
props.apply_to(&mut paint);
|
||||
children
|
||||
}
|
||||
UiNode::Link { props, children } => {
|
||||
paint.href = Some(props.href.0.into());
|
||||
paint.modifiers = paint.modifiers.underlined();
|
||||
children
|
||||
}
|
||||
UiNode::Bold { children } => {
|
||||
paint.modifiers = paint.modifiers.bold();
|
||||
children
|
||||
}
|
||||
UiNode::Italic { children } => {
|
||||
paint.modifiers = paint.modifiers.italic();
|
||||
children
|
||||
}
|
||||
UiNode::Underline { children } => {
|
||||
paint.modifiers = paint.modifiers.underlined();
|
||||
children
|
||||
}
|
||||
};
|
||||
for node in children.into_iter().flatten() {
|
||||
Self::collect_inline(items, inline, node, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "prepare_tests.rs"]
|
||||
mod tests;
|
||||
20
codex-rs/tui/src/ui_tree/render/prepare_tests.rs
Normal file
20
codex-rs/tui/src/ui_tree/render/prepare_tests.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::Paint;
|
||||
use super::PreparedNode;
|
||||
use crate::ui_tree::UiNode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_row_measures_whole_children_and_intervening_gaps() {
|
||||
let node: UiNode = serde_json::from_value(json!({
|
||||
"type": "row", "props": { "gap": 2 }, "children": [
|
||||
{"type":"text","children":[{"type":"bold","children":["bu"]},"ild ready"]}, // codespell:ignore bu
|
||||
null, "", "\u{301}\n", {"type":"row","props":{"gap":1},"children":["中","PR\u{a0}2"]}
|
||||
]
|
||||
}))
|
||||
.unwrap();
|
||||
let node = PreparedNode::from_node(node, Paint::default()).unwrap();
|
||||
assert_eq!((node.widths.minimum, node.widths.preferred), (16, 22));
|
||||
}
|
||||
397
codex-rs/tui/src/ui_tree/render/text.rs
Normal file
397
codex-rs/tui/src/ui_tree/render/text.rs
Normal file
@@ -0,0 +1,397 @@
|
||||
//! Prepared inline text retains styled chunks and their legal line breaks across leaves.
|
||||
|
||||
use super::Fragment;
|
||||
use super::RenderTheme;
|
||||
use super::Visit;
|
||||
use super::sanitize_leaf;
|
||||
use crate::line_truncation::span_width;
|
||||
use crate::ui_tree::theme::Color;
|
||||
use ratatui::buffer::CellWidth;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::text::Span;
|
||||
use std::ops::Deref;
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
use unicode_linebreak::linebreaks;
|
||||
use unicode_linebreak::split_at_safe;
|
||||
use unicode_segmentation::GraphemeCursor;
|
||||
use unicode_segmentation::GraphemeIncomplete;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct Paint {
|
||||
pub(super) modifiers: Style,
|
||||
pub(super) foreground: Option<Color>,
|
||||
pub(super) background: Option<Color>,
|
||||
pub(super) href: Option<Arc<String>>,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
pub(super) fn style(&self, theme: &mut RenderTheme<'_>) -> Style {
|
||||
let mut style = self.modifiers;
|
||||
style.fg = self.foreground.map(|c| theme.resolve(c));
|
||||
style.bg = self.background.map(|c| theme.resolve(c));
|
||||
style
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Run {
|
||||
text: RunText,
|
||||
paint: Paint,
|
||||
}
|
||||
|
||||
// Splitting a leaf at style, whitespace or wrap boundaries shares its original buffer.
|
||||
#[derive(Debug)]
|
||||
enum RunText {
|
||||
Slice(Arc<String>, Range<usize>),
|
||||
Space,
|
||||
}
|
||||
|
||||
impl RunText {
|
||||
fn new(text: String) -> Self {
|
||||
let len = text.len();
|
||||
Self::Slice(Arc::new(text), 0..len)
|
||||
}
|
||||
|
||||
fn slice(&self, range: Range<usize>) -> Self {
|
||||
match self {
|
||||
Self::Slice(text, bytes) => Self::Slice(
|
||||
Arc::clone(text),
|
||||
bytes.start + range.start..bytes.start + range.end,
|
||||
),
|
||||
Self::Space => Self::Space,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for RunText {
|
||||
type Target = str;
|
||||
|
||||
fn deref(&self) -> &str {
|
||||
match self {
|
||||
Self::Slice(text, bytes) => &text[bytes.clone()],
|
||||
Self::Space => " ",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for RunText {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
**self == **other
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(super) struct Chunk {
|
||||
runs: Vec<Run>,
|
||||
pub(super) width_cells: usize,
|
||||
pub(super) trailing_space: Option<Paint>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(super) struct PreparedText {
|
||||
pub(super) has_authored_break: bool,
|
||||
pub(super) lines: Vec<Vec<Chunk>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct InlineText {
|
||||
text: PreparedText,
|
||||
line: Vec<Run>,
|
||||
space: Option<Paint>,
|
||||
}
|
||||
|
||||
impl InlineText {
|
||||
pub(super) fn push_leaf(&mut self, raw: String, paint: Paint) {
|
||||
let text = RunText::new(sanitize_leaf(raw));
|
||||
let mut start = 0;
|
||||
for (end, ch) in text
|
||||
.match_indices([' ', '\t', '\n'])
|
||||
.chain(std::iter::once((text.len(), "")))
|
||||
{
|
||||
if start < end {
|
||||
if let Some(paint) = self.space.take() {
|
||||
self.line.push(Run {
|
||||
text: RunText::Space,
|
||||
paint,
|
||||
});
|
||||
}
|
||||
self.line.push(Run {
|
||||
text: text.slice(start..end),
|
||||
paint: paint.clone(),
|
||||
});
|
||||
}
|
||||
if ch == "\n" {
|
||||
self.text.lines.push(chunks(std::mem::take(&mut self.line)));
|
||||
self.space = None;
|
||||
} else if !ch.is_empty() && !self.line.is_empty() {
|
||||
self.space.get_or_insert_with(|| paint.clone());
|
||||
}
|
||||
start = end + ch.len();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish(mut self) -> PreparedText {
|
||||
self.text.has_authored_break = !self.text.lines.is_empty();
|
||||
if !self.line.is_empty() {
|
||||
self.text.lines.push(chunks(self.line));
|
||||
}
|
||||
self.text
|
||||
}
|
||||
}
|
||||
|
||||
// Most seams already fall between graphemes. Only a cluster that actually crosses a
|
||||
// seam needs contiguous storage, including when it spans more than two leaves.
|
||||
fn join_graphemes(runs: Vec<Run>) -> Vec<Run> {
|
||||
let mut runs = runs.into_iter().peekable();
|
||||
let mut joined = Vec::new();
|
||||
while let Some(run) = runs.next() {
|
||||
let Some(next) = runs.peek() else {
|
||||
joined.push(run);
|
||||
break;
|
||||
};
|
||||
if run.text.as_bytes().last().is_some_and(u8::is_ascii)
|
||||
&& next.text.as_bytes()[0].is_ascii()
|
||||
{
|
||||
joined.push(run);
|
||||
continue;
|
||||
}
|
||||
// Reverse segmentation in unicode-segmentation 1.12 disagrees on Indic conjuncts.
|
||||
#[expect(clippy::double_ended_iterator_last)]
|
||||
let Some(tail) = run.text.graphemes(true).last() else {
|
||||
continue;
|
||||
};
|
||||
let split = tail.len();
|
||||
let mut cursor = GraphemeCursor::new(split, usize::MAX, true);
|
||||
while let Err(GraphemeIncomplete::PreContext(_)) = cursor.is_boundary(&next.text, split) {
|
||||
cursor.provide_context(tail, 0);
|
||||
}
|
||||
if cursor.is_boundary(&next.text, split) == Ok(true) {
|
||||
joined.push(run);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut cluster = tail.to_owned();
|
||||
let mut paint = run.paint;
|
||||
let prefix = run.text.len() - split;
|
||||
if prefix > 0 {
|
||||
joined.push(Run {
|
||||
text: run.text.slice(0..prefix),
|
||||
paint: paint.clone(),
|
||||
});
|
||||
}
|
||||
// Resume in the growing cluster so even a long chain of combining marks
|
||||
// advances once per character and Unicode lookbehind stays available.
|
||||
let mut cursor = GraphemeCursor::new(0, usize::MAX, true);
|
||||
let _ = cursor.next_boundary(&cluster, 0);
|
||||
while let Some(next) = runs.peek_mut() {
|
||||
let mut consumed = 0;
|
||||
for ch in next.text.chars() {
|
||||
cluster.push(ch);
|
||||
if cursor.next_boundary(&cluster, 0).is_ok() {
|
||||
cluster.pop();
|
||||
break;
|
||||
}
|
||||
consumed += ch.len_utf8();
|
||||
}
|
||||
if consumed > 0 && paint.href != next.paint.href {
|
||||
paint.href = None;
|
||||
}
|
||||
if consumed < next.text.len() {
|
||||
if consumed > 0 {
|
||||
next.text = next.text.slice(consumed..next.text.len());
|
||||
}
|
||||
break;
|
||||
}
|
||||
runs.next();
|
||||
}
|
||||
joined.push(Run {
|
||||
text: RunText::new(cluster),
|
||||
paint,
|
||||
});
|
||||
}
|
||||
joined
|
||||
}
|
||||
|
||||
// Keep the context needed for breaks across style boundaries.
|
||||
fn break_offsets<'a>(runs: impl Iterator<Item = &'a str>) -> Vec<usize> {
|
||||
let mut runs = runs.peekable();
|
||||
let mut breaks = Vec::new();
|
||||
let mut scratch = String::new();
|
||||
let mut base = 0;
|
||||
while let Some(&run) = runs.peek() {
|
||||
let scanned = scratch.len();
|
||||
let window = if scanned == 0 {
|
||||
runs.next();
|
||||
run
|
||||
} else {
|
||||
// Match the retained context with fresh bytes to keep rescanning linear.
|
||||
// Bound each read so a short prefix never pulls a large ASCII run into scratch.
|
||||
while scratch.len() - scanned < scanned
|
||||
&& let Some(next) = runs.peek_mut()
|
||||
{
|
||||
let (part, rest) = next.split_at(next.floor_char_boundary(scanned.max(128)));
|
||||
scratch.push_str(part);
|
||||
*next = rest;
|
||||
runs.next_if(|s| s.is_empty());
|
||||
}
|
||||
scratch.as_str()
|
||||
};
|
||||
breaks.extend(
|
||||
linebreaks(window)
|
||||
.filter_map(|(i, _)| (i >= scanned && i < window.len()).then_some(base + i)),
|
||||
);
|
||||
if runs.peek().is_none() {
|
||||
break;
|
||||
}
|
||||
let discard = split_at_safe(window).0.len();
|
||||
base += discard;
|
||||
if scanned == 0 {
|
||||
scratch.push_str(&run[discard..]);
|
||||
} else {
|
||||
scratch.drain(..discard);
|
||||
}
|
||||
}
|
||||
breaks
|
||||
}
|
||||
|
||||
fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
|
||||
let runs = join_graphemes(runs);
|
||||
let mut breaks = break_offsets(runs.iter().map(|run| run.text.as_ref()))
|
||||
.into_iter()
|
||||
.peekable();
|
||||
let mut out = Vec::new();
|
||||
let mut chunk = Chunk::default();
|
||||
let mut offset = 0;
|
||||
let mut previous = None;
|
||||
let mut word_hyphen = false;
|
||||
for run in runs {
|
||||
let mut start = 0;
|
||||
for (i, grapheme) in run.text.grapheme_indices(true) {
|
||||
let position = offset + i;
|
||||
while breaks.next_if(|b| *b < position).is_some() {}
|
||||
// Match textwrap's default hyphen splitter, even across style boundaries.
|
||||
let can_break = match previous {
|
||||
Some('-') => word_hyphen && grapheme.starts_with(char::is_alphanumeric),
|
||||
Some('\u{ad}') => false,
|
||||
_ => breaks.peek() == Some(&position),
|
||||
};
|
||||
if can_break {
|
||||
chunk.push(&run, start..i);
|
||||
if chunk.runs.last().is_some_and(|r| &*r.text == " ") {
|
||||
chunk.trailing_space = chunk.runs.pop().map(|r| r.paint);
|
||||
chunk.width_cells -= 1;
|
||||
}
|
||||
if !chunk.runs.is_empty() {
|
||||
out.push(std::mem::take(&mut chunk));
|
||||
}
|
||||
start = i;
|
||||
}
|
||||
for ch in grapheme.chars() {
|
||||
word_hyphen = ch == '-' && previous.is_some_and(char::is_alphanumeric);
|
||||
previous = Some(ch);
|
||||
}
|
||||
}
|
||||
chunk.push(&run, start..run.text.len());
|
||||
offset += run.text.len();
|
||||
}
|
||||
if !chunk.runs.is_empty() {
|
||||
out.push(chunk);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
fn push(&mut self, run: &Run, range: Range<usize>) {
|
||||
if !range.is_empty() {
|
||||
let text = run.text.slice(range);
|
||||
self.width_cells += span_width(&Span::raw(&*text));
|
||||
self.runs.push(Run {
|
||||
text,
|
||||
paint: run.paint.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PreparedText {
|
||||
pub(super) fn layout<'a>(
|
||||
&'a self,
|
||||
width: usize,
|
||||
limit: usize,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
let mut y = 0;
|
||||
for line in &self.lines {
|
||||
let mut start = 0;
|
||||
let mut used = 0;
|
||||
let mut space = 0;
|
||||
for (i, chunk) in line.iter().enumerate() {
|
||||
if i > start && used + space + chunk.width_cells > width {
|
||||
visit(y, Fragment::Text(&line[start..i], used));
|
||||
y += 1;
|
||||
if y == limit {
|
||||
return y;
|
||||
}
|
||||
start = i;
|
||||
used = 0;
|
||||
space = 0;
|
||||
}
|
||||
used += space + chunk.width_cells;
|
||||
space = usize::from(chunk.trailing_space.is_some());
|
||||
}
|
||||
visit(y, Fragment::Text(&line[start..], used));
|
||||
y += 1;
|
||||
if y == limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn visit_chunks<'a>(
|
||||
chunks: &'a [Chunk],
|
||||
limit: usize,
|
||||
mut draw: impl FnMut(usize, &str, usize, &'a Paint),
|
||||
) -> usize {
|
||||
let mut used = 0;
|
||||
|
||||
for (index, chunk) in chunks.iter().enumerate() {
|
||||
for run in &chunk.runs {
|
||||
let text = &*run.text;
|
||||
let mut bytes = 0;
|
||||
let mut cells = 0;
|
||||
for g in text.graphemes(true) {
|
||||
let w = usize::from(g.cell_width());
|
||||
if used + cells + w > limit {
|
||||
break;
|
||||
}
|
||||
cells += w;
|
||||
bytes += g.len();
|
||||
}
|
||||
if bytes > 0 && (used < limit || bytes == text.len()) {
|
||||
draw(used, &text[..bytes], cells, &run.paint);
|
||||
}
|
||||
used += cells;
|
||||
if bytes < text.len() {
|
||||
return used;
|
||||
}
|
||||
}
|
||||
if index + 1 < chunks.len()
|
||||
&& let Some(paint) = &chunk.trailing_space
|
||||
{
|
||||
if used == limit {
|
||||
return used;
|
||||
}
|
||||
draw(used, " ", 1, paint);
|
||||
used += 1;
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "text_tests.rs"]
|
||||
mod tests;
|
||||
34
codex-rs/tui/src/ui_tree/render/text_tests.rs
Normal file
34
codex-rs/tui/src/ui_tree/render/text_tests.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use unicode_linebreak::linebreaks;
|
||||
|
||||
#[test]
|
||||
fn styled_runs_have_the_same_breaks_as_contiguous_text() {
|
||||
let long = "中日".repeat(200);
|
||||
let runs = ["bu", "ild (", " ready)", "— ", "—"] // codespell:ignore bu
|
||||
.into_iter()
|
||||
.chain(std::iter::repeat_n("🇨", 79))
|
||||
.chain([long.as_str(), " done"]);
|
||||
let text: String = runs.clone().collect();
|
||||
let expected: Vec<_> = linebreaks(&text).map(|(i, _)| i).collect();
|
||||
assert_eq!(super::break_offsets(runs), expected[..expected.len() - 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_of_a_clean_leaf_share_its_original_buffer() {
|
||||
let leaf = String::from("build ready");
|
||||
let start = leaf.as_ptr();
|
||||
let mut inline = super::InlineText::default();
|
||||
inline.push_leaf(leaf, super::Paint::default());
|
||||
let prepared = inline.finish();
|
||||
let runs: Vec<_> = prepared.lines[0]
|
||||
.iter()
|
||||
.map(|chunk| &*chunk.runs[0].text)
|
||||
.collect();
|
||||
assert_eq!(runs, ["build", "ready"]);
|
||||
assert_eq!(
|
||||
[runs[0].as_ptr(), runs[1].as_ptr()],
|
||||
[start, start.wrapping_add(6)]
|
||||
);
|
||||
}
|
||||
154
codex-rs/tui/src/ui_tree/theme.rs
Normal file
154
codex-rs/tui/src/ui_tree/theme.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
//! Resolve typed wire colors against the active theme and terminal palette.
|
||||
|
||||
use ratatui::style::Color as TerminalColor;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::bottom_pane::StatusLineAccent;
|
||||
use crate::render::highlight;
|
||||
use crate::terminal_palette;
|
||||
use crate::terminal_palette::StdoutColorLevel;
|
||||
use std::cell::OnceCell;
|
||||
use std::collections::HashMap;
|
||||
use syntect::highlighting::Highlighter;
|
||||
use syntect::highlighting::Theme;
|
||||
use syntect::parsing::Scope;
|
||||
|
||||
pub(super) struct RenderTheme<'a> {
|
||||
theme: &'a Theme,
|
||||
highlighter: OnceCell<Highlighter<'a>>,
|
||||
resolved: HashMap<Color, TerminalColor>,
|
||||
}
|
||||
|
||||
impl<'a> RenderTheme<'a> {
|
||||
pub(super) fn new(theme: &'a Theme) -> Self {
|
||||
Self {
|
||||
theme,
|
||||
highlighter: OnceCell::new(),
|
||||
resolved: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// A color can occur on many chunks. Match its theme scopes once per paint.
|
||||
pub(super) fn resolve(&mut self, color: Color) -> TerminalColor {
|
||||
if let Some(&resolved) = self.resolved.get(&color) {
|
||||
return resolved;
|
||||
}
|
||||
let resolved = color.resolve(self);
|
||||
self.resolved.insert(color, resolved);
|
||||
resolved
|
||||
}
|
||||
|
||||
// Plain text and literal colors need no TextMate scope matching.
|
||||
fn highlighter(&self) -> &Highlighter<'a> {
|
||||
self.highlighter
|
||||
.get_or_init(|| Highlighter::new(self.theme))
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal_color(color: Option<TerminalColor>, fallback: TerminalColor) -> TerminalColor {
|
||||
let Some(color) = color else { return fallback };
|
||||
let level = terminal_palette::effective_stdout_color_level();
|
||||
match (level, color) {
|
||||
(
|
||||
StdoutColorLevel::Ansi16 | StdoutColorLevel::Unknown,
|
||||
TerminalColor::Rgb(..) | TerminalColor::Indexed(16..),
|
||||
) => fallback,
|
||||
(_, TerminalColor::Rgb(r, g, b)) => {
|
||||
terminal_palette::best_color_for_level((r, g, b), level)
|
||||
}
|
||||
_ => color,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub(super) enum Color {
|
||||
Primary,
|
||||
Surface,
|
||||
Accent,
|
||||
Black,
|
||||
Red,
|
||||
Green,
|
||||
Yellow,
|
||||
Blue,
|
||||
Magenta,
|
||||
Cyan,
|
||||
White,
|
||||
#[serde(untagged)]
|
||||
Status(StatusLineAccent),
|
||||
#[serde(untagged)]
|
||||
Rgb(HexRgb),
|
||||
}
|
||||
|
||||
impl Color {
|
||||
fn resolve(self, palette: &RenderTheme<'_>) -> TerminalColor {
|
||||
let setting = |color: Option<syntect::highlighting::Color>| {
|
||||
terminal_color(
|
||||
color.and_then(highlight::convert_syntect_color),
|
||||
TerminalColor::Reset,
|
||||
)
|
||||
};
|
||||
match self {
|
||||
Self::Primary => setting(palette.theme.settings.foreground),
|
||||
Self::Surface => setting(palette.theme.settings.background),
|
||||
Self::Accent => setting(
|
||||
Scope::new("codex.accent")
|
||||
.ok()
|
||||
.and_then(|scope| {
|
||||
palette
|
||||
.highlighter()
|
||||
.style_mod_for_stack(&[scope])
|
||||
.foreground
|
||||
})
|
||||
.or(palette.theme.settings.accent),
|
||||
),
|
||||
Self::Status(role) => terminal_color(
|
||||
highlight::foreground_color_for_scopes(palette.highlighter(), role.scopes()),
|
||||
role.fallback_color(),
|
||||
),
|
||||
Self::Rgb(rgb) => terminal_palette::best_color(rgb.0),
|
||||
Self::Black => TerminalColor::Black,
|
||||
Self::Red => TerminalColor::Red,
|
||||
Self::Green => TerminalColor::Green,
|
||||
Self::Yellow => TerminalColor::Yellow,
|
||||
Self::Blue => TerminalColor::Blue,
|
||||
Self::Magenta => TerminalColor::Magenta,
|
||||
Self::Cyan => TerminalColor::Cyan,
|
||||
// Ratatui maps Gray to ANSI slot 7 and White to slot 15.
|
||||
Self::White => TerminalColor::Gray,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "String", into = "String")]
|
||||
pub(super) struct HexRgb((u8, u8, u8));
|
||||
|
||||
impl TryFrom<String> for HexRgb {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(source: String) -> Result<Self, Self::Error> {
|
||||
const INVALID: &str = "expected #RRGGBB";
|
||||
if source.len() != 7 {
|
||||
return Err(INVALID);
|
||||
}
|
||||
let color = source
|
||||
.parse::<syntect::highlighting::Color>()
|
||||
.map_err(|_| INVALID)?;
|
||||
Ok(Self((color.r, color.g, color.b)))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HexRgb> for String {
|
||||
fn from(HexRgb((r, g, b)): HexRgb) -> Self {
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub(super) enum TextWeight {
|
||||
Normal,
|
||||
Bold,
|
||||
}
|
||||
Reference in New Issue
Block a user