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
qsvgdocument.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
5
7#include "qsvgfont_p.h"
8
9#include "qpainter.h"
10#include "qfile.h"
11#include "qbuffer.h"
12#include "qbytearray.h"
13#include "qstack.h"
14#include "qtransform.h"
15#include "qdebug.h"
16
17#ifndef QT_NO_COMPRESS
18#include <zlib.h>
19#endif
20
21QT_BEGIN_NAMESPACE
22
23using namespace Qt::StringLiterals;
24
25QSvgDocument::QSvgDocument(QtSvg::Options options, QtSvg::AnimatorType type)
26 : QSvgStructureNode(0)
27 , m_widthPercent(false)
28 , m_heightPercent(false)
29 , m_animated(false)
30 , m_fps(30)
31 , m_options(options)
32{
33 bool animationEnabled = !m_options.testFlag(QtSvg::DisableAnimations);
34 switch (type) {
35 case QtSvg::AnimatorType::Automatic:
36 if (animationEnabled)
37 m_animator.reset(new QSvgAnimator);
38 break;
39 case QtSvg::AnimatorType::Controlled:
40 if (animationEnabled)
41 m_animator.reset(new QSvgAnimationController);
42 }
43}
44
45QSvgDocument::~QSvgDocument()
46{
47}
48
49static bool hasSvgHeader(const QByteArray &buf)
50{
51 QTextStream s(buf); // Handle multi-byte encodings
52 QString h = s.readAll();
53 QStringView th = QStringView(h).trimmed();
54 bool matched = false;
55 if (th.startsWith("<svg"_L1) || th.startsWith("<!DOCTYPE svg"_L1))
56 matched = true;
57 else if (th.startsWith("<?xml"_L1) || th.startsWith("<!--"_L1))
58 matched = th.contains("<!DOCTYPE svg"_L1) || th.contains("<svg"_L1);
59 return matched;
60}
61
62#ifndef QT_NO_COMPRESS
63static QByteArray qt_inflateSvgzDataFrom(QIODevice *device, bool doCheckContent = true);
64# ifdef QT_BUILD_INTERNAL
65Q_AUTOTEST_EXPORT QByteArray qt_inflateGZipDataFrom(QIODevice *device)
66{
67 return qt_inflateSvgzDataFrom(device, false); // autotest wants unchecked result
68}
69# endif
70
71static QByteArray qt_inflateSvgzDataFrom(QIODevice *device, bool doCheckContent)
72{
73 if (!device)
74 return QByteArray();
75
76 if (!device->isOpen())
77 device->open(QIODevice::ReadOnly);
78
79 Q_ASSERT(device->isOpen() && device->isReadable());
80
81 static const int CHUNK_SIZE = 4096;
82 int zlibResult = Z_OK;
83
84 QByteArray source;
85 QByteArray destination;
86
87 // Initialize zlib stream struct
88 z_stream zlibStream;
89 zlibStream.next_in = Z_NULL;
90 zlibStream.avail_in = 0;
91 zlibStream.avail_out = 0;
92 zlibStream.zalloc = Z_NULL;
93 zlibStream.zfree = Z_NULL;
94 zlibStream.opaque = Z_NULL;
95
96 // Adding 16 to the window size gives us gzip decoding
97 if (inflateInit2(&zlibStream, MAX_WBITS + 16) != Z_OK) {
98 qCWarning(lcSvgHandler, "Cannot initialize zlib, because: %s",
99 (zlibStream.msg != NULL ? zlibStream.msg : "Unknown error"));
100 return QByteArray();
101 }
102
103 bool stillMoreWorkToDo = true;
104 while (stillMoreWorkToDo) {
105
106 if (!zlibStream.avail_in) {
107 source = device->read(CHUNK_SIZE);
108
109 if (source.isEmpty())
110 break;
111
112 zlibStream.avail_in = source.size();
113 zlibStream.next_in = reinterpret_cast<Bytef*>(source.data());
114 }
115
116 do {
117 // Prepare the destination buffer
118 int oldSize = destination.size();
119 if (oldSize > INT_MAX - CHUNK_SIZE) {
120 inflateEnd(&zlibStream);
121 qCWarning(lcSvgHandler, "Error while inflating gzip file: integer size overflow");
122 return QByteArray();
123 }
124
125 destination.resize(oldSize + CHUNK_SIZE);
126 zlibStream.next_out = reinterpret_cast<Bytef*>(
127 destination.data() + oldSize - zlibStream.avail_out);
128 zlibStream.avail_out += CHUNK_SIZE;
129
130 zlibResult = inflate(&zlibStream, Z_NO_FLUSH);
131 switch (zlibResult) {
132 case Z_NEED_DICT:
133 case Z_DATA_ERROR:
134 case Z_STREAM_ERROR:
135 case Z_MEM_ERROR: {
136 inflateEnd(&zlibStream);
137 qCWarning(lcSvgHandler, "Error while inflating gzip file: %s",
138 (zlibStream.msg != NULL ? zlibStream.msg : "Unknown error"));
139 return QByteArray();
140 }
141 }
142
143 // If the output buffer still has more room after calling inflate
144 // it means we have to provide more data, so exit the loop here
145 } while (!zlibStream.avail_out);
146
147 if (doCheckContent) {
148 // Quick format check, equivalent to QSvgIOHandler::canRead()
149 const qsizetype destinationContents = std::min(destination.size(), static_cast<qsizetype>(zlibStream.total_out));
150 Q_ASSERT(destinationContents == static_cast<qsizetype>(zlibStream.total_out));
151 if (!hasSvgHeader(QByteArray::fromRawData(destination.constData(), destinationContents))) {
152 inflateEnd(&zlibStream);
153 qCWarning(lcSvgHandler, "Error while inflating gzip file: SVG format check failed");
154 return QByteArray();
155 }
156 doCheckContent = false; // Run only once, on first chunk
157 }
158
159 if (zlibResult == Z_STREAM_END) {
160 // Make sure there are no more members to process before exiting
161 if (!(zlibStream.avail_in && inflateReset(&zlibStream) == Z_OK))
162 stillMoreWorkToDo = false;
163 }
164 }
165
166 // Chop off trailing space in the buffer
167 destination.chop(zlibStream.avail_out);
168
169 inflateEnd(&zlibStream);
170 return destination;
171}
172#else
173static QByteArray qt_inflateSvgzDataFrom(QIODevice *)
174{
175 return QByteArray();
176}
177#endif
178
179std::unique_ptr<QSvgDocument> QSvgDocument::load(const QString &fileName, QtSvg::Options options,
180 QtSvg::AnimatorType type)
181{
182 std::unique_ptr<QSvgDocument> doc;
183 QFile file(fileName);
184 if (!file.open(QFile::ReadOnly)) {
185 qCWarning(lcSvgHandler, "Cannot open file '%s', because: %s",
186 qPrintable(fileName), qPrintable(file.errorString()));
187 return doc;
188 }
189
190 if (fileName.endsWith(QLatin1String(".svgz"), Qt::CaseInsensitive)
191 || fileName.endsWith(QLatin1String(".svg.gz"), Qt::CaseInsensitive)) {
192 return load(qt_inflateSvgzDataFrom(&file));
193 }
194
195 QSvgHandler handler(&file, options, type);
196 if (handler.ok()) {
197 doc.reset(handler.document());
198 if (doc->m_animator)
199 doc->m_animator->setAnimationDuration(handler.animationDuration());
200 } else {
201 qCWarning(lcSvgHandler, "Cannot read file '%s', because: %s (line %d)",
202 qPrintable(fileName), qPrintable(handler.errorString()), handler.lineNumber());
203 delete handler.document();
204 }
205 return doc;
206}
207
208std::unique_ptr<QSvgDocument> QSvgDocument::load(const QByteArray &contents, QtSvg::Options options,
209 QtSvg::AnimatorType type)
210{
211 std::unique_ptr<QSvgDocument> doc;
212 QByteArray svg;
213 // Check for gzip magic number and inflate if appropriate
214 if (contents.startsWith("\x1f\x8b")) {
215 QBuffer buffer;
216 buffer.setData(contents);
217 svg = qt_inflateSvgzDataFrom(&buffer);
218 } else {
219 svg = contents;
220 }
221 if (svg.isNull())
222 return doc;
223
224 QBuffer buffer;
225 buffer.setData(svg);
226 buffer.open(QIODevice::ReadOnly);
227 QSvgHandler handler(&buffer, options, type);
228
229 if (handler.ok()) {
230 doc.reset(handler.document());
231 if (doc->m_animator)
232 doc->m_animator->setAnimationDuration(handler.animationDuration());
233 } else {
234 delete handler.document();
235 }
236 return doc;
237}
238
239std::unique_ptr<QSvgDocument> QSvgDocument::load(QXmlStreamReader *contents, QtSvg::Options options,
240 QtSvg::AnimatorType type)
241{
242 QSvgHandler handler(contents, options, type);
243
244 std::unique_ptr<QSvgDocument> doc;
245 if (handler.ok()) {
246 doc.reset(handler.document());
247 if (doc->m_animator)
248 doc->m_animator->setAnimationDuration(handler.animationDuration());
249 } else {
250 delete handler.document();
251 }
252 return doc;
253}
254
255void QSvgDocument::draw(QPainter *p, const QRectF &bounds)
256{
257 if (displayMode() == QSvgNode::NoneMode)
258 return;
259
260 p->save();
261 //sets default style on the painter
262 //### not the most optimal way
263 mapSourceToTarget(p, bounds);
264 initPainter(p);
265 applyStyle(p, m_states);
266 for (const auto &node : renderers()) {
267 if ((node->isVisible()) && (node->displayMode() != QSvgNode::NoneMode))
268 node->draw(p, m_states);
269 }
270 revertStyle(p, m_states);
271 p->restore();
272}
273
274
275void QSvgDocument::draw(QPainter *p, const QString &id,
276 const QRectF &bounds)
277{
278 QSvgNode *node = scopeNode(id);
279
280 if (!node) {
281 qCDebug(lcSvgHandler, "Couldn't find node %s. Skipping rendering.", qPrintable(id));
282 return;
283 }
284
285 if (node->displayMode() == QSvgNode::NoneMode)
286 return;
287
288 p->save();
289
290 const QRectF elementBounds = node->bounds();
291
292 mapSourceToTarget(p, bounds, elementBounds);
293 QTransform originalTransform = p->worldTransform();
294
295 //XXX set default style on the painter
296 QPen pen(Qt::NoBrush, 1, Qt::SolidLine, Qt::FlatCap, Qt::SvgMiterJoin);
297 pen.setMiterLimit(4);
298 p->setPen(pen);
299 p->setBrush(Qt::black);
300 p->setRenderHint(QPainter::Antialiasing);
301 p->setRenderHint(QPainter::SmoothPixmapTransform);
302
303 QStack<QSvgNode*> parentApplyStack;
304 QSvgNode *parent = node->parent();
305 while (parent) {
306 parentApplyStack.push(parent);
307 parent = parent->parent();
308 }
309
310 for (int i = parentApplyStack.size() - 1; i >= 0; --i)
311 parentApplyStack[i]->applyStyle(p, m_states);
312
313 // Reset the world transform so that our parents don't affect
314 // the position
315 QTransform currentTransform = p->worldTransform();
316 p->setWorldTransform(originalTransform);
317
318 node->draw(p, m_states);
319
320 p->setWorldTransform(currentTransform);
321
322 for (int i = 0; i < parentApplyStack.size(); ++i)
323 parentApplyStack[i]->revertStyle(p, m_states);
324
325 //p->fillRect(bounds.adjusted(-5, -5, 5, 5), QColor(0, 0, 255, 100));
326
327 p->restore();
328}
329
330QSvgNode::Type QSvgDocument::type() const
331{
332 return Doc;
333}
334
335void QSvgDocument::setWidth(int len, bool percent)
336{
337 m_size.setWidth(len);
338 m_widthPercent = percent;
339}
340
341void QSvgDocument::setHeight(int len, bool percent)
342{
343 m_size.setHeight(len);
344 m_heightPercent = percent;
345}
346
347void QSvgDocument::setPreserveAspectRatio(bool on)
348{
349 m_preserveAspectRatio = on;
350}
351
352void QSvgDocument::setViewBox(const QRectF &rect)
353{
354 m_viewBox = rect;
355 m_implicitViewBox = rect.isNull();
356}
357
358QtSvg::Options QSvgDocument::options() const
359{
360 return m_options;
361}
362
363void QSvgDocument::addSvgFont(QSvgFont *font)
364{
365 m_fonts.insert(font->familyName(), font);
366}
367
368QSvgFont * QSvgDocument::svgFont(const QString &family) const
369{
370 return m_fonts[family];
371}
372
373void QSvgDocument::addNamedNode(const QString &id, QSvgNode *node)
374{
375 m_namedNodes.insert(id, node);
376}
377
378QSvgNode *QSvgDocument::namedNode(const QString &id) const
379{
380 return m_namedNodes.value(id);
381}
382
383void QSvgDocument::addNamedStyle(const QString &id, QSvgPaintStyleProperty *style)
384{
385 if (!m_namedStyles.contains(id))
386 m_namedStyles.insert(id, style);
387 else
388 qCWarning(lcSvgHandler) << "Duplicate unique style id:" << id;
389}
390
391QSvgPaintStyleProperty *QSvgDocument::namedStyle(const QString &id) const
392{
393 return m_namedStyles.value(id);
394}
395
396void QSvgDocument::restartAnimation()
397{
398 if (m_animator)
399 m_animator->restartAnimation();
400}
401
402bool QSvgDocument::animated() const
403{
404 return m_animated;
405}
406
407void QSvgDocument::setAnimated(bool a)
408{
409 m_animated = a;
410}
411
412void QSvgDocument::draw(QPainter *p)
413{
414 draw(p, QRectF());
415}
416
417void QSvgDocument::drawCommand(QPainter *, QSvgExtraStates &)
418{
419 qCDebug(lcSvgHandler) << "SVG Tiny does not support nested <svg> elements: ignored.";
420 return;
421}
422
423static bool isValidMatrix(const QTransform &transform)
424{
425 qreal determinant = transform.determinant();
426 return qIsFinite(determinant);
427}
428
429void QSvgDocument::mapSourceToTarget(QPainter *p, const QRectF &targetRect, const QRectF &sourceRect)
430{
431 QTransform oldTransform = p->worldTransform();
432
433 QRectF target = targetRect;
434 if (target.isEmpty()) {
435 QPaintDevice *dev = p->device();
436 QRectF deviceRect(0, 0, dev->width(), dev->height());
437 if (deviceRect.isEmpty()) {
438 if (sourceRect.isEmpty())
439 target = QRectF(QPointF(0, 0), size());
440 else
441 target = QRectF(QPointF(0, 0), sourceRect.size());
442 } else {
443 target = deviceRect;
444 }
445 }
446
447 QRectF source = sourceRect;
448 if (source.isEmpty())
449 source = viewBox();
450
451 if (source != target && !qFuzzyIsNull(source.width()) && !qFuzzyIsNull(source.height())) {
452 if (m_implicitViewBox || !preserveAspectRatio()) {
453 // Code path used when no view box is set, or IgnoreAspectRatio requested
454 QTransform transform;
455 transform.scale(target.width() / source.width(),
456 target.height() / source.height());
457 QRectF c2 = transform.mapRect(source);
458 p->translate(target.x() - c2.x(),
459 target.y() - c2.y());
460 p->scale(target.width() / source.width(),
461 target.height() / source.height());
462 } else {
463 // Code path used when KeepAspectRatio is requested. This attempts to emulate the default values
464 // of the <preserveAspectRatio tag that's implicitly defined when <viewbox> is used.
465
466 // Scale the view box into the view port (target) by preserve the aspect ratio.
467 QSizeF viewBoxSize = source.size();
468 viewBoxSize.scale(target.width(), target.height(), Qt::KeepAspectRatio);
469
470 // Center the view box in the view port
471 p->translate(target.x() + (target.width() - viewBoxSize.width()) / 2,
472 target.y() + (target.height() - viewBoxSize.height()) / 2);
473
474 p->scale(viewBoxSize.width() / source.width(),
475 viewBoxSize.height() / source.height());
476
477 // Apply the view box translation if specified.
478 p->translate(-source.x(), -source.y());
479 }
480 }
481
482 if (!isValidMatrix(p->worldTransform()))
483 p->setWorldTransform(oldTransform);
484}
485
486QRectF QSvgDocument::boundsOnElement(const QString &id) const
487{
488 const QSvgNode *node = scopeNode(id);
489 if (!node)
490 node = this;
491 return node->bounds();
492}
493
494bool QSvgDocument::elementExists(const QString &id) const
495{
496 QSvgNode *node = scopeNode(id);
497
498 return (node!=0);
499}
500
501QTransform QSvgDocument::transformForElement(const QString &id) const
502{
503 QSvgNode *node = scopeNode(id);
504
505 if (!node) {
506 qCDebug(lcSvgHandler, "Couldn't find node %s. Skipping rendering.", qPrintable(id));
507 return QTransform();
508 }
509
510 QTransform t;
511
512 node = node->parent();
513 while (node) {
514 if (node->m_style.transform)
515 t *= node->m_style.transform->qtransform();
516 node = node->parent();
517 }
518
519 return t;
520}
521
522int QSvgDocument::currentFrame() const
523{
524 const double runningPercentage = qMin(currentElapsed() / double(animationDuration()), 1.);
525 const int totalFrames = m_fps * animationDuration() / 1000;
526 return int(runningPercentage * totalFrames);
527}
528
529void QSvgDocument::setCurrentFrame(int frame)
530{
531 if (!m_animator)
532 return;
533
534 const int totalFrames = m_fps * animationDuration() / 1000;
535 if (totalFrames == 0)
536 return;
537
538 const int timeForFrame = frame * animationDuration() / totalFrames; //in ms
539 const int timeToAdd = timeForFrame - currentElapsed();
540 m_animator->setAnimatorTime(timeToAdd);
541}
542
543void QSvgDocument::setFramesPerSecond(int num)
544{
545 m_fps = num;
546}
547
548QSharedPointer<QSvgAbstractAnimator> QSvgDocument::animator() const
549{
550 return m_animator;
551}
552
553bool QSvgDocument::isLikelySvg(QIODevice *device, bool *isCompressed)
554{
555 constexpr int bufSize = 4096;
556 char buf[bufSize];
557 char inflateBuf[bufSize];
558 bool useInflateBuf = false;
559 int readLen = device->peek(buf, bufSize);
560 if (readLen < 8)
561 return false;
562#ifndef QT_NO_COMPRESS
563 if (quint8(buf[0]) == 0x1f && quint8(buf[1]) == 0x8b) {
564 // Indicates gzip compressed content, i.e. svgz
565 z_stream zlibStream;
566 zlibStream.avail_in = readLen;
567 zlibStream.next_out = reinterpret_cast<Bytef *>(inflateBuf);
568 zlibStream.avail_out = bufSize;
569 zlibStream.next_in = reinterpret_cast<Bytef *>(buf);
570 zlibStream.zalloc = Z_NULL;
571 zlibStream.zfree = Z_NULL;
572 zlibStream.opaque = Z_NULL;
573 if (inflateInit2(&zlibStream, MAX_WBITS + 16) != Z_OK)
574 return false;
575 int zlibResult = inflate(&zlibStream, Z_NO_FLUSH);
576 inflateEnd(&zlibStream);
577 if ((zlibResult != Z_OK && zlibResult != Z_STREAM_END) || zlibStream.total_out < 8)
578 return false;
579 readLen = zlibStream.total_out;
580 if (isCompressed)
581 *isCompressed = true;
582 useInflateBuf = true;
583 }
584#endif
585 return hasSvgHeader(QByteArray::fromRawData(useInflateBuf ? inflateBuf : buf, readLen));
586}
587
588QT_END_NAMESPACE
#define qPrintable(string)
Definition qstring.h:1683
static QByteArray qt_inflateSvgzDataFrom(QIODevice *device, bool doCheckContent=true)
static bool isValidMatrix(const QTransform &transform)
static bool hasSvgHeader(const QByteArray &buf)