23using namespace Qt::StringLiterals;
25QSvgDocument::QSvgDocument(QtSvg::Options options, QtSvg::AnimatorType type)
26 : QSvgStructureNode(0)
30 m_states.trustedSource = m_options.testFlag(QtSvg::AssumeTrustedSource);
31 bool animationEnabled = !m_options.testFlag(QtSvg::DisableAnimations);
33 case QtSvg::AnimatorType::Automatic:
35 m_animator.reset(
new QSvgAnimator);
37 case QtSvg::AnimatorType::Controlled:
39 m_animator.reset(
new QSvgAnimationController);
43QSvgDocument::~QSvgDocument()
47 if (!m_states.trustedSource)
54 QString h = s.readAll();
55 QStringView th = QStringView(h).trimmed();
57 if (th.startsWith(
"<svg"_L1) || th.startsWith(
"<!DOCTYPE svg"_L1))
59 else if (th.startsWith(
"<?xml"_L1) || th.startsWith(
"<!--"_L1))
60 matched = th.contains(
"<!DOCTYPE svg"_L1) || th.contains(
"<svg"_L1);
66# ifdef QT_BUILD_INTERNAL
67Q_AUTOTEST_EXPORT QByteArray qt_inflateGZipDataFrom(QIODevice *device)
69 return qt_inflateSvgzDataFrom(device,
false);
78 if (!device->isOpen())
79 device->open(QIODevice::ReadOnly);
81 Q_ASSERT(device->isOpen() && device->isReadable());
83 static const int CHUNK_SIZE = 4096;
84 int zlibResult = Z_OK;
91 zlibStream.next_in = Z_NULL;
92 zlibStream.avail_in = 0;
93 zlibStream.avail_out = 0;
94 zlibStream.zalloc = Z_NULL;
95 zlibStream.zfree = Z_NULL;
96 zlibStream.opaque = Z_NULL;
99 if (inflateInit2(&zlibStream, MAX_WBITS + 16) != Z_OK) {
100 qCWarning(lcSvgHandler,
"Cannot initialize zlib, because: %s",
101 (zlibStream.msg != NULL ? zlibStream.msg :
"Unknown error"));
105 bool stillMoreWorkToDo =
true;
106 while (stillMoreWorkToDo) {
108 if (!zlibStream.avail_in) {
109 source = device->read(CHUNK_SIZE);
111 if (source.isEmpty())
114 zlibStream.avail_in = source.size();
115 zlibStream.next_in =
reinterpret_cast<Bytef*>(source.data());
120 int oldSize = destination.size();
121 if (oldSize > INT_MAX - CHUNK_SIZE) {
122 inflateEnd(&zlibStream);
123 qCWarning(lcSvgHandler,
"Error while inflating gzip file: integer size overflow");
127 destination.resize(oldSize + CHUNK_SIZE);
128 zlibStream.next_out =
reinterpret_cast<Bytef*>(
129 destination.data() + oldSize - zlibStream.avail_out);
130 zlibStream.avail_out += CHUNK_SIZE;
132 zlibResult = inflate(&zlibStream, Z_NO_FLUSH);
133 switch (zlibResult) {
138 inflateEnd(&zlibStream);
139 qCWarning(lcSvgHandler,
"Error while inflating gzip file: %s",
140 (zlibStream.msg != NULL ? zlibStream.msg :
"Unknown error"));
147 }
while (!zlibStream.avail_out);
149 if (doCheckContent) {
151 const qsizetype destinationContents =
std::min(destination.size(),
static_cast<qsizetype>(zlibStream.total_out));
152 Q_ASSERT(destinationContents ==
static_cast<qsizetype>(zlibStream.total_out));
153 if (!hasSvgHeader(QByteArray::fromRawData(destination.constData(), destinationContents))) {
154 inflateEnd(&zlibStream);
155 qCWarning(lcSvgHandler,
"Error while inflating gzip file: SVG format check failed");
158 doCheckContent =
false;
161 if (zlibResult == Z_STREAM_END) {
163 if (!(zlibStream.avail_in && inflateReset(&zlibStream) == Z_OK))
164 stillMoreWorkToDo =
false;
169 destination.chop(zlibStream.avail_out);
171 inflateEnd(&zlibStream);
175static QByteArray qt_inflateSvgzDataFrom(QIODevice *)
181std::unique_ptr<QSvgDocument> QSvgDocument::load(
const QString &fileName, QtSvg::Options options,
182 QtSvg::AnimatorType type)
184 std::unique_ptr<QSvgDocument> doc;
185 QFile file(fileName);
186 if (!file.open(QFile::ReadOnly)) {
187 qCWarning(lcSvgHandler,
"Cannot open file '%s', because: %s",
192 if (fileName.endsWith(QLatin1String(
".svgz"), Qt::CaseInsensitive)
193 || fileName.endsWith(QLatin1String(
".svg.gz"), Qt::CaseInsensitive)) {
194 return load(qt_inflateSvgzDataFrom(&file));
197 QSvgHandler handler(&file, options, type);
199 doc = handler.takeDocument();
201 doc->m_animator->setAnimationDuration(handler.animationDuration());
203 qCWarning(lcSvgHandler,
"Cannot read file '%s', because: %s (line %d)",
209std::unique_ptr<QSvgDocument> QSvgDocument::load(
const QByteArray &contents, QtSvg::Options options,
210 QtSvg::AnimatorType type)
212 std::unique_ptr<QSvgDocument> doc;
215 if (contents.startsWith(
"\x1f\x8b")) {
217 buffer.setData(contents);
218 svg = qt_inflateSvgzDataFrom(&buffer);
227 buffer.open(QIODevice::ReadOnly);
228 QSvgHandler handler(&buffer, options, type);
231 doc = handler.takeDocument();
233 doc->m_animator->setAnimationDuration(handler.animationDuration());
238std::unique_ptr<QSvgDocument> QSvgDocument::load(QXmlStreamReader *contents, QtSvg::Options options,
239 QtSvg::AnimatorType type)
241 QSvgHandler handler(contents, options, type);
243 std::unique_ptr<QSvgDocument> doc;
245 doc = handler.takeDocument();
247 doc->m_animator->setAnimationDuration(handler.animationDuration());
252void QSvgDocument::draw(QPainter *p,
const QRectF &bounds)
254 if (displayMode() == QSvgNode::NoneMode)
260 mapSourceToTarget(p, bounds);
262 applyStyle(p, m_states);
263 for (
const auto &node : renderers()) {
264 if ((node->isVisible()) && (node->displayMode() != QSvgNode::NoneMode))
265 node->draw(p, m_states);
267 revertStyle(p, m_states);
272void QSvgDocument::draw(QPainter *p,
const QString &id,
273 const QRectF &bounds)
275 QSvgNode *node = namedNode(id);
278 qCDebug(lcSvgHandler,
"Couldn't find node %s. Skipping rendering.",
qPrintable(id));
282 if (node->displayMode() == QSvgNode::NoneMode)
287 const QRectF elementBounds = node->bounds(
this);
289 mapSourceToTarget(p, bounds, elementBounds);
290 QTransform originalTransform = p->worldTransform();
293 QPen pen(Qt::NoBrush, 1, Qt::SolidLine, Qt::FlatCap, Qt::SvgMiterJoin);
294 pen.setMiterLimit(4);
296 p->setBrush(Qt::black);
297 p->setRenderHint(QPainter::Antialiasing);
298 p->setRenderHint(QPainter::SmoothPixmapTransform);
300 QStack<QSvgNode*> parentApplyStack;
301 QSvgNode *parent = node->parent();
303 parentApplyStack.push(parent);
304 parent = parent->parent();
307 for (
int i = parentApplyStack.size() - 1; i >= 0; --i)
308 parentApplyStack[i]->applyStyle(p, m_states);
312 QTransform currentTransform = p->worldTransform();
313 p->setWorldTransform(originalTransform);
315 node->draw(p, m_states);
317 p->setWorldTransform(currentTransform);
319 for (
int i = 0; i < parentApplyStack.size(); ++i)
320 parentApplyStack[i]->revertStyle(p, m_states);
327QSvgNode::Type QSvgDocument::type()
const
332void QSvgDocument::setWidth(
int len,
bool percent)
334 m_size.setWidth(len);
335 m_widthPercent = percent;
338void QSvgDocument::setHeight(
int len,
bool percent)
340 m_size.setHeight(len);
341 m_heightPercent = percent;
344void QSvgDocument::setPreserveAspectRatio(
bool on)
346 m_preserveAspectRatio = on;
349void QSvgDocument::setViewBox(
const QRectF &rect)
352 m_implicitViewBox = rect.isNull();
355QtSvg::Options QSvgDocument::options()
const
360void QSvgDocument::addSvgFont(
const QString &name, QSvgFontPtr font)
365 if (!m_fonts.insert({ name, std::move(font) }).second)
366 qCWarning(lcSvgHandler) <<
"Font Family already added: " << name;
369QSvgFont *QSvgDocument::svgFont(
const QString &family)
const
371 auto it = m_fonts.find(family);
372 return it != m_fonts.end() ? it->second.get() :
nullptr;
375void QSvgDocument::addNamedNode(
const QString &id, QSvgNode *node)
377 m_namedNodes.insert(id, node);
380QSvgNode *QSvgDocument::namedNode(
const QString &id)
const
382 return m_namedNodes.value(id);
385void QSvgDocument::addPaintServer(QSvgPaintServerSharedPtr paintServer,
const QString &id)
390 if (!m_paintServers.insert({ id, paintServer }).second)
391 qCWarning(lcSvgHandler) <<
"Duplicate unique style id:" << id;
394QSvgPaintServerSharedPtr QSvgDocument::paintServer(QStringView id)
const
396 auto it = m_paintServers.find(id.toString());
397 return it != m_paintServers.end() ? it->second :
nullptr;
400void QSvgDocument::restartAnimation()
403 m_animator->restartAnimation();
406bool QSvgDocument::animated()
const
411void QSvgDocument::setAnimated(
bool a)
416void QSvgDocument::draw(QPainter *p)
421void QSvgDocument::drawCommand(QPainter *, QSvgExtraStates &)
423 qCDebug(lcSvgHandler) <<
"SVG Tiny does not support nested <svg> elements: ignored.";
429 qreal determinant = transform.determinant();
430 return qIsFinite(determinant);
433void QSvgDocument::mapSourceToTarget(QPainter *p,
const QRectF &targetRect,
const QRectF &sourceRect)
435 QTransform oldTransform = p->worldTransform();
437 QRectF target = targetRect;
438 if (target.isEmpty()) {
439 QPaintDevice *dev = p->device();
440 QRectF deviceRect(0, 0, dev->width(), dev->height());
441 if (deviceRect.isEmpty()) {
442 if (sourceRect.isEmpty())
443 target = QRectF(QPointF(0, 0), size());
445 target = QRectF(QPointF(0, 0), sourceRect.size());
451 QRectF source = sourceRect;
452 if (source.isEmpty())
455 if (source != target && !qFuzzyIsNull(source.width()) && !qFuzzyIsNull(source.height())) {
456 if (m_implicitViewBox || !preserveAspectRatio()) {
458 QTransform transform;
459 transform.scale(target.width() / source.width(),
460 target.height() / source.height());
461 QRectF c2 = transform.mapRect(source);
462 p->translate(target.x() - c2.x(),
463 target.y() - c2.y());
464 p->scale(target.width() / source.width(),
465 target.height() / source.height());
471 QSizeF viewBoxSize = source.size();
472 viewBoxSize.scale(target.width(), target.height(), Qt::KeepAspectRatio);
475 p->translate(target.x() + (target.width() - viewBoxSize.width()) / 2,
476 target.y() + (target.height() - viewBoxSize.height()) / 2);
478 p->scale(viewBoxSize.width() / source.width(),
479 viewBoxSize.height() / source.height());
482 p->translate(-source.x(), -source.y());
486 if (!isValidMatrix(p->worldTransform()))
487 p->setWorldTransform(oldTransform);
490QRectF QSvgDocument::boundsOnElement(
const QString &id)
const
492 const QSvgNode *node = namedNode(id);
495 return node->bounds(
this);
498bool QSvgDocument::elementExists(
const QString &id)
const
500 return bool(namedNode(id));
503QTransform QSvgDocument::transformForElement(
const QString &id)
const
505 QSvgNode *node = namedNode(id);
508 qCDebug(lcSvgHandler,
"Couldn't find node %s. Skipping rendering.",
qPrintable(id));
514 node = node->parent();
516 if (
auto prop = node->m_style.property(QSvgStyleProperty::Transform))
517 t *=
static_cast<QSvgTransformStyle*>(prop)->qtransform();
518 node = node->parent();
524int QSvgDocument::currentFrame()
const
526 const double runningPercentage = qMin(currentElapsed() /
double(animationDuration()), 1.);
527 const int totalFrames = m_fps * animationDuration() / 1000;
528 return int(runningPercentage * totalFrames);
531void QSvgDocument::setCurrentFrame(
int frame)
536 const int totalFrames = m_fps * animationDuration() / 1000;
537 if (totalFrames == 0)
540 const int timeForFrame = frame * animationDuration() / totalFrames;
541 const int timeToAdd = timeForFrame - currentElapsed();
542 m_animator->setAnimatorTime(timeToAdd);
545void QSvgDocument::setFramesPerSecond(
int num)
550QSharedPointer<QSvgAbstractAnimator> QSvgDocument::animator()
const
555bool QSvgDocument::isLikelySvg(QIODevice *device,
bool *isCompressed)
557 constexpr int bufSize = 4096;
559 char inflateBuf[bufSize];
560 bool useInflateBuf =
false;
561 int readLen = device->peek(buf, bufSize);
564#ifndef QT_NO_COMPRESS
565 if (quint8(buf[0]) == 0x1f && quint8(buf[1]) == 0x8b) {
568 zlibStream.avail_in = readLen;
569 zlibStream.next_out =
reinterpret_cast<Bytef *>(inflateBuf);
570 zlibStream.avail_out = bufSize;
571 zlibStream.next_in =
reinterpret_cast<Bytef *>(buf);
572 zlibStream.zalloc = Z_NULL;
573 zlibStream.zfree = Z_NULL;
574 zlibStream.opaque = Z_NULL;
575 if (inflateInit2(&zlibStream, MAX_WBITS + 16) != Z_OK)
577 int zlibResult = inflate(&zlibStream, Z_NO_FLUSH);
578 inflateEnd(&zlibStream);
579 if ((zlibResult != Z_OK && zlibResult != Z_STREAM_END) || zlibStream.total_out < 8)
581 readLen = zlibStream.total_out;
583 *isCompressed =
true;
584 useInflateBuf =
true;
587 return hasSvgHeader(QByteArray::fromRawData(useInflateBuf ? inflateBuf : buf, readLen));
#define qPrintable(string)
static QByteArray qt_inflateSvgzDataFrom(QIODevice *device, bool doCheckContent=true)
static bool isValidMatrix(const QTransform &transform)
static bool hasSvgHeader(const QByteArray &buf)