1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
|
/***************************************************************************
* Copyright (C) 2007 Mark A. Taff <kde@marktaff.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License *
* version 2 as published by the Free Software Foundation *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "kgamesvgdocument.h"
#include "kgamesvgdocument_p.h"
#include <KFilterDev>
#include <QBuffer>
#include <QFile>
#include <QString>
#include <QDomElement>
#include <QDomNode>
#include <QDebug>
#include <math.h>
//
// Public
//
/**
* @brief A class holding private members for KGameSvgDocument
*
* @see KGameSvgDocument
* @author Mark A. Taff \<kde@marktaff.com\>
* @version 0.1
*/
class KGameSvgDocumentPrivate
{
public:
/**
* @brief Instantiates a KGameSvgDocumentPrivate object
*/
KGameSvgDocumentPrivate()
{}
~KGameSvgDocumentPrivate()
{}
/**
* @brief Performs a preorder traversal of the DOM tree to find element matching @c attributeName & @c attributeValue
*
* @param attributeName The name of the attribute to find
* @param attributeValue The value of the @p attributeName attribute to find
* @param node The node to start the traversal from.
* @returns the node with id of @c elementId. If no node has that id, returns a null node.
*/
QDomNode findElementById(const QString& attributeName, const QString& attributeValue, const QDomNode& node);
/**
* @brief Returns the current element
* @returns The current element
*/
QDomElement currentElement() const;
/**
* @brief Sets the current element
*
* @returns nothing
*/
void setCurrentElement();
/**
* @brief Returns whether the original style attribute has a trailing semicolon
* @returns whether the original style attribute has a trailing semicolon
*/
bool styleHasTrailingSemicolon() const;
/**
* @brief Sets whether the original style attribute has a trailing semicolon
*
* @param hasSemicolon whether the original style attribute has a trailing semicolon
* @returns nothing
*/
void setStyleHasTrailingSemicolon(bool hasSemicolon);
/**
* @brief The last node found by elementById, or a null node if not found.
*/
QDomNode m_currentNode;
/**
* @brief The current node turned into an element.
*/
QDomElement m_currentElement;
/**
* @brief The order Inkscape write properties in the style attribute of an element.
*
* Inkscape order is defined as:
* "fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-linecap",
* "stroke-linejoin", "stroke-miterlimit", "stroke-dasharray", "stroke-opacity"
*/
QStringList m_inkscapeOrder;
/**
* @brief The xml that must be prepended to a node to make it a valid svg document
*
* Defined as: <?xml version="1.0" encoding="UTF-8" standalone="no"?>\<svg\>
*/
static const QString SVG_XML_PREPEND;
/**
* @brief The xml that must be appended to a node to make it a valid svg document
*
* Defined as: \</svg\>
*/
static const QString SVG_XML_APPEND;
/**
* @brief The filename of the SVG file to open.
*/
QString m_svgFilename;
/**
* @brief Whether the style attribute has a trailing semicolon
*/
bool m_hasSemicolon;
};
const QString KGameSvgDocumentPrivate::SVG_XML_PREPEND = QStringLiteral("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><svg>");
const QString KGameSvgDocumentPrivate::SVG_XML_APPEND = QStringLiteral("</svg>");
KGameSvgDocument::KGameSvgDocument()
: QDomDocument(), d(new KGameSvgDocumentPrivate)
{}
KGameSvgDocument::KGameSvgDocument(const KGameSvgDocument &doc)
: QDomDocument(), d(new KGameSvgDocumentPrivate(*doc.d))
{
}
KGameSvgDocument::~KGameSvgDocument()
{
delete d;
}
KGameSvgDocument& KGameSvgDocument::operator=(const KGameSvgDocument &doc)
{
QDomDocument::operator=(doc);
*d = *doc.d;
return *this;
}
QDomNode KGameSvgDocument::elementByUniqueAttributeValue(const QString& attributeName, const QString& attributeValue)
{
/* DOM is always "live", so there maybe a new root node. We always have to ask for the
* root node instead of keeping a pointer to it.
*/
QDomElement docElem = documentElement();
QDomNode n = docElem.firstChild();
QDomNode node = d->findElementById(attributeName, attributeValue, n);
setCurrentNode(node);
return node;
}
QDomNode KGameSvgDocument::elementById(const QString& attributeValue)
{
return elementByUniqueAttributeValue(QStringLiteral( "id" ), attributeValue);
}
void KGameSvgDocument::load()
{
if (d->m_svgFilename.isNull())
{
qCDebug(GAMES_LIB) << "KGameSvgDocument::load(): Filename not specified.";
return;
}
QFile file(d->m_svgFilename);
if (!file.open(QIODevice::ReadOnly))
{
return;
}
QByteArray content = file.readAll();
// If the file is compressed, decompress the contents before loading it.
if (!content.startsWith("<?xml")) // krazy:exclude=strings
{
QBuffer buf(&content);
KCompressionDevice::CompressionType type = KFilterDev::compressionTypeForMimeType(QStringLiteral("application/x-gzip"));
KCompressionDevice flt(&buf, false, type);
if (!flt.open(QIODevice::ReadOnly))
{
flt.close();
return;
}
QByteArray ar = flt.readAll();
flt.close();
content = ar;
}
if (!setContent(content))
{
file.close();
qCDebug(GAMES_LIB) << "DOM content not set.";
return;
}
file.close();
}
void KGameSvgDocument::load(const QString& svgFilename)
{
setSvgFilename(svgFilename);
load();
}
void KGameSvgDocument::rotate(double degrees, const MatrixOptions& options)
{
QTransform matrix;
if (options == ApplyToCurrentMatrix)
{
matrix = transformMatrix().QTransform::rotate(degrees);
}
else
{
matrix = QTransform();
matrix.QTransform::rotate(degrees);
}
setTransformMatrix(matrix, ReplaceCurrentMatrix);
}
void KGameSvgDocument::translate(int xPixels, int yPixels, const MatrixOptions& options)
{
QTransform matrix;
if (options == ApplyToCurrentMatrix)
{
matrix = transformMatrix().QTransform::translate(xPixels, yPixels);
}
else
{
matrix = QTransform();
matrix.QTransform::translate(xPixels, yPixels);
}
setTransformMatrix(matrix, ReplaceCurrentMatrix);
}
void KGameSvgDocument::shear(double xRadians, double yRadians, const MatrixOptions& options)
{
QTransform matrix;
if (options == ApplyToCurrentMatrix)
{
matrix = transformMatrix().QTransform::shear(xRadians, yRadians);
}
else
{
matrix = QTransform();
matrix.QTransform::shear(xRadians, yRadians);
}
setTransformMatrix(matrix, ReplaceCurrentMatrix);
}
void KGameSvgDocument::skew(double xDegrees, double yDegrees, const MatrixOptions& options)
{
double xRadians = xDegrees * (M_PI / 180);
double yRadians = yDegrees * (M_PI / 180);
shear(xRadians, yRadians, options);
}
void KGameSvgDocument::scale(double xFactor, double yFactor, const MatrixOptions& options)
{
QTransform matrix;
if ((xFactor == 0) || (yFactor == 0))
{
qWarning () << "KGameSvgDocument::scale: You cannot scale by zero";
}
if (options == ApplyToCurrentMatrix)
{
matrix = transformMatrix().QTransform::scale(xFactor, yFactor);
}
else
{
matrix = QTransform();
matrix.QTransform::scale(xFactor, yFactor);
}
setTransformMatrix(matrix, ReplaceCurrentMatrix);
}
QDomNode KGameSvgDocument::currentNode() const
{
return d->m_currentNode;
}
void KGameSvgDocument::setCurrentNode(const QDomNode& node)
{
d->m_currentNode = node;
d->setCurrentElement();
}
QString KGameSvgDocument::svgFilename() const
{
return d->m_svgFilename;
}
void KGameSvgDocument::setSvgFilename(const QString& svgFilename)
{
d->m_svgFilename = svgFilename;
}
QString KGameSvgDocument::styleProperty(const QString& propertyName) const
{
return styleProperties().value(propertyName);
}
void KGameSvgDocument::setStyleProperty(const QString& propertyName, const QString& propertyValue)
{
QHash<QString, QString> properties;
properties = styleProperties();
properties.insert(propertyName, propertyValue);
setStyleProperties(properties, UseInkscapeOrder);
}
QString KGameSvgDocument::nodeToSvg() const
{
QString s, t, xml, defs, pattern;
QTextStream str(&s);
QTextStream str_t(&t);
QStringList defsAdded;
int result = 0;
QRegExp rx;
currentNode().save(str, 1);
xml = *str.string();
// Find and add any required gradients or patterns
pattern = QLatin1String( "url" ) + WSP_ASTERISK + OPEN_PARENS + WSP_ASTERISK + QLatin1String( "#(.*)" ) + WSP_ASTERISK + CLOSE_PARENS;
rx.setPattern(pattern);
if (rx.indexIn(xml, result) != -1)
{
QDomNode node, nodeBase;
QString baseId;
QDomNode n = def();
result = 0;
while ((result = rx.indexIn(xml, result)) != -1)
{
// Find the pattern or gradient referenced
result += rx.matchedLength();
if (!defsAdded.contains(rx.cap(1)))
{
node = d->findElementById(QStringLiteral( "id" ), rx.cap(1), n);
node.save(str_t, 1);
defsAdded.append(rx.cap(1));
}
// Find the gradient the above gradient is based on
baseId = node.toElement().attribute(QStringLiteral( "xlink:href" )).mid(1);
if (!defsAdded.contains(baseId))
{
nodeBase = d->findElementById(QStringLiteral( "id" ), baseId, n);
nodeBase.save(str_t, 1);
defsAdded.append(baseId);
}
}
defs = *str_t.string();
defs = QLatin1String( "<defs>" ) + defs + QLatin1String( "</defs>" );
}
// Need to make node be a real svg document, so prepend and append required tags.
xml = d->SVG_XML_PREPEND + defs + xml + d->SVG_XML_APPEND;
return xml;
}
QByteArray KGameSvgDocument::nodeToByteArray() const
{
return nodeToSvg().toUtf8();
}
QString KGameSvgDocument::style() const
{
return d->m_currentElement.attribute( QStringLiteral( "style" ), QStringLiteral( "Element has no style attribute." ));
}
void KGameSvgDocument::setStyle(const QString& styleAttribute)
{
d->m_currentElement.setAttribute(QStringLiteral( "style" ), styleAttribute);
}
QDomNodeList KGameSvgDocument::patterns() const
{
return elementsByTagName(QStringLiteral( "pattern" ));
}
QDomNodeList KGameSvgDocument::linearGradients() const
{
return elementsByTagName(QStringLiteral( "linearGradient" ));
}
QDomNodeList KGameSvgDocument::radialGradients() const
{
return elementsByTagName(QStringLiteral( "radialGradient" ));
}
QDomNodeList KGameSvgDocument::defs() const
{
return elementsByTagName(QStringLiteral( "defs" ));
}
QDomNode KGameSvgDocument::def() const
{
return defs().at(0);
}
QString KGameSvgDocument::transform() const
{
return d->m_currentElement.attribute( QStringLiteral( "transform" ), QStringLiteral( "Element has no transform attribute." ) );
}
void KGameSvgDocument::setTransform(const QString& transformAttribute)
{
d->m_currentElement.setAttribute(QStringLiteral( "transform" ), transformAttribute);
}
QHash<QString, QString> KGameSvgDocument::styleProperties() const
{
QHash<QString, QString> stylePropertiesHash;
QStringList styleProperties, keyValuePair;
QString styleProperty;
styleProperties = style().split(QLatin1Char( ';' ));
/* The style attr may have a trailing semi-colon. If it does, split()
* gives us an empty final element. Remove it or we get 'index out of range' errors
*/
if (styleProperties.at((styleProperties.count()-1)).isEmpty())
{
styleProperties.removeAt((styleProperties.count()-1));
d->setStyleHasTrailingSemicolon(true);
}
else {d->setStyleHasTrailingSemicolon(false);}
for (int i = 0; i < styleProperties.size(); i++)
{
styleProperty = styleProperties.at(i);
keyValuePair = styleProperty.split(QLatin1Char( ':' ));
stylePropertiesHash.insert(keyValuePair.at(0), keyValuePair.at(1));
}
return stylePropertiesHash;
}
void KGameSvgDocument::setStyleProperties(const QHash<QString, QString>& _styleProperties, const StylePropertySortOptions& options)
{
QHash<QString, QString> styleProperties = _styleProperties;
QString styleBuffer, property;
d->m_inkscapeOrder << QStringLiteral( "fill" ) << QStringLiteral( "fill-opacity" ) << QStringLiteral( "fill-rule" ) << QStringLiteral( "stroke" ) << QStringLiteral( "stroke-width" ) << QStringLiteral( "stroke-linecap" )
<< QStringLiteral( "stroke-linejoin" ) << QStringLiteral( "stroke-miterlimit" ) << QStringLiteral( "stroke-dasharray" ) << QStringLiteral( "stroke-opacity" );
if (options == UseInkscapeOrder)
{
for (int i = 0; i < d->m_inkscapeOrder.size(); i++)
{
property = d->m_inkscapeOrder.at(i);
if (styleProperties.contains(property))
{
styleBuffer += property + QLatin1Char( ':' ) + styleProperties.take(property) + QLatin1Char( ';' );
}
else
{
// Do Nothing
}
}
}
// Append any style properties
if (!styleProperties.isEmpty())
{
QHashIterator<QString, QString> it(styleProperties);
while (it.hasNext())
{
it.next();
styleBuffer += it.key() + QLatin1Char( ':' ) + it.value() + QLatin1Char( ';' );
}
}
// Remove trailing semicolon if original didn't have one
if (!d->styleHasTrailingSemicolon()) {styleBuffer.chop(1);}
setStyle(styleBuffer);
}
QTransform KGameSvgDocument::transformMatrix() const
{
/*
* Transform attributes can be quite complex. Here, we assemble this tangled web of
* complexity into an single matrix.
*
* The regex's that make this bearable live in kgamesvgdocument_p.h. As these regex's
* get quite complex, we have some code in tests/kgamesvgdocumenttest.cpp to help verify
* they are still correct after being edited.
*
* Warning: This code depends on the capturing parenthesis in the regex's not changing.
*
* For all the gory details, see http://www.w3.org/TR/SVG/coords.html#TransformAttribute
*/
QRegExp rx;
QString transformAttribute;
int result;
int i = 0;
QTransform baseMatrix = QTransform();
transformAttribute = transform();
if (transformAttribute == QLatin1String( "Element has no transform attribute." ))
{
return QTransform();
}
transformAttribute = transformAttribute.trimmed();
rx.setPattern(TRANSFORMS);
if (!rx.exactMatch(transformAttribute))
{
qWarning () << "Transform attribute seems to be invalid. Check your SVG file.";
return QTransform();
}
rx.setPattern(TRANSFORM);
while (transformAttribute.size() > 0 && i < 32) // 32 is an arbitrary limit for the number of transforms for a single node
{
result = rx.indexIn(transformAttribute);
if (result != -1) // Found left-most transform
{
if (rx.cap(1) == QLatin1String( "matrix" ))
{
// If the first transform found is a matrix, use it as the base,
// else we use a null matrix.
if (i == 0)
{
baseMatrix = QTransform(rx.cap(2).toDouble(), rx.cap(3).toDouble(), rx.cap(4).toDouble(),
rx.cap(5).toDouble(), rx.cap(6).toDouble(), rx.cap(7).toDouble());
}
else
{
baseMatrix = QTransform(rx.cap(2).toDouble(), rx.cap(3).toDouble(), rx.cap(4).toDouble(),
rx.cap(5).toDouble(), rx.cap(6).toDouble(), rx.cap(7).toDouble()) * baseMatrix;
}
}
if (rx.cap(8) == QLatin1String( "translate" ))
{
double x = rx.cap(9).toDouble();
double y = rx.cap(10).toDouble();
if (rx.cap(10).isEmpty()) // y defaults to zero per SVG standard
{
y = 0;
}
baseMatrix = baseMatrix.translate(x, y);
}
if (rx.cap(11) == QLatin1String( "scale" ))
{
double x = rx.cap(12).toDouble();
double y = rx.cap(12).toDouble();
if (rx.cap(13).isEmpty()) // y defaults to x per SVG standard
{
y = x;
}
baseMatrix = baseMatrix.scale(x, y);
}
if (rx.cap(14) == QLatin1String( "rotate" ))
{
double a = rx.cap(15).toDouble();
double cx = rx.cap(16).toDouble();
double cy = rx.cap(17).toDouble();
if ((cx > 0) || (cy > 0)) // rotate around point (cx, cy)
{
baseMatrix.translate(cx, cy);
baseMatrix.rotate(a);
baseMatrix.translate((cx * -1), (cy * -1));
}
else
{
baseMatrix = baseMatrix.rotate(a); // rotate around origin
}
}
if (rx.cap(18) == QLatin1String( "skewX" ))
{
baseMatrix = baseMatrix.shear(rx.cap(19).toDouble() * (M_PI / 180), 0);
}
if (rx.cap(20) == QLatin1String( "skewY" ))
{
baseMatrix = baseMatrix.shear(0, rx.cap(21).toDouble() * (M_PI / 180));
}
}
transformAttribute = transformAttribute.mid(rx.matchedLength() + result);
i++;
}
return baseMatrix;
}
void KGameSvgDocument::setTransformMatrix(QTransform& matrix, const MatrixOptions& options)
{
QString transformBuffer, tmp;
QTransform null = QTransform();
if (options == ApplyToCurrentMatrix)
{
matrix = transformMatrix() * matrix;
}
transformBuffer = QStringLiteral( "matrix(" );
transformBuffer += tmp.setNum(matrix.m11(),'g',7) + QLatin1Char( ',' );
transformBuffer += tmp.setNum(matrix.m12(),'g',7) + QLatin1Char( ',' );
transformBuffer += tmp.setNum(matrix.m21(),'g',7) + QLatin1Char( ',' );
transformBuffer += tmp.setNum(matrix.m22(),'g',7) + QLatin1Char( ',' );
transformBuffer += tmp.setNum(matrix.dx(),'g',7) + QLatin1Char( ',' );
transformBuffer += tmp.setNum(matrix.dy(),'g',7) + QLatin1Char( ')' );
if ((transform() == QLatin1String( "Element has no transform attribute." )) && (matrix == null))
{
// Do not write a meaningless matrix to DOM
}
else
{
setTransform(transformBuffer);
}
}
//
// Private
//
QDomNode KGameSvgDocumentPrivate::findElementById(const QString& attributeName, const QString& attributeValue, const QDomNode& node)
{
QDomElement e = node.toElement(); // try to convert the node to an element.
QString value = e.attribute( attributeName, QStringLiteral( "Element has no attribute with that name." ));
if (value == attributeValue)
{
// We found our node. Stop recursion and return it.
return node;
}
if (!node.firstChild().isNull())
{
QDomNode result = findElementById(attributeName, attributeValue, node.firstChild());
/** We have recursed, now we need to have this recursion end when
* the function call above returns
*/
if (!result.isNull()) return result; // If we found the node with id, then return it
}
if (!node.nextSibling().isNull())
{
QDomNode result = findElementById(attributeName, attributeValue, node.nextSibling());
/** We have recursed, now we need to have this recursion end when
* the function call above returns */
if (!result.isNull()) return result;
}
if (!node.firstChild().isNull() && !node.nextSibling().isNull())
{
// Do Nothing
//qCDebug(GAMES_LIB) << "No children or siblings.";
}
// Matching node not found, so return a null node.
return QDomNode();
}
QDomElement KGameSvgDocumentPrivate::currentElement() const
{
return m_currentElement;
}
void KGameSvgDocumentPrivate::setCurrentElement()
{
m_currentElement = m_currentNode.toElement();
}
bool KGameSvgDocumentPrivate::styleHasTrailingSemicolon() const
{
return m_hasSemicolon;
}
void KGameSvgDocumentPrivate::setStyleHasTrailingSemicolon(bool hasSemicolon)
{
m_hasSemicolon = hasSemicolon;
}
|