#include "geometry/ShapeGeometryLimits.h" #include "parsing/tkrTikzParserExplicit.h" #include #include #include namespace TikzRefinery { namespace { ParseResult rejectSource(const QString &strReason, qsizetype nByteOffset = 0) { ParseResult parseResult; parseResult.listDiagnostics.append( QStringLiteral("Diagram display unavailable at byte %1: %2 Source was preserved.") .arg(nByteOffset).arg(strReason)); return parseResult; // Never return a misleading partial diagram. } bool parseAppearance(const QString &strOptions, qreal &rLineWidthPoints, bool &bArrowAtStart, bool &bArrowAtEnd) { if (strOptions.isNull()) { return true; } // No style lookup, transformations, fills, or executable TeX options. const QRegularExpression expressionWidth( QStringLiteral(R"(^line\s+width\s*=\s*((?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+))\s*pt$)")); bool bWidthSeen = false; bool bArrowSeen = false; const QStringList listOptions = strOptions.split(QLatin1Char(',')); for (const QString &strOption : listOptions) { const QString strTrimmed = strOption.trimmed(); if (strTrimmed == QStringLiteral("black") || strTrimmed == QStringLiteral("solid")) { continue; } if (strTrimmed == QStringLiteral("->") || strTrimmed == QStringLiteral("<-") || strTrimmed == QStringLiteral("<->")) { if (bArrowSeen) { return false; } bArrowAtStart = strTrimmed.startsWith(QLatin1Char('<')); bArrowAtEnd = strTrimmed.endsWith(QLatin1Char('>')); bArrowSeen = true; continue; } const QRegularExpressionMatch matchWidth = expressionWidth.match(strTrimmed); if (!matchWidth.hasMatch() || bWidthSeen) { return false; } bool bConverted = false; rLineWidthPoints = matchWidth.captured(1).toDouble(&bConverted); if (!bConverted || !std::isfinite(rLineWidthPoints) || rLineWidthPoints <= 0.0) { return false; } bWidthSeen = true; } return true; } } // namespace ParseResult tkrTikzParserExplicit::parse(const QByteArray &baSource, quint64 uDocumentRevision) const { // One Latin-1 code unit per byte, including UTF-8 comments. Mask rather than // delete comments so regex captures remain offsets in the original QByteArray. QByteArray baMasked = baSource; if (baMasked.startsWith(QByteArray::fromHex("efbbbf"))) { baMasked.replace(0, 3, " "); } bool bInComment = false; for (qsizetype nByte = 0; nByte < baMasked.size(); ++nByte) { const char chByte = baMasked.at(nByte); if (chByte == '\r' || chByte == '\n') { bInComment = false; } else if (bInComment || chByte == '%') { // Escaped percent is deliberately unsupported by the grammar below. bInComment = true; baMasked[nByte] = ' '; } } const QString strSource = QString::fromLatin1(baMasked); for (qsizetype nByte = 0; nByte < baMasked.size(); ++nByte) { const unsigned char chByte = static_cast(baMasked.at(nByte)); if ((chByte < 32 && chByte != '\t' && chByte != '\r' && chByte != '\n') || chByte > 126) { return rejectSource(QStringLiteral("unsupported non-ASCII source outside comments."), nByte); } } QString strBody = strSource; qsizetype nBodyOffset = 0; // Recognize the corpus wrapper as a whole. Never search for draw commands // inside arbitrary TeX (macros, loops, scopes, or altered catcodes/units). const QRegularExpression expressionDocument(QStringLiteral( R"(\A\s*\\documentclass\s*\{article\}\s*\\usepackage\s*\{tikz\}\s*\\pagestyle\s*\{empty\}\s*\\begin\s*\{document\}\s*(?:\\noindent\s*)?\\begin\s*\{tikzpicture\}([\s\S]*)\\end\s*\{tikzpicture\}\s*\\end\s*\{document\}\s*\z)")); const QRegularExpression expressionPicture(QStringLiteral( R"(\A\s*\\begin\s*\{tikzpicture\}([\s\S]*)\\end\s*\{tikzpicture\}\s*\z)")); QRegularExpressionMatch matchEnvelope = expressionDocument.match(strSource); if (!matchEnvelope.hasMatch()) { matchEnvelope = expressionPicture.match(strSource); } if (matchEnvelope.hasMatch()) { strBody = matchEnvelope.captured(1); nBodyOffset = matchEnvelope.capturedStart(1); } const QString strNumber = QStringLiteral(R"(([+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)))"); const QString strPoint = QStringLiteral(R"(\(\s*)") + strNumber + QStringLiteral(R"(\s*cm\s*,\s*)") + strNumber + QStringLiteral(R"(\s*cm\s*\))"); const QString strCorners = strPoint + QStringLiteral(R"(\s*(rectangle|--)\s*)") + strPoint + QStringLiteral(R"(\s*;)"); const QRegularExpression expressionDraw( QStringLiteral(R"(\\draw\s*(?:\[([^\[\]]*)\]\s*)?)") + strCorners); const QRegularExpression expressionExtent( QStringLiteral(R"(\\path\s*\[\s*use\s+as\s+bounding\s+box\s*\]\s*)") + strPoint + QStringLiteral(R"(\s*rectangle\s*)") + strPoint + QStringLiteral(R"(\s*;)")); ParseResult parseResult; qsizetype nPosition = 0; while (nPosition < strBody.size()) { const QChar chCurrent = strBody.at(nPosition); if (chCurrent == QLatin1Char(' ') || chCurrent == QLatin1Char('\t') || chCurrent == QLatin1Char('\r') || chCurrent == QLatin1Char('\n')) { ++nPosition; continue; } const QRegularExpressionMatch matchDraw = expressionDraw.match( strBody, nPosition, QRegularExpression::NormalMatch, QRegularExpression::AnchorAtOffsetMatchOption); const bool bIsDraw = matchDraw.hasMatch(); const QRegularExpressionMatch matchCommand = bIsDraw ? matchDraw : expressionExtent.match( strBody, nPosition, QRegularExpression::NormalMatch, QRegularExpression::AnchorAtOffsetMatchOption); if (!matchCommand.hasMatch()) { return rejectSource(QStringLiteral("unsupported syntax or wrapper; expected an absolute cm rectangle or straight segment."), nBodyOffset + nPosition); } qreal rLineWidthPoints = 0.4; bool bArrowAtStart = false; bool bArrowAtEnd = false; if (bIsDraw && !parseAppearance(matchCommand.captured(1), rLineWidthPoints, bArrowAtStart, bArrowAtEnd)) { return rejectSource(QStringLiteral("unsupported appearance options."), nBodyOffset + nPosition); } const bool bIsRectangle = !bIsDraw || matchCommand.captured(4) == QStringLiteral("rectangle"); const int iFirstCoordinate = bIsDraw ? 2 : 1; qreal rCoordinates[4]; SourceRange rangesCoordinates[4]; for (int iCoordinate = 0; iCoordinate < 4; ++iCoordinate) { const int iCapture = iFirstCoordinate + iCoordinate + (bIsDraw && iCoordinate >= 2 ? 1 : 0); bool bConverted = false; rCoordinates[iCoordinate] = matchCommand.captured(iCapture).toDouble(&bConverted); if (!bConverted || !std::isfinite(rCoordinates[iCoordinate])) { return rejectSource(QStringLiteral("coordinate is not finite."), nBodyOffset + nPosition); } rangesCoordinates[iCoordinate] = {nBodyOffset + matchCommand.capturedStart(iCapture), matchCommand.capturedLength(iCapture)}; } const QPointF ptFirst(rCoordinates[0], rCoordinates[1]); const QPointF ptSecond(rCoordinates[2], rCoordinates[3]); if ((bIsRectangle && (ptFirst.x() == ptSecond.x() || ptFirst.y() == ptSecond.y())) || (!bIsRectangle && ptFirst == ptSecond)) { return rejectSource(QStringLiteral("degenerate geometry."), nBodyOffset + nPosition); } if (bIsRectangle && (bArrowAtStart || bArrowAtEnd)) { return rejectSource(QStringLiteral("arrow options require a straight segment."), nBodyOffset + nPosition); } if (bIsDraw) { ElementRecord elementRecord; elementRecord.uElementId = static_cast(parseResult.vecElements.size()) + 1; elementRecord.uDocumentRevision = uDocumentRevision; elementRecord.elementKind = bIsRectangle ? ElementKind::Rectangle : (bArrowAtStart || bArrowAtEnd ? ElementKind::Arrow : ElementKind::Line); elementRecord.bArrowAtStart = bArrowAtStart; elementRecord.bArrowAtEnd = bArrowAtEnd; elementRecord.ptFirstTikzPosition = ptFirst; elementRecord.ptSecondTikzPosition = ptSecond; elementRecord.rangeFirstX = rangesCoordinates[0]; elementRecord.rangeFirstY = rangesCoordinates[1]; elementRecord.rangeSecondX = rangesCoordinates[2]; elementRecord.rangeSecondY = rangesCoordinates[3]; elementRecord.rLineWidthPoints = rLineWidthPoints; parseResult.vecElements.append(elementRecord); } else { if (parseResult.comparisonExtent.bIsPresent || !parseResult.vecElements.isEmpty()) { return rejectSource(QStringLiteral("comparison extent must occur once, before drawing."), nBodyOffset + nPosition); } parseResult.comparisonExtent = {true, ptFirst, ptSecond}; } nPosition = matchCommand.capturedEnd(); } if (parseResult.vecElements.isEmpty()) { return rejectSource(QStringLiteral("no supported drawing elements found.")); } if (parseResult.comparisonExtent.bIsPresent) { const QRectF rectExtent = QRectF(parseResult.comparisonExtent.ptFirstTikzPosition, parseResult.comparisonExtent.ptSecondTikzPosition).normalized(); for (const ElementRecord &elementRecord : parseResult.vecElements) { // A conservative envelope also includes the default curved 'to' tip. const qreal rHalfStrokeCentimeters = outlineMarginCentimeters(elementRecord); const QRectF rectOutline = QRectF(elementRecord.ptFirstTikzPosition, elementRecord.ptSecondTikzPosition).normalized() .adjusted(-rHalfStrokeCentimeters, -rHalfStrokeCentimeters, rHalfStrokeCentimeters, rHalfStrokeCentimeters); if (!rectExtent.contains(rectOutline)) { return rejectSource(QStringLiteral("drawing exceeds the fixed comparison extent.")); } } } parseResult.bSafeToEdit = true; // Safe source records; gestures are still unavailable. return parseResult; } } // namespace TikzRefinery