diff --git a/lib/libimhex/include/hex/helpers/utils.hpp b/lib/libimhex/include/hex/helpers/utils.hpp index 49336df5b..cf2f50e73 100644 --- a/lib/libimhex/include/hex/helpers/utils.hpp +++ b/lib/libimhex/include/hex/helpers/utils.hpp @@ -294,12 +294,29 @@ namespace hex { [[nodiscard]] std::optional getEnvironmentVariable(const std::string &env); [[nodiscard]] inline std::string limitStringLength(const std::string &string, size_t maxLength) { - if (string.size() < maxLength) return string; + // If the string is shorter than the max length, return it as is + if (string.size() < maxLength) + return string; + // If the string is longer than the max length, find the last space before the max length auto it = string.begin() + maxLength; while (it != string.begin() && !std::isspace(*it)) --it; - return std::string(string.begin(), it) + "..."; + // If there's no space before the max length, just cut the string + if (it == string.begin()) { + it = string.begin() + maxLength; + + // Try to find a UTF-8 character boundary + while (it != string.begin() && (*it & 0x80) != 0x00) --it; + ++it; + } + + // If we still didn't find a valid boundary, just return the string as is + if (it == string.begin()) + return string; + + // Append + return std::string(string.begin(), it) + "…"; } [[nodiscard]] std::optional getInitialFilePath();