Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,52 @@
//! Compatibility coverage for bundled theme files and existing user overrides.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn model_theme_files_preserve_custom_precedence_and_invalid_file_warnings() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir(home.path().join("themes")).unwrap();
let path = custom_theme_path("ada", home.path());
std::fs::write(&path, model_themes::THEMES[1].1).unwrap();
assert_eq!(
resolve_theme_by_name("ada", Some(home.path())),
resolve_theme_by_name("babbage", /*codex_home*/ None)
);
let entries = list_available_themes(Some(home.path()));
let entries = entries
.iter()
.filter(|entry| entry.name == "ada")
.collect::<Vec<_>>();
assert_eq!(entries.len(), 1);
assert!(entries[0].is_custom);
let uppercase_path = custom_theme_path("Ada", home.path());
std::fs::rename(&path, &uppercase_path).unwrap();
let entries = list_available_themes(Some(home.path()));
let lowercase = entries.iter().find(|entry| entry.name == "ada").unwrap();
assert_eq!(lowercase.is_custom, path.exists());
assert!(
entries
.iter()
.any(|entry| entry.name == "Ada" && entry.is_custom)
);
std::fs::rename(&uppercase_path, &path).unwrap();
std::fs::write(&path, "invalid theme").unwrap();
assert!(
validate_theme_name(Some("ada"), Some(home.path()))
.unwrap()
.contains("could not be loaded")
);
assert!(resolve_theme_by_name("ada", Some(home.path())).is_none());
assert_eq!(
resolve_theme_with_override(Some("ada"), Some(home.path())),
resolve_theme_with_override(/*name*/ None, Some(home.path()))
);
assert!(
!list_available_themes(Some(home.path()))
.iter()
.any(|entry| entry.name == "ada")
);
}

View File

@@ -0,0 +1,119 @@
//! Append-only syntax highlighting for complete lines in an open code fence.
use super::MAX_HIGHLIGHT_LINE_BYTES;
use super::exceeds_highlight_limits;
use super::find_syntax;
use super::highlighted_line_spans;
use super::syntax_set;
use super::syntax_theme_revision;
use super::theme_lock;
use ratatui::text::Line;
use syntect::easy::HighlightLines;
use syntect::highlighting::HighlightState;
use syntect::parsing::ParseState;
use syntect::util::LinesWithEndings;
/// Retains only Syntect's parser state, subject to the ordinary highlighting limits.
///
/// An absent state means the whole fence already uses the permanent plain-text fallback because
/// its language is unknown or a size limit was exceeded. The caller owns the rendered prefix.
pub(crate) struct StreamingCodeHighlighter {
state: Option<HighlightedCode>,
}
struct HighlightedCode {
bytes: usize,
lines: usize,
theme_revision: u64,
syntax: (HighlightState, ParseState),
}
impl StreamingCodeHighlighter {
/// Reconstruct highlighting state after the canonical renderer emitted `code`.
///
/// Unknown languages and oversized input retain a permanent plain-text fallback. A changed
/// theme or failed replay returns `None`, requiring the caller to render the whole fence again.
pub(crate) fn new(code: &str, lang: &str, theme_revision: u64) -> Option<Self> {
let active_theme = theme_lock();
let theme = match active_theme.read() {
Ok(theme) => theme,
Err(poisoned) => poisoned.into_inner(),
};
if theme_revision != syntax_theme_revision() {
return None;
}
let lines = code.lines().count();
let syntax = find_syntax(lang).filter(|_| {
!exceeds_highlight_limits(code.len(), lines)
&& !code
.lines()
.any(|line| line.len() > MAX_HIGHLIGHT_LINE_BYTES)
});
let Some(syntax) = syntax else {
return Some(Self { state: None });
};
let mut highlighter = HighlightLines::new(syntax, &theme);
for line in LinesWithEndings::from(code) {
highlighter.highlight_line(line, syntax_set()).ok()?;
}
Some(Self {
state: Some(HighlightedCode {
bytes: code.len(),
lines,
theme_revision,
syntax: highlighter.state(),
}),
})
}
/// Consume the previous state and highlight just the newly committed complete lines.
///
/// Every appended line must be newline-terminated to preserve Syntect's parser state.
/// Returning `None` discards the state: the caller must render the whole fence again, which
/// also removes old colors when the aggregate input crosses a highlighting limit.
pub(crate) fn append(mut self, appended: &str) -> Option<(Self, Vec<Line<'static>>)> {
if !appended.ends_with('\n') {
return None;
}
let Some(mut state) = self.state.take() else {
let lines = appended
.lines()
.map(|line| Line::from(line.to_string()))
.collect();
return Some((self, lines));
};
let bytes = state.bytes.checked_add(appended.len())?;
let lines = state.lines.checked_add(appended.lines().count())?;
if exceeds_highlight_limits(bytes, lines)
|| appended
.lines()
.any(|line| line.len() > MAX_HIGHLIGHT_LINE_BYTES)
{
return None;
}
let active_theme = theme_lock();
let theme = match active_theme.read() {
Ok(theme) => theme,
Err(poisoned) => poisoned.into_inner(),
};
if state.theme_revision != syntax_theme_revision() {
return None;
}
let (highlight_state, parse_state) = state.syntax;
let mut highlighter = HighlightLines::from_state(&theme, highlight_state, parse_state);
let mut rendered = Vec::with_capacity(lines - state.lines);
for line in LinesWithEndings::from(appended) {
let ranges = highlighter.highlight_line(line, syntax_set()).ok()?;
rendered.push(Line::from(highlighted_line_spans(ranges)));
}
state.bytes = bytes;
state.lines = lines;
state.syntax = highlighter.state();
self.state = Some(state);
Some((self, rendered))
}
}
#[cfg(test)]
#[path = "highlight_streaming_tests.rs"]
mod tests;

View File

@@ -0,0 +1,75 @@
use super::super::MAX_HIGHLIGHT_BYTES;
use super::super::MAX_HIGHLIGHT_LINE_BYTES;
use super::super::MAX_HIGHLIGHT_LINES;
use super::super::highlight_code_to_lines;
use super::super::syntax_theme_revision;
use super::StreamingCodeHighlighter;
use pretty_assertions::assert_eq;
#[test]
fn appended_lines_preserve_multiline_syntax_state() {
let first = "fn main() {\n /* comment\n";
let appended = " continues */\n println!(\"界 e\u{301}\");\n}\n";
let code = format!("{first}{appended}");
let highlighter =
StreamingCodeHighlighter::new(first, "rust", syntax_theme_revision()).unwrap();
let (_, lines) = highlighter.append(appended).unwrap();
assert_eq!(
lines,
highlight_code_to_lines(&code, "rust")
.into_iter()
.skip(first.lines().count())
.collect::<Vec<_>>(),
);
}
#[test]
fn empty_and_unknown_language_fences_append() {
for lang in ["rust", "unknown-language"] {
let highlighter = StreamingCodeHighlighter::new("", lang, syntax_theme_revision()).unwrap();
let (_, lines) = highlighter.append("fn main() {}\n\n").unwrap();
assert_eq!(lines, highlight_code_to_lines("fn main() {}\n\n", lang));
}
}
#[test]
fn incomplete_lines_and_theme_changes_discard_state() {
let highlighter =
StreamingCodeHighlighter::new("fn first() {}\n", "rust", syntax_theme_revision()).unwrap();
assert!(highlighter.append("fn partial()").is_none());
let mut highlighter =
StreamingCodeHighlighter::new("fn first() {}\n", "rust", syntax_theme_revision()).unwrap();
let state = highlighter.state.as_mut().unwrap();
state.theme_revision = state.theme_revision.wrapping_sub(1);
assert!(highlighter.append("fn second() {}\n").is_none());
}
#[test]
fn crossing_each_highlighting_limit_requires_a_canonical_render() {
let cases = [
(
String::new(),
format!("{}\n", "x".repeat(MAX_HIGHLIGHT_LINE_BYTES + 1)),
),
("x\n".repeat(MAX_HIGHLIGHT_LINES), "x\n".to_string()),
(
format!("{}\n", "x".repeat(1023)).repeat(MAX_HIGHLIGHT_BYTES / 1024),
"x\n".to_string(),
),
];
for (initial, appended) in cases {
let highlighter =
StreamingCodeHighlighter::new(&initial, "rust", syntax_theme_revision()).unwrap();
assert!(highlighter.state.is_some());
assert!(highlighter.append(&appended).is_none());
let complete = format!("{initial}{appended}");
let highlighter =
StreamingCodeHighlighter::new(&complete, "rust", syntax_theme_revision()).unwrap();
assert!(highlighter.state.is_none());
let (_, lines) = highlighter.append("next\n").unwrap();
assert_eq!(lines, highlight_code_to_lines("next\n", "unknown-language"));
}
}

View File

@@ -0,0 +1,76 @@
use ratatui::text::Line;
use ratatui::text::Span;
/// Create a ratatui `Line` that borrows the contents of another line.
pub fn line_to_borrowed<'a>(line: &'a Line<'_>) -> Line<'a> {
Line {
style: line.style,
alignment: line.alignment,
spans: line
.spans
.iter()
.map(|span| Span {
style: span.style,
content: std::borrow::Cow::Borrowed(span.content.as_ref()),
})
.collect(),
}
}
/// Clone a borrowed ratatui `Line` into an owned `'static` line.
pub fn line_to_static(line: &Line<'_>) -> Line<'static> {
Line {
style: line.style,
alignment: line.alignment,
spans: line
.spans
.iter()
.map(|s| Span {
style: s.style,
content: std::borrow::Cow::Owned(s.content.to_string()),
})
.collect(),
}
}
/// Append owned copies of borrowed lines to `out`.
pub fn push_owned_lines<'a>(src: &[Line<'a>], out: &mut Vec<Line<'static>>) {
for l in src {
out.push(line_to_static(l));
}
}
/// Consider a line blank if it has no spans or only spans whose contents are
/// empty or consist solely of spaces (no tabs/newlines).
#[cfg(test)]
pub fn is_blank_line_spaces_only(line: &Line<'_>) -> bool {
if line.spans.is_empty() {
return true;
}
line.spans
.iter()
.all(|s| s.content.is_empty() || s.content.chars().all(|c| c == ' '))
}
/// Prefix each line with `initial_prefix` for the first line and
/// `subsequent_prefix` for following lines. Returns a new Vec of owned lines.
pub fn prefix_lines(
lines: Vec<Line<'static>>,
initial_prefix: Span<'static>,
subsequent_prefix: Span<'static>,
) -> Vec<Line<'static>> {
lines
.into_iter()
.enumerate()
.map(|(i, l)| {
let mut spans = Vec::with_capacity(l.spans.len() + 1);
spans.push(if i == 0 {
initial_prefix.clone()
} else {
subsequent_prefix.clone()
});
spans.extend(l.spans);
Line::from(spans).style(l.style)
})
.collect()
}

View File

@@ -0,0 +1,51 @@
use ratatui::layout::Rect;
pub(crate) mod highlight;
pub(crate) mod line_utils;
mod model_themes;
pub(crate) mod renderable;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Insets {
left: u16,
top: u16,
right: u16,
bottom: u16,
}
impl Insets {
pub fn tlbr(top: u16, left: u16, bottom: u16, right: u16) -> Self {
Self {
top,
left,
bottom,
right,
}
}
pub fn vh(v: u16, h: u16) -> Self {
Self {
top: v,
left: h,
bottom: v,
right: h,
}
}
}
pub trait RectExt {
fn inset(&self, insets: Insets) -> Rect;
}
impl RectExt for Rect {
fn inset(&self, insets: Insets) -> Rect {
let horizontal = insets.left.saturating_add(insets.right);
let vertical = insets.top.saturating_add(insets.bottom);
Rect {
x: self.x.saturating_add(insets.left),
y: self.y.saturating_add(insets.top),
width: self.width.saturating_sub(horizontal),
height: self.height.saturating_sub(vertical),
}
}
}

View File

@@ -0,0 +1,28 @@
//! Fixed model-named theme assets loaded through the standard TextMate parser.
use std::io::Cursor;
use syntect::highlighting::Theme;
use syntect::highlighting::ThemeSet;
pub(super) const THEMES: &[(&str, &str)] = &[
("ada", include_str!("../../assets/themes/ada.tmTheme")),
(
"babbage",
include_str!("../../assets/themes/babbage.tmTheme"),
),
("curie", include_str!("../../assets/themes/curie.tmTheme")),
(
"cushman",
include_str!("../../assets/themes/cushman.tmTheme"),
),
("dali", include_str!("../../assets/themes/dali.tmTheme")),
(
"davinci",
include_str!("../../assets/themes/davinci.tmTheme"),
),
];
pub(super) fn resolve(name: &str) -> Option<Theme> {
let (_, source) = THEMES.iter().find(|(key, _)| *key == name)?;
ThemeSet::load_from_reader(&mut Cursor::new(source.as_bytes())).ok()
}

View File

@@ -0,0 +1,499 @@
use std::cell::Cell;
use std::sync::Arc;
use crossterm::cursor::SetCursorStyle;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use ratatui::widgets::WidgetRef;
use crate::render::Insets;
use crate::render::RectExt as _;
pub trait Renderable {
fn render(&self, area: Rect, buf: &mut Buffer);
fn desired_height(&self, width: u16) -> u16;
/// Renders visible rows after `scroll_offset` when direct scrolling is supported.
///
/// Implementations returning `false` must leave `buf` unchanged so callers can use their
/// existing full-height rendering fallback. Supporting wrappers must forward this method.
fn render_scrolled(&self, _area: Rect, _buf: &mut Buffer, _scroll_offset: u16) -> bool {
false
}
fn cursor_pos(&self, _area: Rect) -> Option<(u16, u16)> {
None
}
fn cursor_style(&self, _area: Rect) -> SetCursorStyle {
SetCursorStyle::DefaultUserShape
}
}
pub enum RenderableItem<'a> {
Owned(Box<dyn Renderable + 'a>),
Borrowed(&'a dyn Renderable),
}
impl<'a> Renderable for RenderableItem<'a> {
fn render(&self, area: Rect, buf: &mut Buffer) {
match self {
RenderableItem::Owned(child) => child.render(area, buf),
RenderableItem::Borrowed(child) => child.render(area, buf),
}
}
fn desired_height(&self, width: u16) -> u16 {
match self {
RenderableItem::Owned(child) => child.desired_height(width),
RenderableItem::Borrowed(child) => child.desired_height(width),
}
}
fn render_scrolled(&self, area: Rect, buf: &mut Buffer, scroll_offset: u16) -> bool {
match self {
RenderableItem::Owned(child) => child.render_scrolled(area, buf, scroll_offset),
RenderableItem::Borrowed(child) => child.render_scrolled(area, buf, scroll_offset),
}
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
match self {
RenderableItem::Owned(child) => child.cursor_pos(area),
RenderableItem::Borrowed(child) => child.cursor_pos(area),
}
}
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
match self {
RenderableItem::Owned(child) => child.cursor_style(area),
RenderableItem::Borrowed(child) => child.cursor_style(area),
}
}
}
impl<'a> From<Box<dyn Renderable + 'a>> for RenderableItem<'a> {
fn from(value: Box<dyn Renderable + 'a>) -> Self {
RenderableItem::Owned(value)
}
}
impl<'a, R> From<R> for Box<dyn Renderable + 'a>
where
R: Renderable + 'a,
{
fn from(value: R) -> Self {
Box::new(value)
}
}
impl Renderable for () {
fn render(&self, _area: Rect, _buf: &mut Buffer) {}
fn desired_height(&self, _width: u16) -> u16 {
0
}
}
impl Renderable for &str {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.render_ref(area, buf);
}
fn desired_height(&self, _width: u16) -> u16 {
1
}
}
impl Renderable for String {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.render_ref(area, buf);
}
fn desired_height(&self, _width: u16) -> u16 {
1
}
}
impl<'a> Renderable for Span<'a> {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.render_ref(area, buf);
}
fn desired_height(&self, _width: u16) -> u16 {
1
}
}
impl<'a> Renderable for Line<'a> {
fn render(&self, area: Rect, buf: &mut Buffer) {
Widget::render(self, area, buf);
}
fn desired_height(&self, _width: u16) -> u16 {
1
}
}
impl<'a> Renderable for Paragraph<'a> {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.render_ref(area, buf);
}
fn desired_height(&self, width: u16) -> u16 {
self.line_count(width) as u16
}
}
impl<R: Renderable> Renderable for Option<R> {
fn render(&self, area: Rect, buf: &mut Buffer) {
if let Some(renderable) = self {
renderable.render(area, buf);
}
}
fn desired_height(&self, width: u16) -> u16 {
if let Some(renderable) = self {
renderable.desired_height(width)
} else {
0
}
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
self.as_ref()
.and_then(|renderable| renderable.cursor_pos(area))
}
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
self.as_ref()
.map_or(SetCursorStyle::DefaultUserShape, |renderable| {
renderable.cursor_style(area)
})
}
}
impl<R: Renderable> Renderable for Arc<R> {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.as_ref().render(area, buf);
}
fn desired_height(&self, width: u16) -> u16 {
self.as_ref().desired_height(width)
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
self.as_ref().cursor_pos(area)
}
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
self.as_ref().cursor_style(area)
}
}
pub struct ColumnRenderable<'a> {
children: Vec<RenderableItem<'a>>,
}
impl Renderable for ColumnRenderable<'_> {
fn render(&self, area: Rect, buf: &mut Buffer) {
let mut y = area.y;
for child in &self.children {
if y >= area.bottom() {
break;
}
let child_area = Rect::new(area.x, y, area.width, child.desired_height(area.width))
.intersection(area);
if !child_area.is_empty() {
child.render(child_area, buf);
}
y += child_area.height;
}
}
fn desired_height(&self, width: u16) -> u16 {
self.children
.iter()
.map(|child| child.desired_height(width))
.sum()
}
/// Returns the cursor position of the first child that has a cursor position, offset by the
/// child's position in the column.
///
/// It is generally assumed that either zero or one child will have a cursor position.
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
let mut y = area.y;
for child in &self.children {
let child_area = Rect::new(area.x, y, area.width, child.desired_height(area.width))
.intersection(area);
if !child_area.is_empty()
&& let Some((px, py)) = child.cursor_pos(child_area)
{
return Some((px, py));
}
y += child_area.height;
}
None
}
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
let mut y = area.y;
for child in &self.children {
let child_area = Rect::new(area.x, y, area.width, child.desired_height(area.width))
.intersection(area);
if !child_area.is_empty() && child.cursor_pos(child_area).is_some() {
return child.cursor_style(child_area);
}
y += child_area.height;
}
SetCursorStyle::DefaultUserShape
}
}
impl<'a> ColumnRenderable<'a> {
pub fn new() -> Self {
Self { children: vec![] }
}
pub fn with<I, T>(children: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<RenderableItem<'a>>,
{
Self {
children: children.into_iter().map(Into::into).collect(),
}
}
pub fn push(&mut self, child: impl Into<Box<dyn Renderable + 'a>>) {
self.children.push(RenderableItem::Owned(child.into()));
}
}
pub struct FlexChild<'a> {
flex: i32,
child: RenderableItem<'a>,
cached_height: Cell<Option<(u16, u16)>>,
}
pub struct FlexRenderable<'a> {
children: Vec<FlexChild<'a>>,
}
/// Lays out children in a column, with the ability to specify a flex factor for each child.
///
/// Children with flex factor > 0 will be allocated the remaining space after the non-flex children,
/// proportional to the flex factor.
impl<'a> FlexRenderable<'a> {
pub fn new() -> Self {
Self { children: vec![] }
}
pub fn push(&mut self, flex: i32, child: impl Into<RenderableItem<'a>>) {
self.children.push(FlexChild {
flex,
child: child.into(),
cached_height: Cell::new(None),
});
}
/// Loosely inspired by Flutter's Flex widget.
///
/// Ref https://github.com/flutter/flutter/blob/3fd81edbf1e015221e143c92b2664f4371bdc04a/packages/flutter/lib/src/rendering/flex.dart#L1205-L1209
fn allocate(&self, area: Rect) -> Vec<Rect> {
let mut allocated_rects = Vec::with_capacity(self.children.len());
let mut child_sizes = vec![0; self.children.len()];
let mut allocated_size = 0;
let mut flex_children = Vec::new();
// 1. Allocate space to non-flex children.
let max_size = area.height;
for (i, child) in self.children.iter().enumerate() {
let desired_height = if let Some((width, height)) = child.cached_height.get()
&& width == area.width
{
height
} else {
let height = child.child.desired_height(area.width);
child.cached_height.set(Some((area.width, height)));
height
};
if child.flex > 0 {
flex_children.push((i, child.flex as u16, desired_height));
} else {
child_sizes[i] = desired_height.min(max_size.saturating_sub(allocated_size));
allocated_size += child_sizes[i];
}
}
let free_space = max_size.saturating_sub(allocated_size);
// 2. Satisfy flex children that need less than their proportional share so their unused
// space can be redistributed instead of leaving blank rows.
let mut remaining_space = free_space;
while !flex_children.is_empty() {
let total_flex = flex_children.iter().map(|(_, flex, _)| *flex).sum::<u16>();
let mut satisfied_any = false;
flex_children.retain(|(i, flex, desired_height)| {
let proportional_share =
(u32::from(remaining_space) * u32::from(*flex) / u32::from(total_flex)) as u16;
if *desired_height <= proportional_share {
child_sizes[*i] = *desired_height;
remaining_space = remaining_space.saturating_sub(*desired_height);
satisfied_any = true;
false
} else {
true
}
});
if !satisfied_any {
break;
}
}
// 3. Divide the remaining space proportionally. The final child absorbs rounding slack.
let total_flex = flex_children.iter().map(|(_, flex, _)| *flex).sum::<u16>();
let mut allocated_flex_space = 0;
let last_flex_child_idx = flex_children.last().map(|(i, _, _)| *i);
for (i, flex, desired_height) in flex_children {
let max_child_extent = if Some(i) == last_flex_child_idx {
remaining_space.saturating_sub(allocated_flex_space)
} else {
(u32::from(remaining_space) * u32::from(flex) / u32::from(total_flex)) as u16
};
let child_size = desired_height.min(max_child_extent);
child_sizes[i] = child_size;
allocated_flex_space += child_size;
}
let mut y = area.y;
for size in child_sizes {
let child_area = Rect::new(area.x, y, area.width, size);
allocated_rects.push(child_area);
y += child_area.height;
}
allocated_rects
}
}
impl<'a> Renderable for FlexRenderable<'a> {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.allocate(area)
.into_iter()
.zip(self.children.iter())
.for_each(|(rect, child)| {
child.child.render(rect, buf);
});
}
fn desired_height(&self, width: u16) -> u16 {
self.allocate(Rect::new(0, 0, width, u16::MAX))
.last()
.map(|rect| rect.bottom())
.unwrap_or(0)
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
self.allocate(area)
.into_iter()
.zip(self.children.iter())
.find_map(|(rect, child)| child.child.cursor_pos(rect))
}
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
self.allocate(area)
.into_iter()
.zip(self.children.iter())
.find_map(|(rect, child)| {
child
.child
.cursor_pos(rect)
.map(|_| child.child.cursor_style(rect))
})
.unwrap_or(SetCursorStyle::DefaultUserShape)
}
}
pub struct InsetRenderable<'a> {
child: RenderableItem<'a>,
insets: Insets,
}
impl<'a> Renderable for InsetRenderable<'a> {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.child.render(area.inset(self.insets), buf);
}
fn desired_height(&self, width: u16) -> u16 {
self.child.desired_height(
width
.saturating_sub(self.insets.left)
.saturating_sub(self.insets.right),
) + self.insets.top
+ self.insets.bottom
}
/// Preserve clipped inset padding while forwarding only visible child rows.
fn render_scrolled(&self, area: Rect, buf: &mut Buffer, scroll_offset: u16) -> bool {
let top_padding = self.insets.top.saturating_sub(scroll_offset);
let child_width = area
.width
.saturating_sub(self.insets.left.saturating_add(self.insets.right));
if child_width == 0 || top_padding >= area.height {
return true;
}
let child_offset = scroll_offset.saturating_sub(self.insets.top);
// The fallback applies bottom padding to its clipped scratch buffer, even mid-scroll.
let child_height = self
.child
.desired_height(child_width)
.saturating_sub(child_offset)
.min(
area.height
.saturating_sub(top_padding)
.saturating_sub(self.insets.bottom),
);
if child_height == 0 {
return true;
}
let child_area = Rect::new(
area.x.saturating_add(self.insets.left),
area.y.saturating_add(top_padding),
child_width,
child_height,
);
if child_offset == 0 {
self.child.render(child_area, buf);
true
} else {
self.child.render_scrolled(child_area, buf, child_offset)
}
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
self.child.cursor_pos(area.inset(self.insets))
}
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
self.child.cursor_style(area.inset(self.insets))
}
}
impl<'a> InsetRenderable<'a> {
pub fn new(child: impl Into<RenderableItem<'a>>, insets: Insets) -> Self {
Self {
child: child.into(),
insets,
}
}
}
pub trait RenderableExt<'a> {
fn inset(self, insets: Insets) -> RenderableItem<'a>;
}
impl<'a, R> RenderableExt<'a> for R
where
R: Renderable + 'a,
{
fn inset(self, insets: Insets) -> RenderableItem<'a> {
let child: RenderableItem<'a> =
RenderableItem::Owned(Box::new(self) as Box<dyn Renderable + 'a>);
RenderableItem::Owned(Box::new(InsetRenderable { child, insets }))
}
}
#[cfg(test)]
#[path = "renderable_tests.rs"]
mod tests;

View File

@@ -0,0 +1,112 @@
use super::*;
use pretty_assertions::assert_eq;
use std::cell::Cell;
struct HeightRenderable(u16);
impl HeightRenderable {
fn with_height(height: u16) -> Self {
Self(height)
}
}
impl Renderable for HeightRenderable {
fn render(&self, _area: Rect, _buf: &mut Buffer) {}
fn desired_height(&self, _width: u16) -> u16 {
self.0
}
}
#[test]
fn flex_redistributes_space_unused_by_short_children() {
let mut flex = FlexRenderable::new();
flex.push(
/*flex*/ 1,
RenderableItem::Owned(Box::new(HeightRenderable::with_height(/*height*/ 20))),
);
flex.push(
/*flex*/ 1,
RenderableItem::Owned(Box::new(HeightRenderable::with_height(/*height*/ 2))),
);
let allocated = flex.allocate(Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 10,
));
assert_eq!(
allocated
.into_iter()
.map(|area| area.height)
.collect::<Vec<_>>(),
vec![8, 2],
);
}
#[test]
fn flex_reserves_non_flex_space_before_flexible_children() {
let mut flex = FlexRenderable::new();
flex.push(
/*flex*/ 1,
RenderableItem::Owned(Box::new(HeightRenderable::with_height(/*height*/ 20))),
);
flex.push(
/*flex*/ 0,
RenderableItem::Owned(Box::new(HeightRenderable::with_height(/*height*/ 2))),
);
flex.push(
/*flex*/ 1,
RenderableItem::Owned(Box::new(HeightRenderable::with_height(/*height*/ 20))),
);
let allocated = flex.allocate(Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 10,
));
assert_eq!(
allocated
.into_iter()
.map(|area| area.height)
.collect::<Vec<_>>(),
vec![4, 2, 4],
);
}
#[test]
fn flex_caches_child_height_across_frame_passes() {
struct CountingRenderable<'a>(&'a Cell<usize>);
impl Renderable for CountingRenderable<'_> {
fn render(&self, _area: Rect, _buf: &mut Buffer) {}
fn desired_height(&self, _width: u16) -> u16 {
self.0.set(self.0.get() + 1);
1
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
Some((area.x, area.y))
}
}
let calls = Cell::new(0);
let renderable = CountingRenderable(&calls);
let mut flex = FlexRenderable::new();
flex.push(/*flex*/ 1, RenderableItem::Borrowed(&renderable));
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 10,
);
let mut buf = Buffer::empty(area);
assert_eq!(flex.desired_height(area.width), 1);
flex.render(area, &mut buf);
assert_eq!(flex.cursor_pos(area), Some((0, 0)));
assert!(matches!(
flex.cursor_style(area),
crossterm::cursor::SetCursorStyle::DefaultUserShape
));
assert_eq!(calls.get(), 1);
assert_eq!(flex.desired_height(/*width*/ 100), 1);
assert_eq!(calls.get(), 2);
}

View File

@@ -0,0 +1,22 @@
---
source: tui/src/render/highlight.rs
assertion_line: 1196
expression: out
---
ansi:
Blue
Green
Magenta
Yellow
base16:
Blue
Gray
Green
Indexed(9)
Magenta
base16-256:
Blue
Gray
Green
Indexed(16)
Magenta