diff --git a/crates/egui/src/atomics/atom_kind.rs b/crates/egui/src/atomics/atom_kind.rs index 2672e646b..75b03c04a 100644 --- a/crates/egui/src/atomics/atom_kind.rs +++ b/crates/egui/src/atomics/atom_kind.rs @@ -81,9 +81,21 @@ impl<'a> AtomKind<'a> { ) -> (Vec2, SizedAtomKind<'a>) { match self { AtomKind::Text(text) => { - let galley = text.into_galley(ui, wrap_mode, available_size.x, TextStyle::Button); + let wrap_mode = wrap_mode.unwrap_or(ui.wrap_mode()); + let desired_size = matches!(wrap_mode, TextWrapMode::Truncate).then(|| { + text.clone() + .into_galley( + ui, + Some(TextWrapMode::Extend), + available_size.x, + TextStyle::Button, + ) + .desired_size() + }); + let galley = + text.into_galley(ui, Some(wrap_mode), available_size.x, TextStyle::Button); ( - galley.size(), // TODO(#5762): calculate the preferred size + desired_size.unwrap_or_else(|| galley.desired_size()), SizedAtomKind::Text(galley), ) } diff --git a/crates/epaint/src/text/text_layout_types.rs b/crates/epaint/src/text/text_layout_types.rs index f7e11911b..f6a182dcb 100644 --- a/crates/epaint/src/text/text_layout_types.rs +++ b/crates/epaint/src/text/text_layout_types.rs @@ -795,6 +795,31 @@ impl Galley { self.rect.size() } + // TODO: Instead return Option? + pub fn desired_size(&self) -> Vec2 { + let mut current_width: f32 = 0.0; + let mut widest_width: f32 = 0.0; + let mut height = self.rows.first().map_or(0.0, |row| row.height()); + for row in &self.rows { + if current_width != 0.0 { + let space = row.glyphs.last(); + if let Some(space) = space { + if space.chr.is_whitespace() { + // TODO: Needed or not? Doesn't seem like it's needed + // current_width += space.advance_width; + } + } + } + current_width += row.rect().width(); + widest_width = widest_width.max(current_width); + if row.ends_with_newline { + height += row.height(); + current_width = 0.0; + } + } + vec2(widest_width, height) + } + pub(crate) fn round_output_to_gui(&mut self) { for placed_row in &mut self.rows { // Optimization: only call `make_mut` if necessary (can cause a deep clone)