From 0faf9c020672387db55d74aba17d7ca372209a74 Mon Sep 17 00:00:00 2001 From: David Capello Date: Mon, 6 Oct 2025 18:27:34 -0300 Subject: [PATCH] Fix TextEdit::caretFromPosition() when lines have different heights --- src/ui/textedit.cpp | 22 ++++++++++++++++------ src/ui/textedit.h | 1 + 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/ui/textedit.cpp b/src/ui/textedit.cpp index 5169ec7db..763da8dd0 100644 --- a/src/ui/textedit.cpp +++ b/src/ui/textedit.cpp @@ -533,10 +533,9 @@ TextEdit::Caret TextEdit::caretFromPosition(const gfx::Point& position) offsetPosition += View::getView(this)->viewScroll(); Caret caret(&m_lines); - const int lineHeight = font()->lineHeight(); // First check if the offset position is blank (below all the lines) - if (offsetPosition.y > m_lines.size() * lineHeight) { + if (offsetPosition.y >= maxHeight()) { // Get the last character in the last line. caret.setLine(m_lines.size() - 1); @@ -547,12 +546,13 @@ TextEdit::Caret TextEdit::caretFromPosition(const gfx::Point& position) return caret; } + int lineStartY = 0; for (const Line& line : m_lines) { - const int lineStartY = line.i * lineHeight; - const int lineEndY = (line.i + 1) * lineHeight; - - if (offsetPosition.y > lineEndY || offsetPosition.y < lineStartY) + const int lineEndY = lineStartY + line.height; + if (offsetPosition.y < lineStartY || offsetPosition.y >= lineEndY) { + lineStartY = lineEndY; continue; // We're not in this line + } caret.setLine(line.i); @@ -582,7 +582,9 @@ TextEdit::Caret TextEdit::caretFromPosition(const gfx::Point& position) } }); + // Done, we've found the clicked caret position caret.setPos(best); + break; } return caret; @@ -767,6 +769,14 @@ void TextEdit::onSetFont() onSetText(); } +int TextEdit::maxHeight() const +{ + int h = 0; + for (const auto& line : m_lines) + h += line.height; + return h; +} + void TextEdit::startTimer() { if (s_timer) diff --git a/src/ui/textedit.h b/src/ui/textedit.h index a51a490b4..78d80f93d 100644 --- a/src/ui/textedit.h +++ b/src/ui/textedit.h @@ -174,6 +174,7 @@ private: void insertCharacter(base::codepoint_t character); void deleteSelection(); void ensureCaretVisible(); + int maxHeight() const; void startTimer(); void stopTimer();