From e04bbf2ded1fffd3e75838d3b3c21c47ab3bc55b Mon Sep 17 00:00:00 2001 From: Adrian Stanea Date: Mon, 25 Nov 2024 11:53:46 +0200 Subject: [PATCH] logic analyzer: fix annotation empty string causing infinite loop - Handle the edge case where an empty string passed to the shortenAnnotationText function causes an infinite loop. This fix ensures that the function returns the extension ("...") when the text is empty or the maxWidth is too small to fit the extension. Signed-off-by: Adrian Stanea --- src/logicanalyzer/annotationcurve.cpp | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/logicanalyzer/annotationcurve.cpp b/src/logicanalyzer/annotationcurve.cpp index e2222b81b1..b18051ae32 100644 --- a/src/logicanalyzer/annotationcurve.cpp +++ b/src/logicanalyzer/annotationcurve.cpp @@ -700,16 +700,27 @@ uint64_t AnnotationCurve::getMaxAnnotationCount(int index) QString AnnotationCurve::shortenAnnotationText(const QString text, const double maxWidth, QPainter *painter) const { - const int padding = 12; - const QString extension = "..."; - int count = 0; + const int PADDING = 12; + const QString EXTENSION = "..."; + int count = 0; - // find maximum number of characters that fit - while(QSizeF(QwtText(text.left(count) + extension).textSize(painter->font())).width() <= maxWidth - padding) { - count++; - } + bool isWithinTextLength = true; + bool isWithinMaxWidth = true; + + // Empty text or maxWidth is too small to even fit the extension + if(text.isEmpty() || maxWidth <= PADDING + painter->fontMetrics().horizontalAdvance(EXTENSION)) { + return EXTENSION; + } + + // find maximum number of characters that fit + while(isWithinTextLength && isWithinMaxWidth) { + count++; + isWithinTextLength = count < text.length(); + isWithinMaxWidth = QSizeF(QwtText(text.left(count) + EXTENSION).textSize(painter->font())).width() <= + maxWidth - PADDING; + } - return count ? text.left(count) + extension : ""; + return isWithinTextLength ? text.left(count) + EXTENSION : ""; }