Skip to content

Commit c43a29a

Browse files
committed
[Rust - libgui] Allow calculating text layout size on a TextView
1 parent f6846b6 commit c43a29a

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

rust_programs/libgui/src/text_view.rs

+29
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use alloc::{
1919
};
2020
use axle_rt::AmcMessage;
2121
use core::fmt::Formatter;
22+
use core::ops::Add;
2223
use core::ptr;
2324
use file_manager_messages::{ReadFile, ReadFileResponse, FILE_SERVER_SERVICE_NAME};
2425
use libgui_derive::{Drawable, NestedLayerSlice, UIElement};
@@ -180,6 +181,34 @@ impl TextView {
180181
cursor_pos
181182
}
182183

184+
/// Note that this will respect the need to split onto newlines due to the size of the parent slice.
185+
pub fn rendered_string_size(
186+
s: &str,
187+
font: &Font,
188+
font_size: Size,
189+
container_size: Size,
190+
text_origin: Point,
191+
) -> Size {
192+
// Pretend we're doing layout and keep track of the area we cross
193+
let mut layout_size = Size::new(0, font.scaled_line_height(font_size));
194+
let mut cursor_pos = text_origin;
195+
for ch in s.chars() {
196+
let next_cursor_pos = Self::next_cursor_pos_for_char(
197+
cursor_pos,
198+
ch,
199+
font,
200+
font_size,
201+
container_size,
202+
);
203+
layout_size = layout_size + Size::new(
204+
next_cursor_pos.x - cursor_pos.x,
205+
next_cursor_pos.y - cursor_pos.y,
206+
);
207+
cursor_pos = next_cursor_pos;
208+
}
209+
layout_size
210+
}
211+
183212
pub fn cursor_pos(&self) -> CursorPos {
184213
*self.cursor_pos.borrow()
185214
}

rust_programs/ttf_renderer/src/render.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ pub fn render_char_onto(
3030
render_glyph_onto(glyph, font, onto, draw_loc, draw_color, font_size)
3131
}
3232

33+
/// Note that this implementation does not respect the need to split onto newlines due to the size
34+
/// of the parent container.
3335
pub fn rendered_string_size(s: &str, font: &Font, font_size: Size) -> Size {
3436
let scale_factor = font_size.height as f64 / font.units_per_em as f64;
3537
let mut bounding_box = Size::new(
@@ -68,9 +70,9 @@ pub fn render_antialiased_glyph_onto(
6870
let scaled_glyph_metrics = glyph.metrics().scale(scale_x, scale_y);
6971
let draw_loc = draw_loc
7072
+ Point::new(
71-
scaled_glyph_metrics.left_side_bearing,
72-
scaled_glyph_metrics.top_side_bearing,
73-
);
73+
scaled_glyph_metrics.left_side_bearing,
74+
scaled_glyph_metrics.top_side_bearing,
75+
);
7476
let draw_box = Rect::from_parts(draw_loc, font_size);
7577
let mut dest_slice = onto.get_slice(draw_box);
7678

0 commit comments

Comments
 (0)