From ad538e5be047f3fc2eff0b1dcae86132352e8af3 Mon Sep 17 00:00:00 2001 From: Adrian Stanea Date: Mon, 25 Nov 2024 11:40:36 +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 --- .../sigrok-gui/src/annotationcurve.cpp | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/plugins/m2k/m2k-gui/sigrok-gui/src/annotationcurve.cpp b/plugins/m2k/m2k-gui/sigrok-gui/src/annotationcurve.cpp index de8006c113..e7a9cd69a1 100644 --- a/plugins/m2k/m2k-gui/sigrok-gui/src/annotationcurve.cpp +++ b/plugins/m2k/m2k-gui/sigrok-gui/src/annotationcurve.cpp @@ -672,16 +672,27 @@ uint64_t AnnotationCurve::getMaxAnnotationCount(int index) // shorten text to fit maxWidth pixels in width QString AnnotationCurve::shortenAnnotationText(const QString text, const double maxWidth, QPainter *painter) const { - const int padding = 12; - const QString extension = "..."; + const int PADDING = 12; + const QString EXTENSION = "..."; int count = 0; + 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(QSizeF(QwtText(text.left(count) + extension).textSize(painter->font())).width() <= maxWidth - padding) { + 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 : ""; } void AnnotationCurve::drawTwoSampleAnnotation(int row, const Annotation &ann, QPainter *painter,