Fix TextEdit::caretFromPosition() when lines have different heights

This commit is contained in:
David Capello 2025-10-06 18:27:34 -03:00
parent c089bb87ff
commit 2c9a2998df
2 changed files with 17 additions and 6 deletions

View File

@ -533,10 +533,9 @@ TextEdit::Caret TextEdit::caretFromPosition(const gfx::Point& position)
offsetPosition += View::getView(this)->viewScroll(); offsetPosition += View::getView(this)->viewScroll();
Caret caret(&m_lines); Caret caret(&m_lines);
const int lineHeight = font()->lineHeight();
// First check if the offset position is blank (below all the lines) // 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. // Get the last character in the last line.
caret.setLine(m_lines.size() - 1); caret.setLine(m_lines.size() - 1);
@ -547,12 +546,13 @@ TextEdit::Caret TextEdit::caretFromPosition(const gfx::Point& position)
return caret; return caret;
} }
int lineStartY = 0;
for (const Line& line : m_lines) { for (const Line& line : m_lines) {
const int lineStartY = line.i * lineHeight; const int lineEndY = lineStartY + line.height;
const int lineEndY = (line.i + 1) * lineHeight; if (offsetPosition.y < lineStartY || offsetPosition.y >= lineEndY) {
lineStartY = lineEndY;
if (offsetPosition.y > lineEndY || offsetPosition.y < lineStartY)
continue; // We're not in this line continue; // We're not in this line
}
caret.setLine(line.i); 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); caret.setPos(best);
break;
} }
return caret; return caret;
@ -767,6 +769,14 @@ void TextEdit::onSetFont()
onSetText(); onSetText();
} }
int TextEdit::maxHeight() const
{
int h = 0;
for (const auto& line : m_lines)
h += line.height;
return h;
}
void TextEdit::startTimer() void TextEdit::startTimer()
{ {
if (s_timer) if (s_timer)

View File

@ -174,6 +174,7 @@ private:
void insertCharacter(base::codepoint_t character); void insertCharacter(base::codepoint_t character);
void deleteSelection(); void deleteSelection();
void ensureCaretVisible(); void ensureCaretVisible();
int maxHeight() const;
void startTimer(); void startTimer();
void stopTimer(); void stopTimer();