use abstracttui::text::width as cells;
use abstracttui::widgets::{ColWidth, Column, Table};
const GAP: i32 = 1;
const SCROLLBAR: i32 = 1;
pub const BLOCK_CHROME: i32 = 2;
#[derive(Clone, Copy, Debug)]
pub struct ColRule {
pub title: &'static str,
pub min: i32,
pub tail: bool,
}
impl ColRule {
pub const fn tail(title: &'static str, min: i32) -> ColRule {
ColRule {
title,
min,
tail: true,
}
}
pub const fn head(title: &'static str, min: i32) -> ColRule {
ColRule {
title,
min,
tail: false,
}
}
}
pub fn solve(rules: &[ColRule], rows: &[Vec<String>], rect_w: i32) -> Vec<i32> {
let n = rules.len();
if n == 0 {
return Vec::new();
}
let usable = (rect_w - SCROLLBAR - GAP * (n as i32 - 1)).max(0);
let mut natural: Vec<i32> = rules.iter().map(|r| cells(r.title)).collect();
for row in rows {
for (i, cell) in row.iter().enumerate().take(n) {
natural[i] = natural[i].max(cells(cell));
}
}
for (i, r) in rules.iter().enumerate() {
natural[i] = natural[i].max(r.min.min(cells(r.title)));
}
let total: i32 = natural.iter().sum();
if total <= usable {
return natural;
}
let slack: Vec<i32> = rules
.iter()
.enumerate()
.map(|(i, r)| (natural[i] - r.min).max(0))
.collect();
let total_slack: i32 = slack.iter().sum();
let mut out = natural;
let deficit = total - usable;
if total_slack > 0 {
let take = deficit.min(total_slack);
let mut shares = vec![0i32; n];
let mut rems: Vec<(i64, usize)> = Vec::with_capacity(n);
let mut given = 0i32;
for (i, s) in slack.iter().enumerate() {
let exact = i64::from(take) * i64::from(*s);
let whole = (exact / i64::from(total_slack)) as i32;
shares[i] = whole;
given += whole;
rems.push((exact % i64::from(total_slack), i));
}
rems.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let mut left = take - given;
for (_, i) in rems {
if left == 0 {
break;
}
if shares[i] < slack[i] {
shares[i] += 1;
left -= 1;
}
}
for (i, s) in shares.iter().enumerate() {
out[i] -= s;
}
}
let mut over: i32 = out.iter().sum::<i32>() - usable;
while over > 0 {
let Some(i) = widest(&out) else { break };
if out[i] <= 1 {
break;
}
out[i] -= 1;
over -= 1;
}
out
}
fn widest(out: &[i32]) -> Option<usize> {
out.iter()
.enumerate()
.max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(&a.0)))
.map(|(i, _)| i)
}
pub fn fit_cells(rules: &[ColRule], rows: &mut [Vec<String>], widths: &[i32]) {
for row in rows.iter_mut() {
for (i, cell) in row.iter_mut().enumerate() {
let (Some(w), Some(rule)) = (widths.get(i), rules.get(i)) else {
continue;
};
if cells(cell) <= *w {
continue;
}
*cell = if rule.tail {
middle_fit(cell, *w)
} else {
head_fit(cell, *w)
};
}
}
}
pub fn columns(rules: &[ColRule], rows: &mut [Vec<String>], rect_w: i32) -> Vec<Column> {
let widths = solve(rules, rows, rect_w);
fit_cells(rules, rows, &widths);
rules
.iter()
.zip(&widths)
.map(|(r, w)| Column::new(r.title, ColWidth::Cells(*w)))
.collect()
}
pub fn table(rules: &[ColRule], mut rows: Vec<Vec<String>>, rect_w: i32) -> Table {
let cols = columns(rules, &mut rows, rect_w);
Table::new(cols).rows(rows)
}
pub fn head_fit(s: &str, max: i32) -> String {
if max <= 0 {
return String::new();
}
if cells(s) <= max {
return s.to_string();
}
let mut out = String::new();
let mut used = 0;
for ch in s.chars() {
let w = cells(&ch.to_string());
if used + w > max - 1 {
break;
}
out.push(ch);
used += w;
}
out.push('…');
out
}
pub fn middle_fit(s: &str, max: i32) -> String {
if max <= 0 {
return String::new();
}
if cells(s) <= max {
return s.to_string();
}
if max == 1 {
return "…".to_string();
}
let body = max - 1; let head_budget = if body >= 5 { body / 5 } else { 0 };
let tail_budget = body - head_budget;
let mut head = String::new();
let mut used = 0;
let mut chars = s.chars().peekable();
while let Some(&ch) = chars.peek() {
let w = cells(&ch.to_string());
if used + w > head_budget {
break;
}
head.push(ch);
used += w;
chars.next();
}
let rest: Vec<char> = chars.collect();
let mut tail_rev = String::new();
let mut used = 0;
for ch in rest.iter().rev() {
let w = cells(&ch.to_string());
if used + w > tail_budget {
break;
}
tail_rev.push(*ch);
used += w;
}
let tail: String = tail_rev.chars().rev().collect();
format!("{head}…{tail}")
}
pub fn elastic_budget(fixed: &[&str], available: i32) -> i32 {
let spent: i32 = fixed.iter().map(|s| cells(s)).sum();
(available - spent).max(0)
}
pub fn fits(parts: &[&str], available: i32) -> bool {
parts.iter().map(|s| cells(s)).sum::<i32>() <= available
}
#[cfg(test)]
mod tests {
use super::*;
fn rows(cells: &[&[&str]]) -> Vec<Vec<String>> {
cells
.iter()
.map(|r| r.iter().map(|c| (*c).to_string()).collect())
.collect()
}
#[test]
fn wide_terminal_truncates_nothing() {
let rules = [
ColRule::tail("route", 18),
ColRule::head("state", 14),
ColRule::tail("model", 22),
];
let mut r = rows(&[
&[
"output.video.text_to_video",
"configured",
"AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
],
&["input.text", "configured", "gpt-5.4"],
]);
let w = solve(&rules, &r, 200);
assert_eq!(w[0], 26, "route sizes to its widest key, not a constant");
assert_eq!(w[1], 10, "state sizes to 'configured'");
assert_eq!(w[2], 48, "model sizes to the full artifact name");
fit_cells(&rules, &mut r, &w);
assert_eq!(
r[0][2], "AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
"a model that fits is printed whole"
);
assert!(
!r.iter().any(|row| row.iter().any(|c| c.contains('…'))),
"no ellipsis anywhere at 200 cells: {r:?}"
);
}
#[test]
fn solved_widths_always_tile_inside_the_budget() {
let rules = [
ColRule::tail("route", 18),
ColRule::head("state", 14),
ColRule::tail("provider", 10),
ColRule::tail("model", 22),
ColRule::head("weights", 14),
ColRule::tail("source", 12),
];
let r = rows(&[&[
"output.scene3d.image_to_scene3d",
"covered by input.text",
"endpoint:airbender",
"AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
"not downloaded",
"abstractcore.capability_defaults",
]]);
for w in [40, 60, 80, 100, 120, 160, 200, 300] {
let solved = solve(&rules, &r, w);
let used: i32 = solved.iter().sum::<i32>() + (rules.len() as i32 - 1) + 1;
assert!(
used <= w,
"widths overflow the {w}-cell budget: {solved:?} -> {used}"
);
assert!(
solved.iter().all(|c| *c >= 1),
"every column keeps a cell at {w}: {solved:?}"
);
}
}
#[test]
fn narrow_terminal_shares_the_squeeze() {
let rules = [
ColRule::tail("route", 18),
ColRule::head("state", 14),
ColRule::tail("model", 22),
ColRule::tail("source", 12),
];
let r = rows(&[&[
"output.scene3d.image_to_scene3d",
"covered by input.text",
"AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
"abstractcore.capability_defaults",
]]);
let wide = solve(&rules, &r, 200);
let tight = solve(&rules, &r, 90);
assert!(tight.iter().sum::<i32>() < wide.iter().sum::<i32>());
for (i, rule) in rules.iter().enumerate() {
assert!(
tight[i] < wide[i],
"{} carried none of the squeeze: {wide:?} -> {tight:?}",
rule.title
);
assert!(
tight[i] >= rule.min,
"{} squeezed past its floor: {tight:?}",
rule.title
);
}
}
#[test]
fn middle_fit_keeps_what_tells_rows_apart() {
let t2v = "AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit";
let i2v = "AbstractFramework/wan2.2-i2v-a14b-diffusers-8bit";
let a = middle_fit(t2v, 30);
let b = middle_fit(i2v, 30);
assert_eq!(cells(&a), 30, "fits exactly: {a:?}");
assert!(
a.ends_with("t2v-a14b-diffusers-8bit"),
"tail survives: {a:?}"
);
assert!(a.starts_with("Abstr"), "family still readable: {a:?}");
assert!(a.contains('…'), "the cut is marked: {a:?}");
assert_ne!(
a, b,
"two different models must still read differently: {a:?} vs {b:?}"
);
let live = [
"AbstractFramework/flux.2-klein-9b-8bit",
"AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit",
"AbstractFramework/seedvr2-7b-8bit",
];
let headed: Vec<String> = live.iter().map(|m| head_fit(m, 15)).collect();
assert!(
headed[0] == headed[1] && headed[1] == headed[2],
"head_fit really does collapse these — that is the bug: {headed:?}"
);
let middled: Vec<String> = live.iter().map(|m| middle_fit(m, 15)).collect();
assert!(
middled[0] != middled[1] && middled[1] != middled[2] && middled[0] != middled[2],
"middle_fit keeps them apart at the same width: {middled:?}"
);
assert_eq!(middle_fit("short", 30), "short", "no cut when it fits");
assert_eq!(middle_fit("anything", 1), "…");
assert_eq!(middle_fit("anything", 0), "");
for w in 1..12 {
assert!(
cells(&middle_fit(t2v, w)) <= w,
"middle_fit overflows at {w}"
);
}
}
#[test]
fn cuts_are_cell_aware_not_char_aware() {
let cjk = "模型模型模型模型模型模型";
assert_eq!(cells(cjk), 24);
for w in 2..24 {
assert!(cells(&middle_fit(cjk, w)) <= w, "middle_fit at {w}");
assert!(cells(&head_fit(cjk, w)) <= w, "head_fit at {w}");
}
let rules = [ColRule::tail("m", 4)];
let r = rows(&[&[cjk]]);
assert_eq!(solve(&rules, &r, 40)[0], 24, "natural width counts cells");
}
#[test]
fn elastic_budget_reserves_the_fixed_parts() {
let head = "recommended models: 2 of 3 present";
let mid = " · missing: ";
let verb = " · w downloads the selected route's weights";
let budget = elastic_budget(&[head, mid, verb], 120);
assert_eq!(budget, 120 - cells(head) - cells(mid) - cells(verb));
let list = middle_fit("lmstudio qwen/qwen3.5-9b@4bit", budget);
assert!(
list.ends_with("@4bit"),
"the artifact tag survives: {list:?}"
);
let total = cells(head) + cells(mid) + cells(&list) + cells(verb);
assert!(total <= 120, "the whole line fits: {total}");
assert_eq!(
elastic_budget(&[head, mid, verb], 60),
0,
"no room, no list"
);
let count = " · 1 missing";
assert!(
fits(&[head, count, verb], 100),
"the short form fits at 100"
);
assert!(
!fits(&[head, count, verb], 90),
"at 90 even the count has to go, or the verb loses its end"
);
assert!(fits(&[head, verb], 90), "…and without it the verb survives");
}
}