From 668d010f70e02ea41056943f5cfc7580e030ad25 Mon Sep 17 00:00:00 2001 From: Harley Acheson Date: Mon, 15 Apr 2024 11:23:14 -0700 Subject: [PATCH] Refactor: BLF Offset from Cursor Position Early Exits BLF function blf_str_offset_from_cursor_position returns the character offset in a string given a horizontal cursor position. It currently has no early exits, but can do so for no string or empty string. For negative position values (so left of the string), do not exit out with zero but instead act as if it were zero to ensure we test against the first glyph, which might not be part of the character. --- source/blender/blenfont/intern/blf_font.cc | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source/blender/blenfont/intern/blf_font.cc b/source/blender/blenfont/intern/blf_font.cc index 47dc246841f..aa18e974f35 100644 --- a/source/blender/blenfont/intern/blf_font.cc +++ b/source/blender/blenfont/intern/blf_font.cc @@ -1024,10 +1024,18 @@ size_t blf_str_offset_from_cursor_position(FontBLF *font, size_t str_len, int location_x) { + if (!str || !str[0] || !str_len) { + return 0; + } + CursorPositionForeachGlyph_Data data{}; data.location_x = location_x; data.r_offset = size_t(-1); + /* For negative position, don't early exit with 0 but instead test as + * if it were zero. First glyph might not be from first character. */ + location_x = std::max(location_x, 0); + blf_font_boundbox_foreach_glyph(font, str, str_len, blf_cursor_position_foreach_glyph, &data); if (data.r_offset == size_t(-1)) { -- 2.30.2