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

This commit is contained in:
David Capello 2025-10-06 18:27:34 -03:00
parent d8193f5acc
commit 0faf9c0206
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();
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)

View File

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