Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qguisvg.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5
6#include "qguisvg_p.h"
7#include <cmath>
8#include <QtCore/qpoint.h>
9#include <QtCore/qregularexpression.h>
10#include <QtCore/qvarlengtharray.h>
11#include <QtCore/qloggingcategory.h>
12#include <QtGui/private/qmath_p.h>
13#include <array>
14
15QT_BEGIN_NAMESPACE
16
17using namespace Qt::Literals::StringLiterals;
18
19Q_STATIC_LOGGING_CATEGORY(lcGuiSvg, "qt.gui.svg")
20
21namespace {
22
23using namespace Qt::StringLiterals;
24
25static void pathArcSegment(QPainterPath &path,
26 qreal xc, qreal yc,
27 qreal th0, qreal th1,
28 qreal rx, qreal ry, qreal xAxisRotation)
29{
30 qreal sinTh, cosTh;
31 qreal a00, a01, a10, a11;
32 qreal x1, y1, x2, y2, x3, y3;
33 qreal t;
34 qreal thHalf;
35
36 sinTh = qSin(xAxisRotation * (Q_PI / 180.0));
37 cosTh = qCos(xAxisRotation * (Q_PI / 180.0));
38
39 a00 = cosTh * rx;
40 a01 = -sinTh * ry;
41 a10 = sinTh * rx;
42 a11 = cosTh * ry;
43
44 thHalf = 0.5 * (th1 - th0);
45 t = (8.0 / 3.0) * qSin(thHalf * 0.5) * qSin(thHalf * 0.5) / qSin(thHalf);
46 x1 = xc + qCos(th0) - t * qSin(th0);
47 y1 = yc + qSin(th0) + t * qCos(th0);
48 x3 = xc + qCos(th1);
49 y3 = yc + qSin(th1);
50 x2 = x3 + t * qSin(th1);
51 y2 = y3 - t * qCos(th1);
52
53 path.cubicTo(a00 * x1 + a01 * y1, a10 * x1 + a11 * y1,
54 a00 * x2 + a01 * y2, a10 * x2 + a11 * y2,
55 a00 * x3 + a01 * y3, a10 * x3 + a11 * y3);
56}
57
58}
59namespace QGuiSvg {
60
61// '0' is 0x30 and '9' is 0x39
62bool isDigit(ushort ch)
63{
64 static quint16 magic = 0x3ff;
65 return ((ch >> 4) == 3) && (magic >> (ch & 15));
66}
67
69{
70 const int maxLen = 255;//technically doubles can go til 308+ but whatever
71 char temp[maxLen+1];
72 int pos = 0;
73
74 if (str->startsWith(QLatin1Char('-'))) {
75 temp[pos++] = '-';
76 str->slice(1);
77 } else if (str->startsWith(QLatin1Char('+'))) {
78 str->slice(1);
79 }
80 while (!str->isEmpty() && isDigit(str->first().unicode()) && pos < maxLen) {
81 temp[pos++] = str->first().toLatin1();
82 str->slice(1);
83 }
84 if (str->startsWith(QLatin1Char('.')) && pos < maxLen) {
85 temp[pos++] = '.';
86 str->slice(1);
87 }
88 while (!str->isEmpty() && isDigit(str->first().unicode()) && pos < maxLen) {
89 temp[pos++] = str->first().toLatin1();
90 str->slice(1);
91 }
92 bool exponent = false;
93 if ((str->startsWith(QLatin1Char('e')) || str->startsWith(QLatin1Char('E'))) && pos < maxLen) {
94 exponent = true;
95 temp[pos++] = 'e';
96 str->slice(1);
97 if ((str->startsWith(QLatin1Char('-')) || str->startsWith(QLatin1Char('+')))
98 && pos < maxLen) {
99 temp[pos++] = str->first().toLatin1();
100 str->slice(1);
101 }
102 while (!str->isEmpty() && isDigit(str->first().unicode()) && pos < maxLen) {
103 temp[pos++] = str->first().toLatin1();
104 str->slice(1);
105 }
106 }
107
108 temp[pos] = '\0';
109
110 qreal val;
111 if (!exponent && pos < 10) {
112 int ival = 0;
113 const char *t = temp;
114 bool neg = false;
115 if (*t == '-') {
116 neg = true;
117 ++t;
118 }
119 while (*t && *t != '.') {
120 ival *= 10;
121 ival += (*t) - '0';
122 ++t;
123 }
124 if (*t == '.') {
125 ++t;
126 int div = 1;
127 while (*t) {
128 ival *= 10;
129 ival += (*t) - '0';
130 div *= 10;
131 ++t;
132 }
133 val = ((qreal)ival)/((qreal)div);
134 } else {
135 val = ival;
136 }
137 if (neg)
138 val = -val;
139 } else {
141 // Do not tolerate values too wild to be represented normally by floats
142 if (qFpClassify(float(val)) != FP_NORMAL)
143 val = 0;
144 }
145 return val;
146
147}
148
149qreal toDouble(QStringView str, bool *ok)
150{
151 const qreal res{ toDouble(&str) };
152 if (ok)
153 *ok = str.isEmpty();
154 return res;
155}
156
157qreal parseLength(QStringView str, LengthType *type, bool *ok, bool tiny12FeaturesOnly)
158{
159 QStringView numStr = QGuiSvg::trimmed(str, tiny12FeaturesOnly);
160
161 if (numStr.isEmpty()) {
162 if (ok)
163 *ok = false;
164 *type = LengthType::LT_OTHER;
165 return false;
166 }
167 if (numStr.endsWith(QLatin1Char('%'))) {
168 numStr.chop(1);
170 } else if (numStr.endsWith(QLatin1String("px"))) {
171 numStr.chop(2);
172 *type = LengthType::LT_PX;
173 } else if (numStr.endsWith(QLatin1String("pc"))) {
174 numStr.chop(2);
175 *type = LengthType::LT_PC;
176 } else if (numStr.endsWith(QLatin1String("pt"))) {
177 numStr.chop(2);
178 *type = LengthType::LT_PT;
179 } else if (numStr.endsWith(QLatin1String("mm"))) {
180 numStr.chop(2);
181 *type = LengthType::LT_MM;
182 } else if (numStr.endsWith(QLatin1String("cm"))) {
183 numStr.chop(2);
184 *type = LengthType::LT_CM;
185 } else if (numStr.endsWith(QLatin1String("in"))) {
186 numStr.chop(2);
187 *type = LengthType::LT_IN;
188 } else {
189 // default coordinate system
190 *type = LengthType::LT_PX;
191 }
192 qreal len = toDouble(numStr, ok);
193 return len;
194}
195
196// this should really be called convertToDefaultCoordinateSystem
197// and convert when type != QSvgHandler::defaultCoordinateSystem
198qreal convertToPixels(qreal len, bool , LengthType type)
199{
200
201 switch (type) {
203 break;
205 break;
207 break;
209 return len * 1.25;
210 break;
212 return len * 3.543307;
213 break;
215 return len * 35.43307;
216 break;
218 return len * 90;
219 break;
221 break;
222 default:
223 break;
224 }
225 return len;
226}
227
228// Parses the angle from a string and convert it to degrees.
229// In CSS, units are not optional so if a non-zero value is defined,
230// without a unit it should be treated as invalid.
231std::optional<qreal> parseAngle(QStringView str, bool tiny12FeaturesOnly)
232{
233 QStringView numStr = QGuiSvg::trimmed(str, tiny12FeaturesOnly);
234
235 if (numStr.isEmpty())
236 return std::nullopt;
237
238 qreal unitFactor = 1.0;
239 if (numStr.endsWith(QLatin1String("deg"))) {
240 numStr.chop(3);
241 unitFactor = 1.0;
242 } else if (numStr.endsWith(QLatin1String("grad"))) {
243 numStr.chop(4);
244 // deg = grad * 0.9;
245 unitFactor = 0.9;
246 } else if (numStr.endsWith(QLatin1String("rad"))) {
247 numStr.chop(3);
248 unitFactor = 180.0 / Q_PI;
249 } else if (numStr.endsWith(QLatin1String("turn"))) {
250 numStr.chop(4);
251 // one circle = one turn
252 unitFactor = 360.0;
253 } else {
254 return std::nullopt;
255 }
256
257 bool ok;
258 qreal angle = numStr.toDouble(&ok);
259 if (!ok)
260 return std::nullopt;
261
262 return angle * unitFactor;
263}
264
266{
268 while (!str->isEmpty() && str->first().isSpace())
269 str->slice(1);
270 while ((!str->isEmpty() && QGuiSvg::isDigit(str->first().unicode()))
272 || str->startsWith(QLatin1Char('.'))) {
273
274 if (patternLen && pattern[points.size() % patternLen] == 'f') {
275 // flag expected, may only be 0 or 1
276 if (!str->startsWith(QLatin1Char('0')) && !str->startsWith(QLatin1Char('1')))
277 return;
278 points.append(str->startsWith(QLatin1Char('0')) ? 0.0 : 1.0);
279 str->slice(1);
280 } else {
282 }
283
284 while (!str->isEmpty() && str->first().isSpace())
285 str->slice(1);
286 if (str->startsWith(QLatin1Char(',')))
287 str->slice(1);
288
289 //eat the rest of space
290 while (!str->isEmpty() && str->first().isSpace())
291 str->slice(1);
292 }
293}
294
295std::optional<QPainterPath> parsePath(QStringView dataStr, bool limitLength)
296{
297 if (dataStr.isEmpty())
298 return std::nullopt;
299
300 // Max QPainterPath element count when limitLength is set to true.
301 constexpr int maxElementCount = 0x7fff;
302
303 // Return parameters count for the command or -1 for invalid commands.
304 constexpr auto paramCountFor = [](char16_t c) {
305 switch (c) {
306 case 'm': case 'l': case 't': return 2;
307 case 'z': return 0;
308 case 'h': case 'v': return 1;
309 case 's': case 'q': return 4;
310 case 'c': return 6;
311 case 'a': return 7;
312 }
313 return -1;
314 };
315
316 QPointF startPoint;
317 QPointF currPoint;
318 QPointF ctrlPoint;
319 char16_t lastMode = 0;
320
321 QPainterPath path;
322 while (!dataStr.isEmpty()) {
323 while (dataStr.first().isSpace() && dataStr.length() > 1)
324 dataStr.slice(1);
325
326 const char16_t rawCmd = dataStr.first().unicode();
327 char16_t cmd = rawCmd | 0x20; // ASCII-lowercase
328
329 int paramCount = paramCountFor(cmd);
330 if (paramCount == -1)
331 break;
332 // If the raw command is lowercase -> it is relative.
333 const bool isRelative = rawCmd >= 'a' && rawCmd <= 'z';
334
335 dataStr.slice(1);
336 const char *pattern = nullptr;
337 if (cmd == 'a')
338 pattern = "rrrffrr";
339 QVarLengthArray<qreal, 8> arg;
340 parseNumbersArray(&dataStr, arg, pattern);
341 const qreal *num = arg.constData();
342 int count = arg.size();
343
344 do {
345 if (count < paramCount)
346 return path;
347
348 QPointF offset = isRelative ? currPoint : QPointF {0., 0.};
349 switch (cmd) {
350 case 'm': {
351 currPoint = startPoint = QPointF {num[0], num[1]} + offset;
352 path.moveTo(startPoint);
353
354 // As per 1.2 spec 8.3.2 The "moveto" commands
355 // If a 'moveto' is followed by multiple pairs of coordinates without explicit commands,
356 // the subsequent pairs shall be treated as implicit 'lineto' commands.
357 cmd = 'l';
358 }
359 break;
360 case 'z': {
361 currPoint = startPoint;
362 path.closeSubpath();
363 }
364 break;
365 case 'l': {
366 currPoint = QPointF {num[0], num[1]} + offset;
367 path.lineTo(currPoint);
368 }
369 break;
370 case 'h': {
371 currPoint.setX(num[0] + offset.x());
372 path.lineTo(currPoint);
373 }
374 break;
375 case 'v': {
376 currPoint.setY(num[0] + offset.y());
377 path.lineTo(currPoint);
378 }
379 break;
380 case 'c': {
381 QPointF c1 = QPointF {num[0], num[1]} + offset;
382 QPointF c2 = QPointF {num[2], num[3]} + offset;
383 QPointF e = QPointF {num[4], num[5]} + offset;
384 path.cubicTo(c1, c2, e);
385 ctrlPoint = c2;
386 currPoint = e;
387 break;
388 }
389 case 's': {
390 QPointF c1;
391 if (lastMode == 'c' || lastMode == 's')
392 c1 = 2 * currPoint - ctrlPoint;
393 else
394 c1 = currPoint;
395 QPointF c2 = QPointF {num[0], num[1]} + offset;
396 QPointF e = QPointF {num[2], num[3]} + offset;
397
398 path.cubicTo(c1, c2, e);
399 ctrlPoint = c2;
400 currPoint = e;
401 break;
402 }
403 case 'q': {
404 QPointF c = QPointF {num[0], num[1]} + offset;
405 QPointF e = QPointF {num[2], num[3]} + offset;
406 path.quadTo(c, e);
407 ctrlPoint = c;
408 currPoint = e;
409 break;
410 }
411 case 't': {
412 QPointF e = QPointF {num[0], num[1]} + offset;
413 QPointF c;
414 if (lastMode == 'q' || lastMode == 't')
415 c = 2 * currPoint - ctrlPoint;
416 else
417 c = currPoint;
418 path.quadTo(c, e);
419 ctrlPoint = c;
420 currPoint = e;
421 break;
422 }
423 case 'a': {
424 qreal rx = num[0];
425 qreal ry = num[1];
426 qreal xAxisRotation = num[2];
427 qreal largeArcFlag = num[3];
428 qreal sweepFlag = num[4];
429 qreal ex = num[5] + offset.x();
430 qreal ey = num[6] + offset.y();
431 qreal curx = currPoint.x();
432 qreal cury = currPoint.y();
433 pathArc(path, rx, ry, xAxisRotation, int(largeArcFlag),
434 int(sweepFlag), ex, ey, curx, cury);
435
436 currPoint = QPointF {ex, ey};
437 }
438 break;
439 default:
440 Q_ASSERT_X(false, "parsePath", "command table out of sync with switch");
441 return std::nullopt;
442 }
443
444 lastMode = cmd;
445 if (limitLength && path.elementCount() > maxElementCount) {
446 qCWarning(lcGuiSvg, "Untrusted SVG path limit exceeded. Path truncated.");
447 return path;
448 }
449
450 // the z/Z command should have no arguments. Otherwise,
451 // the remaining part of the path is invalid.
452 if (cmd == 'z' && count != 0)
453 return path;
454
455 count -= paramCount;
456 num += paramCount;
457 } while (count > 0);
458 }
459
460 return path;
461}
462
463// the arc handling code underneath is from XSVG (BSD license)
464/*
465 * Copyright 2002 USC/Information Sciences Institute
466 *
467 * Permission to use, copy, modify, distribute, and sell this software
468 * and its documentation for any purpose is hereby granted without
469 * fee, provided that the above copyright notice appear in all copies
470 * and that both that copyright notice and this permission notice
471 * appear in supporting documentation, and that the name of
472 * Information Sciences Institute not be used in advertising or
473 * publicity pertaining to distribution of the software without
474 * specific, written prior permission. Information Sciences Institute
475 * makes no representations about the suitability of this software for
476 * any purpose. It is provided "as is" without express or implied
477 * warranty.
478 *
479 * INFORMATION SCIENCES INSTITUTE DISCLAIMS ALL WARRANTIES WITH REGARD
480 * TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
481 * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL INFORMATION SCIENCES
482 * INSTITUTE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
483 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
484 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
485 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
486 * PERFORMANCE OF THIS SOFTWARE.
487 *
488 */
489void pathArc(QPainterPath &path, qreal rx, qreal ry,
490 qreal x_axis_rotation, int large_arc_flag,
491 int sweep_flag, qreal x, qreal y,
492 qreal curx, qreal cury)
493{
494 // Check if the start point is equal to the end point.
495 if (QPointF(curx, cury) == QPointF(x, y))
496 return;
497
498 const qreal Pr1 = rx * rx;
499 const qreal Pr2 = ry * ry;
500
501 // Avoid nans and division by zero.
502 if (qFuzzyIsNull(Pr1) || qFuzzyIsNull(Pr2)) {
503 // https://www.w3.org/TR/SVG/paths.html#ArcOutOfRangeParameters says:
504 // "If either rx or ry is 0, then this arc is treated as a straight line
505 // segment (a "lineto") joining the endpoints."
506 path.lineTo(x, y);
507 return;
508 }
509
510 qreal sin_th, cos_th;
511 qreal a00, a01, a10, a11;
512 qreal x0, y0, x1, y1, xc, yc;
513 qreal d, sfactor, sfactor_sq;
514 qreal th0, th1, th_arc;
515 int i, n_segs;
516 qreal dx, dy, dx1, dy1, Px, Py, check;
517
518 rx = qAbs(rx);
519 ry = qAbs(ry);
520
521 sin_th = qSin(x_axis_rotation * (Q_PI / 180.0));
522 cos_th = qCos(x_axis_rotation * (Q_PI / 180.0));
523
524 dx = (curx - x) / 2.0;
525 dy = (cury - y) / 2.0;
526 dx1 = cos_th * dx + sin_th * dy;
527 dy1 = -sin_th * dx + cos_th * dy;
528 Px = dx1 * dx1;
529 Py = dy1 * dy1;
530 /* Spec : check if radii are large enough */
531 check = Px / Pr1 + Py / Pr2;
532 if (check > 1) {
533 rx = rx * qSqrt(check);
534 ry = ry * qSqrt(check);
535 }
536
537 a00 = cos_th / rx;
538 a01 = sin_th / rx;
539 a10 = -sin_th / ry;
540 a11 = cos_th / ry;
541 x0 = a00 * curx + a01 * cury;
542 y0 = a10 * curx + a11 * cury;
543 x1 = a00 * x + a01 * y;
544 y1 = a10 * x + a11 * y;
545 /* (x0, y0) is current point in transformed coordinate space.
546 (x1, y1) is new point in transformed coordinate space.
547
548 The arc fits a unit-radius circle in this space.
549 */
550 d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
551 if (!d)
552 return;
553 sfactor_sq = 1.0 / d - 0.25;
554 if (sfactor_sq < 0) sfactor_sq = 0;
555 sfactor = qSqrt(sfactor_sq);
556 if (sweep_flag == large_arc_flag) sfactor = -sfactor;
557 xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
558 yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
559 /* (xc, yc) is center of the circle. */
560
561 th0 = qAtan2(y0 - yc, x0 - xc);
562 th1 = qAtan2(y1 - yc, x1 - xc);
563
564 th_arc = th1 - th0;
565 if (th_arc < 0 && sweep_flag)
566 th_arc += 2 * Q_PI;
567 else if (th_arc > 0 && !sweep_flag)
568 th_arc -= 2 * Q_PI;
569
570 n_segs = qCeil(qAbs(th_arc / (Q_PI * 0.5 + 0.001)));
571
572 for (i = 0; i < n_segs; i++) {
573 pathArcSegment(path, xc, yc,
574 th0 + i * th_arc / n_segs,
575 th0 + (i + 1) * th_arc / n_segs,
576 rx, ry, x_axis_rotation);
577 }
578}
579
580namespace {
581namespace svgChars {
582constexpr auto spaces = " \\t\\n\\r\\f"_L1;
583constexpr auto spacesTiny = " \\t\\n\\r"_L1;
584} // namespace svgChars
585} // namespace
586
587static const QRegularExpression &reNoSpace(bool tiny12FeaturesOnly)
588{
589 if (tiny12FeaturesOnly) {
590 static QRegularExpression reTiny("[^"_L1 + svgChars::spacesTiny + "]"_L1);
591 return reTiny;
592 } else {
593 static QRegularExpression re("[^"_L1 + svgChars::spaces + "]"_L1);
594 return re;
595 }
596}
597
598QStringView trimmed(QStringView sv, bool tiny12FeaturesOnly)
599{
600 const QRegularExpression &re = reNoSpace(tiny12FeaturesOnly);
601 const qsizetype first = sv.indexOf(re);
602 if (first == -1) // implies last
603 return sv.first(0);
604 else
605 return sv.sliced(first, sv.lastIndexOf(re) - first + 1);
606}
607}
608
609QT_END_NAMESPACE
@ LT_PERCENT
Definition qguisvg_p.h:30
@ LT_OTHER
Definition qguisvg_p.h:37
std::optional< QPainterPath > parsePath(QStringView dataStr, bool limitLength)
Definition qguisvg.cpp:295
QStringView trimmed(QStringView sv, bool tiny12FeaturesOnly)
Definition qguisvg.cpp:598
void pathArc(QPainterPath &path, qreal rx, qreal ry, qreal x_axis_rotation, int large_arc_flag, int sweep_flag, qreal x, qreal y, qreal curx, qreal cury)
Definition qguisvg.cpp:489
void parseNumbersArray(QStringView *str, QVarLengthArray< qreal, 8 > &points, const char *pattern)
Definition qguisvg.cpp:265
std::optional< qreal > parseAngle(QStringView str, bool tiny12FeaturesOnly)
Definition qguisvg.cpp:231
bool isDigit(ushort ch)
Definition qguisvg.cpp:62
qreal convertToPixels(qreal len, bool, LengthType type)
Definition qguisvg.cpp:198
static const QRegularExpression & reNoSpace(bool tiny12FeaturesOnly)
Definition qguisvg.cpp:587
qreal toDouble(QStringView str, bool *ok)
Definition qguisvg.cpp:149
qreal parseLength(QStringView str, LengthType *type, bool *ok, bool tiny12FeaturesOnly)
Definition qguisvg.cpp:157
qreal toDouble(QStringView *str)
Definition qguisvg.cpp:68
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)