Skip to content

Commit

Permalink
[Rust - libgui] Allow calculating text layout size on a TextView
Browse files Browse the repository at this point in the history
  • Loading branch information
codyd51 committed Apr 5, 2024
1 parent f6846b6 commit c43a29a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
29 changes: 29 additions & 0 deletions rust_programs/libgui/src/text_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use alloc::{
};
use axle_rt::AmcMessage;
use core::fmt::Formatter;
use core::ops::Add;
use core::ptr;
use file_manager_messages::{ReadFile, ReadFileResponse, FILE_SERVER_SERVICE_NAME};
use libgui_derive::{Drawable, NestedLayerSlice, UIElement};
Expand Down Expand Up @@ -180,6 +181,34 @@ impl TextView {
cursor_pos
}

/// Note that this will respect the need to split onto newlines due to the size of the parent slice.
pub fn rendered_string_size(
s: &str,
font: &Font,
font_size: Size,
container_size: Size,
text_origin: Point,
) -> Size {
// Pretend we're doing layout and keep track of the area we cross
let mut layout_size = Size::new(0, font.scaled_line_height(font_size));
let mut cursor_pos = text_origin;
for ch in s.chars() {
let next_cursor_pos = Self::next_cursor_pos_for_char(
cursor_pos,
ch,
font,
font_size,
container_size,
);
layout_size = layout_size + Size::new(
next_cursor_pos.x - cursor_pos.x,
next_cursor_pos.y - cursor_pos.y,
);
cursor_pos = next_cursor_pos;
}
layout_size
}

pub fn cursor_pos(&self) -> CursorPos {
*self.cursor_pos.borrow()
}
Expand Down
8 changes: 5 additions & 3 deletions rust_programs/ttf_renderer/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub fn render_char_onto(
render_glyph_onto(glyph, font, onto, draw_loc, draw_color, font_size)
}

/// Note that this implementation does not respect the need to split onto newlines due to the size
/// of the parent container.
pub fn rendered_string_size(s: &str, font: &Font, font_size: Size) -> Size {
let scale_factor = font_size.height as f64 / font.units_per_em as f64;
let mut bounding_box = Size::new(
Expand Down Expand Up @@ -68,9 +70,9 @@ pub fn render_antialiased_glyph_onto(
let scaled_glyph_metrics = glyph.metrics().scale(scale_x, scale_y);
let draw_loc = draw_loc
+ Point::new(
scaled_glyph_metrics.left_side_bearing,
scaled_glyph_metrics.top_side_bearing,
);
scaled_glyph_metrics.left_side_bearing,
scaled_glyph_metrics.top_side_bearing,
);
let draw_box = Rect::from_parts(draw_loc, font_size);
let mut dest_slice = onto.get_slice(draw_box);

Expand Down

0 comments on commit c43a29a

Please sign in to comment.