diff --git a/ext/native/util/text/wrap_text.cpp b/ext/native/util/text/wrap_text.cpp index e63733225d..70754b4aa1 100644 --- a/ext/native/util/text/wrap_text.cpp +++ b/ext/native/util/text/wrap_text.cpp @@ -82,6 +82,7 @@ void WordWrapper::WrapBeforeWord() { out_[out_.size() - 1] = '-'; } out_ += "\n"; + lastLineStart_ = (int)out_.size(); x_ = 0.0f; forceEarlyWrap_ = false; } @@ -93,6 +94,13 @@ void WordWrapper::AppendWord(int endIndex, bool addNewline) { out_ += std::string(str_ + lastIndex_, endIndex - lastIndex_); if (addNewline) { out_ += "\n"; + lastLineStart_ = (int)out_.size(); + } else { + // We may have appended a newline - check. + size_t pos = out_.find_last_of("\n", lastLineStart_); + if (pos != out_.npos) { + lastLineStart_ = (int)pos; + } } lastIndex_ = endIndex; } @@ -135,9 +143,8 @@ void WordWrapper::Wrap() { // Is this the end of a word (space)? if (wordWidth_ > 0.0f && IsSpace(c)) { AppendWord(afterIndex, false); - // We include the space in the x increase. - // If the space takes it over, we'll wrap on the next word. - x_ += newWordWidth; + // To account for kerning around spaces, we recalculate the entire line width. + x_ = MeasureWidth(out_.c_str() + lastLineStart_, out_.size() - lastLineStart_); wordWidth_ = 0.0f; continue; } diff --git a/ext/native/util/text/wrap_text.h b/ext/native/util/text/wrap_text.h index a5f95d6bc8..ed2bc06d00 100644 --- a/ext/native/util/text/wrap_text.h +++ b/ext/native/util/text/wrap_text.h @@ -5,7 +5,7 @@ class WordWrapper { public: WordWrapper(const char *str, float maxW) - : str_(str), maxW_(maxW), lastIndex_(0), x_(0.0f), forceEarlyWrap_(false) { + : str_(str), maxW_(maxW) { } std::string Wrapped(); @@ -25,11 +25,13 @@ protected: const float maxW_; std::string out_; // Index of last output / start of current word. - int lastIndex_; + int lastIndex_ = 0; + // Index of last line start. + int lastLineStart_ = 0; // Position the current word starts at. - float x_; + float x_ = 0.0f; // Most recent width of word since last index. float wordWidth_; // Force the next word to cut partially and wrap. - bool forceEarlyWrap_; + bool forceEarlyWrap_ = false; };