From 6319796f58714116b4db496dd73fd779128b8f85 Mon Sep 17 00:00:00 2001 From: LuK1337 Date: Tue, 6 Jul 2021 12:08:06 +0200 Subject: [PATCH] LibGfx: BitmapFont: Handle '\r' and '\n' when calculating text width Previously calculating multiline text width would return invalid value, this change makes it so that we are returning the longest line width. We are now also reusing same width() implementation for both UTF-8 and UTF-32 strings. --- Userland/Libraries/LibGfx/BitmapFont.cpp | 29 ++++++++++++++++-------- Userland/Libraries/LibGfx/BitmapFont.h | 3 +++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/Userland/Libraries/LibGfx/BitmapFont.cpp b/Userland/Libraries/LibGfx/BitmapFont.cpp index 0ba46568e1..b44091830a 100644 --- a/Userland/Libraries/LibGfx/BitmapFont.cpp +++ b/Userland/Libraries/LibGfx/BitmapFont.cpp @@ -263,29 +263,40 @@ int BitmapFont::width(const StringView& string) const return width(utf8); } -int BitmapFont::width(const Utf8View& utf8) const +template +int BitmapFont::unicode_view_width(T const& view) const { + if (view.is_empty()) + return 0; bool first = true; int width = 0; + int longest_width = 0; - for (u32 code_point : utf8) { + for (u32 code_point : view) { + if (code_point == '\n' || code_point == '\r') { + first = true; + width = 0; + continue; + } if (!first) width += glyph_spacing(); first = false; width += glyph_or_emoji_width(code_point); + if (width > longest_width) + longest_width = width; } - return width; + return longest_width; +} + +int BitmapFont::width(const Utf8View& utf8) const +{ + return unicode_view_width(utf8); } int BitmapFont::width(const Utf32View& view) const { - if (view.length() == 0) - return 0; - int width = (view.length() - 1) * glyph_spacing(); - for (size_t i = 0; i < view.length(); ++i) - width += glyph_or_emoji_width(view.code_points()[i]); - return width; + return unicode_view_width(view); } void BitmapFont::set_type(FontTypes type) diff --git a/Userland/Libraries/LibGfx/BitmapFont.h b/Userland/Libraries/LibGfx/BitmapFont.h index 4a1508056f..845395343a 100644 --- a/Userland/Libraries/LibGfx/BitmapFont.h +++ b/Userland/Libraries/LibGfx/BitmapFont.h @@ -115,6 +115,9 @@ private: static RefPtr load_from_memory(const u8*); + template + int unicode_view_width(T const& view) const; + void update_x_height() { m_x_height = m_baseline - m_mean_line; }; int glyph_or_emoji_width_for_variable_width_font(u32 code_point) const;