use std::sync::Arc;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Wrap {
#[default]
Word,
Any,
Nowrap,
Truncate,
}
#[must_use]
pub fn resolve(ui: &egui::Ui, wrap: Option<Wrap>) -> Wrap {
wrap.unwrap_or_else(|| ui.style().wrap_mode.map_or(Wrap::Word, Into::into))
}
impl From<egui::TextWrapMode> for Wrap {
fn from(mode: egui::TextWrapMode) -> Self {
match mode {
egui::TextWrapMode::Extend => Self::Nowrap,
egui::TextWrapMode::Wrap => Self::Word,
egui::TextWrapMode::Truncate => Self::Truncate,
}
}
}
pub fn layout(
ui: &egui::Ui,
text: impl Into<String>,
font_id: egui::FontId,
color: egui::Color32,
max_width: f32,
wrap: Option<Wrap>,
) -> Arc<egui::Galley> {
resolved_layout(
ui,
text.into(),
font_id,
color,
max_width.max(0.0),
resolve(ui, wrap),
)
}
fn resolved_layout(
ui: &egui::Ui,
text: String,
font_id: egui::FontId,
color: egui::Color32,
max_width: f32,
wrap: Wrap,
) -> Arc<egui::Galley> {
match wrap {
Wrap::Nowrap => ui.painter().layout_no_wrap(text, font_id, color),
Wrap::Word => {
let galley = row_layout(
ui,
text.clone(),
font_id.clone(),
color,
max_width,
false,
usize::MAX,
);
if !galley.size().x.is_finite() || galley.size().x <= max_width {
galley
} else {
row_layout(ui, text, font_id, color, max_width, true, usize::MAX)
}
}
Wrap::Any => row_layout(ui, text, font_id, color, max_width, true, usize::MAX),
Wrap::Truncate => row_layout(ui, text, font_id, color, max_width, true, 1),
}
}
fn row_layout(
ui: &egui::Ui,
text: impl Into<String>,
font_id: egui::FontId,
color: egui::Color32,
max_width: f32,
break_anywhere: bool,
max_rows: usize,
) -> Arc<egui::Galley> {
let mut job = egui::text::LayoutJob::simple(text.into(), font_id, color, max_width);
job.wrap.break_anywhere = break_anywhere;
job.wrap.max_rows = max_rows;
ui.fonts_mut(|fonts| fonts.layout_job(job))
}
#[must_use]
pub fn natural_width(ctx: &egui::Context, text: impl Into<String>, font_id: egui::FontId) -> f32 {
ctx.fonts_mut(|fonts| fonts.layout_no_wrap(text.into(), font_id, egui::Color32::WHITE))
.size()
.x
}
#[must_use]
pub fn box_height(galley: &egui::Galley, min_height: f32) -> f32 {
let line_height = galley.rows.first().map_or(0.0, |row| row.height());
let padding_y = ((min_height - line_height) * 0.5).max(0.0);
min_height.max(galley.size().y + padding_y * 2.0)
}
#[must_use]
pub fn intrinsic_box_height(galley: &egui::Galley, min_height: f32) -> f32 {
let line_height = galley.intrinsic_size().y;
let padding_y = ((min_height - line_height) * 0.5).max(0.0);
min_height.max(line_height + padding_y * 2.0)
}