diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 16:51:28 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 16:51:28 +0000 |
commit | 940b4d1848e8c70ab7642901a68594e8016caffc (patch) | |
tree | eb72f344ee6c3d9b80a7ecc079ea79e9fba8676d /svgio/source | |
parent | Initial commit. (diff) | |
download | libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.tar.xz libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.zip |
Adding upstream version 1:7.0.4.upstream/1%7.0.4upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
36 files changed, 13321 insertions, 0 deletions
diff --git a/svgio/source/svgreader/svganode.cxx b/svgio/source/svgreader/svganode.cxx new file mode 100644 index 000000000..35e5e290b --- /dev/null +++ b/svgio/source/svgreader/svganode.cxx @@ -0,0 +1,102 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svganode.hxx> + +namespace svgio::svgreader +{ + SvgANode::SvgANode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenA, rDocument, pParent), + maSvgStyleAttributes(*this) + { + } + + SvgANode::~SvgANode() + { + } + + const SvgStyleAttributes* SvgANode::getSvgStyleAttributes() const + { + return checkForCssStyle("a", maSvgStyleAttributes); + } + + void SvgANode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + case SVGTokenXlinkHref: + //TODO: add support for xlink:href + break; + default: + { + break; + } + } + } + + void SvgANode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool bReferenced) const + { + // #i125258# for SVGTokenA decompose children + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!pStyle) + return; + + const double fOpacity(pStyle->getOpacity().getNumber()); + + if(fOpacity > 0.0 && Display_none != getDisplay()) + { + drawinglayer::primitive2d::Primitive2DContainer aContent; + + // decompose children + SvgNode::decomposeSvgNode(aContent, bReferenced); + + if(!aContent.empty()) + { + pStyle->add_postProcess(rTarget, aContent, getTransform()); + } + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgcharacternode.cxx b/svgio/source/svgreader/svgcharacternode.cxx new file mode 100644 index 000000000..bc4e739ec --- /dev/null +++ b/svgio/source/svgreader/svgcharacternode.cxx @@ -0,0 +1,755 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgcharacternode.hxx> +#include <svgstyleattributes.hxx> +#include <drawinglayer/attribute/fontattribute.hxx> +#include <drawinglayer/primitive2d/textprimitive2d.hxx> +#include <drawinglayer/primitive2d/textlayoutdevice.hxx> +#include <drawinglayer/primitive2d/textbreakuphelper.hxx> +#include <drawinglayer/primitive2d/textdecoratedprimitive2d.hxx> + +namespace svgio::svgreader +{ + SvgTextPositions::SvgTextPositions() + : maX(), + maY(), + maDx(), + maDy(), + maRotate(), + maTextLength(), + mbLengthAdjust(true) + { + } + + void SvgTextPositions::parseTextPositionAttributes(SVGToken aSVGToken, const OUString& aContent) + { + // parse own + switch(aSVGToken) + { + case SVGTokenX: + { + if(!aContent.isEmpty()) + { + SvgNumberVector aVector; + + if(readSvgNumberVector(aContent, aVector)) + { + setX(aVector); + } + } + break; + } + case SVGTokenY: + { + if(!aContent.isEmpty()) + { + SvgNumberVector aVector; + + if(readSvgNumberVector(aContent, aVector)) + { + setY(aVector); + } + } + break; + } + case SVGTokenDx: + { + if(!aContent.isEmpty()) + { + SvgNumberVector aVector; + + if(readSvgNumberVector(aContent, aVector)) + { + setDx(aVector); + } + } + break; + } + case SVGTokenDy: + { + if(!aContent.isEmpty()) + { + SvgNumberVector aVector; + + if(readSvgNumberVector(aContent, aVector)) + { + setDy(aVector); + } + } + break; + } + case SVGTokenRotate: + { + if(!aContent.isEmpty()) + { + SvgNumberVector aVector; + + if(readSvgNumberVector(aContent, aVector)) + { + setRotate(aVector); + } + } + break; + } + case SVGTokenTextLength: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + setTextLength(aNum); + } + } + break; + } + case SVGTokenLengthAdjust: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("spacing")) + { + setLengthAdjust(true); + } + else if(aContent.startsWith("spacingAndGlyphs")) + { + setLengthAdjust(false); + } + } + break; + } + default: + { + break; + } + } + } + +} // end of namespace svgio::svgreader + + +namespace svgio::svgreader +{ + namespace { + + class localTextBreakupHelper : public drawinglayer::primitive2d::TextBreakupHelper + { + private: + SvgTextPosition& mrSvgTextPosition; + + protected: + /// allow user callback to allow changes to the new TextTransformation. Default + /// does nothing. + virtual bool allowChange(sal_uInt32 nCount, basegfx::B2DHomMatrix& rNewTransform, sal_uInt32 nIndex, sal_uInt32 nLength) override; + + public: + localTextBreakupHelper( + const drawinglayer::primitive2d::TextSimplePortionPrimitive2D& rSource, + SvgTextPosition& rSvgTextPosition) + : drawinglayer::primitive2d::TextBreakupHelper(rSource), + mrSvgTextPosition(rSvgTextPosition) + { + } + }; + + } + + bool localTextBreakupHelper::allowChange(sal_uInt32 /*nCount*/, basegfx::B2DHomMatrix& rNewTransform, sal_uInt32 /*nIndex*/, sal_uInt32 /*nLength*/) + { + const double fRotation(mrSvgTextPosition.consumeRotation()); + + if(0.0 != fRotation) + { + const basegfx::B2DPoint aBasePoint(rNewTransform * basegfx::B2DPoint(0.0, 0.0)); + + rNewTransform.translate(-aBasePoint.getX(), -aBasePoint.getY()); + rNewTransform.rotate(fRotation); + rNewTransform.translate(aBasePoint.getX(), aBasePoint.getY()); + } + + return true; + } + +} // end of namespace svgio::svgreader + + +namespace svgio::svgreader +{ + SvgCharacterNode::SvgCharacterNode( + SvgDocument& rDocument, + SvgNode* pParent, + const OUString& rText) + : SvgNode(SVGTokenCharacter, rDocument, pParent), + maText(rText) + { + } + + SvgCharacterNode::~SvgCharacterNode() + { + } + + const SvgStyleAttributes* SvgCharacterNode::getSvgStyleAttributes() const + { + // no own style, use parent's + if(getParent()) + { + return getParent()->getSvgStyleAttributes(); + } + else + { + return nullptr; + } + } + + drawinglayer::primitive2d::TextSimplePortionPrimitive2D* SvgCharacterNode::createSimpleTextPrimitive( + SvgTextPosition& rSvgTextPosition, + const SvgStyleAttributes& rSvgStyleAttributes) const + { + // prepare retval, index and length + drawinglayer::primitive2d::TextSimplePortionPrimitive2D* pRetval = nullptr; + sal_uInt32 nIndex(0); + sal_uInt32 nLength(getText().getLength()); + + if(nLength) + { + // prepare FontAttribute + const SvgStringVector& rFontFamilyVector = rSvgStyleAttributes.getFontFamily(); + OUString aFontFamily = rFontFamilyVector.empty() ? + OUString("Times New Roman") : + rFontFamilyVector[0]; + + // #i122324# if the FontFamily name ends on ' embedded' it is probably a re-import + // of a SVG export with font embedding. Remove this to make font matching work. This + // is pretty safe since there should be no font family names ending on ' embedded'. + // Remove again when FontEmbedding is implemented in SVG import + if(aFontFamily.endsWith(" embedded")) + { + aFontFamily = aFontFamily.copy(0, aFontFamily.getLength() - 9); + } + + const ::FontWeight nFontWeight(getVclFontWeight(rSvgStyleAttributes.getFontWeight())); + bool bItalic(FontStyle_italic == rSvgStyleAttributes.getFontStyle() || FontStyle_oblique == rSvgStyleAttributes.getFontStyle()); + + const drawinglayer::attribute::FontAttribute aFontAttribute( + aFontFamily, + OUString(), + nFontWeight, + false/*bSymbol*/, + false/*bVertical*/, + bItalic, + false/*bMonospaced*/, + false/*bOutline*/, + false/*bRTL*/, + false/*bBiDiStrong*/); + + // prepare FontSizeNumber + double fFontWidth(rSvgStyleAttributes.getFontSizeNumber().solve(*this)); + double fFontHeight(fFontWidth); + + // prepare locale + css::lang::Locale aLocale; + + // prepare TextLayouterDevice + drawinglayer::primitive2d::TextLayouterDevice aTextLayouterDevice; + aTextLayouterDevice.setFontAttribute(aFontAttribute, fFontWidth, fFontHeight, aLocale); + + // prepare TextArray + ::std::vector< double > aTextArray(rSvgTextPosition.getX()); + + if(!aTextArray.empty() && aTextArray.size() < nLength) + { + const sal_uInt32 nArray(aTextArray.size()); + + if(nArray < nLength) + { + double fStartX(0.0); + + if(rSvgTextPosition.getParent() && rSvgTextPosition.getParent()->getAbsoluteX()) + { + fStartX = rSvgTextPosition.getParent()->getPosition().getX(); + } + else + { + fStartX = aTextArray[nArray - 1]; + } + + ::std::vector< double > aExtendArray(aTextLayouterDevice.getTextArray(getText(), nArray, nLength - nArray)); + aTextArray.reserve(nLength); + + for(size_t a(0); a < aExtendArray.size(); a++) + { + aTextArray.push_back(aExtendArray[a] + fStartX); + } + } + } + + // get current TextPosition and TextWidth in units + basegfx::B2DPoint aPosition(rSvgTextPosition.getPosition()); + double fTextWidth(aTextLayouterDevice.getTextWidth(getText(), nIndex, nLength)); + + // check for user-given TextLength + if(0.0 != rSvgTextPosition.getTextLength() + && !basegfx::fTools::equal(fTextWidth, rSvgTextPosition.getTextLength())) + { + const double fFactor(rSvgTextPosition.getTextLength() / fTextWidth); + + if(rSvgTextPosition.getLengthAdjust()) + { + // spacing, need to create and expand TextArray + if(aTextArray.empty()) + { + aTextArray = aTextLayouterDevice.getTextArray(getText(), nIndex, nLength); + } + + for(size_t a(0); a < aTextArray.size(); a++) + { + aTextArray[a] *= fFactor; + } + } + else + { + // spacing and glyphs, just apply to FontWidth + fFontWidth *= fFactor; + } + + fTextWidth = rSvgTextPosition.getTextLength(); + } + + // get TextAlign + TextAlign aTextAlign(rSvgStyleAttributes.getTextAlign()); + + // map TextAnchor to TextAlign, there seems not to be a difference + if(TextAnchor_notset != rSvgStyleAttributes.getTextAnchor()) + { + switch(rSvgStyleAttributes.getTextAnchor()) + { + case TextAnchor_start: + { + aTextAlign = TextAlign_left; + break; + } + case TextAnchor_middle: + { + aTextAlign = TextAlign_center; + break; + } + case TextAnchor_end: + { + aTextAlign = TextAlign_right; + break; + } + default: + { + break; + } + } + } + + // apply TextAlign + switch(aTextAlign) + { + case TextAlign_right: + { + aPosition.setX(aPosition.getX() - fTextWidth); + break; + } + case TextAlign_center: + { + aPosition.setX(aPosition.getX() - (fTextWidth * 0.5)); + break; + } + case TextAlign_notset: + case TextAlign_left: + case TextAlign_justify: + { + // TextAlign_notset, TextAlign_left: nothing to do + // TextAlign_justify is not clear currently; handle as TextAlign_left + break; + } + } + + // get BaselineShift + const BaselineShift aBaselineShift(rSvgStyleAttributes.getBaselineShift()); + + // apply BaselineShift + switch(aBaselineShift) + { + case BaselineShift_Sub: + { + aPosition.setY(aPosition.getY() + aTextLayouterDevice.getUnderlineOffset()); + break; + } + case BaselineShift_Super: + { + aPosition.setY(aPosition.getY() + aTextLayouterDevice.getOverlineOffset()); + break; + } + case BaselineShift_Percentage: + case BaselineShift_Length: + { + const SvgNumber aNumber(rSvgStyleAttributes.getBaselineShiftNumber()); + const double mfBaselineShift(aNumber.solve(*this)); + + aPosition.setY(aPosition.getY() + mfBaselineShift); + break; + } + default: // BaselineShift_Baseline + { + // nothing to do + break; + } + } + + // get fill color + const basegfx::BColor aFill(rSvgStyleAttributes.getFill() + ? *rSvgStyleAttributes.getFill() + : basegfx::BColor(0.0, 0.0, 0.0)); + + // prepare TextTransformation + basegfx::B2DHomMatrix aTextTransform; + + aTextTransform.scale(fFontWidth, fFontHeight); + aTextTransform.translate(aPosition.getX(), aPosition.getY()); + + // check TextDecoration and if TextDecoratedPortionPrimitive2D is needed + const TextDecoration aDeco(rSvgStyleAttributes.getTextDecoration()); + + if(TextDecoration_underline == aDeco + || TextDecoration_overline == aDeco + || TextDecoration_line_through == aDeco) + { + // get the fill for decoration as described by SVG. We cannot + // have different stroke colors/definitions for those, though + const SvgStyleAttributes* pDecoDef = rSvgStyleAttributes.getTextDecorationDefiningSvgStyleAttributes(); + const basegfx::BColor aDecoColor(pDecoDef && pDecoDef->getFill() ? *pDecoDef->getFill() : aFill); + + // create decorated text primitive + pRetval = new drawinglayer::primitive2d::TextDecoratedPortionPrimitive2D( + aTextTransform, + getText(), + nIndex, + nLength, + aTextArray, + aFontAttribute, + aLocale, + aFill, + COL_TRANSPARENT, + + // extra props for decorated + aDecoColor, + aDecoColor, + TextDecoration_overline == aDeco ? drawinglayer::primitive2d::TEXT_LINE_SINGLE : drawinglayer::primitive2d::TEXT_LINE_NONE, + TextDecoration_underline == aDeco ? drawinglayer::primitive2d::TEXT_LINE_SINGLE : drawinglayer::primitive2d::TEXT_LINE_NONE, + false, + TextDecoration_line_through == aDeco ? drawinglayer::primitive2d::TEXT_STRIKEOUT_SINGLE : drawinglayer::primitive2d::TEXT_STRIKEOUT_NONE, + false, + drawinglayer::primitive2d::TEXT_FONT_EMPHASIS_MARK_NONE, + true, + false, + drawinglayer::primitive2d::TEXT_RELIEF_NONE, + false); + } + else + { + // create text primitive + pRetval = new drawinglayer::primitive2d::TextSimplePortionPrimitive2D( + aTextTransform, + getText(), + nIndex, + nLength, + aTextArray, + aFontAttribute, + aLocale, + aFill); + } + + // advance current TextPosition + rSvgTextPosition.setPosition(rSvgTextPosition.getPosition() + basegfx::B2DVector(fTextWidth, 0.0)); + } + + return pRetval; + } + + void SvgCharacterNode::decomposeTextWithStyle( + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + SvgTextPosition& rSvgTextPosition, + const SvgStyleAttributes& rSvgStyleAttributes) const + { + const drawinglayer::primitive2d::Primitive2DReference xRef( + createSimpleTextPrimitive( + rSvgTextPosition, + rSvgStyleAttributes)); + + if(!(xRef.is() && (Visibility_visible == rSvgStyleAttributes.getVisibility()))) + return; + + if(!rSvgTextPosition.isRotated()) + { + rTarget.push_back(xRef); + } + else + { + // need to apply rotations to each character as given + const drawinglayer::primitive2d::TextSimplePortionPrimitive2D* pCandidate = + dynamic_cast< const drawinglayer::primitive2d::TextSimplePortionPrimitive2D* >(xRef.get()); + + if(pCandidate) + { + const localTextBreakupHelper alocalTextBreakupHelper(*pCandidate, rSvgTextPosition); + const drawinglayer::primitive2d::Primitive2DContainer& aResult( + alocalTextBreakupHelper.getResult()); + + if(!aResult.empty()) + { + rTarget.append(aResult); + } + + // also consume for the implied single space + rSvgTextPosition.consumeRotation(); + } + else + { + OSL_ENSURE(false, "Used primitive is not a text primitive (!)"); + } + } + } + + void SvgCharacterNode::whiteSpaceHandling() + { + if(XmlSpace_default == getXmlSpace()) + { + maText = whiteSpaceHandlingDefault(maText); + } + else + { + maText = whiteSpaceHandlingPreserve(maText); + } + } + + void SvgCharacterNode::addGap() + { + maText += " "; + } + + void SvgCharacterNode::concatenate(const OUString& rText) + { + maText += rText; + } + + void SvgCharacterNode::decomposeText(drawinglayer::primitive2d::Primitive2DContainer& rTarget, SvgTextPosition& rSvgTextPosition) const + { + if(!getText().isEmpty()) + { + const SvgStyleAttributes* pSvgStyleAttributes = getSvgStyleAttributes(); + + if(pSvgStyleAttributes) + { + decomposeTextWithStyle(rTarget, rSvgTextPosition, *pSvgStyleAttributes); + } + } + } + +} // end of namespace svgio::svgreader + + +namespace svgio::svgreader +{ + SvgTextPosition::SvgTextPosition( + SvgTextPosition* pParent, + const InfoProvider& rInfoProvider, + const SvgTextPositions& rSvgTextPositions) + : mpParent(pParent), + maX(), // computed below + maY(), // computed below + maRotate(solveSvgNumberVector(rSvgTextPositions.getRotate(), rInfoProvider)), + mfTextLength(0.0), + maPosition(), // computed below + mnRotationIndex(0), + mbLengthAdjust(rSvgTextPositions.getLengthAdjust()), + mbAbsoluteX(false) + { + // get TextLength if provided + if(rSvgTextPositions.getTextLength().isSet()) + { + mfTextLength = rSvgTextPositions.getTextLength().solve(rInfoProvider); + } + + // SVG does not really define in which units a \91rotate\92 for Text/TSpan is given, + // but it seems to be degrees. Convert here to radians + if(!maRotate.empty()) + { + for (double& f : maRotate) + { + f = basegfx::deg2rad(f); + } + } + + // get text positions X + const sal_uInt32 nSizeX(rSvgTextPositions.getX().size()); + + if(nSizeX) + { + // we have absolute positions, get first one as current text position X + maPosition.setX(rSvgTextPositions.getX()[0].solve(rInfoProvider, xcoordinate)); + mbAbsoluteX = true; + + if(nSizeX > 1) + { + // fill deltas to maX + maX.reserve(nSizeX); + + for(sal_uInt32 a(1); a < nSizeX; a++) + { + maX.push_back(rSvgTextPositions.getX()[a].solve(rInfoProvider, xcoordinate) - maPosition.getX()); + } + } + } + else + { + // no absolute position, get from parent + if(pParent) + { + maPosition.setX(pParent->getPosition().getX()); + } + + const sal_uInt32 nSizeDx(rSvgTextPositions.getDx().size()); + + if(nSizeDx) + { + // relative positions given, translate position derived from parent + maPosition.setX(maPosition.getX() + rSvgTextPositions.getDx()[0].solve(rInfoProvider, xcoordinate)); + + if(nSizeDx > 1) + { + // fill deltas to maX + maX.reserve(nSizeDx); + + for(sal_uInt32 a(1); a < nSizeDx; a++) + { + maX.push_back(rSvgTextPositions.getDx()[a].solve(rInfoProvider, xcoordinate)); + } + } + } + } + + // get text positions Y + const sal_uInt32 nSizeY(rSvgTextPositions.getY().size()); + + if(nSizeY) + { + // we have absolute positions, get first one as current text position Y + maPosition.setY(rSvgTextPositions.getY()[0].solve(rInfoProvider, ycoordinate)); + mbAbsoluteX = true; + + if(nSizeY > 1) + { + // fill deltas to maY + maY.reserve(nSizeY); + + for(sal_uInt32 a(1); a < nSizeY; a++) + { + maY.push_back(rSvgTextPositions.getY()[a].solve(rInfoProvider, ycoordinate) - maPosition.getY()); + } + } + } + else + { + // no absolute position, get from parent + if(pParent) + { + maPosition.setY(pParent->getPosition().getY()); + } + + const sal_uInt32 nSizeDy(rSvgTextPositions.getDy().size()); + + if(nSizeDy) + { + // relative positions given, translate position derived from parent + maPosition.setY(maPosition.getY() + rSvgTextPositions.getDy()[0].solve(rInfoProvider, ycoordinate)); + + if(nSizeDy > 1) + { + // fill deltas to maY + maY.reserve(nSizeDy); + + for(sal_uInt32 a(1); a < nSizeDy; a++) + { + maY.push_back(rSvgTextPositions.getDy()[a].solve(rInfoProvider, ycoordinate)); + } + } + } + } + } + + bool SvgTextPosition::isRotated() const + { + if(maRotate.empty()) + { + if(getParent()) + { + return getParent()->isRotated(); + } + else + { + return false; + } + } + else + { + return true; + } + } + + double SvgTextPosition::consumeRotation() + { + double fRetval(0.0); + + if(maRotate.empty()) + { + if(getParent()) + { + fRetval = mpParent->consumeRotation(); + } + else + { + fRetval = 0.0; + } + } + else + { + const sal_uInt32 nSize(maRotate.size()); + + if(mnRotationIndex < nSize) + { + fRetval = maRotate[mnRotationIndex++]; + } + else + { + fRetval = maRotate[nSize - 1]; + } + } + + return fRetval; + } + +} // end of namespace svgio + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgcirclenode.cxx b/svgio/source/svgreader/svgcirclenode.cxx new file mode 100644 index 000000000..284110749 --- /dev/null +++ b/svgio/source/svgreader/svgcirclenode.cxx @@ -0,0 +1,143 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgcirclenode.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolypolygon.hxx> + +namespace svgio::svgreader +{ + SvgCircleNode::SvgCircleNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenCircle, rDocument, pParent), + maSvgStyleAttributes(*this), + maCx(0), + maCy(0), + maR(0) + { + } + + SvgCircleNode::~SvgCircleNode() + { + } + + const SvgStyleAttributes* SvgCircleNode::getSvgStyleAttributes() const + { + return checkForCssStyle("circle", maSvgStyleAttributes); + } + + void SvgCircleNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenCx: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maCx = aNum; + } + break; + } + case SVGTokenCy: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maCy = aNum; + } + break; + } + case SVGTokenR: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maR = aNum; + } + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgCircleNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!(pStyle && getR().isSet())) + return; + + const double fR(getR().solve(*this)); + + if(fR <= 0.0) + return; + + const basegfx::B2DPolygon aPath( + basegfx::utils::createPolygonFromCircle( + basegfx::B2DPoint( + getCx().isSet() ? getCx().solve(*this, xcoordinate) : 0.0, + getCy().isSet() ? getCy().solve(*this, ycoordinate) : 0.0), + fR)); + + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + pStyle->add_path(basegfx::B2DPolyPolygon(aPath), aNewTarget, nullptr); + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgclippathnode.cxx b/svgio/source/svgreader/svgclippathnode.cxx new file mode 100644 index 000000000..e321e6511 --- /dev/null +++ b/svgio/source/svgreader/svgclippathnode.cxx @@ -0,0 +1,259 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgclippathnode.hxx> +#include <drawinglayer/primitive2d/transformprimitive2d.hxx> +#include <drawinglayer/primitive2d/maskprimitive2d.hxx> +#include <basegfx/matrix/b2dhommatrixtools.hxx> +#include <drawinglayer/geometry/viewinformation2d.hxx> +#include <drawinglayer/processor2d/contourextractor2d.hxx> +#include <basegfx/polygon/b2dpolypolygoncutter.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> + +namespace svgio::svgreader +{ + SvgClipPathNode::SvgClipPathNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenClipPathNode, rDocument, pParent), + maSvgStyleAttributes(*this), + maClipPathUnits(userSpaceOnUse) + { + } + + SvgClipPathNode::~SvgClipPathNode() + { + } + + const SvgStyleAttributes* SvgClipPathNode::getSvgStyleAttributes() const + { + return &maSvgStyleAttributes; + } + + void SvgClipPathNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + case SVGTokenClipPathUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setClipPathUnits(userSpaceOnUse); + } + else if(aContent.match(commonStrings::aStrObjectBoundingBox)) + { + setClipPathUnits(objectBoundingBox); + } + } + break; + } + default: + { + break; + } + } + } + + void SvgClipPathNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool bReferenced) const + { + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + // decompose children + SvgNode::decomposeSvgNode(aNewTarget, bReferenced); + + if(aNewTarget.empty()) + return; + + if(getTransform()) + { + // create embedding group element with transformation + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + *getTransform(), + aNewTarget)); + + rTarget.push_back(xRef); + } + else + { + // append to current target + rTarget.append(aNewTarget); + } + } + + void SvgClipPathNode::apply( + drawinglayer::primitive2d::Primitive2DContainer& rContent, + const basegfx::B2DHomMatrix* pTransform) const + { + if(rContent.empty() || Display_none == getDisplay()) + return; + + const drawinglayer::geometry::ViewInformation2D aViewInformation2D; + drawinglayer::primitive2d::Primitive2DContainer aClipTarget; + basegfx::B2DPolyPolygon aClipPolyPolygon; + + // get clipPath definition as primitives + decomposeSvgNode(aClipTarget, true); + + if(!aClipTarget.empty()) + { + // extract filled polygons as base for a mask PolyPolygon + drawinglayer::processor2d::ContourExtractor2D aExtractor(aViewInformation2D, true); + + aExtractor.process(aClipTarget); + + const basegfx::B2DPolyPolygonVector& rResult(aExtractor.getExtractedContour()); + const sal_uInt32 nSize(rResult.size()); + + if(nSize > 1) + { + // merge to single clipPolyPolygon + aClipPolyPolygon = basegfx::utils::mergeToSinglePolyPolygon(rResult); + } + else + { + aClipPolyPolygon = rResult[0]; + } + } + + if(aClipPolyPolygon.count()) + { + if(objectBoundingBox == getClipPathUnits()) + { + // clip is object-relative, transform using content transformation + const basegfx::B2DRange aContentRange(rContent.getB2DRange(aViewInformation2D)); + + aClipPolyPolygon.transform( + basegfx::utils::createScaleTranslateB2DHomMatrix( + aContentRange.getRange(), + aContentRange.getMinimum())); + } + else // userSpaceOnUse + { + // #i124852# + if(pTransform) + { + aClipPolyPolygon.transform(*pTransform); + } + } + + // #i124313# try to avoid creating an embedding to a MaskPrimitive2D if + // possible; MaskPrimitive2D processing is potentially expensive + bool bCreateEmbedding(true); + bool bAddContent(true); + + if(basegfx::utils::isRectangle(aClipPolyPolygon)) + { + // ClipRegion is a rectangle, thus it is not expensive to tell + // if the content is completely inside or outside of it; get ranges + const basegfx::B2DRange aClipRange(aClipPolyPolygon.getB2DRange()); + const basegfx::B2DRange aContentRange( + rContent.getB2DRange( + aViewInformation2D)); + + if(aClipRange.isInside(aContentRange)) + { + // completely contained, no need to clip at all, so no need for embedding + bCreateEmbedding = false; + } + else if(aClipRange.overlaps(aContentRange)) + { + // overlap; embedding needed. ClipRegion can be minimized by using + // the intersection of the ClipRange and the ContentRange. Minimizing + // the ClipRegion potentially enhances further processing since + // usually clip operations are expensive. + basegfx::B2DRange aCommonRange(aContentRange); + + aCommonRange.intersect(aClipRange); + aClipPolyPolygon = basegfx::B2DPolyPolygon(basegfx::utils::createPolygonFromRect(aCommonRange)); + } + else + { + // not inside and no overlap -> completely outside + // no need for embedding, no need for content at all + bCreateEmbedding = false; + bAddContent = false; + } + } + else + { + // ClipRegion is not a simple rectangle, it would be possible but expensive to + // tell if the content needs clipping or not. It is also dependent of + // the content's decomposition. To do this, a processor would be needed that + // is capable if processing the given sequence of primitives and decide + // if all is inside or all is outside. Such a ClipProcessor could be written, + // but for now just create the embedding + } + + if(bCreateEmbedding) + { + // redefine target. Use MaskPrimitive2D with created clip + // geometry. Using the automatically set mbIsClipPathContent at + // SvgStyleAttributes the clip definition is without fill, stroke, + // and strokeWidth and forced to black + const drawinglayer::primitive2d::Primitive2DReference xEmbedTransparence( + new drawinglayer::primitive2d::MaskPrimitive2D( + aClipPolyPolygon, + rContent)); + + rContent = drawinglayer::primitive2d::Primitive2DContainer { xEmbedTransparence }; + } + else + { + if(!bAddContent) + { + rContent.clear(); + } + } + } + else + { + // An empty clipping path will completely clip away the element that had + // the clip-path property applied. (Svg spec) + rContent.clear(); + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgdocument.cxx b/svgio/source/svgreader/svgdocument.cxx new file mode 100644 index 000000000..458f4d1ce --- /dev/null +++ b/svgio/source/svgreader/svgdocument.cxx @@ -0,0 +1,96 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgdocument.hxx> + +namespace svgio::svgreader +{ + SvgDocument::SvgDocument(const OUString& rAbsolutePath) + : maNodes(), + maAbsolutePath(rAbsolutePath), + maIdTokenMapperList(), + maIdStyleTokenMapperList() + { + } + + SvgDocument::~SvgDocument() + { + } + + void SvgDocument::appendNode(std::unique_ptr<SvgNode> pNode) + { + assert(pNode); + maNodes.push_back(std::move(pNode)); + } + + void SvgDocument::addSvgNodeToMapper(const OUString& rStr, const SvgNode& rNode) + { + if(!rStr.isEmpty()) + { + maIdTokenMapperList.emplace(rStr, &rNode); + } + } + + void SvgDocument::removeSvgNodeFromMapper(const OUString& rStr) + { + if(!rStr.isEmpty()) + { + maIdTokenMapperList.erase(rStr); + } + } + + const SvgNode* SvgDocument::findSvgNodeById(const OUString& rStr) const + { + const IdTokenMapper::const_iterator aResult(maIdTokenMapperList.find(rStr)); + + if(aResult == maIdTokenMapperList.end()) + { + return nullptr; + } + else + { + return aResult->second; + } + } + + void SvgDocument::addSvgStyleAttributesToMapper(const OUString& rStr, const SvgStyleAttributes& rSvgStyleAttributes) + { + if(!rStr.isEmpty()) + { + maIdStyleTokenMapperList.emplace(rStr, &rSvgStyleAttributes); + } + } + + const SvgStyleAttributes* SvgDocument::findGlobalCssStyleAttributes(const OUString& rStr) const + { + const IdStyleTokenMapper::const_iterator aResult(maIdStyleTokenMapperList.find(rStr)); + + if(aResult == maIdStyleTokenMapperList.end()) + { + return nullptr; + } + else + { + return aResult->second; + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgdocumenthandler.cxx b/svgio/source/svgreader/svgdocumenthandler.cxx new file mode 100644 index 000000000..1a44d64ae --- /dev/null +++ b/svgio/source/svgreader/svgdocumenthandler.cxx @@ -0,0 +1,643 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgdocumenthandler.hxx> +#include <svgtoken.hxx> +#include <svgsvgnode.hxx> +#include <svggnode.hxx> +#include <svganode.hxx> +#include <svgnode.hxx> +#include <svgpathnode.hxx> +#include <svgrectnode.hxx> +#include <svggradientnode.hxx> +#include <svggradientstopnode.hxx> +#include <svgsymbolnode.hxx> +#include <svgusenode.hxx> +#include <svgcirclenode.hxx> +#include <svgellipsenode.hxx> +#include <svglinenode.hxx> +#include <svgpolynode.hxx> +#include <svgtextnode.hxx> +#include <svgcharacternode.hxx> +#include <svgtspannode.hxx> +#include <svgtrefnode.hxx> +#include <svgtextpathnode.hxx> +#include <svgstylenode.hxx> +#include <svgimagenode.hxx> +#include <svgclippathnode.hxx> +#include <svgmasknode.hxx> +#include <svgmarkernode.hxx> +#include <svgpatternnode.hxx> +#include <svgtitledescnode.hxx> +#include <sal/log.hxx> + +using namespace com::sun::star; + +namespace +{ + svgio::svgreader::SvgCharacterNode* whiteSpaceHandling(svgio::svgreader::SvgNode const * pNode, svgio::svgreader::SvgCharacterNode* pLast) + { + if(pNode) + { + const auto& rChilds = pNode->getChildren(); + const sal_uInt32 nCount(rChilds.size()); + + for(sal_uInt32 a(0); a < nCount; a++) + { + svgio::svgreader::SvgNode* pCandidate = rChilds[a].get(); + + if(pCandidate) + { + switch(pCandidate->getType()) + { + case svgio::svgreader::SVGTokenCharacter: + { + // clean whitespace in text span + svgio::svgreader::SvgCharacterNode* pCharNode = static_cast< svgio::svgreader::SvgCharacterNode* >(pCandidate); + pCharNode->whiteSpaceHandling(); + + // pCharNode may have lost all text. If that's the case, ignore + // as invalid character node + if(!pCharNode->getText().isEmpty()) + { + if(pLast) + { + bool bAddGap(true); + static bool bNoGapsForBaselineShift(true); // loplugin:constvars:ignore + + if(bNoGapsForBaselineShift) + { + // With this option a baseline shift between two char parts ('words') + // will not add a space 'gap' to the end of the (non-last) word. This + // seems to be the standard behaviour, see last bugdoc attached #122524# + const svgio::svgreader::SvgStyleAttributes* pStyleLast = pLast->getSvgStyleAttributes(); + const svgio::svgreader::SvgStyleAttributes* pStyleCurrent = pCandidate->getSvgStyleAttributes(); + + if(pStyleLast && pStyleCurrent && pStyleLast->getBaselineShift() != pStyleCurrent->getBaselineShift()) + { + bAddGap = false; + } + } + + // add in-between whitespace (single space) to last + // known character node + if(bAddGap) + { + pLast->addGap(); + } + } + + // remember new last corrected character node + pLast = pCharNode; + } + break; + } + case svgio::svgreader::SVGTokenTspan: + case svgio::svgreader::SVGTokenTextPath: + case svgio::svgreader::SVGTokenTref: + { + // recursively clean whitespaces in subhierarchy + pLast = whiteSpaceHandling(pCandidate, pLast); + break; + } + default: + { + OSL_ENSURE(false, "Unexpected token inside SVGTokenText (!)"); + break; + } + } + } + } + } + + return pLast; + } +} + + +namespace svgio::svgreader +{ + SvgDocHdl::SvgDocHdl(const OUString& aAbsolutePath) + : maDocument(aAbsolutePath), + mpTarget(nullptr), + maCssContents(), + bSkip(false) + { + } + + SvgDocHdl::~SvgDocHdl() + { + if (mpTarget) + { + OSL_ENSURE(false, "SvgDocHdl destructed with active target (!)"); + + while (mpTarget->getParent()) + mpTarget = const_cast< SvgNode* >(mpTarget->getParent()); + + const SvgNodeVector& rOwnedTopLevels = maDocument.getSvgNodeVector(); + if (std::none_of(rOwnedTopLevels.begin(), rOwnedTopLevels.end(), + [&](std::unique_ptr<SvgNode> const & p) { return p.get() == mpTarget; })) + delete mpTarget; + } + OSL_ENSURE(maCssContents.empty(), "SvgDocHdl destructed with active css style stack entry (!)"); + } + + void SvgDocHdl::startDocument( ) + { + OSL_ENSURE(!mpTarget, "Already a target at document start (!)"); + OSL_ENSURE(maCssContents.empty(), "SvgDocHdl startDocument with active css style stack entry (!)"); + } + + void SvgDocHdl::endDocument( ) + { + OSL_ENSURE(!mpTarget, "Still a target at document end (!)"); + OSL_ENSURE(maCssContents.empty(), "SvgDocHdl endDocument with active css style stack entry (!)"); + } + + void SvgDocHdl::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs ) + { + if (bSkip) + return; + if(aName.isEmpty()) + return; + + const SVGToken aSVGToken(StrToSVGToken(aName, false)); + + switch(aSVGToken) + { + /// structural elements + case SVGTokenSymbol: + { + /// new basic node for Symbol. Content gets scanned, but + /// will not be decomposed (see SvgNode::decomposeSvgNode and bReferenced) + mpTarget = new SvgSymbolNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenDefs: + case SVGTokenG: + { + /// new node for Defs/G + mpTarget = new SvgGNode(aSVGToken, maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenSvg: + { + /// new node for Svg + mpTarget = new SvgSvgNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenUse: + { + /// new node for Use + mpTarget = new SvgUseNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenA: + { + /// new node for A + mpTarget = new SvgANode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// shape elements + case SVGTokenCircle: + { + /// new node for Circle + mpTarget = new SvgCircleNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenEllipse: + { + /// new node for Ellipse + mpTarget = new SvgEllipseNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenLine: + { + /// new node for Line + mpTarget = new SvgLineNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenPath: + { + /// new node for Path + mpTarget = new SvgPathNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenPolygon: + { + /// new node for Polygon + mpTarget = new SvgPolyNode(maDocument, mpTarget, false); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenPolyline: + { + /// new node for Polyline + mpTarget = new SvgPolyNode(maDocument, mpTarget, true); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenRect: + { + /// new node for Rect + mpTarget = new SvgRectNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenImage: + { + /// new node for Image + mpTarget = new SvgImageNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// title and description + case SVGTokenTitle: + case SVGTokenDesc: + { + /// new node for Title and/or Desc + mpTarget = new SvgTitleDescNode(aSVGToken, maDocument, mpTarget); + break; + } + + /// gradients + case SVGTokenLinearGradient: + case SVGTokenRadialGradient: + { + mpTarget = new SvgGradientNode(aSVGToken, maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// gradient stops + case SVGTokenStop: + { + mpTarget = new SvgGradientStopNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// text + case SVGTokenText: + { + mpTarget = new SvgTextNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenTspan: + { + mpTarget = new SvgTspanNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenTref: + { + mpTarget = new SvgTrefNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenTextPath: + { + mpTarget = new SvgTextPathNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// styles (as stylesheets) + case SVGTokenStyle: + { + SvgStyleNode* pNew = new SvgStyleNode(maDocument, mpTarget); + mpTarget = pNew; + const sal_uInt32 nAttributes(xAttribs->getLength()); + + if(0 == nAttributes) + { + // #i125326# no attributes, thus also no type="text/css". This is allowed to be missing, + // thus do mark this style as CssStyle. This is required to read the contained + // text (which defines the css style) + pNew->setTextCss(true); + } + else + { + // #i125326# there are attributes, read them. This will set isTextCss to true if + // a type="text/css" is contained as exact match, else not + mpTarget->parseAttributes(xAttribs); + } + + if(pNew->isTextCss()) + { + // if it is a Css style, allow reading text between the start and end tag (see + // SvgDocHdl::characters for details) + maCssContents.emplace_back(); + } + break; + } + + /// structural elements clip-path and mask. Content gets scanned, but + /// will not be decomposed (see SvgNode::decomposeSvgNode and bReferenced) + case SVGTokenClipPathNode: + { + /// new node for ClipPath + mpTarget = new SvgClipPathNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + case SVGTokenMask: + { + /// new node for Mask + mpTarget = new SvgMaskNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// structural element marker + case SVGTokenMarker: + { + /// new node for marker + mpTarget = new SvgMarkerNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + /// structural element pattern + case SVGTokenPattern: + { + /// new node for pattern + mpTarget = new SvgPatternNode(maDocument, mpTarget); + mpTarget->parseAttributes(xAttribs); + break; + } + + // ignore FlowRoot and child nodes + case SVGTokenFlowRoot: + { + bSkip = true; + break; + } + + default: + { + /// invalid token, ignore + SAL_INFO( "svgio", "Unknown Base SvgToken <" + aName + "> (!)" ); + break; + } + } + } + + void SvgDocHdl::endElement( const OUString& aName ) + { + if(aName.isEmpty()) + return; + + const SVGToken aSVGToken(StrToSVGToken(aName, false)); + SvgNode* pWhitespaceCheck(SVGTokenText == aSVGToken ? mpTarget : nullptr); + SvgStyleNode* pCssStyle(SVGTokenStyle == aSVGToken ? static_cast< SvgStyleNode* >(mpTarget) : nullptr); + SvgTitleDescNode* pSvgTitleDescNode(SVGTokenTitle == aSVGToken || SVGTokenDesc == aSVGToken ? static_cast< SvgTitleDescNode* >(mpTarget) : nullptr); + + // if we are in skipping mode and we reach the flowRoot end tag: stop skipping mode + if(bSkip && aSVGToken == SVGTokenFlowRoot) + bSkip = false; + // we are in skipping mode: do nothing until we found the flowRoot end tag + else if(bSkip) + return; + + switch(aSVGToken) + { + /// valid tokens for which a new one was created + + /// structural elements + case SVGTokenDefs: + case SVGTokenG: + case SVGTokenSvg: + case SVGTokenSymbol: + case SVGTokenUse: + case SVGTokenA: + + /// shape elements + case SVGTokenCircle: + case SVGTokenEllipse: + case SVGTokenLine: + case SVGTokenPath: + case SVGTokenPolygon: + case SVGTokenPolyline: + case SVGTokenRect: + case SVGTokenImage: + + /// title and description + case SVGTokenTitle: + case SVGTokenDesc: + + /// gradients + case SVGTokenLinearGradient: + case SVGTokenRadialGradient: + + /// gradient stops + case SVGTokenStop: + + /// text + case SVGTokenText: + case SVGTokenTspan: + case SVGTokenTextPath: + case SVGTokenTref: + + /// styles (as stylesheets) + case SVGTokenStyle: + + /// structural elements clip-path and mask + case SVGTokenClipPathNode: + case SVGTokenMask: + + /// structural element marker + case SVGTokenMarker: + + /// structural element pattern + case SVGTokenPattern: + + /// content handling after parsing + { + if(mpTarget) + { + if(!mpTarget->getParent()) + { + // last element closing, save this tree + maDocument.appendNode(std::unique_ptr<SvgNode>(mpTarget)); + } + + mpTarget = const_cast< SvgNode* >(mpTarget->getParent()); + } + else + { + OSL_ENSURE(false, "Closing token, but no context (!)"); + } + break; + } + default: + { + /// invalid token, ignore + } + } + + if(pSvgTitleDescNode && mpTarget) + { + const OUString& aText(pSvgTitleDescNode->getText()); + + if(!aText.isEmpty()) + { + if(SVGTokenTitle == aSVGToken) + { + mpTarget->parseAttribute(getStrTitle(), aSVGToken, aText); + } + else // if(SVGTokenDesc == aSVGToken) + { + mpTarget->parseAttribute(getStrDesc(), aSVGToken, aText); + } + } + } + + if(pCssStyle && pCssStyle->isTextCss()) + { + // css style parsing + if(!maCssContents.empty()) + { + // need to interpret css styles and remember them as StyleSheets + // #125325# Caution! the Css content may contain block comments + // (see http://www.w3.org/wiki/CSS_basics#CSS_comments). These need + // to be removed first + const OUString aCommentFreeSource(removeBlockComments(*(maCssContents.end() - 1))); + + if(aCommentFreeSource.getLength()) + { + pCssStyle->addCssStyleSheet(aCommentFreeSource); + } + + maCssContents.pop_back(); + } + else + { + OSL_ENSURE(false, "Closing CssStyle, but no collector string on stack (!)"); + } + } + + if(pWhitespaceCheck) + { + // cleanup read strings + whiteSpaceHandling(pWhitespaceCheck, nullptr); + } + } + + void SvgDocHdl::characters( const OUString& aChars ) + { + const sal_uInt32 nLength(aChars.getLength()); + + if(!(mpTarget && nLength)) + return; + + switch(mpTarget->getType()) + { + case SVGTokenText: + case SVGTokenTspan: + case SVGTokenTextPath: + { + const auto& rChilds = mpTarget->getChildren(); + SvgCharacterNode* pTarget = nullptr; + + if(!rChilds.empty()) + { + pTarget = dynamic_cast< SvgCharacterNode* >(rChilds[rChilds.size() - 1].get()); + } + + if(pTarget) + { + // concatenate to current character span + pTarget->concatenate(aChars); + } + else + { + // add character span as simplified tspan (no arguments) + // as direct child of SvgTextNode/SvgTspanNode/SvgTextPathNode + new SvgCharacterNode(maDocument, mpTarget, aChars); + } + break; + } + case SVGTokenStyle: + { + SvgStyleNode& rSvgStyleNode = static_cast< SvgStyleNode& >(*mpTarget); + + if(rSvgStyleNode.isTextCss()) + { + // collect characters for css style + if(!maCssContents.empty()) + { + const OUString aTrimmedChars(aChars.trim()); + + if(!aTrimmedChars.isEmpty()) + { + std::vector< OUString >::iterator aString(maCssContents.end() - 1); + (*aString) += aTrimmedChars; + } + } + else + { + OSL_ENSURE(false, "Closing CssStyle, but no collector string on stack (!)"); + } + } + break; + } + case SVGTokenTitle: + case SVGTokenDesc: + { + SvgTitleDescNode& rSvgTitleDescNode = static_cast< SvgTitleDescNode& >(*mpTarget); + + // add text directly to SvgTitleDescNode + rSvgTitleDescNode.concatenate(aChars); + break; + } + default: + { + // characters not used by a known node + break; + } + } + } + + void SvgDocHdl::ignorableWhitespace(const OUString& /*aWhitespaces*/) + { + } + + void SvgDocHdl::processingInstruction(const OUString& /*aTarget*/, const OUString& /*aData*/) + { + } + + void SvgDocHdl::setDocumentLocator(const uno::Reference< xml::sax::XLocator >& /*xLocator*/) + { + } +} // end of namespace svgio + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgellipsenode.cxx b/svgio/source/svgreader/svgellipsenode.cxx new file mode 100644 index 000000000..59b635981 --- /dev/null +++ b/svgio/source/svgreader/svgellipsenode.cxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgellipsenode.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolypolygon.hxx> + +namespace svgio::svgreader +{ + SvgEllipseNode::SvgEllipseNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenEllipse, rDocument, pParent), + maSvgStyleAttributes(*this), + maCx(0), + maCy(0), + maRx(0), + maRy(0) + { + } + + SvgEllipseNode::~SvgEllipseNode() + { + } + + const SvgStyleAttributes* SvgEllipseNode::getSvgStyleAttributes() const + { + return checkForCssStyle("ellipse", maSvgStyleAttributes); + } + + void SvgEllipseNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenCx: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maCx = aNum; + } + break; + } + case SVGTokenCy: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maCy = aNum; + } + break; + } + case SVGTokenRx: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maRx = aNum; + } + } + break; + } + case SVGTokenRy: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maRy = aNum; + } + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgEllipseNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!(pStyle && getRx().isSet() && getRy().isSet())) + return; + + const double fRx(getRx().solve(*this, xcoordinate)); + const double fRy(getRy().solve(*this, ycoordinate)); + + if(!(fRx > 0.0 && fRy > 0.0)) + return; + + const basegfx::B2DPolygon aPath( + basegfx::utils::createPolygonFromEllipse( + basegfx::B2DPoint( + getCx().isSet() ? getCx().solve(*this, xcoordinate) : 0.0, + getCy().isSet() ? getCy().solve(*this, ycoordinate) : 0.0), + fRx, fRy)); + + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + pStyle->add_path(basegfx::B2DPolyPolygon(aPath), aNewTarget, nullptr); + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svggnode.cxx b/svgio/source/svgreader/svggnode.cxx new file mode 100644 index 000000000..03eba6908 --- /dev/null +++ b/svgio/source/svgreader/svggnode.cxx @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svggnode.hxx> + +namespace svgio::svgreader +{ + SvgGNode::SvgGNode( + SVGToken aType, + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(aType, rDocument, pParent), + maSvgStyleAttributes(*this) + { + OSL_ENSURE(aType == SVGTokenDefs || aType == SVGTokenG, "SvgGNode should only be used for Group and Defs (!)"); + } + + SvgGNode::~SvgGNode() + { + } + + const SvgStyleAttributes* SvgGNode::getSvgStyleAttributes() const + { + if (SVGTokenDefs == getType()) + { + // tdf#98599 attributes may be inherit by the children, therefore read them + return checkForCssStyle("defs", maSvgStyleAttributes); + } + else + { + // #i125258# for SVGTokenG take CssStyles into account + return checkForCssStyle("g", maSvgStyleAttributes); + } + } + + void SvgGNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgGNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool bReferenced) const + { + if(SVGTokenDefs == getType()) + { + // #i125258# no decompose needed for defs element, call parent for SVGTokenDefs + SvgNode::decomposeSvgNode(rTarget, bReferenced); + } + else + { + // #i125258# for SVGTokenG decompose children + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(pStyle) + { + const double fOpacity(pStyle->getOpacity().getNumber()); + + if(fOpacity > 0.0 && Display_none != getDisplay()) + { + drawinglayer::primitive2d::Primitive2DContainer aContent; + + // decompose children + SvgNode::decomposeSvgNode(aContent, bReferenced); + + if(!aContent.empty()) + { + pStyle->add_postProcess(rTarget, aContent, getTransform()); + } + } + } + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svggradientnode.cxx b/svgio/source/svgreader/svggradientnode.cxx new file mode 100644 index 000000000..639467b92 --- /dev/null +++ b/svgio/source/svgreader/svggradientnode.cxx @@ -0,0 +1,525 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svggradientnode.hxx> +#include <svgdocument.hxx> +#include <svggradientstopnode.hxx> + +namespace svgio::svgreader +{ + void SvgGradientNode::tryToFindLink() + { + if(!mpXLink && !maXLink.isEmpty()) + { + mpXLink = dynamic_cast< const SvgGradientNode* >(getDocument().findSvgNodeById(maXLink)); + } + } + + SvgGradientNode::SvgGradientNode( + SVGToken aType, + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(aType, rDocument, pParent), + maSvgStyleAttributes(*this), + maX1(), + maY1(), + maX2(), + maY2(), + maCx(), + maCy(), + maR(), + maFx(), + maFy(), + maGradientUnits(objectBoundingBox), + maSpreadMethod(drawinglayer::primitive2d::SpreadMethod::Pad), + mbResolvingLink(false), + maXLink(), + mpXLink(nullptr) + { + OSL_ENSURE(aType == SVGTokenLinearGradient || aType == SVGTokenRadialGradient, "SvgGradientNode should only be used for Linear and Radial gradient (!)"); + } + + SvgGradientNode::~SvgGradientNode() + { + // do NOT delete mpXLink, it's only referenced, not owned + } + + const SvgStyleAttributes* SvgGradientNode::getSvgStyleAttributes() const + { + return checkForCssStyle( + SVGTokenLinearGradient == getType() ? OUString("linearGradient") : OUString("radialGradient"), + maSvgStyleAttributes); + } + + void SvgGradientNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenX1: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX1 = aNum; + } + break; + } + case SVGTokenY1: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY1 = aNum; + } + break; + } + case SVGTokenX2: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX2 = aNum; + } + break; + } + case SVGTokenY2: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY2 = aNum; + } + break; + } + case SVGTokenCx: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maCx = aNum; + } + break; + } + case SVGTokenCy: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maCy = aNum; + } + break; + } + case SVGTokenFx: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maFx = aNum; + } + break; + } + case SVGTokenFy: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maFy = aNum; + } + break; + } + case SVGTokenR: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maR = aNum; + } + } + break; + } + case SVGTokenGradientUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setGradientUnits(userSpaceOnUse); + } + else if(aContent.match(commonStrings::aStrObjectBoundingBox)) + { + setGradientUnits(objectBoundingBox); + } + } + break; + } + case SVGTokenSpreadMethod: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("pad")) + { + setSpreadMethod(drawinglayer::primitive2d::SpreadMethod::Pad); + } + else if(aContent.startsWith("reflect")) + { + setSpreadMethod(drawinglayer::primitive2d::SpreadMethod::Reflect); + } + else if(aContent.startsWith("repeat")) + { + setSpreadMethod(drawinglayer::primitive2d::SpreadMethod::Repeat); + } + } + break; + } + case SVGTokenGradientTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setGradientTransform(&aMatrix); + } + break; + } + case SVGTokenXlinkHref: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen && '#' == aContent[0]) + { + maXLink = aContent.copy(1); + tryToFindLink(); + } + break; + } + default: + { + break; + } + } + } + + void SvgGradientNode::collectGradientEntries(drawinglayer::primitive2d::SvgGradientEntryVector& aVector) const + { + if(getChildren().empty()) + { + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + mpXLink->collectGradientEntries(aVector); + mbResolvingLink = false; + } + } + else + { + const sal_uInt32 nCount(getChildren().size()); + + for(sal_uInt32 a(0); a < nCount; a++) + { + const SvgGradientStopNode* pCandidate = dynamic_cast< const SvgGradientStopNode* >(getChildren()[a].get()); + + if(pCandidate) + { + const SvgStyleAttributes* pStyle = pCandidate->getSvgStyleAttributes(); + + if(pStyle) + { + const SvgNumber aOffset(pCandidate->getOffset()); + double fOffset(0.0); + + if(Unit_percent == aOffset.getUnit()) + { + // percent is not relative to distances in ColorStop context, solve locally + fOffset = aOffset.getNumber() * 0.01; + } + else + { + fOffset = aOffset.solve(*this); + } + + if(fOffset < 0.0) + { + OSL_ENSURE(false, "OOps, SvgGradientStopNode with offset out of range (!)"); + fOffset = 0.0; + } + else if(fOffset > 1.0) + { + OSL_ENSURE(false, "OOps, SvgGradientStopNode with offset out of range (!)"); + fOffset = 1.0; + } + + aVector.emplace_back( + fOffset, + pStyle->getStopColor(), + pStyle->getStopOpacity().solve(*this)); + } + else + { + OSL_ENSURE(false, "OOps, SvgGradientStopNode without Style (!)"); + } + } + } + } + } + + SvgNumber SvgGradientNode::getX1() const + { + if(maX1.isSet()) + { + return maX1; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getX1(); + mbResolvingLink = false; + return ret; + } + + // default is 0% + return SvgNumber(0.0, Unit_percent); + } + + SvgNumber SvgGradientNode::getY1() const + { + if(maY1.isSet()) + { + return maY1; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getY1(); + mbResolvingLink = false; + return ret; + } + + // default is 0% + return SvgNumber(0.0, Unit_percent); + } + + SvgNumber SvgGradientNode::getX2() const + { + if(maX2.isSet()) + { + return maX2; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getX2(); + mbResolvingLink = false; + return ret; + } + + // default is 100% + return SvgNumber(100.0, Unit_percent); + } + + SvgNumber SvgGradientNode::getY2() const + { + if(maY2.isSet()) + { + return maY2; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getY2(); + mbResolvingLink = false; + return ret; + } + + // default is 0% + return SvgNumber(0.0, Unit_percent); + } + + SvgNumber SvgGradientNode::getCx() const + { + if(maCx.isSet()) + { + return maCx; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getCx(); + mbResolvingLink = false; + return ret; + } + + // default is 50% + return SvgNumber(50.0, Unit_percent); + } + + SvgNumber SvgGradientNode::getCy() const + { + if(maCy.isSet()) + { + return maCy; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getCy(); + mbResolvingLink = false; + return ret; + } + + // default is 50% + return SvgNumber(50.0, Unit_percent); + } + + SvgNumber SvgGradientNode::getR() const + { + if(maR.isSet()) + { + return maR; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getR(); + mbResolvingLink = false; + return ret; + } + + // default is 50% + return SvgNumber(50.0, Unit_percent); + } + + const SvgNumber* SvgGradientNode::getFx() const + { + if(maFx.isSet()) + { + return &maFx; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getFx(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + + const SvgNumber* SvgGradientNode::getFy() const + { + if(maFy.isSet()) + { + return &maFy; + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getFy(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + + const basegfx::B2DHomMatrix* SvgGradientNode::getGradientTransform() const + { + if(mpaGradientTransform) + { + return mpaGradientTransform.get(); + } + + const_cast< SvgGradientNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getGradientTransform(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + + void SvgGradientNode::setGradientTransform(const basegfx::B2DHomMatrix* pMatrix) + { + mpaGradientTransform.reset(); + + if(pMatrix) + { + mpaGradientTransform.reset(new basegfx::B2DHomMatrix(*pMatrix) ); + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svggradientstopnode.cxx b/svgio/source/svgreader/svggradientstopnode.cxx new file mode 100644 index 000000000..f271cddc8 --- /dev/null +++ b/svgio/source/svgreader/svggradientstopnode.cxx @@ -0,0 +1,80 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svggradientstopnode.hxx> + +namespace svgio::svgreader +{ + SvgGradientStopNode::SvgGradientStopNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenStop, rDocument, pParent), + maSvgStyleAttributes(*this), + maOffset() + { + } + + SvgGradientStopNode::~SvgGradientStopNode() + { + } + + const SvgStyleAttributes* SvgGradientStopNode::getSvgStyleAttributes() const + { + return checkForCssStyle("stop", maSvgStyleAttributes); + } + + void SvgGradientStopNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenOffset: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maOffset = aNum; + } + } + break; + } + default: + { + break; + } + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgimagenode.cxx b/svgio/source/svgreader/svgimagenode.cxx new file mode 100644 index 000000000..8dfc70e64 --- /dev/null +++ b/svgio/source/svgreader/svgimagenode.cxx @@ -0,0 +1,360 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgimagenode.hxx> +#include <svgdocument.hxx> +#include <tools/stream.hxx> +#include <vcl/bitmapex.hxx> +#include <vcl/graphicfilter.hxx> +#include <basegfx/matrix/b2dhommatrixtools.hxx> +#include <drawinglayer/primitive2d/bitmapprimitive2d.hxx> +#include <drawinglayer/primitive2d/transformprimitive2d.hxx> +#include <drawinglayer/primitive2d/maskprimitive2d.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <rtl/uri.hxx> +#include <sal/log.hxx> +#include <drawinglayer/geometry/viewinformation2d.hxx> +#include <comphelper/base64.hxx> +#include <toolkit/helper/vclunohelper.hxx> + +namespace svgio::svgreader +{ + SvgImageNode::SvgImageNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenRect, rDocument, pParent), + maSvgStyleAttributes(*this), + maSvgAspectRatio(), + maX(0), + maY(0), + maWidth(0), + maHeight(0), + maXLink(), + maUrl(), + maMimeType(), + maData() + { + } + + SvgImageNode::~SvgImageNode() + { + } + + const SvgStyleAttributes* SvgImageNode::getSvgStyleAttributes() const + { + return checkForCssStyle("image", maSvgStyleAttributes); + } + + void SvgImageNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenPreserveAspectRatio: + { + maSvgAspectRatio = readSvgAspectRatio(aContent); + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + case SVGTokenX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX = aNum; + } + break; + } + case SVGTokenY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY = aNum; + } + break; + } + case SVGTokenWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maWidth = aNum; + } + } + break; + } + case SVGTokenHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maHeight = aNum; + } + } + break; + } + case SVGTokenXlinkHref: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen) + { + readImageLink(aContent, maXLink, maUrl, maMimeType, maData); + } + break; + } + default: + { + break; + } + } + } + + static void extractFromGraphic( + const Graphic& rGraphic, + drawinglayer::primitive2d::Primitive2DContainer& rEmbedded, + basegfx::B2DRange& rViewBox, + BitmapEx& rBitmapEx) + { + if(GraphicType::Bitmap == rGraphic.GetType()) + { + if(rGraphic.getVectorGraphicData()) + { + // embedded Svg + rEmbedded = rGraphic.getVectorGraphicData()->getPrimitive2DSequence(); + + // fill aViewBox + rViewBox = rGraphic.getVectorGraphicData()->getRange(); + } + else + { + // get bitmap + rBitmapEx = rGraphic.GetBitmapEx(); + } + } + else + { + // evtl. convert to bitmap + rBitmapEx = rGraphic.GetBitmapEx(); + } + } + + void SvgImageNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + // get size range and create path + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!(pStyle && getWidth().isSet() && getHeight().isSet())) + return; + + const double fWidth(getWidth().solve(*this, xcoordinate)); + const double fHeight(getHeight().solve(*this, ycoordinate)); + + if(!(fWidth > 0.0 && fHeight > 0.0)) + return; + + BitmapEx aBitmapEx; + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + // prepare Target and ViewBox for evtl. AspectRatio mappings + const double fX(getX().isSet() ? getX().solve(*this, xcoordinate) : 0.0); + const double fY(getY().isSet() ? getY().solve(*this, ycoordinate) : 0.0); + const basegfx::B2DRange aTarget(fX, fY, fX + fWidth, fY + fHeight); + basegfx::B2DRange aViewBox(aTarget); + + if(!maMimeType.isEmpty() && !maData.isEmpty()) + { + // use embedded base64 encoded data + css::uno::Sequence< sal_Int8 > aPass; + ::comphelper::Base64::decode(aPass, maData); + + if(aPass.hasElements()) + { + SvMemoryStream aStream(aPass.getArray(), aPass.getLength(), StreamMode::READ); + Graphic aGraphic; + + if(ERRCODE_NONE == GraphicFilter::GetGraphicFilter().ImportGraphic( + aGraphic, + OUString(), + aStream)) + { + extractFromGraphic(aGraphic, aNewTarget, aViewBox, aBitmapEx); + } + } + } + else if(!maUrl.isEmpty()) + { + const OUString& rPath = getDocument().getAbsolutePath(); + OUString aAbsUrl; + try { + aAbsUrl = rtl::Uri::convertRelToAbs(rPath, maUrl); + } catch (rtl::MalformedUriException & e) { + SAL_WARN( + "svg", + "caught rtl::MalformedUriException \"" + << e.getMessage() << "\""); + } + + if (!aAbsUrl.isEmpty() && rPath != aAbsUrl) + { + SvFileStream aStream(aAbsUrl, StreamMode::STD_READ); + Graphic aGraphic; + + if(ERRCODE_NONE == GraphicFilter::GetGraphicFilter().ImportGraphic( + aGraphic, + aAbsUrl, + aStream)) + { + extractFromGraphic(aGraphic, aNewTarget, aViewBox, aBitmapEx); + } + } + } + else if(!maXLink.isEmpty()) + { + const SvgNode* pXLink = getDocument().findSvgNodeById(maXLink); + + if(pXLink && Display_none != pXLink->getDisplay()) + { + pXLink->decomposeSvgNode(aNewTarget, true); + + if(!aNewTarget.empty()) + { + aViewBox = aNewTarget.getB2DRange(drawinglayer::geometry::ViewInformation2D()); + } + } + } + + if(!aBitmapEx.IsEmpty() && 0 != aBitmapEx.GetSizePixel().Width() && 0 != aBitmapEx.GetSizePixel().Height()) + { + // calculate centered unit size + const double fAspectRatio = static_cast<double>(aBitmapEx.GetSizePixel().Width()) / static_cast<double>(aBitmapEx.GetSizePixel().Height()); + + if(basegfx::fTools::equal(fAspectRatio, 0.0)) + { + // use unit range + aViewBox = basegfx::B2DRange(0.0, 0.0, 1.0, 1.0); + } + else if(basegfx::fTools::more(fAspectRatio, 0.0)) + { + // width bigger height + const double fHalfHeight((1.0 / fAspectRatio) * 0.5); + aViewBox = basegfx::B2DRange( + 0.0, + 0.5 - fHalfHeight, + 1.0, + 0.5 + fHalfHeight); + } + else + { + // height bigger width + const double fHalfWidth(fAspectRatio * 0.5); + aViewBox = basegfx::B2DRange( + 0.5 - fHalfWidth, + 0.0, + 0.5 + fHalfWidth, + 1.0); + } + + // create content from created bitmap, use calculated unit range size + // as transformation to map the picture data correctly + aNewTarget.resize(1); + aNewTarget[0] = new drawinglayer::primitive2d::BitmapPrimitive2D( + VCLUnoHelper::CreateVCLXBitmap(aBitmapEx), + basegfx::utils::createScaleTranslateB2DHomMatrix( + aViewBox.getRange(), + aViewBox.getMinimum())); + } + + if(aNewTarget.empty()) + return; + + if(aTarget.equal(aViewBox)) + { + // just add to rTarget + rTarget.append(aNewTarget); + } + else + { + // create mapping + const SvgAspectRatio& rRatio = maSvgAspectRatio; + + // even when ratio is not set, use the defaults + // let mapping be created from SvgAspectRatio + const basegfx::B2DHomMatrix aEmbeddingTransform(rRatio.createMapping(aTarget, aViewBox)); + + if(!aEmbeddingTransform.isIdentity()) + { + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + aEmbeddingTransform, + aNewTarget)); + + aNewTarget = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + + if(!rRatio.isMeetOrSlice()) + { + // need to embed in MaskPrimitive2D to ensure clipping + const drawinglayer::primitive2d::Primitive2DReference xMask( + new drawinglayer::primitive2d::MaskPrimitive2D( + basegfx::B2DPolyPolygon( + basegfx::utils::createPolygonFromRect(aTarget)), + aNewTarget)); + + aNewTarget = drawinglayer::primitive2d::Primitive2DContainer { xMask }; + } + + // embed and add to rTarget, take local extra-transform into account + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svglinenode.cxx b/svgio/source/svgreader/svglinenode.cxx new file mode 100644 index 000000000..e00647640 --- /dev/null +++ b/svgio/source/svgreader/svglinenode.cxx @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svglinenode.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolypolygon.hxx> + +namespace svgio::svgreader +{ + SvgLineNode::SvgLineNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenLine, rDocument, pParent), + maSvgStyleAttributes(*this), + maX1(0), + maY1(0), + maX2(0), + maY2(0) + { + } + + SvgLineNode::~SvgLineNode() + { + } + + const SvgStyleAttributes* SvgLineNode::getSvgStyleAttributes() const + { + return checkForCssStyle("line", maSvgStyleAttributes); + } + + void SvgLineNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenX1: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX1 = aNum; + } + break; + } + case SVGTokenY1: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY1 = aNum; + } + break; + } + case SVGTokenX2: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX2 = aNum; + } + break; + } + case SVGTokenY2: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY2 = aNum; + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgLineNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!pStyle) + return; + + const basegfx::B2DPoint X( + getX1().isSet() ? getX1().solve(*this, xcoordinate) : 0.0, + getY1().isSet() ? getY1().solve(*this, ycoordinate) : 0.0); + const basegfx::B2DPoint Y( + getX2().isSet() ? getX2().solve(*this, xcoordinate) : 0.0, + getY2().isSet() ? getY2().solve(*this, ycoordinate) : 0.0); + + // X and Y may be equal, do not drop them. Markers or linecaps 'round' and 'square' + // need to be drawn for zero-length lines too. + + basegfx::B2DPolygon aPath; + + aPath.append(X); + aPath.append(Y); + + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + pStyle->add_path(basegfx::B2DPolyPolygon(aPath), aNewTarget, nullptr); + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgmarkernode.cxx b/svgio/source/svgreader/svgmarkernode.cxx new file mode 100644 index 000000000..89375c756 --- /dev/null +++ b/svgio/source/svgreader/svgmarkernode.cxx @@ -0,0 +1,196 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgmarkernode.hxx> + +namespace svgio::svgreader +{ + SvgMarkerNode::SvgMarkerNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenMarker, rDocument, pParent), + aPrimitives(), + maSvgStyleAttributes(*this), + maSvgAspectRatio(), + maRefX(0), + maRefY(0), + maMarkerUnits(MarkerUnits::strokeWidth), + maMarkerWidth(3), + maMarkerHeight(3), + mfAngle(0.0), + mbOrientAuto(false) + { + } + + SvgMarkerNode::~SvgMarkerNode() + { + } + + const SvgStyleAttributes* SvgMarkerNode::getSvgStyleAttributes() const + { + return checkForCssStyle("marker", maSvgStyleAttributes); + } + + void SvgMarkerNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenViewBox: + { + const basegfx::B2DRange aRange(readViewBox(aContent, *this)); + + if(!aRange.isEmpty()) + { + setViewBox(&aRange); + } + break; + } + case SVGTokenPreserveAspectRatio: + { + maSvgAspectRatio = readSvgAspectRatio(aContent); + break; + } + case SVGTokenRefX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maRefX = aNum; + } + break; + } + case SVGTokenRefY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maRefY = aNum; + } + break; + } + case SVGTokenMarkerUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("strokeWidth")) + { + setMarkerUnits(MarkerUnits::strokeWidth); + } + else if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setMarkerUnits(MarkerUnits::userSpaceOnUse); + } + } + break; + } + case SVGTokenMarkerWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maMarkerWidth = aNum; + } + } + break; + } + case SVGTokenMarkerHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maMarkerHeight = aNum; + } + } + break; + } + case SVGTokenOrient: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen) + { + if(aContent.startsWith("auto")) + { + mbOrientAuto = true; + } + else + { + sal_Int32 nPos(0); + double fAngle(0.0); + + if(readAngle(aContent, nPos, fAngle, nLen)) + { + setAngle(fAngle); + } + } + } + break; + } + default: + { + break; + } + } + } + + const drawinglayer::primitive2d::Primitive2DContainer& SvgMarkerNode::getMarkerPrimitives() const + { + if(aPrimitives.empty() && Display_none != getDisplay()) + { + decomposeSvgNode(const_cast< SvgMarkerNode* >(this)->aPrimitives, true); + } + + return aPrimitives; + } + + basegfx::B2DRange SvgMarkerNode::getCurrentViewPort() const + { + if(getViewBox()) + { + return *(getViewBox()); + } + else + { + return SvgNode::getCurrentViewPort(); + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgmasknode.cxx b/svgio/source/svgreader/svgmasknode.cxx new file mode 100644 index 000000000..543b8eede --- /dev/null +++ b/svgio/source/svgreader/svgmasknode.cxx @@ -0,0 +1,316 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgmasknode.hxx> +#include <drawinglayer/primitive2d/transformprimitive2d.hxx> +#include <drawinglayer/primitive2d/transparenceprimitive2d.hxx> +#include <basegfx/matrix/b2dhommatrixtools.hxx> +#include <drawinglayer/geometry/viewinformation2d.hxx> +#include <drawinglayer/primitive2d/modifiedcolorprimitive2d.hxx> +#include <drawinglayer/primitive2d/maskprimitive2d.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> + +namespace svgio::svgreader +{ + SvgMaskNode::SvgMaskNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenMask, rDocument, pParent), + maSvgStyleAttributes(*this), + maX(SvgNumber(-10.0, Unit_percent, true)), + maY(SvgNumber(-10.0, Unit_percent, true)), + maWidth(SvgNumber(120.0, Unit_percent, true)), + maHeight(SvgNumber(120.0, Unit_percent, true)), + maMaskUnits(objectBoundingBox), + maMaskContentUnits(userSpaceOnUse) + { + } + + SvgMaskNode::~SvgMaskNode() + { + } + + const SvgStyleAttributes* SvgMaskNode::getSvgStyleAttributes() const + { + return &maSvgStyleAttributes; + } + + void SvgMaskNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX = aNum; + } + break; + } + case SVGTokenY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY = aNum; + } + break; + } + case SVGTokenWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maWidth = aNum; + } + } + break; + } + case SVGTokenHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maHeight = aNum; + } + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + case SVGTokenMaskUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setMaskUnits(userSpaceOnUse); + } + else if(aContent.match(commonStrings::aStrObjectBoundingBox)) + { + setMaskUnits(objectBoundingBox); + } + } + break; + } + case SVGTokenMaskContentUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setMaskContentUnits(userSpaceOnUse); + } + else if(aContent.match(commonStrings::aStrObjectBoundingBox)) + { + setMaskContentUnits(objectBoundingBox); + } + } + break; + } + default: + { + break; + } + } + } + + void SvgMaskNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool bReferenced) const + { + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + // decompose children + SvgNode::decomposeSvgNode(aNewTarget, bReferenced); + + if(aNewTarget.empty()) + return; + + if(getTransform()) + { + // create embedding group element with transformation + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + *getTransform(), + aNewTarget)); + + aNewTarget = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + + // append to current target + rTarget.append(aNewTarget); + } + + void SvgMaskNode::apply( + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const basegfx::B2DHomMatrix* pTransform) const + { + if(rTarget.empty() || Display_none == getDisplay()) + return; + + drawinglayer::primitive2d::Primitive2DContainer aMaskTarget; + + // get mask definition as primitives + decomposeSvgNode(aMaskTarget, true); + + if(!aMaskTarget.empty()) + { + // get range of content to be masked + const basegfx::B2DRange aContentRange( + rTarget.getB2DRange( + drawinglayer::geometry::ViewInformation2D())); + const double fContentWidth(aContentRange.getWidth()); + const double fContentHeight(aContentRange.getHeight()); + + if(fContentWidth > 0.0 && fContentHeight > 0.0) + { + // create OffscreenBufferRange + basegfx::B2DRange aOffscreenBufferRange; + + if(objectBoundingBox == maMaskUnits) + { + // fractions or percentages of the bounding box of the element to which the mask is applied + const double fX(Unit_percent == getX().getUnit() ? getX().getNumber() * 0.01 : getX().getNumber()); + const double fY(Unit_percent == getY().getUnit() ? getY().getNumber() * 0.01 : getY().getNumber()); + const double fW(Unit_percent == getWidth().getUnit() ? getWidth().getNumber() * 0.01 : getWidth().getNumber()); + const double fH(Unit_percent == getHeight().getUnit() ? getHeight().getNumber() * 0.01 : getHeight().getNumber()); + + aOffscreenBufferRange = basegfx::B2DRange( + aContentRange.getMinX() + (fX * fContentWidth), + aContentRange.getMinY() + (fY * fContentHeight), + aContentRange.getMinX() + ((fX + fW) * fContentWidth), + aContentRange.getMinY() + ((fY + fH) * fContentHeight)); + } + else + { + const double fX(getX().isSet() ? getX().solve(*this, xcoordinate) : 0.0); + const double fY(getY().isSet() ? getY().solve(*this, ycoordinate) : 0.0); + + aOffscreenBufferRange = basegfx::B2DRange( + fX, + fY, + fX + (getWidth().isSet() ? getWidth().solve(*this, xcoordinate) : 0.0), + fY + (getHeight().isSet() ? getHeight().solve(*this, ycoordinate) : 0.0)); + } + + if(objectBoundingBox == maMaskContentUnits) + { + // mask is object-relative, embed in content transformation + const drawinglayer::primitive2d::Primitive2DReference xTransform( + new drawinglayer::primitive2d::TransformPrimitive2D( + basegfx::utils::createScaleTranslateB2DHomMatrix( + aContentRange.getRange(), + aContentRange.getMinimum()), + aMaskTarget)); + + aMaskTarget = drawinglayer::primitive2d::Primitive2DContainer { xTransform }; + } + else // userSpaceOnUse + { + // #i124852# + if(pTransform) + { + const drawinglayer::primitive2d::Primitive2DReference xTransform( + new drawinglayer::primitive2d::TransformPrimitive2D( + *pTransform, + aMaskTarget)); + + aMaskTarget = drawinglayer::primitive2d::Primitive2DContainer { xTransform }; + } + } + + // embed content to a ModifiedColorPrimitive2D since the definitions + // how content is used as alpha is special for Svg + { + const drawinglayer::primitive2d::Primitive2DReference xInverseMask( + new drawinglayer::primitive2d::ModifiedColorPrimitive2D( + aMaskTarget, + std::make_shared<basegfx::BColorModifier_luminance_to_alpha>())); + + aMaskTarget = drawinglayer::primitive2d::Primitive2DContainer { xInverseMask }; + } + + // prepare new content + drawinglayer::primitive2d::Primitive2DReference xNewContent( + new drawinglayer::primitive2d::TransparencePrimitive2D( + rTarget, + aMaskTarget)); + + // output up to now is defined by aContentRange and mask is oriented + // relative to it. It is possible that aOffscreenBufferRange defines + // a smaller area. In that case, embed to a mask primitive + if(!aOffscreenBufferRange.isInside(aContentRange)) + { + xNewContent = new drawinglayer::primitive2d::MaskPrimitive2D( + basegfx::B2DPolyPolygon( + basegfx::utils::createPolygonFromRect( + aOffscreenBufferRange)), + drawinglayer::primitive2d::Primitive2DContainer { xNewContent }); + } + + // redefine target. Use TransparencePrimitive2D with created mask + // geometry + rTarget = drawinglayer::primitive2d::Primitive2DContainer { xNewContent }; + } + else + { + // content is geometrically empty + rTarget.clear(); + } + } + else + { + // An empty clipping path will completely clip away the element that had + // the clip-path property applied. (Svg spec) + rTarget.clear(); + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgnode.cxx b/svgio/source/svgreader/svgnode.cxx new file mode 100644 index 000000000..0d8b5c68a --- /dev/null +++ b/svgio/source/svgreader/svgnode.cxx @@ -0,0 +1,688 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgdocument.hxx> +#include <svgnode.hxx> +#include <svgstyleattributes.hxx> +#include <drawinglayer/primitive2d/objectinfoprimitive2d.hxx> +#include <tools/urlobj.hxx> + + +namespace svgio::svgreader +{ + /// #i125258# + bool SvgNode::supportsParentStyle() const + { + return true; + } + + const SvgStyleAttributes* SvgNode::getSvgStyleAttributes() const + { + return nullptr; + } + + void SvgNode::fillCssStyleVectorUsingHierarchyAndSelectors( + const OUString& rClassStr, + const SvgNode& rCurrent, + const OUString& aConcatenated) + { + const SvgDocument& rDocument = getDocument(); + + if(!rDocument.hasGlobalCssStyleAttributes()) + return; + + const SvgNode* pParent = rCurrent.getParent(); + + // check for ID (highest priority) + if(rCurrent.getId()) + { + const OUString& rId = *rCurrent.getId(); + + if(rId.getLength()) + { + const OUString aNewConcatenated( + "#" + rId + aConcatenated); + + if(pParent) + { + // check for combined selectors at parent firstso that higher specificity will be in front + fillCssStyleVectorUsingHierarchyAndSelectors(rClassStr, *pParent, aNewConcatenated); + } + + const SvgStyleAttributes* pNew = rDocument.findGlobalCssStyleAttributes(aNewConcatenated); + + if(pNew) + { + // add CssStyle if found + maCssStyleVector.push_back(pNew); + } + } + } + + // check for 'class' references (a list of entries is allowed) + if(rCurrent.getClass()) + { + const OUString& rClassList = *rCurrent.getClass(); + const sal_Int32 nLen(rClassList.getLength()); + + if(nLen) + { + std::vector< OUString > aParts; + sal_Int32 nPos(0); + OUStringBuffer aToken; + + while(nPos < nLen) + { + const sal_Int32 nInitPos(nPos); + copyToLimiter(rClassList, u' ', nPos, aToken, nLen); + skip_char(rClassList, u' ', nPos, nLen); + const OUString aPart(aToken.makeStringAndClear().trim()); + + if(aPart.getLength()) + { + aParts.push_back(aPart); + } + + if(nInitPos == nPos) + { + OSL_ENSURE(false, "Could not interpret on current position (!)"); + nPos++; + } + } + + for(size_t a(0); a < aParts.size(); a++) + { + const OUString aNewConcatenated( + "." + aParts[a] + aConcatenated); + + if(pParent) + { + // check for combined selectors at parent firstso that higher specificity will be in front + fillCssStyleVectorUsingHierarchyAndSelectors(rClassStr, *pParent, aNewConcatenated); + } + + const SvgStyleAttributes* pNew = rDocument.findGlobalCssStyleAttributes(aNewConcatenated); + + if(pNew) + { + // add CssStyle if found + maCssStyleVector.push_back(pNew); + } + } + } + } + + // check for class-dependent references to CssStyles + if(rClassStr.isEmpty()) + return; + + OUString aNewConcatenated(aConcatenated); + + if(!rCurrent.getId() && !rCurrent.getClass() && 0 == aConcatenated.indexOf(rClassStr)) + { + // no new CssStyle Selector and already starts with rClassStr, do not concatenate; + // we pass an 'empty' node (in the sense of CssStyle Selector) + } + else + { + aNewConcatenated = rClassStr + aConcatenated; + } + + if(pParent) + { + // check for combined selectors at parent firstso that higher specificity will be in front + fillCssStyleVectorUsingHierarchyAndSelectors(rClassStr, *pParent, aNewConcatenated); + } + + const SvgStyleAttributes* pNew = rDocument.findGlobalCssStyleAttributes(aNewConcatenated); + + if(pNew) + { + // add CssStyle if found + maCssStyleVector.push_back(pNew); + } + } + + void SvgNode::fillCssStyleVector(const OUString& rClassStr, const SvgStyleAttributes& rOriginal) + { + OSL_ENSURE(!mbCssStyleVectorBuilt, "OOps, fillCssStyleVector called double ?!?"); + mbCssStyleVectorBuilt = true; + + // #i125293# If we have CssStyles we need to build a linked list of SvgStyleAttributes + // which represent this for the current object. There are various methods to + // specify CssStyles which need to be taken into account in a given order: + // - local CssStyle (independent from global CssStyles at SvgDocument) + // - 'id' CssStyle + // - 'class' CssStyle(s) + // - type-dependent elements (e..g. 'rect' for all rect elements) + // - Css selector '*' + // - local attributes (rOriginal) + // - inherited attributes (up the hierarchy) + // The first four will be collected in maCssStyleVector for the current element + // (once, this will not change) and be linked in the needed order using the + // get/setCssStyleParent at the SvgStyleAttributes which will be used preferred in + // member evaluation over the existing parent hierarchy + + // check for local CssStyle with highest priority + if(mpLocalCssStyle) + { + // if we have one, use as first entry + maCssStyleVector.push_back(mpLocalCssStyle.get()); + } + + // check the hierarchy for concatenated patterns of Selectors + fillCssStyleVectorUsingHierarchyAndSelectors(rClassStr, *this, OUString()); + + // tdf#99115, Add css selector '*' style only if the element is on top of the hierarchy + // meaning its parent is <svg> + const SvgNode* pParent = this->getParent(); + + if(pParent && pParent->getType() == SVGTokenSvg) + { + // #i125329# find Css selector '*', add as last element if found + const SvgStyleAttributes* pNew = getDocument().findGlobalCssStyleAttributes("*"); + + if(pNew) + { + // add CssStyle for selector '*' if found + maCssStyleVector.push_back(pNew); + } + } + + //local attributes + maCssStyleVector.push_back(&rOriginal); + } + + const SvgStyleAttributes* SvgNode::checkForCssStyle(const OUString& rClassStr, const SvgStyleAttributes& rOriginal) const + { + if(!mbCssStyleVectorBuilt) + { + // build needed CssStyleVector for local node + const_cast< SvgNode* >(this)->fillCssStyleVector(rClassStr, rOriginal); + } + + if(maCssStyleVector.empty()) + { + // return given original if no CssStyles found + return &rOriginal; + } + else + { + // #i125293# rOriginal will be the last element in the linked list; use no CssStyleParent + // there (reset it) to ensure that the parent hierarchy will be used when it's base + // is referenced. This new chaining inserts the CssStyles before the original style, + // this makes the whole process much safer since the original style when used will + // be not different to the situation without CssStyles; thus loops which may be caused + // by trying to use the parent hierarchy of the owner of the style will be avoided + // already in this mechanism. It's still good to keep the supportsParentStyle + // from #i125258# in place, though. + // This chain building using pointers will be done every time when checkForCssStyle + // is used (not the search, only the chaining). This is needed since the CssStyles + // themselves will be potentially used multiple times. It is not expensive since it's + // only changing some pointers. + // The alternative would be to create the style hierarchy for every element (or even + // for the element containing the hierarchy) in a vector of pointers and to use that. + // Resetting the CssStyleParent on rOriginal is probably not needed + // but simply safer to do. + + // loop over the existing CssStyles and link them. There is a first one, take + // as current + SvgStyleAttributes* pCurrent = const_cast< SvgStyleAttributes* >(maCssStyleVector[0]); + + for(size_t a(1); a < maCssStyleVector.size(); a++) + { + SvgStyleAttributes* pNext = const_cast< SvgStyleAttributes* >(maCssStyleVector[a]); + + pCurrent->setCssStyleParent(pNext); + pCurrent = pNext; + } + + // return 1st CssStyle as style chain start element (only for the + // local element, still no hierarchy used here) + return maCssStyleVector[0]; + } + } + + SvgNode::SvgNode( + SVGToken aType, + SvgDocument& rDocument, + SvgNode* pParent) + : maType(aType), + mrDocument(rDocument), + mpParent(pParent), + mpAlternativeParent(nullptr), + maChildren(), + maXmlSpace(XmlSpace_notset), + maDisplay(Display_inline), + maCssStyleVector(), + mbDecomposing(false), + mbCssStyleVectorBuilt(false) + { + OSL_ENSURE(SVGTokenUnknown != maType, "SvgNode with unknown type created (!)"); + + if(pParent) + { + pParent->maChildren.emplace_back(this); + } + else + { +#ifdef DBG_UTIL + if(SVGTokenSvg != getType()) + { + OSL_ENSURE(false, "No parent for this node (!)"); + } +#endif + } + } + + SvgNode::~SvgNode() + { + } + + void SvgNode::readLocalCssStyle(const OUString& aContent) + { + if(!mpLocalCssStyle) + { + // create LocalCssStyle if needed but not yet added + mpLocalCssStyle.reset(new SvgStyleAttributes(*this)); + } + else + { + // 2nd fill would be an error + OSL_ENSURE(false, "Svg node has two local CssStyles, this may lead to problems (!)"); + } + + if(mpLocalCssStyle) + { + // parse and set values to it + mpLocalCssStyle->readCssStyle(aContent); + } + else + { + OSL_ENSURE(false, "Could not get/create a local CssStyle for a node (!)"); + } + } + + void SvgNode::parseAttributes(const css::uno::Reference< css::xml::sax::XAttributeList >& xAttribs) + { + // no longer need to pre-sort moving 'style' entries to the back so that + // values get overwritten - that was the previous, not complete solution for + // handling the priorities between svg and Css properties + const sal_uInt32 nAttributes(xAttribs->getLength()); + + for(sal_uInt32 a(0); a < nAttributes; a++) + { + const OUString aTokenName(xAttribs->getNameByIndex(a)); + const SVGToken aSVGToken(StrToSVGToken(aTokenName, false)); + + parseAttribute(aTokenName, aSVGToken, xAttribs->getValueByIndex(a)); + } + } + + Display getDisplayFromContent(const OUString& aContent) + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("inline")) + { + return Display_inline; + } + else if(aContent.startsWith("none")) + { + return Display_none; + } + else if(aContent.startsWith("inherit")) + { + return Display_inherit; + } + else if(aContent.startsWith("block")) + { + return Display_block; + } + else if(aContent.startsWith("list-item")) + { + return Display_list_item; + } + else if(aContent.startsWith("run-in")) + { + return Display_run_in; + } + else if(aContent.startsWith("compact")) + { + return Display_compact; + } + else if(aContent.startsWith("marker")) + { + return Display_marker; + } + else if(aContent.startsWith("table")) + { + return Display_table; + } + else if(aContent.startsWith("inline-table")) + { + return Display_inline_table; + } + else if(aContent.startsWith("table-row-group")) + { + return Display_table_row_group; + } + else if(aContent.startsWith("table-header-group")) + { + return Display_table_header_group; + } + else if(aContent.startsWith("table-footer-group")) + { + return Display_table_footer_group; + } + else if(aContent.startsWith("table-row")) + { + return Display_table_row; + } + else if(aContent.startsWith("table-column-group")) + { + return Display_table_column_group; + } + else if(aContent.startsWith("table-column")) + { + return Display_table_column; + } + else if(aContent.startsWith("table-cell")) + { + return Display_table_cell; + } + else if(aContent.startsWith("table-caption")) + { + return Display_table_caption; + } + } + + // return the default + return Display_inline; + } + + void SvgNode::parseAttribute(const OUString& /*rTokenName*/, SVGToken aSVGToken, const OUString& aContent) + { + switch(aSVGToken) + { + case SVGTokenId: + { + if(!aContent.isEmpty()) + { + setId(aContent); + } + break; + } + case SVGTokenClass: + { + if(!aContent.isEmpty()) + { + setClass(aContent); + } + break; + } + case SVGTokenXmlSpace: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("default")) + { + setXmlSpace(XmlSpace_default); + } + else if(aContent.startsWith("preserve")) + { + setXmlSpace(XmlSpace_preserve); + } + } + break; + } + case SVGTokenDisplay: + { + if(!aContent.isEmpty()) + { + setDisplay(getDisplayFromContent(aContent)); + } + break; + } + default: + { + break; + } + } + } + + void SvgNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool bReferenced) const + { + if (mbDecomposing) //guard against infinite recurse + return; + + if(Display_none == getDisplay()) + { + return; + } + + if(!bReferenced) + { + if(SVGTokenDefs == getType() || + SVGTokenSymbol == getType() || + SVGTokenClipPathNode == getType() || + SVGTokenMask == getType() || + SVGTokenMarker == getType() || + SVGTokenPattern == getType()) + { + // do not decompose defs or symbol nodes (these hold only style-like + // objects which may be used by referencing them) except when doing + // so controlled referenced + + // also do not decompose ClipPaths and Masks. These should be embedded + // in a defs node (which gets not decomposed by itself), but you never + // know + + // also not directly used are Markers and Patterns, only indirectly used + // by reference + + // #i121656# also do not decompose nodes which have display="none" set + // as property + return; + } + } + + const auto& rChildren = getChildren(); + + if(rChildren.empty()) + return; + + mbDecomposing = true; + + const sal_uInt32 nCount(rChildren.size()); + + for(sal_uInt32 a(0); a < nCount; a++) + { + SvgNode* pCandidate = rChildren[a].get(); + + if(pCandidate && Display_none != pCandidate->getDisplay()) + { + const auto& rGrandChildren = pCandidate->getChildren(); + const SvgStyleAttributes* pChildStyles = pCandidate->getSvgStyleAttributes(); + // decompose: + // - visible terminal nodes + // - all non-terminal nodes (might contain visible nodes down the hierarchy) + if( !rGrandChildren.empty() || ( pChildStyles && (Visibility_visible == pChildStyles->getVisibility())) ) + { + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + pCandidate->decomposeSvgNode(aNewTarget, bReferenced); + + if(!aNewTarget.empty()) + { + rTarget.append(aNewTarget); + } + } + } + else if(!pCandidate) + { + OSL_ENSURE(false, "Null-Pointer in child node list (!)"); + } + } + + if(!rTarget.empty()) + { + const SvgStyleAttributes* pStyles = getSvgStyleAttributes(); + if(pStyles) + { + // check if we have Title or Desc + const OUString& rTitle = pStyles->getTitle(); + const OUString& rDesc = pStyles->getDesc(); + + if(!rTitle.isEmpty() || !rDesc.isEmpty()) + { + // default object name is empty + OUString aObjectName; + + // use path as object name when outmost element + if(SVGTokenSvg == getType()) + { + aObjectName = getDocument().getAbsolutePath(); + + if(!aObjectName.isEmpty()) + { + INetURLObject aURL(aObjectName); + + aObjectName = aURL.getName( + INetURLObject::LAST_SEGMENT, + true, + INetURLObject::DecodeMechanism::WithCharset); + } + } + + // pack in ObjectInfoPrimitive2D group + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::ObjectInfoPrimitive2D( + rTarget, + aObjectName, + rTitle, + rDesc)); + + rTarget = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + } + } + mbDecomposing = false; + } + + basegfx::B2DRange SvgNode::getCurrentViewPort() const + { + if(getParent()) + { + return getParent()->getCurrentViewPort(); + } + else + { + return basegfx::B2DRange(); // return empty B2DRange + } + } + + double SvgNode::getCurrentFontSizeInherited() const + { + if(getParent()) + { + return getParent()->getCurrentFontSize(); + } + else + { + return 0.0; + } + } + + double SvgNode::getCurrentFontSize() const + { + if(getSvgStyleAttributes()) + return getSvgStyleAttributes()->getFontSizeNumber().solve(*this, xcoordinate); + + return getCurrentFontSizeInherited(); + } + + double SvgNode::getCurrentXHeightInherited() const + { + if(getParent()) + { + return getParent()->getCurrentXHeight(); + } + else + { + return 0.0; + } + } + + double SvgNode::getCurrentXHeight() const + { + if(getSvgStyleAttributes()) + // for XHeight, use FontSize currently + return getSvgStyleAttributes()->getFontSizeNumber().solve(*this, ycoordinate); + + return getCurrentXHeightInherited(); + } + + void SvgNode::setId(OUString const & rId) + { + if(mpId) + { + mrDocument.removeSvgNodeFromMapper(*mpId); + mpId.reset(); + } + + mpId = rId; + mrDocument.addSvgNodeToMapper(*mpId, *this); + } + + void SvgNode::setClass(OUString const & rClass) + { + if(mpClass) + { + mrDocument.removeSvgNodeFromMapper(*mpClass); + mpClass.reset(); + } + + mpClass = rClass; + mrDocument.addSvgNodeToMapper(*mpClass, *this); + } + + XmlSpace SvgNode::getXmlSpace() const + { + if(maXmlSpace != XmlSpace_notset) + { + return maXmlSpace; + } + + if(getParent()) + { + return getParent()->getXmlSpace(); + } + + // default is XmlSpace_default + return XmlSpace_default; + } + + void SvgNode::accept(Visitor & rVisitor) + { + rVisitor.visit(*this); + } +} // end of namespace svgio + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgpaint.cxx b/svgio/source/svgreader/svgpaint.cxx new file mode 100644 index 000000000..725dd9174 --- /dev/null +++ b/svgio/source/svgreader/svgpaint.cxx @@ -0,0 +1,22 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgpaint.hxx> + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgpathnode.cxx b/svgio/source/svgreader/svgpathnode.cxx new file mode 100644 index 000000000..4aaca4e8d --- /dev/null +++ b/svgio/source/svgreader/svgpathnode.cxx @@ -0,0 +1,118 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgpathnode.hxx> +#include <basegfx/polygon/b2dpolypolygontools.hxx> + +namespace svgio::svgreader +{ + SvgPathNode::SvgPathNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenPath, rDocument, pParent), + maSvgStyleAttributes(*this), + maPathLength() + { + } + + SvgPathNode::~SvgPathNode() + { + } + + const SvgStyleAttributes* SvgPathNode::getSvgStyleAttributes() const + { + return checkForCssStyle("path", maSvgStyleAttributes); + } + + void SvgPathNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenD: + { + basegfx::B2DPolyPolygon aPath; + + if(basegfx::utils::importFromSvgD(aPath, aContent, false, &maHelpPointIndices)) + { + if(aPath.count()) + { + setPath(&aPath); + } + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + case SVGTokenPathLength: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maPathLength = aNum; + } + break; + } + default: + { + break; + } + } + } + + void SvgPathNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + // fill and/or stroke needed, also a path + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(pStyle && getPath()) + { + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + pStyle->add_path(*getPath(), aNewTarget, &maHelpPointIndices); + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgpatternnode.cxx b/svgio/source/svgreader/svgpatternnode.cxx new file mode 100644 index 000000000..a72846aac --- /dev/null +++ b/svgio/source/svgreader/svgpatternnode.cxx @@ -0,0 +1,475 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgpatternnode.hxx> +#include <svgdocument.hxx> + +namespace svgio::svgreader +{ + void SvgPatternNode::tryToFindLink() + { + if(!mpXLink && !maXLink.isEmpty()) + { + mpXLink = dynamic_cast< const SvgPatternNode* >(getDocument().findSvgNodeById(maXLink)); + } + } + + SvgPatternNode::SvgPatternNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenPattern, rDocument, pParent), + aPrimitives(), + maSvgStyleAttributes(*this), + maSvgAspectRatio(), + maX(), + maY(), + maWidth(), + maHeight(), + mbResolvingLink(false), + maXLink(), + mpXLink(nullptr) + { + } + + SvgPatternNode::~SvgPatternNode() + { + } + + const SvgStyleAttributes* SvgPatternNode::getSvgStyleAttributes() const + { + return checkForCssStyle("pattern", maSvgStyleAttributes); + } + + void SvgPatternNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenViewBox: + { + const basegfx::B2DRange aRange(readViewBox(aContent, *this)); + + if(!aRange.isEmpty()) + { + setViewBox(&aRange); + } + break; + } + case SVGTokenPreserveAspectRatio: + { + maSvgAspectRatio = readSvgAspectRatio(aContent); + break; + } + case SVGTokenX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX = aNum; + } + break; + } + case SVGTokenY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY = aNum; + } + break; + } + case SVGTokenWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maWidth = aNum; + } + } + break; + } + case SVGTokenHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maHeight = aNum; + } + } + break; + } + case SVGTokenPatternUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setPatternUnits(userSpaceOnUse); + } + else if(aContent.match(commonStrings::aStrObjectBoundingBox)) + { + setPatternUnits(objectBoundingBox); + } + } + break; + } + case SVGTokenPatternContentUnits: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrUserSpaceOnUse)) + { + setPatternContentUnits(userSpaceOnUse); + } + else if(aContent.match(commonStrings::aStrObjectBoundingBox)) + { + setPatternContentUnits(objectBoundingBox); + } + } + break; + } + case SVGTokenPatternTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setPatternTransform(&aMatrix); + } + break; + } + case SVGTokenXlinkHref: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen && '#' == aContent[0]) + { + maXLink = aContent.copy(1); + tryToFindLink(); + } + break; + } + default: + { + break; + } + } + } + + void SvgPatternNode::getValuesRelative(double& rfX, double& rfY, double& rfW, double& rfH, const basegfx::B2DRange& rGeoRange, SvgNode const & rUser) const + { + double fTargetWidth(rGeoRange.getWidth()); + double fTargetHeight(rGeoRange.getHeight()); + + if(!(fTargetWidth > 0.0 && fTargetHeight > 0.0)) + return; + + const SvgUnits aPatternUnits(getPatternUnits() ? *getPatternUnits() : objectBoundingBox); + + if(objectBoundingBox == aPatternUnits) + { + rfW = (getWidth().isSet()) ? getWidth().getNumber() : 0.0; + rfH = (getHeight().isSet()) ? getHeight().getNumber() : 0.0; + + if(Unit_percent == getWidth().getUnit()) + { + rfW *= 0.01; + } + + if(Unit_percent == getHeight().getUnit()) + { + rfH *= 0.01; + } + } + else + { + rfW = (getWidth().isSet()) ? getWidth().solve(rUser, xcoordinate) : 0.0; + rfH = (getHeight().isSet()) ? getHeight().solve(rUser, ycoordinate) : 0.0; + + // make relative to rGeoRange + rfW /= fTargetWidth; + rfH /= fTargetHeight; + } + + if(!(rfW > 0.0 && rfH > 0.0)) + return; + + if(objectBoundingBox == aPatternUnits) + { + rfX = (getX().isSet()) ? getX().getNumber() : 0.0; + rfY = (getY().isSet()) ? getY().getNumber() : 0.0; + + if(Unit_percent == getX().getUnit()) + { + rfX *= 0.01; + } + + if(Unit_percent == getY().getUnit()) + { + rfY *= 0.01; + } + } + else + { + rfX = (getX().isSet()) ? getX().solve(rUser, xcoordinate) : 0.0; + rfY = (getY().isSet()) ? getY().solve(rUser, ycoordinate) : 0.0; + + // make relative to rGeoRange + rfX = (rfX - rGeoRange.getMinX()) / fTargetWidth; + rfY = (rfY - rGeoRange.getMinY()) / fTargetHeight; + } + } + + const drawinglayer::primitive2d::Primitive2DContainer& SvgPatternNode::getPatternPrimitives() const + { + if(aPrimitives.empty() && Display_none != getDisplay()) + { + decomposeSvgNode(const_cast< SvgPatternNode* >(this)->aPrimitives, true); + } + + if(aPrimitives.empty() && !maXLink.isEmpty()) + { + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + const drawinglayer::primitive2d::Primitive2DContainer& ret = mpXLink->getPatternPrimitives(); + mbResolvingLink = false; + return ret; + } + } + + return aPrimitives; + } + + basegfx::B2DRange SvgPatternNode::getCurrentViewPort() const + { + if(getViewBox()) + { + return *(getViewBox()); + } + else + { + return SvgNode::getCurrentViewPort(); + } + } + + const basegfx::B2DRange* SvgPatternNode::getViewBox() const + { + if(mpViewBox) + { + return mpViewBox.get(); + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getViewBox(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + + const SvgAspectRatio& SvgPatternNode::getSvgAspectRatio() const + { + if(maSvgAspectRatio.isSet()) + { + return maSvgAspectRatio; + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + const SvgAspectRatio& ret = mpXLink->getSvgAspectRatio(); + mbResolvingLink = false; + return ret; + } + + return maSvgAspectRatio; + } + + const SvgNumber& SvgPatternNode::getX() const + { + if(maX.isSet()) + { + return maX; + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + const SvgNumber& ret = mpXLink->getX(); + mbResolvingLink = false; + return ret; + } + + return maX; + } + + const SvgNumber& SvgPatternNode::getY() const + { + if(maY.isSet()) + { + return maY; + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + const SvgNumber& ret = mpXLink->getY(); + mbResolvingLink = false; + return ret; + } + + return maY; + } + + const SvgNumber& SvgPatternNode::getWidth() const + { + if(maWidth.isSet()) + { + return maWidth; + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + const SvgNumber& ret = mpXLink->getWidth(); + mbResolvingLink = false; + return ret; + } + + return maWidth; + } + + const SvgNumber& SvgPatternNode::getHeight() const + { + if(maHeight.isSet()) + { + return maHeight; + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + const SvgNumber& ret = mpXLink->getHeight(); + mbResolvingLink = false; + return ret; + } + + return maHeight; + } + + const SvgUnits* SvgPatternNode::getPatternUnits() const + { + if(mpPatternUnits) + { + return mpPatternUnits.get(); + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getPatternUnits(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + + const SvgUnits* SvgPatternNode::getPatternContentUnits() const + { + if(mpPatternContentUnits) + { + return mpPatternContentUnits.get(); + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getPatternContentUnits(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + + const basegfx::B2DHomMatrix* SvgPatternNode::getPatternTransform() const + { + if(mpaPatternTransform) + { + return mpaPatternTransform.get(); + } + + const_cast< SvgPatternNode* >(this)->tryToFindLink(); + + if (mpXLink && !mbResolvingLink) + { + mbResolvingLink = true; + auto ret = mpXLink->getPatternTransform(); + mbResolvingLink = false; + return ret; + } + + return nullptr; + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgpolynode.cxx b/svgio/source/svgreader/svgpolynode.cxx new file mode 100644 index 000000000..86cbe164f --- /dev/null +++ b/svgio/source/svgreader/svgpolynode.cxx @@ -0,0 +1,115 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgpolynode.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolypolygon.hxx> + +namespace svgio::svgreader +{ + SvgPolyNode::SvgPolyNode( + SvgDocument& rDocument, + SvgNode* pParent, + bool bIsPolyline) + : SvgNode(SVGTokenPolygon, rDocument, pParent), + maSvgStyleAttributes(*this), + mbIsPolyline(bIsPolyline) + { + } + + SvgPolyNode::~SvgPolyNode() + { + } + + const SvgStyleAttributes* SvgPolyNode::getSvgStyleAttributes() const + { + return checkForCssStyle(mbIsPolyline? OUString("polyline") : OUString("polygon"), maSvgStyleAttributes); + } + + void SvgPolyNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenPoints: + { + basegfx::B2DPolygon aPath; + + if(basegfx::utils::importFromSvgPoints(aPath, aContent)) + { + if(aPath.count()) + { + if(!mbIsPolyline) + { + aPath.setClosed(true); + } + + setPolygon(&aPath); + } + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgPolyNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(pStyle && mpPolygon) + { + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + pStyle->add_path(basegfx::B2DPolyPolygon(*mpPolygon), aNewTarget, nullptr); + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgrectnode.cxx b/svgio/source/svgreader/svgrectnode.cxx new file mode 100644 index 000000000..dca3c3ad5 --- /dev/null +++ b/svgio/source/svgreader/svgrectnode.cxx @@ -0,0 +1,215 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgrectnode.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolypolygon.hxx> + +namespace svgio::svgreader +{ + SvgRectNode::SvgRectNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenRect, rDocument, pParent), + maSvgStyleAttributes(*this), + maX(0), + maY(0), + maWidth(0), + maHeight(0), + maRx(0), + maRy(0) + { + } + + SvgRectNode::~SvgRectNode() + { + } + + const SvgStyleAttributes* SvgRectNode::getSvgStyleAttributes() const + { + return checkForCssStyle("rect", maSvgStyleAttributes); + } + + void SvgRectNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX = aNum; + } + break; + } + case SVGTokenY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY = aNum; + } + break; + } + case SVGTokenWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maWidth = aNum; + } + } + break; + } + case SVGTokenHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maHeight = aNum; + } + } + break; + } + case SVGTokenRx: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maRx = aNum; + } + } + break; + } + case SVGTokenRy: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maRy = aNum; + } + } + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgRectNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + // get size range and create path + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!(pStyle && getWidth().isSet() && getHeight().isSet())) + return; + + const double fWidth(getWidth().solve(*this, xcoordinate)); + const double fHeight(getHeight().solve(*this, ycoordinate)); + + if(!(fWidth > 0.0 && fHeight > 0.0)) + return; + + const double fX(getX().isSet() ? getX().solve(*this, xcoordinate) : 0.0); + const double fY(getY().isSet() ? getY().solve(*this, ycoordinate) : 0.0); + const basegfx::B2DRange aRange(fX, fY, fX + fWidth, fY + fHeight); + basegfx::B2DPolygon aPath; + + if(getRx().isSet() || getRy().isSet()) + { + double frX(getRx().isSet() ? getRx().solve(*this, xcoordinate) : 0.0); + double frY(getRy().isSet() ? getRy().solve(*this, ycoordinate) : 0.0); + + frX = std::max(0.0, frX); + frY = std::max(0.0, frY); + + if(0.0 == frY && frX > 0.0) + { + frY = frX; + } + else if(0.0 == frX && frY > 0.0) + { + frX = frY; + } + + frX /= fWidth; + frY /= fHeight; + + frX = std::min(0.5, frX); + frY = std::min(0.5, frY); + + aPath = basegfx::utils::createPolygonFromRect(aRange, frX * 2.0, frY * 2.0); + } + else + { + aPath = basegfx::utils::createPolygonFromRect(aRange); + } + + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + pStyle->add_path(basegfx::B2DPolyPolygon(aPath), aNewTarget, nullptr); + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgstyleattributes.cxx b/svgio/source/svgreader/svgstyleattributes.cxx new file mode 100644 index 000000000..383545bf4 --- /dev/null +++ b/svgio/source/svgreader/svgstyleattributes.cxx @@ -0,0 +1,3013 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <algorithm> + +#include <svgstyleattributes.hxx> +#include <drawinglayer/primitive2d/transformprimitive2d.hxx> +#include <drawinglayer/primitive2d/PolyPolygonColorPrimitive2D.hxx> +#include <drawinglayer/primitive2d/PolyPolygonStrokePrimitive2D.hxx> +#include <svgnode.hxx> +#include <svgdocument.hxx> +#include <drawinglayer/primitive2d/svggradientprimitive2d.hxx> +#include <svggradientnode.hxx> +#include <drawinglayer/primitive2d/unifiedtransparenceprimitive2d.hxx> +#include <basegfx/vector/b2enums.hxx> +#include <drawinglayer/processor2d/linegeometryextractor2d.hxx> +#include <drawinglayer/processor2d/textaspolygonextractor2d.hxx> +#include <basegfx/polygon/b2dpolypolygoncutter.hxx> +#include <svgclippathnode.hxx> +#include <svgmasknode.hxx> +#include <basegfx/polygon/b2dpolypolygontools.hxx> +#include <svgmarkernode.hxx> +#include <svgpatternnode.hxx> +#include <drawinglayer/primitive2d/patternfillprimitive2d.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <drawinglayer/primitive2d/maskprimitive2d.hxx> +#include <drawinglayer/primitive2d/pagehierarchyprimitive2d.hxx> + +const int nStyleDepthLimit = 1024; + +namespace svgio::svgreader +{ + static basegfx::B2DLineJoin StrokeLinejoinToB2DLineJoin(StrokeLinejoin aStrokeLinejoin) + { + if(StrokeLinejoin_round == aStrokeLinejoin) + { + return basegfx::B2DLineJoin::Round; + } + else if(StrokeLinejoin_bevel == aStrokeLinejoin) + { + return basegfx::B2DLineJoin::Bevel; + } + + return basegfx::B2DLineJoin::Miter; + } + + static css::drawing::LineCap StrokeLinecapToDrawingLineCap(StrokeLinecap aStrokeLinecap) + { + switch(aStrokeLinecap) + { + default: /* StrokeLinecap_notset, StrokeLinecap_butt */ + { + return css::drawing::LineCap_BUTT; + } + case StrokeLinecap_round: + { + return css::drawing::LineCap_ROUND; + } + case StrokeLinecap_square: + { + return css::drawing::LineCap_SQUARE; + } + } + } + + FontStretch getWider(FontStretch aSource) + { + switch(aSource) + { + case FontStretch_ultra_condensed: aSource = FontStretch_extra_condensed; break; + case FontStretch_extra_condensed: aSource = FontStretch_condensed; break; + case FontStretch_condensed: aSource = FontStretch_semi_condensed; break; + case FontStretch_semi_condensed: aSource = FontStretch_normal; break; + case FontStretch_normal: aSource = FontStretch_semi_expanded; break; + case FontStretch_semi_expanded: aSource = FontStretch_expanded; break; + case FontStretch_expanded: aSource = FontStretch_extra_expanded; break; + case FontStretch_extra_expanded: aSource = FontStretch_ultra_expanded; break; + default: break; + } + + return aSource; + } + + FontStretch getNarrower(FontStretch aSource) + { + switch(aSource) + { + case FontStretch_extra_condensed: aSource = FontStretch_ultra_condensed; break; + case FontStretch_condensed: aSource = FontStretch_extra_condensed; break; + case FontStretch_semi_condensed: aSource = FontStretch_condensed; break; + case FontStretch_normal: aSource = FontStretch_semi_condensed; break; + case FontStretch_semi_expanded: aSource = FontStretch_normal; break; + case FontStretch_expanded: aSource = FontStretch_semi_expanded; break; + case FontStretch_extra_expanded: aSource = FontStretch_expanded; break; + case FontStretch_ultra_expanded: aSource = FontStretch_extra_expanded; break; + default: break; + } + + return aSource; + } + + FontWeight getBolder(FontWeight aSource) + { + switch(aSource) + { + case FontWeight_100: aSource = FontWeight_200; break; + case FontWeight_200: aSource = FontWeight_300; break; + case FontWeight_300: aSource = FontWeight_400; break; + case FontWeight_400: aSource = FontWeight_500; break; + case FontWeight_500: aSource = FontWeight_600; break; + case FontWeight_600: aSource = FontWeight_700; break; + case FontWeight_700: aSource = FontWeight_800; break; + case FontWeight_800: aSource = FontWeight_900; break; + default: break; + } + + return aSource; + } + + FontWeight getLighter(FontWeight aSource) + { + switch(aSource) + { + case FontWeight_200: aSource = FontWeight_100; break; + case FontWeight_300: aSource = FontWeight_200; break; + case FontWeight_400: aSource = FontWeight_300; break; + case FontWeight_500: aSource = FontWeight_400; break; + case FontWeight_600: aSource = FontWeight_500; break; + case FontWeight_700: aSource = FontWeight_600; break; + case FontWeight_800: aSource = FontWeight_700; break; + case FontWeight_900: aSource = FontWeight_800; break; + default: break; + } + + return aSource; + } + + ::FontWeight getVclFontWeight(FontWeight aSource) + { + ::FontWeight nRetval(WEIGHT_NORMAL); + + switch(aSource) + { + case FontWeight_100: nRetval = WEIGHT_ULTRALIGHT; break; + case FontWeight_200: nRetval = WEIGHT_LIGHT; break; + case FontWeight_300: nRetval = WEIGHT_SEMILIGHT; break; + case FontWeight_400: nRetval = WEIGHT_NORMAL; break; + case FontWeight_500: nRetval = WEIGHT_MEDIUM; break; + case FontWeight_600: nRetval = WEIGHT_SEMIBOLD; break; + case FontWeight_700: nRetval = WEIGHT_BOLD; break; + case FontWeight_800: nRetval = WEIGHT_ULTRABOLD; break; + case FontWeight_900: nRetval = WEIGHT_BLACK; break; + default: break; + } + + return nRetval; + } + + void SvgStyleAttributes::readCssStyle(const OUString& rCandidate) + { + const sal_Int32 nLen(rCandidate.getLength()); + sal_Int32 nPos(0); + + while(nPos < nLen) + { + // get TokenName + OUStringBuffer aTokenName; + skip_char(rCandidate, u' ', nPos, nLen); + copyString(rCandidate, nPos, aTokenName, nLen); + + if (aTokenName.isEmpty()) + { + // if no TokenName advance one by force to avoid death loop, continue + OSL_ENSURE(false, "Could not interpret on current position, advancing one byte (!)"); + nPos++; + continue; + } + + // get TokenValue + OUStringBuffer aTokenValue; + skip_char(rCandidate, u' ', u':', nPos, nLen); + copyToLimiter(rCandidate, u';', nPos, aTokenValue, nLen); + skip_char(rCandidate, u' ', u';', nPos, nLen); + + if (aTokenValue.isEmpty()) + { + // no value - continue + continue; + } + + // generate OUStrings + const OUString aOUTokenName(aTokenName.makeStringAndClear()); + OUString aOUTokenValue(aTokenValue.makeStringAndClear()); + + // check for '!important' CssStyle mark, currently not supported + // but needs to be extracted for correct parsing + OUString aTokenImportant("!important"); + const sal_Int32 nIndexTokenImportant(aOUTokenValue.indexOf(aTokenImportant)); + + if(-1 != nIndexTokenImportant) + { + // if there currently just remove it and remove spaces to have the value only + OUString aNewOUTokenValue; + + if(nIndexTokenImportant > 0) + { + // copy content before token + aNewOUTokenValue += aOUTokenValue.copy(0, nIndexTokenImportant); + } + + if(aOUTokenValue.getLength() > nIndexTokenImportant + aTokenImportant.getLength()) + { + // copy content after token + aNewOUTokenValue += aOUTokenValue.copy(nIndexTokenImportant + aTokenImportant.getLength()); + } + + // remove spaces + aOUTokenValue = aNewOUTokenValue.trim(); + } + + // valid token-value pair, parse it + parseStyleAttribute(StrToSVGToken(aOUTokenName, true), aOUTokenValue, true); + } + } + + const SvgStyleAttributes* SvgStyleAttributes::getParentStyle() const + { + if(getCssStyleParent()) + { + return getCssStyleParent(); + } + + if(mrOwner.supportsParentStyle() && mrOwner.getParent()) + { + return mrOwner.getParent()->getSvgStyleAttributes(); + } + + return nullptr; + } + + void SvgStyleAttributes::add_text( + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + drawinglayer::primitive2d::Primitive2DContainer const & rSource) const + { + if(rSource.empty()) + return; + + // at this point the primitives in rSource are of type TextSimplePortionPrimitive2D + // or TextDecoratedPortionPrimitive2D and have the Fill Color (pAttributes->getFill()) + // set. When another fill is used and also evtl. stroke is set it gets necessary to + // dismantle to geometry and add needed primitives + const basegfx::BColor* pFill = getFill(); + const SvgGradientNode* pFillGradient = getSvgGradientNodeFill(); + const SvgPatternNode* pFillPattern = getSvgPatternNodeFill(); + const basegfx::BColor* pStroke = getStroke(); + const SvgGradientNode* pStrokeGradient = getSvgGradientNodeStroke(); + const SvgPatternNode* pStrokePattern = getSvgPatternNodeStroke(); + basegfx::B2DPolyPolygon aMergedArea; + + if(pFillGradient || pFillPattern || pStroke || pStrokeGradient || pStrokePattern) + { + // text geometry is needed, create + // use neutral ViewInformation and create LineGeometryExtractor2D + const drawinglayer::geometry::ViewInformation2D aViewInformation2D; + drawinglayer::processor2d::TextAsPolygonExtractor2D aExtractor(aViewInformation2D); + + // process + aExtractor.process(rSource); + + // get results + const drawinglayer::processor2d::TextAsPolygonDataNodeVector& rResult = aExtractor.getTarget(); + const sal_uInt32 nResultCount(rResult.size()); + basegfx::B2DPolyPolygonVector aTextFillVector; + aTextFillVector.reserve(nResultCount); + + for(sal_uInt32 a(0); a < nResultCount; a++) + { + const drawinglayer::processor2d::TextAsPolygonDataNode& rCandidate = rResult[a]; + + if(rCandidate.getIsFilled()) + { + aTextFillVector.push_back(rCandidate.getB2DPolyPolygon()); + } + } + + if(!aTextFillVector.empty()) + { + aMergedArea = basegfx::utils::mergeToSinglePolyPolygon(aTextFillVector); + } + } + + const bool bStrokeUsed(pStroke || pStrokeGradient || pStrokePattern); + + // add fill. Use geometry even for simple color fill when stroke + // is used, else text rendering and the geometry-based stroke will + // normally not really match optically due to diverse system text + // renderers + if(aMergedArea.count() && (pFillGradient || pFillPattern || bStrokeUsed)) + { + // create text fill content based on geometry + add_fill(aMergedArea, rTarget, aMergedArea.getB2DRange()); + } + else if(pFill) + { + // add the already prepared primitives for single color fill + rTarget.append(rSource); + } + + // add stroke + if(aMergedArea.count() && bStrokeUsed) + { + // create text stroke content + add_stroke(aMergedArea, rTarget, aMergedArea.getB2DRange()); + } + } + + void SvgStyleAttributes::add_fillGradient( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const SvgGradientNode& rFillGradient, + const basegfx::B2DRange& rGeoRange) const + { + // create fill content + drawinglayer::primitive2d::SvgGradientEntryVector aSvgGradientEntryVector; + + // get the color stops + rFillGradient.collectGradientEntries(aSvgGradientEntryVector); + + if(aSvgGradientEntryVector.empty()) + return; + + basegfx::B2DHomMatrix aGeoToUnit; + basegfx::B2DHomMatrix aGradientTransform; + + if(rFillGradient.getGradientTransform()) + { + aGradientTransform = *rFillGradient.getGradientTransform(); + } + + if(userSpaceOnUse == rFillGradient.getGradientUnits()) + { + aGeoToUnit.translate(-rGeoRange.getMinX(), -rGeoRange.getMinY()); + aGeoToUnit.scale(1.0 / rGeoRange.getWidth(), 1.0 / rGeoRange.getHeight()); + } + + if(SVGTokenLinearGradient == rFillGradient.getType()) + { + basegfx::B2DPoint aStart(0.0, 0.0); + basegfx::B2DPoint aEnd(1.0, 0.0); + + if(userSpaceOnUse == rFillGradient.getGradientUnits()) + { + // all possible units + aStart.setX(rFillGradient.getX1().solve(mrOwner, xcoordinate)); + aStart.setY(rFillGradient.getY1().solve(mrOwner, ycoordinate)); + aEnd.setX(rFillGradient.getX2().solve(mrOwner, xcoordinate)); + aEnd.setY(rFillGradient.getY2().solve(mrOwner, ycoordinate)); + } + else + { + // fractions or percent relative to object bounds + const SvgNumber X1(rFillGradient.getX1()); + const SvgNumber Y1(rFillGradient.getY1()); + const SvgNumber X2(rFillGradient.getX2()); + const SvgNumber Y2(rFillGradient.getY2()); + + aStart.setX(Unit_percent == X1.getUnit() ? X1.getNumber() * 0.01 : X1.getNumber()); + aStart.setY(Unit_percent == Y1.getUnit() ? Y1.getNumber() * 0.01 : Y1.getNumber()); + aEnd.setX(Unit_percent == X2.getUnit() ? X2.getNumber() * 0.01 : X2.getNumber()); + aEnd.setY(Unit_percent == Y2.getUnit() ? Y2.getNumber() * 0.01 : Y2.getNumber()); + } + + if(!aGeoToUnit.isIdentity()) + { + aStart *= aGeoToUnit; + aEnd *= aGeoToUnit; + } + + rTarget.push_back( + new drawinglayer::primitive2d::SvgLinearGradientPrimitive2D( + aGradientTransform, + rPath, + aSvgGradientEntryVector, + aStart, + aEnd, + userSpaceOnUse != rFillGradient.getGradientUnits(), + rFillGradient.getSpreadMethod())); + } + else + { + basegfx::B2DPoint aStart(0.5, 0.5); + basegfx::B2DPoint aFocal; + double fRadius(0.5); + const SvgNumber* pFx = rFillGradient.getFx(); + const SvgNumber* pFy = rFillGradient.getFy(); + const bool bFocal(pFx || pFy); + + if(userSpaceOnUse == rFillGradient.getGradientUnits()) + { + // all possible units + aStart.setX(rFillGradient.getCx().solve(mrOwner, xcoordinate)); + aStart.setY(rFillGradient.getCy().solve(mrOwner, ycoordinate)); + fRadius = rFillGradient.getR().solve(mrOwner); + + if(bFocal) + { + aFocal.setX(pFx ? pFx->solve(mrOwner, xcoordinate) : aStart.getX()); + aFocal.setY(pFy ? pFy->solve(mrOwner, ycoordinate) : aStart.getY()); + } + } + else + { + // fractions or percent relative to object bounds + const SvgNumber Cx(rFillGradient.getCx()); + const SvgNumber Cy(rFillGradient.getCy()); + const SvgNumber R(rFillGradient.getR()); + + aStart.setX(Unit_percent == Cx.getUnit() ? Cx.getNumber() * 0.01 : Cx.getNumber()); + aStart.setY(Unit_percent == Cy.getUnit() ? Cy.getNumber() * 0.01 : Cy.getNumber()); + fRadius = (Unit_percent == R.getUnit()) ? R.getNumber() * 0.01 : R.getNumber(); + + if(bFocal) + { + aFocal.setX(pFx ? (Unit_percent == pFx->getUnit() ? pFx->getNumber() * 0.01 : pFx->getNumber()) : aStart.getX()); + aFocal.setY(pFy ? (Unit_percent == pFy->getUnit() ? pFy->getNumber() * 0.01 : pFy->getNumber()) : aStart.getY()); + } + } + + if(!aGeoToUnit.isIdentity()) + { + aStart *= aGeoToUnit; + fRadius = (aGeoToUnit * basegfx::B2DVector(fRadius, 0.0)).getLength(); + + if(bFocal) + { + aFocal *= aGeoToUnit; + } + } + + rTarget.push_back( + new drawinglayer::primitive2d::SvgRadialGradientPrimitive2D( + aGradientTransform, + rPath, + aSvgGradientEntryVector, + aStart, + fRadius, + userSpaceOnUse != rFillGradient.getGradientUnits(), + rFillGradient.getSpreadMethod(), + bFocal ? &aFocal : nullptr)); + } + } + + void SvgStyleAttributes::add_fillPatternTransform( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const SvgPatternNode& rFillPattern, + const basegfx::B2DRange& rGeoRange) const + { + // prepare fill polyPolygon with given pattern, check for patternTransform + if(rFillPattern.getPatternTransform() && !rFillPattern.getPatternTransform()->isIdentity()) + { + // PatternTransform is active; Handle by filling the inverse transformed + // path and back-transforming the result + basegfx::B2DPolyPolygon aPath(rPath); + basegfx::B2DHomMatrix aInv(*rFillPattern.getPatternTransform()); + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + aInv.invert(); + aPath.transform(aInv); + add_fillPattern(aPath, aNewTarget, rFillPattern, aPath.getB2DRange()); + + if(!aNewTarget.empty()) + { + rTarget.push_back( + new drawinglayer::primitive2d::TransformPrimitive2D( + *rFillPattern.getPatternTransform(), + aNewTarget)); + } + } + else + { + // no patternTransform, create fillPattern directly + add_fillPattern(rPath, rTarget, rFillPattern, rGeoRange); + } + } + + void SvgStyleAttributes::add_fillPattern( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const SvgPatternNode& rFillPattern, + const basegfx::B2DRange& rGeoRange) const + { + // fill polyPolygon with given pattern + const drawinglayer::primitive2d::Primitive2DContainer& rPrimitives = rFillPattern.getPatternPrimitives(); + + if(rPrimitives.empty()) + return; + + double fTargetWidth(rGeoRange.getWidth()); + double fTargetHeight(rGeoRange.getHeight()); + + if(!(fTargetWidth > 0.0 && fTargetHeight > 0.0)) + return; + + // get relative values from pattern + double fX(0.0); + double fY(0.0); + double fW(0.0); + double fH(0.0); + + rFillPattern.getValuesRelative(fX, fY, fW, fH, rGeoRange, mrOwner); + + if(!(fW > 0.0 && fH > 0.0)) + return; + + // build the reference range relative to the rGeoRange + const basegfx::B2DRange aReferenceRange(fX, fY, fX + fW, fY + fH); + + // find out how the content is mapped to the reference range + basegfx::B2DHomMatrix aMapPrimitivesToUnitRange; + const basegfx::B2DRange* pViewBox = rFillPattern.getViewBox(); + + if(pViewBox) + { + // use viewBox/preserveAspectRatio + const SvgAspectRatio& rRatio = rFillPattern.getSvgAspectRatio(); + const basegfx::B2DRange aUnitRange(0.0, 0.0, 1.0, 1.0); + + if(rRatio.isSet()) + { + // let mapping be created from SvgAspectRatio + aMapPrimitivesToUnitRange = rRatio.createMapping(aUnitRange, *pViewBox); + } + else + { + // choose default mapping + aMapPrimitivesToUnitRange = SvgAspectRatio::createLinearMapping(aUnitRange, *pViewBox); + } + } + else + { + // use patternContentUnits + const SvgUnits aPatternContentUnits(rFillPattern.getPatternContentUnits() ? *rFillPattern.getPatternContentUnits() : userSpaceOnUse); + + if(userSpaceOnUse == aPatternContentUnits) + { + // create relative mapping to unit coordinates + aMapPrimitivesToUnitRange.scale(1.0 / (fW * fTargetWidth), 1.0 / (fH * fTargetHeight)); + } + else + { + aMapPrimitivesToUnitRange.scale(1.0 / fW, 1.0 / fH); + } + } + + // apply aMapPrimitivesToUnitRange to content when used + drawinglayer::primitive2d::Primitive2DContainer aPrimitives(rPrimitives); + + if(!aMapPrimitivesToUnitRange.isIdentity()) + { + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + aMapPrimitivesToUnitRange, + aPrimitives)); + + aPrimitives = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + + // embed in PatternFillPrimitive2D + rTarget.push_back( + new drawinglayer::primitive2d::PatternFillPrimitive2D( + rPath, + aPrimitives, + aReferenceRange)); + } + + void SvgStyleAttributes::add_fill( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const basegfx::B2DRange& rGeoRange) const + { + const basegfx::BColor* pFill = getFill(); + const SvgGradientNode* pFillGradient = getSvgGradientNodeFill(); + const SvgPatternNode* pFillPattern = getSvgPatternNodeFill(); + + if(!(pFill || pFillGradient || pFillPattern)) + return; + + const double fFillOpacity(getFillOpacity().solve(mrOwner)); + + if(!basegfx::fTools::more(fFillOpacity, 0.0)) + return; + + drawinglayer::primitive2d::Primitive2DContainer aNewFill; + + if(pFillGradient) + { + // create fill content with SVG gradient primitive + add_fillGradient(rPath, aNewFill, *pFillGradient, rGeoRange); + } + else if(pFillPattern) + { + // create fill content with SVG pattern primitive + add_fillPatternTransform(rPath, aNewFill, *pFillPattern, rGeoRange); + } + else // if(pFill) + { + // create fill content + aNewFill.resize(1); + aNewFill[0] = new drawinglayer::primitive2d::PolyPolygonColorPrimitive2D( + rPath, + *pFill); + } + + if(aNewFill.empty()) + return; + + if(basegfx::fTools::less(fFillOpacity, 1.0)) + { + // embed in UnifiedTransparencePrimitive2D + rTarget.push_back( + new drawinglayer::primitive2d::UnifiedTransparencePrimitive2D( + aNewFill, + 1.0 - fFillOpacity)); + } + else + { + // append + rTarget.append(aNewFill); + } + } + + void SvgStyleAttributes::add_stroke( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const basegfx::B2DRange& rGeoRange) const + { + const basegfx::BColor* pStroke = getStroke(); + const SvgGradientNode* pStrokeGradient = getSvgGradientNodeStroke(); + const SvgPatternNode* pStrokePattern = getSvgPatternNodeStroke(); + + if(!(pStroke || pStrokeGradient || pStrokePattern)) + return; + + drawinglayer::primitive2d::Primitive2DContainer aNewStroke; + const double fStrokeOpacity(getStrokeOpacity().solve(mrOwner)); + + if(!basegfx::fTools::more(fStrokeOpacity, 0.0)) + return; + + // get stroke width; SVG does not use 0.0 == hairline, so 0.0 is no line at all + const double fStrokeWidth(getStrokeWidth().isSet() ? getStrokeWidth().solve(mrOwner) : 1.0); + + if(!basegfx::fTools::more(fStrokeWidth, 0.0)) + return; + + drawinglayer::primitive2d::Primitive2DReference aNewLinePrimitive; + + // if we have a line with two identical points it is not really a line, + // but used by SVG sometimes to paint a single dot.In that case, create + // the geometry for a single dot + if(1 == rPath.count()) + { + const basegfx::B2DPolygon& aSingle(rPath.getB2DPolygon(0)); + + if(2 == aSingle.count() && aSingle.getB2DPoint(0).equal(aSingle.getB2DPoint(1))) + { + aNewLinePrimitive = new drawinglayer::primitive2d::PolyPolygonColorPrimitive2D( + basegfx::B2DPolyPolygon( + basegfx::utils::createPolygonFromCircle( + aSingle.getB2DPoint(0), + fStrokeWidth * (1.44 * 0.5))), + pStroke ? *pStroke : basegfx::BColor(0.0, 0.0, 0.0)); + } + } + + if(!aNewLinePrimitive.is()) + { + // get LineJoin, LineCap and stroke array + const basegfx::B2DLineJoin aB2DLineJoin(StrokeLinejoinToB2DLineJoin(getStrokeLinejoin())); + const css::drawing::LineCap aLineCap(StrokeLinecapToDrawingLineCap(getStrokeLinecap())); + ::std::vector< double > aDashArray; + + if(!getStrokeDasharray().empty()) + { + aDashArray = solveSvgNumberVector(getStrokeDasharray(), mrOwner); + } + + // convert svg:stroke-miterlimit to LineAttrute:mfMiterMinimumAngle + // The default needs to be set explicitly, because svg default <> Draw default + double fMiterMinimumAngle; + if (getStrokeMiterLimit().isSet()) + { + fMiterMinimumAngle = 2.0 * asin(1.0/getStrokeMiterLimit().getNumber()); + } + else + { + fMiterMinimumAngle = 2.0 * asin(0.25); // 1.0/default 4.0 + } + + // todo: Handle getStrokeDashOffset() + + // prepare line attribute + const drawinglayer::attribute::LineAttribute aLineAttribute( + pStroke ? *pStroke : basegfx::BColor(0.0, 0.0, 0.0), + fStrokeWidth, + aB2DLineJoin, + aLineCap, + fMiterMinimumAngle); + + if(aDashArray.empty()) + { + aNewLinePrimitive = new drawinglayer::primitive2d::PolyPolygonStrokePrimitive2D( + rPath, + aLineAttribute); + } + else + { + const drawinglayer::attribute::StrokeAttribute aStrokeAttribute(aDashArray); + + aNewLinePrimitive = new drawinglayer::primitive2d::PolyPolygonStrokePrimitive2D( + rPath, + aLineAttribute, + aStrokeAttribute); + } + } + + if(pStrokeGradient || pStrokePattern) + { + // put primitive into Primitive2DReference and Primitive2DSequence + const drawinglayer::primitive2d::Primitive2DContainer aSeq { aNewLinePrimitive }; + + // use neutral ViewInformation and create LineGeometryExtractor2D + const drawinglayer::geometry::ViewInformation2D aViewInformation2D; + drawinglayer::processor2d::LineGeometryExtractor2D aExtractor(aViewInformation2D); + + // process + aExtractor.process(aSeq); + + // check for fill rsults + const basegfx::B2DPolyPolygonVector& rLineFillVector(aExtractor.getExtractedLineFills()); + + if(!rLineFillVector.empty()) + { + const basegfx::B2DPolyPolygon aMergedArea( + basegfx::utils::mergeToSinglePolyPolygon( + rLineFillVector)); + + if(aMergedArea.count()) + { + if(pStrokeGradient) + { + // create fill content with SVG gradient primitive. Use original GeoRange, + // e.g. from circle without LineWidth + add_fillGradient(aMergedArea, aNewStroke, *pStrokeGradient, rGeoRange); + } + else // if(pStrokePattern) + { + // create fill content with SVG pattern primitive. Use GeoRange + // from the expanded data, e.g. circle with extended geo by half linewidth + add_fillPatternTransform(aMergedArea, aNewStroke, *pStrokePattern, aMergedArea.getB2DRange()); + } + } + } + } + else // if(pStroke) + { + aNewStroke.push_back(aNewLinePrimitive); + } + + if(aNewStroke.empty()) + return; + + if(basegfx::fTools::less(fStrokeOpacity, 1.0)) + { + // embed in UnifiedTransparencePrimitive2D + rTarget.push_back( + new drawinglayer::primitive2d::UnifiedTransparencePrimitive2D( + aNewStroke, + 1.0 - fStrokeOpacity)); + } + else + { + // append + rTarget.append(aNewStroke); + } + } + + bool SvgStyleAttributes::prepare_singleMarker( + drawinglayer::primitive2d::Primitive2DContainer& rMarkerPrimitives, + basegfx::B2DHomMatrix& rMarkerTransform, + basegfx::B2DRange& rClipRange, + const SvgMarkerNode& rMarker) const + { + // reset return values + rMarkerTransform.identity(); + rClipRange.reset(); + + // get marker primitive representation + rMarkerPrimitives = rMarker.getMarkerPrimitives(); + + if(!rMarkerPrimitives.empty()) + { + basegfx::B2DRange aPrimitiveRange(0.0, 0.0, 1.0, 1.0); + const basegfx::B2DRange* pViewBox = rMarker.getViewBox(); + + if(pViewBox) + { + aPrimitiveRange = *pViewBox; + } + + if(aPrimitiveRange.getWidth() > 0.0 && aPrimitiveRange.getHeight() > 0.0) + { + double fTargetWidth(rMarker.getMarkerWidth().isSet() ? rMarker.getMarkerWidth().solve(mrOwner, xcoordinate) : 3.0); + double fTargetHeight(rMarker.getMarkerHeight().isSet() ? rMarker.getMarkerHeight().solve(mrOwner, xcoordinate) : 3.0); + const bool bStrokeWidth(SvgMarkerNode::MarkerUnits::strokeWidth == rMarker.getMarkerUnits()); + const double fStrokeWidth(getStrokeWidth().isSet() ? getStrokeWidth().solve(mrOwner) : 1.0); + + if(bStrokeWidth) + { + // relative to strokeWidth + fTargetWidth *= fStrokeWidth; + fTargetHeight *= fStrokeWidth; + } + + if(fTargetWidth > 0.0 && fTargetHeight > 0.0) + { + // create mapping + const basegfx::B2DRange aTargetRange(0.0, 0.0, fTargetWidth, fTargetHeight); + const SvgAspectRatio& rRatio = rMarker.getSvgAspectRatio(); + + if(rRatio.isSet()) + { + // let mapping be created from SvgAspectRatio + rMarkerTransform = rRatio.createMapping(aTargetRange, aPrimitiveRange); + + if(rRatio.isMeetOrSlice()) + { + // need to clip + rClipRange = aPrimitiveRange; + } + } + else + { + if(!pViewBox) + { + if(bStrokeWidth) + { + // adapt to strokewidth if needed + rMarkerTransform.scale(fStrokeWidth, fStrokeWidth); + } + } + else + { + // choose default mapping + rMarkerTransform = SvgAspectRatio::createLinearMapping(aTargetRange, aPrimitiveRange); + } + } + + // get and apply reference point. Initially it's in marker local coordinate system + basegfx::B2DPoint aRefPoint( + rMarker.getRefX().isSet() ? rMarker.getRefX().solve(mrOwner, xcoordinate) : 0.0, + rMarker.getRefY().isSet() ? rMarker.getRefY().solve(mrOwner, ycoordinate) : 0.0); + + // apply MarkerTransform to have it in mapped coordinates + aRefPoint *= rMarkerTransform; + + // apply by moving RepPoint to (0.0) + rMarkerTransform.translate(-aRefPoint.getX(), -aRefPoint.getY()); + + return true; + } + } + } + + return false; + } + + void SvgStyleAttributes::add_markers( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const basegfx::utils::PointIndexSet* pHelpPointIndices) const + { + // try to access linked markers + const SvgMarkerNode* pStart = accessMarkerStartXLink(); + const SvgMarkerNode* pMid = accessMarkerMidXLink(); + const SvgMarkerNode* pEnd = accessMarkerEndXLink(); + + if(!(pStart || pMid || pEnd)) + return; + + const sal_uInt32 nSubPathCount(rPath.count()); + + if(!nSubPathCount) + return; + + // remember prepared marker; pStart, pMid and pEnd may all be equal when + // only 'marker' was used instead of 'marker-start', 'marker-mid' or 'marker-end', + // see 'case SVGTokenMarker' in this file; thus in this case only one common + // marker in primitive form will be prepared + const SvgMarkerNode* pPrepared = nullptr; + + // values for the prepared marker, results of prepare_singleMarker + drawinglayer::primitive2d::Primitive2DContainer aPreparedMarkerPrimitives; + basegfx::B2DHomMatrix aPreparedMarkerTransform; + basegfx::B2DRange aPreparedMarkerClipRange; + + for (sal_uInt32 a(0); a < nSubPathCount; a++) + { + // iterate over sub-paths + const basegfx::B2DPolygon& aSubPolygonPath(rPath.getB2DPolygon(a)); + const sal_uInt32 nSubPolygonPointCount(aSubPolygonPath.count()); + const bool bSubPolygonPathIsClosed(aSubPolygonPath.isClosed()); + + if(nSubPolygonPointCount) + { + // for each sub-path, create one marker per point (when closed, two markers + // need to pe created for the 1st point) + const sal_uInt32 nTargetMarkerCount(bSubPolygonPathIsClosed ? nSubPolygonPointCount + 1 : nSubPolygonPointCount); + + for (sal_uInt32 b(0); b < nTargetMarkerCount; b++) + { + const bool bIsFirstMarker(!a && !b); + const bool bIsLastMarker(nSubPathCount - 1 == a && nTargetMarkerCount - 1 == b); + const SvgMarkerNode* pNeeded = nullptr; + + if(bIsFirstMarker) + { + // 1st point in 1st sub-polygon, use pStart + pNeeded = pStart; + } + else if(bIsLastMarker) + { + // last point in last sub-polygon, use pEnd + pNeeded = pEnd; + } + else + { + // anything in-between, use pMid + pNeeded = pMid; + } + + if(pHelpPointIndices && !pHelpPointIndices->empty()) + { + const basegfx::utils::PointIndexSet::const_iterator aFound( + pHelpPointIndices->find(basegfx::utils::PointIndex(a, b))); + + if(aFound != pHelpPointIndices->end()) + { + // this point is a pure helper point; do not create a marker for it + continue; + } + } + + if(!pNeeded) + { + // no marker needs to be created for this point + continue; + } + + if(pPrepared != pNeeded) + { + // if needed marker is not yet prepared, do it now + if(prepare_singleMarker(aPreparedMarkerPrimitives, aPreparedMarkerTransform, aPreparedMarkerClipRange, *pNeeded)) + { + pPrepared = pNeeded; + } + else + { + // error: could not prepare given marker + OSL_ENSURE(false, "OOps, could not prepare given marker as primitives (!)"); + pPrepared = nullptr; + continue; + } + } + + // prepare complete transform + basegfx::B2DHomMatrix aCombinedTransform(aPreparedMarkerTransform); + + // get rotation + if(pPrepared->getOrientAuto()) + { + const sal_uInt32 nPointIndex(b % nSubPolygonPointCount); + + // get entering and leaving tangents; this will search backward/forward + // in the polygon to find tangents unequal to zero, skipping empty edges + // see basegfx descriptions) + // Hint: Mozilla, Inkscape and others use only leaving tangent for start marker + // and entering tangent for end marker. To achieve this (if wanted) it is possible + // to make the fetch of aEntering/aLeaving dependent on bIsFirstMarker/bIsLastMarker. + // This is not done here, see comment 14 in task #1232379# + // or http://www.w3.org/TR/SVG/painting.html#OrientAttribute + basegfx::B2DVector aEntering( + basegfx::utils::getTangentEnteringPoint( + aSubPolygonPath, + nPointIndex)); + basegfx::B2DVector aLeaving( + basegfx::utils::getTangentLeavingPoint( + aSubPolygonPath, + nPointIndex)); + const bool bEntering(!aEntering.equalZero()); + const bool bLeaving(!aLeaving.equalZero()); + + if(bEntering || bLeaving) + { + basegfx::B2DVector aSum(0.0, 0.0); + + if(bEntering) + { + aSum += aEntering.normalize(); + } + + if(bLeaving) + { + aSum += aLeaving.normalize(); + } + + if(!aSum.equalZero()) + { + const double fAngle(atan2(aSum.getY(), aSum.getX())); + + // apply rotation + aCombinedTransform.rotate(fAngle); + } + } + } + else + { + // apply rotation + aCombinedTransform.rotate(pPrepared->getAngle()); + } + + // get and apply target position + const basegfx::B2DPoint aPoint(aSubPolygonPath.getB2DPoint(b % nSubPolygonPointCount)); + + aCombinedTransform.translate(aPoint.getX(), aPoint.getY()); + + // prepare marker + drawinglayer::primitive2d::Primitive2DReference xMarker( + new drawinglayer::primitive2d::TransformPrimitive2D( + aCombinedTransform, + aPreparedMarkerPrimitives)); + + if(!aPreparedMarkerClipRange.isEmpty()) + { + // marker needs to be clipped, it's bigger as the mapping + basegfx::B2DPolyPolygon aClipPolygon(basegfx::utils::createPolygonFromRect(aPreparedMarkerClipRange)); + + aClipPolygon.transform(aCombinedTransform); + xMarker = new drawinglayer::primitive2d::MaskPrimitive2D( + aClipPolygon, + drawinglayer::primitive2d::Primitive2DContainer { xMarker }); + } + + // add marker + rTarget.push_back(xMarker); + } + } + } + } + + void SvgStyleAttributes::add_path( + const basegfx::B2DPolyPolygon& rPath, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const basegfx::utils::PointIndexSet* pHelpPointIndices) const + { + if(!rPath.count()) + { + // no geometry at all + return; + } + + const basegfx::B2DRange aGeoRange(rPath.getB2DRange()); + + if(aGeoRange.isEmpty()) + { + // no geometry range + return; + } + + const double fOpacity(getOpacity().solve(mrOwner)); + + if(basegfx::fTools::equalZero(fOpacity)) + { + // not visible + return; + } + + // check if it's a line + const bool bNoWidth(basegfx::fTools::equalZero(aGeoRange.getWidth())); + const bool bNoHeight(basegfx::fTools::equalZero(aGeoRange.getHeight())); + const bool bIsTwoPointLine(1 == rPath.count() + && !rPath.areControlPointsUsed() + && 2 == rPath.getB2DPolygon(0).count()); + const bool bIsLine(bIsTwoPointLine || bNoWidth || bNoHeight); + + if(!bIsLine) + { + // create fill + basegfx::B2DPolyPolygon aPath(rPath); + const bool bNeedToCheckClipRule(SVGTokenPath == mrOwner.getType() || SVGTokenPolygon == mrOwner.getType()); + const bool bClipPathIsNonzero(bNeedToCheckClipRule && mbIsClipPathContent && FillRule_nonzero == maClipRule); + const bool bFillRuleIsNonzero(bNeedToCheckClipRule && !mbIsClipPathContent && FillRule_nonzero == getFillRule()); + + if(bClipPathIsNonzero || bFillRuleIsNonzero) + { + if(getFill() || getSvgGradientNodeFill() || getSvgPatternNodeFill()) { + // nonzero is wanted, solve geometrically (see description on basegfx) + // basegfx::utils::createNonzeroConform() is expensive for huge paths + // and is only needed if path will be filled later on + aPath = basegfx::utils::createNonzeroConform(aPath); + } + } + + add_fill(aPath, rTarget, aGeoRange); + } + + // create stroke + add_stroke(rPath, rTarget, aGeoRange); + + // Svg supports markers for path, polygon, polyline and line + if(SVGTokenPath == mrOwner.getType() || // path + SVGTokenPolygon == mrOwner.getType() || // polygon, polyline + SVGTokenLine == mrOwner.getType()) // line + { + // try to add markers + add_markers(rPath, rTarget, pHelpPointIndices); + } + } + + void SvgStyleAttributes::add_postProcess( + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const drawinglayer::primitive2d::Primitive2DContainer& rSource, + const basegfx::B2DHomMatrix* pTransform) const + { + if(rSource.empty()) + return; + + const double fOpacity(getOpacity().solve(mrOwner)); + + if(basegfx::fTools::equalZero(fOpacity)) + { + return; + } + + drawinglayer::primitive2d::Primitive2DContainer aSource(rSource); + + if(basegfx::fTools::less(fOpacity, 1.0)) + { + // embed in UnifiedTransparencePrimitive2D + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::UnifiedTransparencePrimitive2D( + aSource, + 1.0 - fOpacity)); + + aSource = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + + if(pTransform) + { + // create embedding group element with transformation. This applies the given + // transformation to the graphical content, but *not* to mask and/or clip (as needed) + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + *pTransform, + aSource)); + + aSource = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + + const SvgClipPathNode* pClip = accessClipPathXLink(); + while(pClip) + { + // #i124852# transform may be needed when userSpaceOnUse + pClip->apply(aSource, pTransform); + pClip = pClip->getSvgStyleAttributes()->accessClipPathXLink(); + } + + if(!aSource.empty()) // test again, applied clipPath may have lead to empty geometry + { + const SvgMaskNode* pMask = accessMaskXLink(); + if(pMask) + { + // #i124852# transform may be needed when userSpaceOnUse + pMask->apply(aSource, pTransform); + } + } + + // This is part of the SVG import of self-written SVGs from + // Draw/Impress containing multiple Slides/Pages. To be able + // to later 'break' these to multiple Pages if wanted, embed + // each Page-Content in an identifiable Primitive Grouping + // Object. + // This is the case when the current Node is a GroupNode, has + // class="Page" set, has a parent that also is a GroupNode + // at which class="Slide" is set. + // Multiple Slides/Pages are possible for Draw and Impress. + if(SVGTokenG == mrOwner.getType() && mrOwner.getClass()) + { + const OUString aOwnerClass(*mrOwner.getClass()); + + if("Page" == aOwnerClass) + { + const SvgNode* pParent(mrOwner.getParent()); + + if(nullptr != pParent && SVGTokenG == pParent->getType() && pParent->getClass()) + { + const OUString aParentClass(*pParent->getClass()); + + if("Slide" == aParentClass) + { + // embed to grouping primitive to identify the + // Slide/Page information + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::PageHierarchyPrimitive2D( + aSource)); + + aSource = drawinglayer::primitive2d::Primitive2DContainer { xRef }; + } + } + } + } + + if(!aSource.empty()) // test again, applied mask may have lead to empty geometry + { + // append to current target + rTarget.append(aSource); + } + } + + SvgStyleAttributes::SvgStyleAttributes(SvgNode& rOwner) + : mrOwner(rOwner), + mpCssStyleParent(nullptr), + maFill(), + maStroke(), + maStopColor(basegfx::BColor(0.0, 0.0, 0.0), true), + maStrokeWidth(), + maStopOpacity(), + maFillOpacity(), + maStrokeDasharray(), + maStrokeDashOffset(), + maStrokeLinecap(StrokeLinecap_notset), + maStrokeLinejoin(StrokeLinejoin_notset), + maStrokeMiterLimit(), + maStrokeOpacity(), + maFontFamily(), + maFontSize(), + maFontSizeNumber(), + maFontStretch(FontStretch_notset), + maFontStyle(FontStyle_notset), + maFontWeight(FontWeight_notset), + maTextAlign(TextAlign_notset), + maTextDecoration(TextDecoration_notset), + maTextAnchor(TextAnchor_notset), + maColor(), + maOpacity(), + maVisibility(Visibility_notset), + maTitle(), + maDesc(), + maClipPathXLink(), + mpClipPathXLink(nullptr), + maMaskXLink(), + mpMaskXLink(nullptr), + maMarkerStartXLink(), + mpMarkerStartXLink(nullptr), + maMarkerMidXLink(), + mpMarkerMidXLink(nullptr), + maMarkerEndXLink(), + mpMarkerEndXLink(nullptr), + maFillRule(FillRule_notset), + maClipRule(FillRule_nonzero), + maBaselineShift(BaselineShift_Baseline), + maBaselineShiftNumber(0), + maResolvingParent(30, 0), + mbIsClipPathContent(SVGTokenClipPathNode == mrOwner.getType()), + mbStrokeDasharraySet(false) + { + const SvgStyleAttributes* pParentStyle = getParentStyle(); + if(!mbIsClipPathContent) + { + if(pParentStyle) + { + mbIsClipPathContent = pParentStyle->mbIsClipPathContent; + } + } + } + + SvgStyleAttributes::~SvgStyleAttributes() + { + } + + void SvgStyleAttributes::parseStyleAttribute( + SVGToken aSVGToken, + const OUString& aContent, + bool bCaseIndependent) + { + switch(aSVGToken) + { + case SVGTokenFill: + { + SvgPaint aSvgPaint; + OUString aURL; + SvgNumber aOpacity; + + if(readSvgPaint(aContent, aSvgPaint, aURL, bCaseIndependent, aOpacity)) + { + setFill(aSvgPaint); + if(aOpacity.isSet()) + { + setOpacity(SvgNumber(std::clamp(aOpacity.getNumber(), 0.0, 1.0))); + } + } + else if(!aURL.isEmpty()) + { + maNodeFillURL = aURL; + } + break; + } + case SVGTokenFillOpacity: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maFillOpacity = SvgNumber(std::clamp(aNum.getNumber(), 0.0, 1.0), aNum.getUnit(), aNum.isSet()); + } + break; + } + case SVGTokenFillRule: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrNonzero)) + { + maFillRule = FillRule_nonzero; + } + else if(aContent.match(commonStrings::aStrEvenOdd)) + { + maFillRule = FillRule_evenodd; + } + } + break; + } + case SVGTokenStroke: + { + SvgPaint aSvgPaint; + OUString aURL; + SvgNumber aOpacity; + + if(readSvgPaint(aContent, aSvgPaint, aURL, bCaseIndependent, aOpacity)) + { + maStroke = aSvgPaint; + if(aOpacity.isSet()) + { + setOpacity(SvgNumber(std::clamp(aOpacity.getNumber(), 0.0, 1.0))); + } + } + else if(!aURL.isEmpty()) + { + maNodeStrokeURL = aURL; + } + break; + } + case SVGTokenStrokeDasharray: + { + if(!aContent.isEmpty()) + { + SvgNumberVector aVector; + + if(aContent.startsWith("none")) + { + // #121221# The special value 'none' needs to be handled + // in the sense that *when* it is set, the parent shall not + // be used. Before this was only dependent on the array being + // empty + mbStrokeDasharraySet = true; + } + else if(readSvgNumberVector(aContent, aVector)) + { + maStrokeDasharray = aVector; + } + } + break; + } + case SVGTokenStrokeDashoffset: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maStrokeDashOffset = aNum; + } + } + break; + } + case SVGTokenStrokeLinecap: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("butt")) + { + setStrokeLinecap(StrokeLinecap_butt); + } + else if(aContent.startsWith("round")) + { + setStrokeLinecap(StrokeLinecap_round); + } + else if(aContent.startsWith("square")) + { + setStrokeLinecap(StrokeLinecap_square); + } + } + break; + } + case SVGTokenStrokeLinejoin: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("miter")) + { + setStrokeLinejoin(StrokeLinejoin_miter); + } + else if(aContent.startsWith("round")) + { + setStrokeLinejoin(StrokeLinejoin_round); + } + else if(aContent.startsWith("bevel")) + { + setStrokeLinejoin(StrokeLinejoin_bevel); + } + } + break; + } + case SVGTokenStrokeMiterlimit: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(basegfx::fTools::moreOrEqual(aNum.getNumber(), 1.0)) + { //readSingleNumber sets Unit_px as default, if unit is missing. Correct it here. + maStrokeMiterLimit = SvgNumber(aNum.getNumber(), Unit_none); + } + } + break; + } + case SVGTokenStrokeOpacity: + { + + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maStrokeOpacity = SvgNumber(std::clamp(aNum.getNumber(), 0.0, 1.0), aNum.getUnit(), aNum.isSet()); + } + break; + } + case SVGTokenStrokeWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maStrokeWidth = aNum; + } + } + break; + } + case SVGTokenStopColor: + { + SvgPaint aSvgPaint; + OUString aURL; + SvgNumber aOpacity; + + if(readSvgPaint(aContent, aSvgPaint, aURL, bCaseIndependent, aOpacity)) + { + maStopColor = aSvgPaint; + if(aOpacity.isSet()) + { + setOpacity(SvgNumber(std::clamp(aOpacity.getNumber(), 0.0, 1.0))); + } + } + break; + } + case SVGTokenStopOpacity: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maStopOpacity = aNum; + } + } + break; + } + case SVGTokenFont: + { + break; + } + case SVGTokenFontFamily: + { + SvgStringVector aSvgStringVector; + + if(readSvgStringVector(aContent, aSvgStringVector)) + { + maFontFamily = aSvgStringVector; + } + break; + } + case SVGTokenFontSize: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("xx-small")) + { + setFontSize(FontSize_xx_small); + } + else if(aContent.startsWith("x-small")) + { + setFontSize(FontSize_x_small); + } + else if(aContent.startsWith("small")) + { + setFontSize(FontSize_small); + } + else if(aContent.startsWith("smaller")) + { + setFontSize(FontSize_smaller); + } + else if(aContent.startsWith("medium")) + { + setFontSize(FontSize_medium); + } + else if(aContent.startsWith("larger")) + { + setFontSize(FontSize_larger); + } + else if(aContent.startsWith("large")) + { + setFontSize(FontSize_large); + } + else if(aContent.startsWith("x-large")) + { + setFontSize(FontSize_x_large); + } + else if(aContent.startsWith("xx-large")) + { + setFontSize(FontSize_xx_large); + } + else if(aContent.startsWith("initial")) + { + setFontSize(FontSize_initial); + } + else + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maFontSizeNumber = aNum; + } + } + } + break; + } + case SVGTokenFontSizeAdjust: + { + break; + } + case SVGTokenFontStretch: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("normal")) + { + setFontStretch(FontStretch_normal); + } + else if(aContent.startsWith("wider")) + { + setFontStretch(FontStretch_wider); + } + else if(aContent.startsWith("narrower")) + { + setFontStretch(FontStretch_narrower); + } + else if(aContent.startsWith("ultra-condensed")) + { + setFontStretch(FontStretch_ultra_condensed); + } + else if(aContent.startsWith("extra-condensed")) + { + setFontStretch(FontStretch_extra_condensed); + } + else if(aContent.startsWith("condensed")) + { + setFontStretch(FontStretch_condensed); + } + else if(aContent.startsWith("semi-condensed")) + { + setFontStretch(FontStretch_semi_condensed); + } + else if(aContent.startsWith("semi-expanded")) + { + setFontStretch(FontStretch_semi_expanded); + } + else if(aContent.startsWith("expanded")) + { + setFontStretch(FontStretch_expanded); + } + else if(aContent.startsWith("extra-expanded")) + { + setFontStretch(FontStretch_extra_expanded); + } + else if(aContent.startsWith("ultra-expanded")) + { + setFontStretch(FontStretch_ultra_expanded); + } + } + break; + } + case SVGTokenFontStyle: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("normal")) + { + setFontStyle(FontStyle_normal); + } + else if(aContent.startsWith("italic")) + { + setFontStyle(FontStyle_italic); + } + else if(aContent.startsWith("oblique")) + { + setFontStyle(FontStyle_oblique); + } + } + break; + } + case SVGTokenFontVariant: + { + break; + } + case SVGTokenFontWeight: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("100")) + { + setFontWeight(FontWeight_100); + } + else if(aContent.startsWith("200")) + { + setFontWeight(FontWeight_200); + } + else if(aContent.startsWith("300")) + { + setFontWeight(FontWeight_300); + } + else if(aContent.startsWith("400") || aContent.startsWith("normal")) + { + setFontWeight(FontWeight_400); + } + else if(aContent.startsWith("500")) + { + setFontWeight(FontWeight_500); + } + else if(aContent.startsWith("600")) + { + setFontWeight(FontWeight_600); + } + else if(aContent.startsWith("700") || aContent.startsWith("bold")) + { + setFontWeight(FontWeight_700); + } + else if(aContent.startsWith("800")) + { + setFontWeight(FontWeight_800); + } + else if(aContent.startsWith("900")) + { + setFontWeight(FontWeight_900); + } + else if(aContent.startsWith("bolder")) + { + setFontWeight(FontWeight_bolder); + } + else if(aContent.startsWith("lighter")) + { + setFontWeight(FontWeight_lighter); + } + } + break; + } + case SVGTokenDirection: + { + break; + } + case SVGTokenLetterSpacing: + { + break; + } + case SVGTokenTextDecoration: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("none")) + { + setTextDecoration(TextDecoration_none); + } + else if(aContent.startsWith("underline")) + { + setTextDecoration(TextDecoration_underline); + } + else if(aContent.startsWith("overline")) + { + setTextDecoration(TextDecoration_overline); + } + else if(aContent.startsWith("line-through")) + { + setTextDecoration(TextDecoration_line_through); + } + else if(aContent.startsWith("blink")) + { + setTextDecoration(TextDecoration_blink); + } + } + break; + } + case SVGTokenUnicodeBidi: + { + break; + } + case SVGTokenWordSpacing: + { + break; + } + case SVGTokenTextAnchor: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("start")) + { + setTextAnchor(TextAnchor_start); + } + else if(aContent.startsWith("middle")) + { + setTextAnchor(TextAnchor_middle); + } + else if(aContent.startsWith("end")) + { + setTextAnchor(TextAnchor_end); + } + } + break; + } + case SVGTokenTextAlign: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("left")) + { + setTextAlign(TextAlign_left); + } + else if(aContent.startsWith("right")) + { + setTextAlign(TextAlign_right); + } + else if(aContent.startsWith("center")) + { + setTextAlign(TextAlign_center); + } + else if(aContent.startsWith("justify")) + { + setTextAlign(TextAlign_justify); + } + } + break; + } + case SVGTokenColor: + { + SvgPaint aSvgPaint; + OUString aURL; + SvgNumber aOpacity; + + if(readSvgPaint(aContent, aSvgPaint, aURL, bCaseIndependent, aOpacity)) + { + maColor = aSvgPaint; + if(aOpacity.isSet()) + { + setOpacity(SvgNumber(std::clamp(aOpacity.getNumber(), 0.0, 1.0))); + } + } + break; + } + case SVGTokenOpacity: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + setOpacity(SvgNumber(std::clamp(aNum.getNumber(), 0.0, 1.0), aNum.getUnit(), aNum.isSet())); + } + break; + } + case SVGTokenVisibility: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("visible")) + { + setVisibility(Visibility_visible); + } + else if(aContent.startsWith("hidden")) + { + setVisibility(Visibility_hidden); + } + else if(aContent.startsWith("collapse")) + { + setVisibility(Visibility_collapse); + } + else if(aContent.startsWith("inherit")) + { + setVisibility(Visibility_inherit); + } + } + break; + } + case SVGTokenTitle: + { + maTitle = aContent; + break; + } + case SVGTokenDesc: + { + maDesc = aContent; + break; + } + case SVGTokenClipPathProperty: + { + readLocalUrl(aContent, maClipPathXLink); + break; + } + case SVGTokenMask: + { + readLocalUrl(aContent, maMaskXLink); + break; + } + case SVGTokenClipRule: + { + if(!aContent.isEmpty()) + { + if(aContent.match(commonStrings::aStrNonzero)) + { + maClipRule = FillRule_nonzero; + } + else if(aContent.match(commonStrings::aStrEvenOdd)) + { + maClipRule = FillRule_evenodd; + } + } + break; + } + case SVGTokenMarker: + { + if(bCaseIndependent) + { + readLocalUrl(aContent, maMarkerEndXLink); + maMarkerStartXLink = maMarkerMidXLink = maMarkerEndXLink; + } + break; + } + case SVGTokenMarkerStart: + { + readLocalUrl(aContent, maMarkerStartXLink); + break; + } + case SVGTokenMarkerMid: + { + readLocalUrl(aContent, maMarkerMidXLink); + break; + } + case SVGTokenMarkerEnd: + { + readLocalUrl(aContent, maMarkerEndXLink); + break; + } + case SVGTokenDisplay: + { + // There may be display:none statements inside of style defines, e.g. the following line: + // style="display:none" + // taken from a svg example; this needs to be parsed and set at the owning node. Do not call + // mrOwner.parseAttribute(...) here, this would lead to a recursion + if(!aContent.isEmpty()) + { + mrOwner.setDisplay(getDisplayFromContent(aContent)); + } + break; + } + case SVGTokenBaselineShift: + { + if(!aContent.isEmpty()) + { + SvgNumber aNum; + + if(aContent.startsWith("sub")) + { + setBaselineShift(BaselineShift_Sub); + } + else if(aContent.startsWith("super")) + { + setBaselineShift(BaselineShift_Super); + } + else if(readSingleNumber(aContent, aNum)) + { + maBaselineShiftNumber = aNum; + + if(Unit_percent == aNum.getUnit()) + { + setBaselineShift(BaselineShift_Percentage); + } + else + { + setBaselineShift(BaselineShift_Length); + } + } + else + { + // no BaselineShift or inherit (which is automatically) + setBaselineShift(BaselineShift_Baseline); + } + } + break; + } + default: + { + break; + } + } + } + + // #i125258# ask if fill is a direct hard attribute (no hierarchy) + bool SvgStyleAttributes::isFillSet() const + { + if(mbIsClipPathContent) + { + return false; + } + else if(maFill.isSet()) + { + return true; + } + + return false; + } + + const basegfx::BColor* SvgStyleAttributes::getCurrentColor() const + { + static basegfx::BColor aBlack(0.0, 0.0, 0.0); + const basegfx::BColor *aColor = getColor(); + if( aColor ) + return aColor; + else + return &aBlack; + } + + const basegfx::BColor* SvgStyleAttributes::getFill() const + { + if(maFill.isSet()) + { + if(maFill.isCurrent()) + { + return getCurrentColor(); + } + else if(maFill.isOn()) + { + return &maFill.getBColor(); + } + else if(mbIsClipPathContent) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[0] < nStyleDepthLimit) + { + ++maResolvingParent[0]; + const basegfx::BColor* pFill = pSvgStyleAttributes->getFill(); + --maResolvingParent[0]; + + return pFill; + } + } + } + else if (maNodeFillURL.isEmpty()) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[0] < nStyleDepthLimit) + { + ++maResolvingParent[0]; + const basegfx::BColor* pFill = pSvgStyleAttributes->getFill(); + --maResolvingParent[0]; + + if(mbIsClipPathContent) + { + if (pFill) + { + return pFill; + } + else + { + static basegfx::BColor aBlack(0.0, 0.0, 0.0); + return &aBlack; + } + } + else + { + return pFill; + } + } + } + + return nullptr; + } + + const basegfx::BColor* SvgStyleAttributes::getStroke() const + { + if(maStroke.isSet()) + { + if(maStroke.isCurrent()) + { + return getCurrentColor(); + } + else if(maStroke.isOn()) + { + return &maStroke.getBColor(); + } + } + else if (maNodeStrokeURL.isEmpty()) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[1] < nStyleDepthLimit) + { + ++maResolvingParent[1]; + auto ret = pSvgStyleAttributes->getStroke(); + --maResolvingParent[1]; + return ret; + } + } + + return nullptr; + } + + const basegfx::BColor& SvgStyleAttributes::getStopColor() const + { + if(maStopColor.isCurrent()) + { + return *getCurrentColor(); + } + else + { + return maStopColor.getBColor(); + } + } + + const SvgGradientNode* SvgStyleAttributes::getSvgGradientNodeFill() const + { + if (!maFill.isSet()) + { + if (!maNodeFillURL.isEmpty()) + { + const SvgNode* pNode = mrOwner.getDocument().findSvgNodeById(maNodeFillURL); + + if(pNode) + { + if(SVGTokenLinearGradient == pNode->getType() || SVGTokenRadialGradient == pNode->getType()) + { + return static_cast< const SvgGradientNode* >(pNode); + } + } + } + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[2] < nStyleDepthLimit) + { + ++maResolvingParent[2]; + auto ret = pSvgStyleAttributes->getSvgGradientNodeFill(); + --maResolvingParent[2]; + return ret; + } + } + + return nullptr; + } + + const SvgGradientNode* SvgStyleAttributes::getSvgGradientNodeStroke() const + { + if (!maStroke.isSet()) + { + if(!maNodeStrokeURL.isEmpty()) + { + const SvgNode* pNode = mrOwner.getDocument().findSvgNodeById(maNodeStrokeURL); + + if(pNode) + { + if(SVGTokenLinearGradient == pNode->getType() || SVGTokenRadialGradient == pNode->getType()) + { + return static_cast< const SvgGradientNode* >(pNode); + } + } + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[3] < nStyleDepthLimit) + { + ++maResolvingParent[3]; + auto ret = pSvgStyleAttributes->getSvgGradientNodeStroke(); + --maResolvingParent[3]; + return ret; + } + } + + return nullptr; + } + + const SvgPatternNode* SvgStyleAttributes::getSvgPatternNodeFill() const + { + if (!maFill.isSet()) + { + if (!maNodeFillURL.isEmpty()) + { + const SvgNode* pNode = mrOwner.getDocument().findSvgNodeById(maNodeFillURL); + + if(pNode) + { + if(SVGTokenPattern == pNode->getType()) + { + return static_cast< const SvgPatternNode* >(pNode); + } + } + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[4] < nStyleDepthLimit) + { + ++maResolvingParent[4]; + auto ret = pSvgStyleAttributes->getSvgPatternNodeFill(); + --maResolvingParent[4]; + return ret; + } + } + + return nullptr; + } + + const SvgPatternNode* SvgStyleAttributes::getSvgPatternNodeStroke() const + { + if (!maStroke.isSet()) + { + if(!maNodeStrokeURL.isEmpty()) + { + const SvgNode* pNode = mrOwner.getDocument().findSvgNodeById(maNodeStrokeURL); + + if(pNode) + { + if(SVGTokenPattern == pNode->getType()) + { + return static_cast< const SvgPatternNode* >(pNode); + } + } + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[5] < nStyleDepthLimit) + { + ++maResolvingParent[5]; + auto ret = pSvgStyleAttributes->getSvgPatternNodeStroke(); + --maResolvingParent[5]; + return ret; + } + } + + return nullptr; + } + + SvgNumber SvgStyleAttributes::getStrokeWidth() const + { + if(maStrokeWidth.isSet()) + { + return maStrokeWidth; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[6] < nStyleDepthLimit) + { + ++maResolvingParent[6]; + auto ret = pSvgStyleAttributes->getStrokeWidth(); + --maResolvingParent[6]; + return ret; + } + + if(mbIsClipPathContent) + { + return SvgNumber(0.0); + } + + // default is 1 + return SvgNumber(1.0); + } + + SvgNumber SvgStyleAttributes::getStopOpacity() const + { + if(maStopOpacity.isSet()) + { + return maStopOpacity; + } + + // default is 1 + return SvgNumber(1.0); + } + + SvgNumber SvgStyleAttributes::getFillOpacity() const + { + if(maFillOpacity.isSet()) + { + return maFillOpacity; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[7] < nStyleDepthLimit) + { + ++maResolvingParent[7]; + auto ret = pSvgStyleAttributes->getFillOpacity(); + --maResolvingParent[7]; + return ret; + } + + // default is 1 + return SvgNumber(1.0); + } + + SvgNumber SvgStyleAttributes::getOpacity() const + { + if(maOpacity.isSet()) + { + return maOpacity; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[8] < nStyleDepthLimit) + { + ++maResolvingParent[8]; + auto ret = pSvgStyleAttributes->getOpacity(); + --maResolvingParent[8]; + return ret; + } + + // default is 1 + return SvgNumber(1.0); + } + + Visibility SvgStyleAttributes::getVisibility() const + { + if(Visibility_notset == maVisibility || Visibility_inherit == maVisibility) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[9] < nStyleDepthLimit) + { + ++maResolvingParent[9]; + auto ret = pSvgStyleAttributes->getVisibility(); + --maResolvingParent[9]; + return ret; + } + //default is Visible + return Visibility_visible; + } + + // Visibility correction/exception for self-exported SVGs: + // When Impress exports single or multi-page SVGs, it puts the + // single slides into <g visibility="hidden">. Not sure why + // this happens, but this leads (correctly) to empty imported + // Graphics. + // Thus, if Visibility_hidden is active and owner is a SVGTokenG + // and it's parent is also a SVGTokenG and it has a Class 'SlideGroup' + // set, check if we are an Impress export. + // We are an Impress export if an SVG-Node titled 'ooo:meta_slides' + // exists. + // All together gives: + if(Visibility_hidden == maVisibility + && SVGTokenG == mrOwner.getType() + && nullptr != mrOwner.getDocument().findSvgNodeById("ooo:meta_slides")) + { + const SvgNode* pParent(mrOwner.getParent()); + + if(nullptr != pParent && SVGTokenG == pParent->getType() && pParent->getClass()) + { + const OUString aClass(*pParent->getClass()); + + if("SlideGroup" == aClass) + { + // if we detect this exception, + // override Visibility_hidden -> Visibility_visible + return Visibility_visible; + } + } + } + + return maVisibility; + } + + FillRule SvgStyleAttributes::getFillRule() const + { + if(FillRule_notset != maFillRule) + { + return maFillRule; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[10] < nStyleDepthLimit) + { + ++maResolvingParent[10]; + auto ret = pSvgStyleAttributes->getFillRule(); + --maResolvingParent[10]; + return ret; + } + + // default is NonZero + return FillRule_nonzero; + } + + const SvgNumberVector& SvgStyleAttributes::getStrokeDasharray() const + { + if(!maStrokeDasharray.empty()) + { + return maStrokeDasharray; + } + else if(mbStrokeDasharraySet) + { + // #121221# is set to empty *by purpose*, do not visit parent styles + return maStrokeDasharray; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[11] < nStyleDepthLimit) + { + ++maResolvingParent[11]; + const SvgNumberVector& ret = pSvgStyleAttributes->getStrokeDasharray(); + --maResolvingParent[11]; + return ret; + } + + // default empty + return maStrokeDasharray; + } + + SvgNumber SvgStyleAttributes::getStrokeDashOffset() const + { + if(maStrokeDashOffset.isSet()) + { + return maStrokeDashOffset; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[12] < nStyleDepthLimit) + { + ++maResolvingParent[12]; + auto ret = pSvgStyleAttributes->getStrokeDashOffset(); + --maResolvingParent[12]; + return ret; + } + + // default is 0 + return SvgNumber(0.0); + } + + StrokeLinecap SvgStyleAttributes::getStrokeLinecap() const + { + if(maStrokeLinecap != StrokeLinecap_notset) + { + return maStrokeLinecap; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[13] < nStyleDepthLimit) + { + ++maResolvingParent[13]; + auto ret = pSvgStyleAttributes->getStrokeLinecap(); + --maResolvingParent[13]; + return ret; + } + + // default is StrokeLinecap_butt + return StrokeLinecap_butt; + } + + StrokeLinejoin SvgStyleAttributes::getStrokeLinejoin() const + { + if(maStrokeLinejoin != StrokeLinejoin_notset) + { + return maStrokeLinejoin; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[14] < nStyleDepthLimit) + { + ++maResolvingParent[14]; + auto ret = pSvgStyleAttributes->getStrokeLinejoin(); + --maResolvingParent[14]; + return ret; + } + + // default is StrokeLinejoin_butt + return StrokeLinejoin_miter; + } + + SvgNumber SvgStyleAttributes::getStrokeMiterLimit() const + { + if(maStrokeMiterLimit.isSet()) + { + return maStrokeMiterLimit; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[15] < nStyleDepthLimit) + { + ++maResolvingParent[15]; + auto ret = pSvgStyleAttributes->getStrokeMiterLimit(); + --maResolvingParent[15]; + return ret; + } + + // default is 4 + return SvgNumber(4.0, Unit_none); + } + + SvgNumber SvgStyleAttributes::getStrokeOpacity() const + { + if(maStrokeOpacity.isSet()) + { + return maStrokeOpacity; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[16] < nStyleDepthLimit) + { + ++maResolvingParent[16]; + auto ret = pSvgStyleAttributes->getStrokeOpacity(); + --maResolvingParent[16]; + return ret; + } + + // default is 1 + return SvgNumber(1.0); + } + + const SvgStringVector& SvgStyleAttributes::getFontFamily() const + { + if(!maFontFamily.empty() && !maFontFamily[0].startsWith("inherit")) + { + return maFontFamily; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[17] < nStyleDepthLimit) + { + ++maResolvingParent[17]; + const SvgStringVector& ret = pSvgStyleAttributes->getFontFamily(); + --maResolvingParent[17]; + return ret; + } + + // default is empty + return maFontFamily; + } + + SvgNumber SvgStyleAttributes::getFontSizeNumber() const + { + // default size is 'medium' or 16px, which is equal to the default PPI used in svgio ( 96.0 ) + // converted to pixels + const double aDefaultSize = F_SVG_PIXEL_PER_INCH / 6.0; + + if(maFontSizeNumber.isSet()) + { + if(!maFontSizeNumber.isPositive()) + return aDefaultSize; + + // #122524# Handle Unit_percent relative to parent FontSize (see SVG1.1 + // spec 10.10 Font selection properties \91font-size\92, lastline (click 'normative + // definition of the property') + if(Unit_percent == maFontSizeNumber.getUnit()) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if(pSvgStyleAttributes) + { + const SvgNumber aParentNumber = pSvgStyleAttributes->getFontSizeNumber(); + + return SvgNumber( + aParentNumber.getNumber() * maFontSizeNumber.getNumber() * 0.01, + aParentNumber.getUnit(), + true); + } + // if there's no parent style, set the font size based on the default size + // 100% = 16px + return SvgNumber( + maFontSizeNumber.getNumber() * aDefaultSize / 100.0, Unit_px, true); + } + else if((Unit_em == maFontSizeNumber.getUnit()) || (Unit_ex == maFontSizeNumber.getUnit())) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if(pSvgStyleAttributes) + { + const SvgNumber aParentNumber = pSvgStyleAttributes->getFontSizeNumber(); + + return SvgNumber( + aParentNumber.getNumber() * maFontSizeNumber.getNumber(), + aParentNumber.getUnit(), + true); + } + } + + return maFontSizeNumber; + } + + //In CSS2, the suggested scaling factor between adjacent indexes is 1.2 + switch(maFontSize) + { + case FontSize_notset: + break; + case FontSize_xx_small: + { + return SvgNumber(aDefaultSize / 1.728); + } + case FontSize_x_small: + { + return SvgNumber(aDefaultSize / 1.44); + } + case FontSize_small: + { + return SvgNumber(aDefaultSize / 1.2); + } + case FontSize_smaller: + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + if(pSvgStyleAttributes) + { + const SvgNumber aParentNumber = pSvgStyleAttributes->getFontSizeNumber(); + return SvgNumber(aParentNumber.getNumber() / 1.2, aParentNumber.getUnit()); + } + [[fallthrough]]; + } + case FontSize_medium: + case FontSize_initial: + { + return SvgNumber(aDefaultSize); + } + case FontSize_large: + { + return SvgNumber(aDefaultSize * 1.2); + } + case FontSize_larger: + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + if(pSvgStyleAttributes) + { + const SvgNumber aParentNumber = pSvgStyleAttributes->getFontSizeNumber(); + return SvgNumber(aParentNumber.getNumber() * 1.2, aParentNumber.getUnit()); + } + [[fallthrough]]; + } + case FontSize_x_large: + { + return SvgNumber(aDefaultSize * 1.44); + } + case FontSize_xx_large: + { + return SvgNumber(aDefaultSize * 1.728); + } + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if(pSvgStyleAttributes) + { + return pSvgStyleAttributes->getFontSizeNumber(); + } + + return SvgNumber(aDefaultSize); + } + + FontStretch SvgStyleAttributes::getFontStretch() const + { + if(maFontStretch != FontStretch_notset) + { + if(FontStretch_wider != maFontStretch && FontStretch_narrower != maFontStretch) + { + return maFontStretch; + } + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[18] < nStyleDepthLimit) + { + ++maResolvingParent[18]; + FontStretch aInherited = pSvgStyleAttributes->getFontStretch(); + --maResolvingParent[18]; + + if(FontStretch_wider == maFontStretch) + { + aInherited = getWider(aInherited); + } + else if(FontStretch_narrower == maFontStretch) + { + aInherited = getNarrower(aInherited); + } + + return aInherited; + } + + // default is FontStretch_normal + return FontStretch_normal; + } + + FontStyle SvgStyleAttributes::getFontStyle() const + { + if(maFontStyle != FontStyle_notset) + { + return maFontStyle; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[19] < nStyleDepthLimit) + { + ++maResolvingParent[19]; + auto ret = pSvgStyleAttributes->getFontStyle(); + --maResolvingParent[19]; + return ret; + } + + // default is FontStyle_normal + return FontStyle_normal; + } + + FontWeight SvgStyleAttributes::getFontWeight() const + { + if(maFontWeight != FontWeight_notset) + { + if(FontWeight_bolder != maFontWeight && FontWeight_lighter != maFontWeight) + { + return maFontWeight; + } + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[20] < nStyleDepthLimit) + { + ++maResolvingParent[20]; + FontWeight aInherited = pSvgStyleAttributes->getFontWeight(); + --maResolvingParent[20]; + + if(FontWeight_bolder == maFontWeight) + { + aInherited = getBolder(aInherited); + } + else if(FontWeight_lighter == maFontWeight) + { + aInherited = getLighter(aInherited); + } + + return aInherited; + } + + // default is FontWeight_400 (FontWeight_normal) + return FontWeight_400; + } + + TextAlign SvgStyleAttributes::getTextAlign() const + { + if(maTextAlign != TextAlign_notset) + { + return maTextAlign; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[21] < nStyleDepthLimit) + { + ++maResolvingParent[21]; + auto ret = pSvgStyleAttributes->getTextAlign(); + --maResolvingParent[21]; + return ret; + } + + // default is TextAlign_left + return TextAlign_left; + } + + const SvgStyleAttributes* SvgStyleAttributes::getTextDecorationDefiningSvgStyleAttributes() const + { + if(maTextDecoration != TextDecoration_notset) + { + return this; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[22] < nStyleDepthLimit) + { + ++maResolvingParent[22]; + auto ret = pSvgStyleAttributes->getTextDecorationDefiningSvgStyleAttributes(); + --maResolvingParent[22]; + return ret; + } + + // default is 0 + return nullptr; + } + + TextDecoration SvgStyleAttributes::getTextDecoration() const + { + const SvgStyleAttributes* pDefining = getTextDecorationDefiningSvgStyleAttributes(); + + if(pDefining) + { + return pDefining->maTextDecoration; + } + else + { + // default is TextDecoration_none + return TextDecoration_none; + } + } + + TextAnchor SvgStyleAttributes::getTextAnchor() const + { + if(maTextAnchor != TextAnchor_notset) + { + return maTextAnchor; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[23] < nStyleDepthLimit) + { + ++maResolvingParent[23]; + auto ret = pSvgStyleAttributes->getTextAnchor(); + --maResolvingParent[23]; + return ret; + } + + // default is TextAnchor_start + return TextAnchor_start; + } + + const basegfx::BColor* SvgStyleAttributes::getColor() const + { + if(maColor.isSet()) + { + if(maColor.isCurrent()) + { + OSL_ENSURE(false, "Svg error: current color uses current color (!)"); + return nullptr; + } + else if(maColor.isOn()) + { + return &maColor.getBColor(); + } + } + else + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[24] < nStyleDepthLimit) + { + ++maResolvingParent[24]; + auto ret = pSvgStyleAttributes->getColor(); + --maResolvingParent[24]; + return ret; + } + } + + return nullptr; + } + + OUString const & SvgStyleAttributes::getClipPathXLink() const + { + return maClipPathXLink; + } + + const SvgClipPathNode* SvgStyleAttributes::accessClipPathXLink() const + { + if(!mpClipPathXLink) + { + const OUString aClipPath(getClipPathXLink()); + + if(!aClipPath.isEmpty()) + { + const_cast< SvgStyleAttributes* >(this)->mpClipPathXLink = dynamic_cast< const SvgClipPathNode* >(mrOwner.getDocument().findSvgNodeById(aClipPath)); + } + } + + return mpClipPathXLink; + } + + OUString SvgStyleAttributes::getMaskXLink() const + { + if(!maMaskXLink.isEmpty()) + { + return maMaskXLink; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && !pSvgStyleAttributes->maMaskXLink.isEmpty() && maResolvingParent[25] < nStyleDepthLimit) + { + ++maResolvingParent[25]; + auto ret = pSvgStyleAttributes->getMaskXLink(); + --maResolvingParent[25]; + return ret; + } + + return OUString(); + } + + const SvgMaskNode* SvgStyleAttributes::accessMaskXLink() const + { + if(!mpMaskXLink) + { + const OUString aMask(getMaskXLink()); + + if(!aMask.isEmpty()) + { + const_cast< SvgStyleAttributes* >(this)->mpMaskXLink = dynamic_cast< const SvgMaskNode* >(mrOwner.getDocument().findSvgNodeById(aMask)); + } + } + + return mpMaskXLink; + } + + OUString SvgStyleAttributes::getMarkerStartXLink() const + { + if(!maMarkerStartXLink.isEmpty()) + { + return maMarkerStartXLink; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[26] < nStyleDepthLimit) + { + ++maResolvingParent[26]; + auto ret = pSvgStyleAttributes->getMarkerStartXLink(); + --maResolvingParent[26]; + return ret; + } + + return OUString(); + } + + const SvgMarkerNode* SvgStyleAttributes::accessMarkerStartXLink() const + { + if(!mpMarkerStartXLink) + { + const OUString aMarker(getMarkerStartXLink()); + + if(!aMarker.isEmpty()) + { + const_cast< SvgStyleAttributes* >(this)->mpMarkerStartXLink = dynamic_cast< const SvgMarkerNode* >(mrOwner.getDocument().findSvgNodeById(getMarkerStartXLink())); + } + } + + return mpMarkerStartXLink; + } + + OUString SvgStyleAttributes::getMarkerMidXLink() const + { + if(!maMarkerMidXLink.isEmpty()) + { + return maMarkerMidXLink; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[27] < nStyleDepthLimit) + { + ++maResolvingParent[27]; + auto ret = pSvgStyleAttributes->getMarkerMidXLink(); + --maResolvingParent[27]; + return ret; + } + + return OUString(); + } + + const SvgMarkerNode* SvgStyleAttributes::accessMarkerMidXLink() const + { + if(!mpMarkerMidXLink) + { + const OUString aMarker(getMarkerMidXLink()); + + if(!aMarker.isEmpty()) + { + const_cast< SvgStyleAttributes* >(this)->mpMarkerMidXLink = dynamic_cast< const SvgMarkerNode* >(mrOwner.getDocument().findSvgNodeById(getMarkerMidXLink())); + } + } + + return mpMarkerMidXLink; + } + + OUString SvgStyleAttributes::getMarkerEndXLink() const + { + if(!maMarkerEndXLink.isEmpty()) + { + return maMarkerEndXLink; + } + + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[28] < nStyleDepthLimit) + { + ++maResolvingParent[28]; + auto ret = pSvgStyleAttributes->getMarkerEndXLink(); + --maResolvingParent[28]; + return ret; + } + + return OUString(); + } + + const SvgMarkerNode* SvgStyleAttributes::accessMarkerEndXLink() const + { + if(!mpMarkerEndXLink) + { + const OUString aMarker(getMarkerEndXLink()); + + if(!aMarker.isEmpty()) + { + const_cast< SvgStyleAttributes* >(this)->mpMarkerEndXLink = dynamic_cast< const SvgMarkerNode* >(mrOwner.getDocument().findSvgNodeById(getMarkerEndXLink())); + } + } + + return mpMarkerEndXLink; + } + + SvgNumber SvgStyleAttributes::getBaselineShiftNumber() const + { + // #122524# Handle Unit_percent relative to parent BaselineShift + if(Unit_percent == maBaselineShiftNumber.getUnit()) + { + const SvgStyleAttributes* pSvgStyleAttributes = getParentStyle(); + + if (pSvgStyleAttributes && maResolvingParent[29] < nStyleDepthLimit) + { + ++maResolvingParent[29]; + const SvgNumber aParentNumber = pSvgStyleAttributes->getBaselineShiftNumber(); + --maResolvingParent[29]; + + return SvgNumber( + aParentNumber.getNumber() * maBaselineShiftNumber.getNumber() * 0.01, + aParentNumber.getUnit(), + true); + } + } + + return maBaselineShiftNumber; + } +} // end of namespace svgio + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ + diff --git a/svgio/source/svgreader/svgstylenode.cxx b/svgio/source/svgreader/svgstylenode.cxx new file mode 100644 index 000000000..995fa2919 --- /dev/null +++ b/svgio/source/svgreader/svgstylenode.cxx @@ -0,0 +1,229 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgstylenode.hxx> +#include <svgdocument.hxx> + +namespace svgio::svgreader +{ + SvgStyleNode::SvgStyleNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenStyle, rDocument, pParent), + maSvgStyleAttributes(), + mbTextCss(false) + { + } + + SvgStyleNode::~SvgStyleNode() + { + while(!maSvgStyleAttributes.empty()) + { + delete *(maSvgStyleAttributes.end() - 1); + maSvgStyleAttributes.pop_back(); + } + } + + // #i125258# no parent when we are a CssStyle holder to break potential loops because + // when using CssStyles we jump uncontrolled inside the node tree hierarchy + bool SvgStyleNode::supportsParentStyle() const + { + if(isTextCss()) + { + return false; + } + + // call parent + return SvgNode::supportsParentStyle(); + } + + void SvgStyleNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // parse own + switch(aSVGToken) + { + case SVGTokenType: + { + if(!aContent.isEmpty()) + { + if(aContent.startsWith("text/css")) + { + setTextCss(true); + } + } + break; + } + default: + { + break; + } + } + } + + void SvgStyleNode::addCssStyleSheet(const OUString& aSelectors, const SvgStyleAttributes& rNewStyle) + { + // aSelectors: CssStyle selectors, any combination, no comma separations, no spaces at start/end + // rNewStyle: the already prepared style to register on that name + if(aSelectors.isEmpty()) + return; + + std::vector< OUString > aSelectorParts; + const sal_Int32 nLen(aSelectors.getLength()); + sal_Int32 nPos(0); + OUStringBuffer aToken; + + // split into single tokens (currently only space separator) + while(nPos < nLen) + { + const sal_Int32 nInitPos(nPos); + copyToLimiter(aSelectors, u' ', nPos, aToken, nLen); + skip_char(aSelectors, u' ', nPos, nLen); + const OUString aSelectorPart(aToken.makeStringAndClear().trim()); + + if(!aSelectorPart.isEmpty()) + { + aSelectorParts.push_back(aSelectorPart); + } + + if(nInitPos == nPos) + { + OSL_ENSURE(false, "Could not interpret on current position (!)"); + nPos++; + } + } + + if(aSelectorParts.empty()) + return; + + OUStringBuffer aConcatenatedSelector; + + // re-combine without spaces, create a unique name (for now) + for(size_t a(0); a < aSelectorParts.size(); a++) + { + aConcatenatedSelector.append(aSelectorParts[a]); + } + + // CssStyles in SVG are currently not completely supported; the current idea for + // supporting the needed minimal set is to register CssStyles associated to a string + // which is just the space-char cleaned, concatenated Selectors. The part to 'match' + // these is in fillCssStyleVectorUsingHierarchyAndSelectors. There, the same string is + // built up using the priorities of local CssStyle, Id, Class and other info combined + // with the existing hierarchy. This creates a specificity and priority-sorted local + // list for each node which is then chained using get/setCssStyleParent. + // The current solution is capable of solving space-separated selectors which can be + // mixed between Id, Class and type specifiers. + // When CssStyles need more specific solving, the start point is here; remember the + // needed infos not in maIdStyleTokenMapperList at the document, but select evtl. + // more specific infos there in a class capable of handling more complex matchings. + // Additionally fillCssStyleVector (or the mechanism above that when a linked list of + // SvgStyleAttributes will not do it) will have to be adapted to make use of it. + + // register new style at document for (evtl. concatenated) stylename + const_cast< SvgDocument& >(getDocument()).addSvgStyleAttributesToMapper(aConcatenatedSelector.makeStringAndClear(), rNewStyle); + } + + void SvgStyleNode::addCssStyleSheet(const OUString& aSelectors, const OUString& aContent) + { + // aSelectors: possible comma-separated list of CssStyle definitions, no spaces at start/end + // aContent: the svg style definitions as string + if(aSelectors.isEmpty() || aContent.isEmpty()) + return; + + // create new style and add to local list (for ownership control) + SvgStyleAttributes* pNewStyle = new SvgStyleAttributes(*this); + maSvgStyleAttributes.push_back(pNewStyle); + + // fill with content + pNewStyle->readCssStyle(aContent); + + // comma-separated split (Css abbreviation for same style for multiple selectors) + const sal_Int32 nLen(aSelectors.getLength()); + sal_Int32 nPos(0); + OUStringBuffer aToken; + + while(nPos < nLen) + { + const sal_Int32 nInitPos(nPos); + copyToLimiter(aSelectors, u',', nPos, aToken, nLen); + skip_char(aSelectors, u' ', u',', nPos, nLen); + + const OUString aSingleName(aToken.makeStringAndClear().trim()); + + if(aSingleName.getLength()) + { + addCssStyleSheet(aSingleName, *pNewStyle); + } + + if(nInitPos == nPos) + { + OSL_ENSURE(false, "Could not interpret on current position (!)"); + nPos++; + } + } + } + + void SvgStyleNode::addCssStyleSheet(const OUString& aSelectorsAndContent) + { + const sal_Int32 nLen(aSelectorsAndContent.getLength()); + + if(!nLen) + return; + + sal_Int32 nPos(0); + OUStringBuffer aToken; + + while(nPos < nLen) + { + // read the full selectors (may be multiple, comma-separated) + const sal_Int32 nInitPos(nPos); + skip_char(aSelectorsAndContent, u' ', nPos, nLen); + copyToLimiter(aSelectorsAndContent, u'{', nPos, aToken, nLen); + skip_char(aSelectorsAndContent, u' ', u'{', nPos, nLen); + + const OUString aSelectors(aToken.makeStringAndClear().trim()); + OUString aContent; + + if(!aSelectors.isEmpty() && nPos < nLen) + { + // isolate content as text, embraced by '{' and '}' + copyToLimiter(aSelectorsAndContent, u'}', nPos, aToken, nLen); + skip_char(aSelectorsAndContent, u' ', u'}', nPos, nLen); + + aContent = aToken.makeStringAndClear().trim(); + } + + if(!aSelectors.isEmpty() && !aContent.isEmpty()) + { + addCssStyleSheet(aSelectors, aContent); + } + + if(nInitPos == nPos) + { + OSL_ENSURE(false, "Could not interpret on current position (!)"); + nPos++; + } + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgsvgnode.cxx b/svgio/source/svgreader/svgsvgnode.cxx new file mode 100644 index 000000000..d462e8001 --- /dev/null +++ b/svgio/source/svgreader/svgsvgnode.cxx @@ -0,0 +1,832 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgsvgnode.hxx> +#include <drawinglayer/geometry/viewinformation2d.hxx> +#include <drawinglayer/primitive2d/transformprimitive2d.hxx> +#include <drawinglayer/primitive2d/maskprimitive2d.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/matrix/b2dhommatrixtools.hxx> +#include <drawinglayer/primitive2d/polygonprimitive2d.hxx> +#include <drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx> +#include <svgdocument.hxx> + +namespace svgio::svgreader +{ + SvgSvgNode::SvgSvgNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenSvg, rDocument, pParent), + maSvgStyleAttributes(*this), + maSvgAspectRatio(), + maX(), + maY(), + maWidth(), + maHeight(), + maVersion(), + mbStyleAttributesInitialized(false) // #i125258# + { + } + + // #i125258# + void SvgSvgNode::initializeStyleAttributes() + { + if(mbStyleAttributesInitialized) + return; + + // #i125258# determine if initial values need to be initialized with hard values + // for the case that this is the outmost SVG statement and it has no parent + // stale (CssStyle for svg may be defined) + bool bSetInitialValues(true); + + if(getParent()) + { + // #i125258# no initial values when it's a SVG element embedded in SVG + bSetInitialValues = false; + } + + if(bSetInitialValues) + { + const SvgStyleAttributes* pStyles = getSvgStyleAttributes(); + + if(pStyles && pStyles->getParentStyle()) + { + // SVG has a parent style (probably CssStyle), check if fill is set there anywhere + // already. If yes, do not set the default fill (black) + bool bFillSet(false); + const SvgStyleAttributes* pParentStyle = pStyles->getParentStyle(); + + while(pParentStyle && !bFillSet) + { + bFillSet = pParentStyle->isFillSet(); + pParentStyle = pParentStyle->getParentStyle(); + } + + if(bFillSet) + { + // #125258# no initial values when SVG has a parent style at which a fill + // is already set + bSetInitialValues = false; + } + } + } + + if(bSetInitialValues) + { + // #i125258# only set if not yet initialized (SvgSvgNode::parseAttribute is already done, + // just setting may revert an already set valid value) + if(!maSvgStyleAttributes.isFillSet()) + { + // #i125258# initial fill is black (see SVG1.1 spec) + maSvgStyleAttributes.setFill(SvgPaint(basegfx::BColor(0.0, 0.0, 0.0), true, true)); + } + } + + mbStyleAttributesInitialized = true; + } + + SvgSvgNode::~SvgSvgNode() + { + } + + const SvgStyleAttributes* SvgSvgNode::getSvgStyleAttributes() const + { + // #i125258# svg node can have CssStyles, too, so check for it here + return checkForCssStyle("svg", maSvgStyleAttributes); + } + + void SvgSvgNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenViewBox: + { + const basegfx::B2DRange aRange(readViewBox(aContent, *this)); + + if(!aRange.isEmpty()) + { + setViewBox(&aRange); + } + break; + } + case SVGTokenPreserveAspectRatio: + { + maSvgAspectRatio = readSvgAspectRatio(aContent); + break; + } + case SVGTokenX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX = aNum; + } + break; + } + case SVGTokenY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY = aNum; + } + break; + } + case SVGTokenWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maWidth = aNum; + } + } + break; + } + case SVGTokenHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maHeight = aNum; + } + } + break; + } + case SVGTokenVersion: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maVersion = aNum; + } + break; + } + default: + { + break; + } + } + } + + void SvgSvgNode::seekReferenceWidth(double& fWidth, bool& bHasFound) const + { + if (!getParent() || bHasFound) + { + return; + } + const SvgSvgNode* pParentSvgSvgNode = nullptr; + // enclosing svg might have relative width, need to cumulate them till they are + // resolved somewhere up in the node tree + double fPercentage(1.0); + for(const SvgNode* pParent = getParent(); pParent && !bHasFound; pParent = pParent->getParent()) + { + // dynamic_cast results Null-pointer for not SvgSvgNode and so skips them in if condition + pParentSvgSvgNode = dynamic_cast< const SvgSvgNode* >(pParent); + if (pParentSvgSvgNode) + { + if (pParentSvgSvgNode->getViewBox()) + { + // viewbox values are already in 'user unit'. + fWidth = pParentSvgSvgNode->getViewBox()->getWidth() * fPercentage; + bHasFound = true; + } + else + { + // take absolute value or cumulate percentage + if (pParentSvgSvgNode->getWidth().isSet()) + { + if (Unit_percent == pParentSvgSvgNode->getWidth().getUnit()) + { + fPercentage *= pParentSvgSvgNode->getWidth().getNumber() * 0.01; + } + else + { + fWidth = pParentSvgSvgNode->getWidth().solveNonPercentage(*pParentSvgSvgNode) * fPercentage; + bHasFound = true; + } + } // not set => width=100% => factor 1, no need for else + } + } + } + } + + void SvgSvgNode::seekReferenceHeight(double& fHeight, bool& bHasFound) const + { + if (!getParent() || bHasFound) + { + return; + } + const SvgSvgNode* pParentSvgSvgNode = nullptr; + // enclosing svg might have relative width and height, need to cumulate them till they are + // resolved somewhere up in the node tree + double fPercentage(1.0); + for(const SvgNode* pParent = getParent(); pParent && !bHasFound; pParent = pParent->getParent()) + { + // dynamic_cast results Null-pointer for not SvgSvgNode and so skips them in if condition + pParentSvgSvgNode = dynamic_cast< const SvgSvgNode* >(pParent); + if (pParentSvgSvgNode) + { + if (pParentSvgSvgNode->getViewBox()) + { + // viewbox values are already in 'user unit'. + fHeight = pParentSvgSvgNode->getViewBox()->getHeight() * fPercentage; + bHasFound = true; + } + else + { + // take absolute value or cumulate percentage + if (pParentSvgSvgNode->getHeight().isSet()) + { + if (Unit_percent == pParentSvgSvgNode->getHeight().getUnit()) + { + fPercentage *= pParentSvgSvgNode->getHeight().getNumber() * 0.01; + } + else + { + fHeight = pParentSvgSvgNode->getHeight().solveNonPercentage(*pParentSvgSvgNode) * fPercentage; + bHasFound = true; + } + } // not set => height=100% => factor 1, no need for else + } + } + } + } + +// ToDo: Consider attribute overflow in method decomposeSvgNode + void SvgSvgNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool bReferenced) const + { + drawinglayer::primitive2d::Primitive2DContainer aSequence; + + // #i125258# check now if we need to init some style settings locally. Do not do this + // in the constructor, there is not yet information e.g. about existing CssStyles. + // Here all nodes are read and interpreted + const_cast< SvgSvgNode* >(this)->initializeStyleAttributes(); + + // decompose children + SvgNode::decomposeSvgNode(aSequence, bReferenced); + + if(!aSequence.empty()) + { + if(getParent()) + { + // #i122594# if width/height is not given, it's 100% (see 5.1.2 The 'svg' element in SVG1.1 spec). + // If it is relative, the question is to what. The previous implementation assumed relative to the + // local ViewBox which is implied by (4.2 Basic data types): + + // "Note that the non-property <length> definition also allows a percentage unit identifier. + // The meaning of a percentage length value depends on the attribute for which the percentage + // length value has been specified. Two common cases are: (a) when a percentage length value + // represents a percentage of the viewport width or height (refer to the section that discusses + // units in general), and (b) when a percentage length value represents a percentage of the + // bounding box width or height on a given object (refer to the section that describes object + // bounding box units)." + + // Comparisons with common browsers show that it's mostly interpreted relative to the viewport + // of the parent, and so does the new implementation. + + // Extract known viewport data + // bXXXIsAbsolute tracks whether relative values could be resolved to absolute values + + // If width or height is not provided, the default 100% is used, see SVG 1.1 section 5.1.2 + // value 0.0 here is only to initialize variable + bool bWidthIsAbsolute(getWidth().isSet() && Unit_percent != getWidth().getUnit()); + double fW( bWidthIsAbsolute ? getWidth().solveNonPercentage(*this) : 0.0); + + bool bHeightIsAbsolute(getHeight().isSet() && Unit_percent != getHeight().getUnit()); + double fH( bHeightIsAbsolute ? getHeight().solveNonPercentage(*this) : 0.0); + + // If x or y not provided, then default 0.0 is used, see SVG 1.1 Section 5.1.2 + bool bXIsAbsolute((getX().isSet() && Unit_percent != getX().getUnit()) || !getX().isSet()); + double fX( bXIsAbsolute && getX().isSet() ? getX().solveNonPercentage(*this) : 0.0); + + bool bYIsAbsolute((getY().isSet() && Unit_percent != getY().getUnit()) || !getY().isSet()); + double fY( bYIsAbsolute && getY().isSet() ? getY().solveNonPercentage(*this) : 0.0); + + if ( !bXIsAbsolute || !bWidthIsAbsolute) + { + // get width of enclosing svg and resolve percentage in x and width; + double fWReference(0.0); + bool bHasFoundWidth(false); + seekReferenceWidth(fWReference, bHasFoundWidth); + if (!bHasFoundWidth) + { + if (getViewBox()) + { + fWReference = getViewBox()->getWidth(); + } + else + { + // Even outermost svg has not all information to resolve relative values, + // I use content itself as fallback to set missing values for viewport + // Any better idea for such ill structured svg documents? + const basegfx::B2DRange aChildRange( + aSequence.getB2DRange( + drawinglayer::geometry::ViewInformation2D())); + fWReference = aChildRange.getWidth(); + } + } + // referenced values are already in 'user unit' + if (!bXIsAbsolute) + { + fX = getX().getNumber() * 0.01 * fWReference; + } + if (!bWidthIsAbsolute) + { + fW = (getWidth().isSet() ? getWidth().getNumber() *0.01 : 1.0) * fWReference; + } + } + + if ( !bYIsAbsolute || !bHeightIsAbsolute) + { + // get height of enclosing svg and resolve percentage in y and height + double fHReference(0.0); + bool bHasFoundHeight(false); + seekReferenceHeight(fHReference, bHasFoundHeight); + if (!bHasFoundHeight) + { + if (getViewBox()) + { + fHReference = getViewBox()->getHeight(); + } + else + { + // Even outermost svg has not all information to resolve relative values, + // I use content itself as fallback to set missing values for viewport + // Any better idea for such ill structured svg documents? + const basegfx::B2DRange aChildRange( + aSequence.getB2DRange( + drawinglayer::geometry::ViewInformation2D())); + fHReference = aChildRange.getHeight(); + } + } + + // referenced values are already in 'user unit' + if (!bYIsAbsolute) + { + fY = getY().getNumber() * 0.01 * fHReference; + } + if (!bHeightIsAbsolute) + { + fH = (getHeight().isSet() ? getHeight().getNumber() *0.01 : 1.0) * fHReference; + } + } + + if(getViewBox()) + { + // SVG 1.1 defines in section 7.7 that a negative value for width or height + // in viewBox is an error and that 0.0 disables rendering + if(basegfx::fTools::more(getViewBox()->getWidth(),0.0) && basegfx::fTools::more(getViewBox()->getHeight(),0.0)) + { + // create target range homing x,y, width and height as calculated above + const basegfx::B2DRange aTarget(fX, fY, fX + fW, fY + fH); + + if(aTarget.equal(*getViewBox())) + { + // no mapping needed, append + rTarget.append(aSequence); + } + else + { + // create mapping + // #i122610 SVG 1.1 defines in section 5.1.2 that if the attribute perserveAspectRatio is not specified, + // then the effect is as if a value of 'xMidYMid meet' were specified. + SvgAspectRatio aRatioDefault(Align_xMidYMid,true); + const SvgAspectRatio& rRatio = getSvgAspectRatio().isSet()? getSvgAspectRatio() : aRatioDefault; + + // let mapping be created from SvgAspectRatio + const basegfx::B2DHomMatrix aEmbeddingTransform( + rRatio.createMapping(aTarget, *getViewBox())); + + // prepare embedding in transformation + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + aEmbeddingTransform, + aSequence)); + + if(rRatio.isMeetOrSlice()) + { + // embed in transformation + rTarget.push_back(xRef); + } + else + { + // need to embed in MaskPrimitive2D, too + const drawinglayer::primitive2d::Primitive2DReference xMask( + new drawinglayer::primitive2d::MaskPrimitive2D( + basegfx::B2DPolyPolygon(basegfx::utils::createPolygonFromRect(aTarget)), + drawinglayer::primitive2d::Primitive2DContainer { xRef })); + + rTarget.push_back(xMask); + } + } + } + } + else // no viewBox attribute + { + // Svg defines that a negative value is an error and that 0.0 disables rendering + if(basegfx::fTools::more(fW, 0.0) && basegfx::fTools::more(fH, 0.0)) + { + if(!basegfx::fTools::equalZero(fX) || !basegfx::fTools::equalZero(fY)) + { + // embed in transform + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + basegfx::utils::createTranslateB2DHomMatrix(fX, fY), + aSequence)); + + aSequence = drawinglayer::primitive2d::Primitive2DContainer { xRef, }; + } + + // embed in MaskPrimitive2D to clip + const drawinglayer::primitive2d::Primitive2DReference xMask( + new drawinglayer::primitive2d::MaskPrimitive2D( + basegfx::B2DPolyPolygon( + basegfx::utils::createPolygonFromRect( + basegfx::B2DRange(fX, fY, fX + fW, fY + fH))), + aSequence)); + + // append + rTarget.push_back(xMask); + } + } + } + else // Outermost SVG element + { + // Svg defines that a negative value is an error and that 0.0 disables rendering + // isPositive() not usable because it allows 0.0 in contrast to mathematical definition of 'positive' + const bool bWidthInvalid(getWidth().isSet() && basegfx::fTools::lessOrEqual(getWidth().getNumber(), 0.0)); + const bool bHeightInvalid(getHeight().isSet() && basegfx::fTools::lessOrEqual(getHeight().getNumber(), 0.0)); + if(!bWidthInvalid && !bHeightInvalid) + { + basegfx::B2DRange aSvgCanvasRange; // viewport + double fW = 0.0; // dummy values + double fH = 0.0; + if (const basegfx::B2DRange* pBox = getViewBox()) + { + // SVG 1.1 defines in section 7.7 that a negative value for width or height + // in viewBox is an error and that 0.0 disables rendering + const double fViewBoxWidth = pBox->getWidth(); + const double fViewBoxHeight = pBox->getHeight(); + if(basegfx::fTools::more(fViewBoxWidth,0.0) && basegfx::fTools::more(fViewBoxHeight,0.0)) + { + // The intrinsic aspect ratio of the svg element is given by absolute values of svg width and svg height + // or by the width and height of the viewBox, if svg width or svg height is relative. + // see SVG 1.1 section 7.12 + bool bNeedsMapping(true); + const bool bWidthIsAbsolute(getWidth().isSet() && Unit_percent != getWidth().getUnit()); + const bool bHeightIsAbsolute(getHeight().isSet() && Unit_percent != getHeight().getUnit()); + const double fViewBoxRatio(fViewBoxWidth/fViewBoxHeight); + if(bWidthIsAbsolute && bHeightIsAbsolute) + { + fW = getWidth().solveNonPercentage(*this); + fH = getHeight().solveNonPercentage(*this); + aSvgCanvasRange = basegfx::B2DRange(0.0, 0.0, fW, fH); + } + else if (bWidthIsAbsolute) + { + fW = getWidth().solveNonPercentage(*this); + fH = fW / fViewBoxRatio ; + aSvgCanvasRange = basegfx::B2DRange(0.0, 0.0, fW, fH); + } + else if (bHeightIsAbsolute) + { + fH = getHeight().solveNonPercentage(*this); + fW = fH * fViewBoxRatio ; + aSvgCanvasRange = basegfx::B2DRange(0.0, 0.0, fW, fH); + } + else + { + // There exists no parent to resolve relative width or height. + // Use child size as fallback and expand to aspect ratio given + // by the viewBox. No mapping. + // We get viewport >= content, therefore no clipping. + bNeedsMapping = false; + + const double fChildWidth(pBox->getWidth()); + const double fChildHeight(pBox->getHeight()); + const double fLeft(pBox->getMinX()); + const double fTop(pBox->getMinY()); + if ( fChildWidth / fViewBoxWidth > fChildHeight / fViewBoxHeight ) + { // expand y + fW = fChildWidth; + fH = fChildWidth / fViewBoxRatio; + } + else + { // expand x + fH = fChildHeight; + fW = fChildHeight * fViewBoxRatio; + } + aSvgCanvasRange = basegfx::B2DRange(fLeft, fTop, fLeft + fW, fTop + fH); + } + + if (bNeedsMapping) + { + // create mapping + // SVG 1.1 defines in section 5.1.2 that if the attribute perserveAspectRatio is not specified, + // then the effect is as if a value of 'xMidYMid meet' were specified. + SvgAspectRatio aRatioDefault(Align_xMidYMid,true); + const SvgAspectRatio& rRatio = getSvgAspectRatio().isSet()? getSvgAspectRatio() : aRatioDefault; + + basegfx::B2DHomMatrix aViewBoxMapping = rRatio.createMapping(aSvgCanvasRange, *pBox); + // no need to check ratio here for slice, the outermost Svg will + // be clipped anyways (see below) + + // scale content to viewBox definitions + const drawinglayer::primitive2d::Primitive2DReference xTransform( + new drawinglayer::primitive2d::TransformPrimitive2D( + aViewBoxMapping, + aSequence)); + + aSequence = drawinglayer::primitive2d::Primitive2DContainer { xTransform }; + } + } + } + else // no viewbox => no mapping + { + const bool bWidthIsAbsolute(getWidth().isSet() && Unit_percent != getWidth().getUnit()); + const bool bHeightIsAbsolute(getHeight().isSet() && Unit_percent != getHeight().getUnit()); + if (bWidthIsAbsolute && bHeightIsAbsolute) + { + fW =getWidth().solveNonPercentage(*this); + fH =getHeight().solveNonPercentage(*this); + aSvgCanvasRange = basegfx::B2DRange(0.0, 0.0, fW, fH); + } + else + { + // There exists no parent to resolve relative width or height. + // Use child size as fallback. We get viewport >= content, therefore no clipping. + const basegfx::B2DRange aChildRange( + aSequence.getB2DRange( + drawinglayer::geometry::ViewInformation2D())); + const double fChildWidth(aChildRange.getWidth()); + const double fChildHeight(aChildRange.getHeight()); + const double fChildLeft(aChildRange.getMinX()); + const double fChildTop(aChildRange.getMinY()); + fW = bWidthIsAbsolute ? getWidth().solveNonPercentage(*this) : fChildWidth; + fH = bHeightIsAbsolute ? getHeight().solveNonPercentage(*this) : fChildHeight; + const double fLeft(bWidthIsAbsolute ? 0.0 : fChildLeft); + const double fTop(bHeightIsAbsolute ? 0.0 : fChildTop); + aSvgCanvasRange = basegfx::B2DRange(fLeft, fTop, fLeft+fW, fTop+fH); + } + + } + + // to be completely correct in Svg sense it is necessary to clip + // the whole content to the given canvas. I choose here to do this + // initially despite I found various examples of Svg files out there + // which have no correct values for this clipping. It's correct + // due to the Svg spec. + + // different from Svg we have the possibility with primitives to get + // a correct bounding box for the geometry. Get it for evtl. taking action + const basegfx::B2DRange aContentRange( + aSequence.getB2DRange( + drawinglayer::geometry::ViewInformation2D())); + + if(aSvgCanvasRange.isInside(aContentRange)) + { + // no clip needed, but an invisible HiddenGeometryPrimitive2D + // to allow getting the full Svg range using the primitive mechanisms. + // This is needed since e.g. an SdrObject using this as graphic will + // create a mapping transformation to exactly map the content to its + // real life size + const drawinglayer::primitive2d::Primitive2DReference xLine( + new drawinglayer::primitive2d::PolygonHairlinePrimitive2D( + basegfx::utils::createPolygonFromRect( + aSvgCanvasRange), + basegfx::BColor(0.0, 0.0, 0.0))); + const drawinglayer::primitive2d::Primitive2DReference xHidden( + new drawinglayer::primitive2d::HiddenGeometryPrimitive2D( + drawinglayer::primitive2d::Primitive2DContainer { xLine })); + + aSequence.push_back(xHidden); + } + else if(aSvgCanvasRange.overlaps(aContentRange)) + { + // Clip is necessary. This will make Svg images evtl. smaller + // than wanted from Svg (the free space which may be around it is + // conform to the Svg spec), but avoids an expensive and unnecessary + // clip. Keep the full Svg range here to get the correct mappings + // to objects using this. Optimizations can be done in the processors + const drawinglayer::primitive2d::Primitive2DReference xMask( + new drawinglayer::primitive2d::MaskPrimitive2D( + basegfx::B2DPolyPolygon( + basegfx::utils::createPolygonFromRect( + aSvgCanvasRange)), + aSequence)); + + aSequence = drawinglayer::primitive2d::Primitive2DContainer { xMask }; + } + else + { + // not inside, no overlap. Empty Svg + aSequence.clear(); + } + + if(!aSequence.empty()) + { + // Another correction: + // If no Width/Height is set (usually done in + // <svg ... width="215.9mm" height="279.4mm" >) which + // is the case for own-Impress-exports, assume that + // the Units are already 100ThMM. + // Maybe only for own-Impress-exports, thus may need to be + // &&ed with getDocument().findSvgNodeById("ooo:meta_slides"), + // but does not need to be. + bool bEmbedInFinalTransformPxTo100ThMM(true); + + if(getDocument().findSvgNodeById("ooo:meta_slides") + && !getWidth().isSet() + && !getHeight().isSet()) + { + bEmbedInFinalTransformPxTo100ThMM = false; + } + + if(bEmbedInFinalTransformPxTo100ThMM) + { + // embed in transform primitive to scale to 1/100th mm + // where 1 inch == 25.4 mm to get from Svg coordinates (px) to + // drawinglayer coordinates + const double fScaleTo100thmm(25.4 * 100.0 / F_SVG_PIXEL_PER_INCH); + const basegfx::B2DHomMatrix aTransform( + basegfx::utils::createScaleB2DHomMatrix( + fScaleTo100thmm, + fScaleTo100thmm)); + + const drawinglayer::primitive2d::Primitive2DReference xTransform( + new drawinglayer::primitive2d::TransformPrimitive2D( + aTransform, + aSequence)); + + aSequence = drawinglayer::primitive2d::Primitive2DContainer { xTransform }; + } + + // append to result + rTarget.append(aSequence); + } + } + } + } + + if(!(aSequence.empty() && !getParent() && getViewBox())) + return; + + // tdf#118232 No geometry, Outermost SVG element and we have a ViewBox. + // Create a HiddenGeometry Primitive containing an expanded + // hairline geometry to have the size contained + const drawinglayer::primitive2d::Primitive2DReference xLine( + new drawinglayer::primitive2d::PolygonHairlinePrimitive2D( + basegfx::utils::createPolygonFromRect( + *getViewBox()), + basegfx::BColor(0.0, 0.0, 0.0))); + const drawinglayer::primitive2d::Primitive2DReference xHidden( + new drawinglayer::primitive2d::HiddenGeometryPrimitive2D( + drawinglayer::primitive2d::Primitive2DContainer { xLine })); + + rTarget.push_back(xHidden); + } + + basegfx::B2DRange SvgSvgNode::getCurrentViewPort() const + { + if(getViewBox()) + { + return *(getViewBox()); + } + else // viewport should be given by x, y, width, and height + { + // Extract known viewport data + // bXXXIsAbsolute tracks whether relative values could be resolved to absolute values + if (getParent()) + { + // If width or height is not provided, the default 100% is used, see SVG 1.1 section 5.1.2 + // value 0.0 here is only to initialize variable + bool bWidthIsAbsolute(getWidth().isSet() && Unit_percent != getWidth().getUnit()); + double fW( bWidthIsAbsolute ? getWidth().solveNonPercentage(*this) : 0.0); + bool bHeightIsAbsolute(getHeight().isSet() && Unit_percent != getHeight().getUnit()); + double fH( bHeightIsAbsolute ? getHeight().solveNonPercentage(*this) : 0.0); + + // If x or y not provided, then default 0.0 is used, see SVG 1.1 Section 5.1.2 + bool bXIsAbsolute((getX().isSet() && Unit_percent != getX().getUnit()) || !getX().isSet()); + double fX( bXIsAbsolute && getX().isSet() ? getX().solveNonPercentage(*this) : 0.0); + + bool bYIsAbsolute((getY().isSet() && Unit_percent != getY().getUnit()) || !getY().isSet()); + double fY( bYIsAbsolute && getY().isSet() ? getY().solveNonPercentage(*this) : 0.0); + + if (bXIsAbsolute && bYIsAbsolute && bWidthIsAbsolute && bHeightIsAbsolute) + { + return basegfx::B2DRange(fX, fY, fX+fW, fY+fH); + } + else // try to resolve relative values + { + if (!bXIsAbsolute || !bWidthIsAbsolute) + { + // get width of enclosing svg and resolve percentage in x and width + double fWReference(0.0); + bool bHasFoundWidth(false); + seekReferenceWidth(fWReference, bHasFoundWidth); + // referenced values are already in 'user unit' + if (!bXIsAbsolute && bHasFoundWidth) + { + fX = getX().getNumber() * 0.01 * fWReference; + bXIsAbsolute = true; + } + if (!bWidthIsAbsolute && bHasFoundWidth) + { + fW = (getWidth().isSet() ? getWidth().getNumber() *0.01 : 1.0) * fWReference; + bWidthIsAbsolute = true; + } + } + if (!bYIsAbsolute || !bHeightIsAbsolute) + { + // get height of enclosing svg and resolve percentage in y and height + double fHReference(0.0); + bool bHasFoundHeight(false); + seekReferenceHeight(fHReference, bHasFoundHeight); + // referenced values are already in 'user unit' + if (!bYIsAbsolute && bHasFoundHeight) + { + fY = getY().getNumber() * 0.01 * fHReference; + bYIsAbsolute = true; + } + if (!bHeightIsAbsolute && bHasFoundHeight) + { + fH = (getHeight().isSet() ? getHeight().getNumber() *0.01 : 1.0) * fHReference; + bHeightIsAbsolute = true; + } + } + + if (bXIsAbsolute && bYIsAbsolute && bWidthIsAbsolute && bHeightIsAbsolute) + { + return basegfx::B2DRange(fX, fY, fX+fW, fY+fH); + } + else // relative values could not be resolved, there exists no fallback + { + return SvgNode::getCurrentViewPort(); + } + } + } + else //outermost svg + { + // If width or height is not provided, the default would be 100%, see SVG 1.1 section 5.1.2 + // But here it cannot be resolved and no fallback exists. + // SVG 1.1 defines in section 5.1.2 that x,y has no meaning for the outermost SVG element. + bool bWidthIsAbsolute(getWidth().isSet() && Unit_percent != getWidth().getUnit()); + bool bHeightIsAbsolute(getHeight().isSet() && Unit_percent != getHeight().getUnit()); + if (bWidthIsAbsolute && bHeightIsAbsolute) + { + double fW( getWidth().solveNonPercentage(*this) ); + double fH( getHeight().solveNonPercentage(*this) ); + return basegfx::B2DRange(0.0, 0.0, fW, fH); + } + else // no fallback exists + { + return SvgNode::getCurrentViewPort(); + } + } +// TODO: Is it possible to decompose and use the bounding box of the children, if even the +// outermost svg has no information to resolve percentage? Is it worth, how expensive is it? + + } + } + +} // end of namespace svgio + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgsymbolnode.cxx b/svgio/source/svgreader/svgsymbolnode.cxx new file mode 100644 index 000000000..6de296b8e --- /dev/null +++ b/svgio/source/svgreader/svgsymbolnode.cxx @@ -0,0 +1,77 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgsymbolnode.hxx> + +namespace svgio::svgreader +{ + SvgSymbolNode::SvgSymbolNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenSvg, rDocument, pParent), + maSvgStyleAttributes(*this), + maSvgAspectRatio() + { + } + + SvgSymbolNode::~SvgSymbolNode() + { + } + + const SvgStyleAttributes* SvgSymbolNode::getSvgStyleAttributes() const + { + return &maSvgStyleAttributes; + } + + void SvgSymbolNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenViewBox: + { + readViewBox(aContent, *this); + break; + } + case SVGTokenPreserveAspectRatio: + { + maSvgAspectRatio = readSvgAspectRatio(aContent); + break; + } + default: + { + break; + } + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtextnode.cxx b/svgio/source/svgreader/svgtextnode.cxx new file mode 100644 index 000000000..aff56aa7f --- /dev/null +++ b/svgio/source/svgreader/svgtextnode.cxx @@ -0,0 +1,264 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtextnode.hxx> +#include <svgcharacternode.hxx> +#include <svgstyleattributes.hxx> +#include <svgtrefnode.hxx> +#include <svgtextpathnode.hxx> +#include <svgtspannode.hxx> + +namespace svgio::svgreader +{ + SvgTextNode::SvgTextNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenText, rDocument, pParent), + maSvgStyleAttributes(*this), + maSvgTextPositions() + { + } + + SvgTextNode::~SvgTextNode() + { + } + + const SvgStyleAttributes* SvgTextNode::getSvgStyleAttributes() const + { + return checkForCssStyle("text", maSvgStyleAttributes); + } + + void SvgTextNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // read text position attributes + maSvgTextPositions.parseTextPositionAttributes(aSVGToken, aContent); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + default: + { + break; + } + } + } + + void SvgTextNode::addTextPrimitives( + const SvgNode& rCandidate, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + drawinglayer::primitive2d::Primitive2DContainer const & rSource) + { + if(rSource.empty()) + return; + + const SvgStyleAttributes* pAttributes = rCandidate.getSvgStyleAttributes(); + + if(pAttributes) + { + // add text with taking all Fill/Stroke attributes into account + pAttributes->add_text(rTarget, rSource); + } + else + { + // should not happen, every subnode from SvgTextNode will at least + // return the attributes from SvgTextNode. Nonetheless, add text + rTarget.append(rSource); + } + } + + void SvgTextNode::DecomposeChild(const SvgNode& rCandidate, drawinglayer::primitive2d::Primitive2DContainer& rTarget, SvgTextPosition& rSvgTextPosition) const + { + switch(rCandidate.getType()) + { + case SVGTokenCharacter: + { + // direct SvgTextPathNode derivates, decompose them + const SvgCharacterNode& rSvgCharacterNode = static_cast< const SvgCharacterNode& >(rCandidate); + rSvgCharacterNode.decomposeText(rTarget, rSvgTextPosition); + break; + } + case SVGTokenTextPath: + { + // direct TextPath decompose + const SvgTextPathNode& rSvgTextPathNode = static_cast< const SvgTextPathNode& >(rCandidate); + const auto& rChildren = rSvgTextPathNode.getChildren(); + const sal_uInt32 nCount(rChildren.size()); + + if(nCount && rSvgTextPathNode.isValid()) + { + // remember original TextStart to later detect hor/ver offsets + const basegfx::B2DPoint aTextStart(rSvgTextPosition.getPosition()); + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + // decompose to regular TextPrimitives + for(sal_uInt32 a(0); a < nCount; a++) + { + DecomposeChild(*rChildren[a], aNewTarget, rSvgTextPosition); + } + + if(!aNewTarget.empty()) + { + const drawinglayer::primitive2d::Primitive2DContainer aPathContent(aNewTarget); + aNewTarget.clear(); + + // dismantle TextPrimitives and map them on curve/path + rSvgTextPathNode.decomposePathNode(aPathContent, aNewTarget, aTextStart); + } + + if(!aNewTarget.empty()) + { + addTextPrimitives(rCandidate, rTarget, aNewTarget); + } + } + + break; + } + case SVGTokenTspan: + { + // Tspan may have children, call recursively + const SvgTspanNode& rSvgTspanNode = static_cast< const SvgTspanNode& >(rCandidate); + const auto& rChildren = rSvgTspanNode.getChildren(); + const sal_uInt32 nCount(rChildren.size()); + + if(nCount) + { + SvgTextPosition aSvgTextPosition(&rSvgTextPosition, rSvgTspanNode, rSvgTspanNode.getSvgTextPositions()); + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + for(sal_uInt32 a(0); a < nCount; a++) + { + DecomposeChild(*rChildren[a], aNewTarget, aSvgTextPosition); + } + + rSvgTextPosition.setPosition(aSvgTextPosition.getPosition()); + + if(!aNewTarget.empty()) + { + addTextPrimitives(rCandidate, rTarget, aNewTarget); + } + } + break; + } + case SVGTokenTref: + { + const SvgTrefNode& rSvgTrefNode = static_cast< const SvgTrefNode& >(rCandidate); + const SvgTextNode* pRefText = rSvgTrefNode.getReferencedSvgTextNode(); + + if(pRefText) + { + const auto& rChildren = pRefText->getChildren(); + const sal_uInt32 nCount(rChildren.size()); + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + if(nCount) + { + for(sal_uInt32 a(0); a < nCount; a++) + { + const SvgNode& rChildCandidate = *rChildren[a]; + const_cast< SvgNode& >(rChildCandidate).setAlternativeParent(this); + + DecomposeChild(rChildCandidate, aNewTarget, rSvgTextPosition); + const_cast< SvgNode& >(rChildCandidate).setAlternativeParent(); + } + + if(!aNewTarget.empty()) + { + addTextPrimitives(rCandidate, rTarget, aNewTarget); + } + } + } + + break; + } + default: + { + OSL_ENSURE(false, "Unexpected node in text token (!)"); + break; + } + } + } + + void SvgTextNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced`*/) const + { + // text has a group of child nodes, allowed are SVGTokenCharacter, SVGTokenTspan, + // SVGTokenTref and SVGTokenTextPath. These increase a given current text position + const SvgStyleAttributes* pStyle = getSvgStyleAttributes(); + + if(!(pStyle && !getChildren().empty())) + return; + + const double fOpacity(pStyle->getOpacity().getNumber()); + + if(fOpacity <= 0.0) + return; + + SvgTextPosition aSvgTextPosition(nullptr, *this, maSvgTextPositions); + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + const auto& rChildren = getChildren(); + const sal_uInt32 nCount(rChildren.size()); + + for(sal_uInt32 a(0); a < nCount; a++) + { + const SvgNode& rCandidate = *rChildren[a]; + + DecomposeChild(rCandidate, aNewTarget, aSvgTextPosition); + } + + if(!aNewTarget.empty()) + { + drawinglayer::primitive2d::Primitive2DContainer aNewTarget2; + + addTextPrimitives(*this, aNewTarget2, aNewTarget); + aNewTarget = aNewTarget2; + } + + if(!aNewTarget.empty()) + { + pStyle->add_postProcess(rTarget, aNewTarget, getTransform()); + } + } + + double SvgTextNode::getCurrentFontSize() const + { + return getCurrentFontSizeInherited(); + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtextpathnode.cxx b/svgio/source/svgreader/svgtextpathnode.cxx new file mode 100644 index 000000000..7793e2634 --- /dev/null +++ b/svgio/source/svgreader/svgtextpathnode.cxx @@ -0,0 +1,442 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtextpathnode.hxx> +#include <svgstyleattributes.hxx> +#include <svgpathnode.hxx> +#include <svgdocument.hxx> +#include <basegfx/polygon/b2dpolygon.hxx> +#include <basegfx/polygon/b2dpolygontools.hxx> +#include <drawinglayer/primitive2d/textbreakuphelper.hxx> +#include <drawinglayer/primitive2d/textprimitive2d.hxx> +#include <basegfx/curve/b2dcubicbezier.hxx> +#include <basegfx/curve/b2dbeziertools.hxx> + +namespace svgio::svgreader +{ + namespace { + + class pathTextBreakupHelper : public drawinglayer::primitive2d::TextBreakupHelper + { + private: + const basegfx::B2DPolygon& mrPolygon; + const double mfBasegfxPathLength; + double mfPosition; + const basegfx::B2DPoint& mrTextStart; + + const sal_uInt32 mnMaxIndex; + sal_uInt32 mnIndex; + basegfx::B2DCubicBezier maCurrentSegment; + std::unique_ptr<basegfx::B2DCubicBezierHelper> mpB2DCubicBezierHelper; + double mfCurrentSegmentLength; + double mfSegmentStartPosition; + + protected: + /// allow user callback to allow changes to the new TextTransformation. Default + /// does nothing. + virtual bool allowChange(sal_uInt32 nCount, basegfx::B2DHomMatrix& rNewTransform, sal_uInt32 nIndex, sal_uInt32 nLength) override; + + void freeB2DCubicBezierHelper(); + basegfx::B2DCubicBezierHelper* getB2DCubicBezierHelper(); + void advanceToPosition(double fNewPosition); + + public: + pathTextBreakupHelper( + const drawinglayer::primitive2d::TextSimplePortionPrimitive2D& rSource, + const basegfx::B2DPolygon& rPolygon, + const double fBasegfxPathLength, + double fPosition, + const basegfx::B2DPoint& rTextStart); + virtual ~pathTextBreakupHelper() override; + + // read access to evtl. advanced position + double getPosition() const { return mfPosition; } + }; + + } + + void pathTextBreakupHelper::freeB2DCubicBezierHelper() + { + mpB2DCubicBezierHelper.reset(); + } + + basegfx::B2DCubicBezierHelper* pathTextBreakupHelper::getB2DCubicBezierHelper() + { + if(!mpB2DCubicBezierHelper && maCurrentSegment.isBezier()) + { + mpB2DCubicBezierHelper.reset(new basegfx::B2DCubicBezierHelper(maCurrentSegment)); + } + + return mpB2DCubicBezierHelper.get(); + } + + void pathTextBreakupHelper::advanceToPosition(double fNewPosition) + { + while(mfSegmentStartPosition + mfCurrentSegmentLength < fNewPosition && mnIndex < mnMaxIndex) + { + mfSegmentStartPosition += mfCurrentSegmentLength; + mnIndex++; + + if(mnIndex < mnMaxIndex) + { + freeB2DCubicBezierHelper(); + mrPolygon.getBezierSegment(mnIndex % mrPolygon.count(), maCurrentSegment); + maCurrentSegment.testAndSolveTrivialBezier(); + mfCurrentSegmentLength = getB2DCubicBezierHelper() + ? getB2DCubicBezierHelper()->getLength() + : maCurrentSegment.getLength(); + } + } + + mfPosition = fNewPosition; + } + + pathTextBreakupHelper::pathTextBreakupHelper( + const drawinglayer::primitive2d::TextSimplePortionPrimitive2D& rSource, + const basegfx::B2DPolygon& rPolygon, + const double fBasegfxPathLength, + double fPosition, + const basegfx::B2DPoint& rTextStart) + : drawinglayer::primitive2d::TextBreakupHelper(rSource), + mrPolygon(rPolygon), + mfBasegfxPathLength(fBasegfxPathLength), + mfPosition(0.0), + mrTextStart(rTextStart), + mnMaxIndex(rPolygon.isClosed() ? rPolygon.count() : rPolygon.count() - 1), + mnIndex(0), + maCurrentSegment(), + mfCurrentSegmentLength(0.0), + mfSegmentStartPosition(0.0) + { + mrPolygon.getBezierSegment(mnIndex % mrPolygon.count(), maCurrentSegment); + mfCurrentSegmentLength = maCurrentSegment.getLength(); + + advanceToPosition(fPosition); + } + + pathTextBreakupHelper::~pathTextBreakupHelper() + { + freeB2DCubicBezierHelper(); + } + + bool pathTextBreakupHelper::allowChange(sal_uInt32 /*nCount*/, basegfx::B2DHomMatrix& rNewTransform, sal_uInt32 nIndex, sal_uInt32 nLength) + { + bool bRetval(false); + + if(mfPosition < mfBasegfxPathLength && nLength && mnIndex < mnMaxIndex) + { + const double fSnippetWidth( + getTextLayouter().getTextWidth( + getSource().getText(), + nIndex, + nLength)); + + if(basegfx::fTools::more(fSnippetWidth, 0.0)) + { + const OUString aText(getSource().getText()); + const OUString aTrimmedChars(aText.copy(nIndex, nLength).trim()); + const double fEndPos(mfPosition + fSnippetWidth); + + if(!aTrimmedChars.isEmpty() && (mfPosition < mfBasegfxPathLength || fEndPos > 0.0)) + { + const double fHalfSnippetWidth(fSnippetWidth * 0.5); + + advanceToPosition(mfPosition + fHalfSnippetWidth); + + // create representation for this snippet + bRetval = true; + + // get target position and tangent in that point + basegfx::B2DPoint aPosition(0.0, 0.0); + basegfx::B2DVector aTangent(0.0, 1.0); + + if(mfPosition < 0.0) + { + // snippet center is left of first segment, but right edge is on it (SVG allows that) + aTangent = maCurrentSegment.getTangent(0.0); + aTangent.normalize(); + aPosition = maCurrentSegment.getStartPoint() + (aTangent * (mfPosition - mfSegmentStartPosition)); + } + else if(mfPosition > mfBasegfxPathLength) + { + // snippet center is right of last segment, but left edge is on it (SVG allows that) + aTangent = maCurrentSegment.getTangent(1.0); + aTangent.normalize(); + aPosition = maCurrentSegment.getEndPoint() + (aTangent * (mfPosition - mfSegmentStartPosition)); + } + else + { + // snippet center inside segment, interpolate + double fBezierDistance(mfPosition - mfSegmentStartPosition); + + if(getB2DCubicBezierHelper()) + { + // use B2DCubicBezierHelper to bridge the non-linear gap between + // length and bezier distances (if it's a bezier segment) + fBezierDistance = getB2DCubicBezierHelper()->distanceToRelative(fBezierDistance); + } + else + { + // linear relationship, make relative to segment length + fBezierDistance = fBezierDistance / mfCurrentSegmentLength; + } + + aPosition = maCurrentSegment.interpolatePoint(fBezierDistance); + aTangent = maCurrentSegment.getTangent(fBezierDistance); + aTangent.normalize(); + } + + // detect evtl. hor/ver translations (depends on text direction) + const basegfx::B2DPoint aBasePoint(rNewTransform * basegfx::B2DPoint(0.0, 0.0)); + const basegfx::B2DVector aOffset(aBasePoint - mrTextStart); + + if(!basegfx::fTools::equalZero(aOffset.getY())) + { + // ...and apply + aPosition.setY(aPosition.getY() + aOffset.getY()); + } + + // move target position from snippet center to left text start + aPosition -= fHalfSnippetWidth * aTangent; + + // remove current translation + rNewTransform.translate(-aBasePoint.getX(), -aBasePoint.getY()); + + // rotate due to tangent + rNewTransform.rotate(atan2(aTangent.getY(), aTangent.getX())); + + // add new translation + rNewTransform.translate(aPosition.getX(), aPosition.getY()); + } + + // advance to end + advanceToPosition(fEndPos); + } + } + + return bRetval; + } + +} // end of namespace svgio::svgreader + + +namespace svgio::svgreader +{ + SvgTextPathNode::SvgTextPathNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenTextPath, rDocument, pParent), + maSvgStyleAttributes(*this), + maXLink(), + maStartOffset() + { + } + + SvgTextPathNode::~SvgTextPathNode() + { + } + + const SvgStyleAttributes* SvgTextPathNode::getSvgStyleAttributes() const + { + return &maSvgStyleAttributes; + } + + void SvgTextPathNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenStartOffset: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maStartOffset = aNum; + } + } + break; + } + case SVGTokenMethod: + { + break; + } + case SVGTokenSpacing: + { + break; + } + case SVGTokenXlinkHref: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen && '#' == aContent[0]) + { + maXLink = aContent.copy(1); + } + break; + } + default: + { + break; + } + } + } + + bool SvgTextPathNode::isValid() const + { + const SvgPathNode* pSvgPathNode = dynamic_cast< const SvgPathNode* >(getDocument().findSvgNodeById(maXLink)); + + if(!pSvgPathNode) + { + return false; + } + + const basegfx::B2DPolyPolygon* pPolyPolyPath = pSvgPathNode->getPath(); + + if(!pPolyPolyPath || !pPolyPolyPath->count()) + { + return false; + } + + const basegfx::B2DPolygon aPolygon(pPolyPolyPath->getB2DPolygon(0)); + + if(!aPolygon.count()) + { + return false; + } + + const double fBasegfxPathLength(basegfx::utils::getLength(aPolygon)); + + return !basegfx::fTools::equalZero(fBasegfxPathLength); + } + + void SvgTextPathNode::decomposePathNode( + const drawinglayer::primitive2d::Primitive2DContainer& rPathContent, + drawinglayer::primitive2d::Primitive2DContainer& rTarget, + const basegfx::B2DPoint& rTextStart) const + { + if(rPathContent.empty()) + return; + + const SvgPathNode* pSvgPathNode = dynamic_cast< const SvgPathNode* >(getDocument().findSvgNodeById(maXLink)); + + if(!pSvgPathNode) + return; + + const basegfx::B2DPolyPolygon* pPolyPolyPath = pSvgPathNode->getPath(); + + if(!(pPolyPolyPath && pPolyPolyPath->count())) + return; + + basegfx::B2DPolygon aPolygon(pPolyPolyPath->getB2DPolygon(0)); + + if(pSvgPathNode->getTransform()) + { + aPolygon.transform(*pSvgPathNode->getTransform()); + } + + const double fBasegfxPathLength(basegfx::utils::getLength(aPolygon)); + + if(basegfx::fTools::equalZero(fBasegfxPathLength)) + return; + + double fUserToBasegfx(1.0); // multiply: user->basegfx, divide: basegfx->user + + if(pSvgPathNode->getPathLength().isSet()) + { + const double fUserLength(pSvgPathNode->getPathLength().solve(*this)); + + if(fUserLength > 0.0 && !basegfx::fTools::equal(fUserLength, fBasegfxPathLength)) + { + fUserToBasegfx = fUserLength / fBasegfxPathLength; + } + } + + double fPosition(0.0); + + if(getStartOffset().isSet()) + { + if(Unit_percent == getStartOffset().getUnit()) + { + // percent are relative to path length + fPosition = getStartOffset().getNumber() * 0.01 * fBasegfxPathLength; + } + else + { + fPosition = getStartOffset().solve(*this) * fUserToBasegfx; + } + } + + if(fPosition < 0.0) + return; + + const sal_Int32 nLength(rPathContent.size()); + sal_Int32 nCurrent(0); + + while(fPosition < fBasegfxPathLength && nCurrent < nLength) + { + const drawinglayer::primitive2d::TextSimplePortionPrimitive2D* pCandidate = nullptr; + const drawinglayer::primitive2d::Primitive2DReference xReference(rPathContent[nCurrent]); + + if(xReference.is()) + { + pCandidate = dynamic_cast< const drawinglayer::primitive2d::TextSimplePortionPrimitive2D* >(xReference.get()); + } + + if(pCandidate) + { + const pathTextBreakupHelper aPathTextBreakupHelper( + *pCandidate, + aPolygon, + fBasegfxPathLength, + fPosition, + rTextStart); + + const drawinglayer::primitive2d::Primitive2DContainer& aResult( + aPathTextBreakupHelper.getResult()); + + if(!aResult.empty()) + { + rTarget.append(aResult); + } + + // advance position to consumed + fPosition = aPathTextBreakupHelper.getPosition(); + } + + nCurrent++; + } + } + +} // end of namespace svgio + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtitledescnode.cxx b/svgio/source/svgreader/svgtitledescnode.cxx new file mode 100644 index 000000000..dbceb2b54 --- /dev/null +++ b/svgio/source/svgreader/svgtitledescnode.cxx @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtitledescnode.hxx> + + +namespace svgio::svgreader +{ + SvgTitleDescNode::SvgTitleDescNode( + SVGToken aType, + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(aType, rDocument, pParent), + maText() + { + OSL_ENSURE(aType == SVGTokenTitle || aType == SVGTokenDesc, "SvgTitleDescNode should only be used for Title and Desc (!)"); + } + + SvgTitleDescNode::~SvgTitleDescNode() + { + } + + void SvgTitleDescNode::concatenate(const OUString& rChars) + { + maText += rChars; + } +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtoken.cxx b/svgio/source/svgreader/svgtoken.cxx new file mode 100644 index 000000000..78c35888a --- /dev/null +++ b/svgio/source/svgreader/svgtoken.cxx @@ -0,0 +1,362 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtoken.hxx> +#include <unordered_map> + +namespace svgio::svgreader +{ + static const char aSVGStrWidth[] = "width"; + static const char aSVGStrHeight[] = "height"; + static const char aSVGStrViewBox[] = "viewBox"; + static const char aSVGStrTransform[] = "transform"; + static const char aSVGStrStyle[] = "style"; + static const char aSVGStrDisplay[] = "display"; // #i121656# + static const char aSVGStrD[] = "d"; + static const char aSVGStrX[] = "x"; + static const char aSVGStrY[] = "y"; + static const char aSVGStrXmlns[] = "xmlns"; + static const char aSVGStrVersion[] = "version"; + static const char aSVGStrId[] = "id"; + static const char aSVGStrRx[] = "rx"; + static const char aSVGStrRy[] = "ry"; + static const char aSVGStrPoints[] = "points"; + static const char aSVGStrDx[] = "dx"; + static const char aSVGStrDy[] = "dy"; + static const char aSVGStrRotate[] = "rotate"; + static const char aSVGStrTextLength[] = "textLength"; + static const char aSVGStrLengthAdjust[] = "lengthAdjust"; + static const char aSVGStrFont[] = "font"; + static const char aSVGStrFontFamily[] = "font-family"; + static const char aSVGStrFontSize[] = "font-size"; + static const char aSVGStrFontSizeAdjust[] = "font-size-adjust"; + static const char aSVGStrFontStretch[] = "font-stretch"; + static const char aSVGStrFontStyle[] = "font-style"; + static const char aSVGStrFontVariant[] = "font-variant"; + static const char aSVGStrFontWeight[] = "font-weight"; + static const char aSVGStrDirection[] = "direction"; + static const char aSVGStrLetterSpacing[] = "letter-spacing"; + static const char aSVGStrTextDecoration[] = "text-decoration"; + static const char aSVGStrUnicodeBidi[] = "unicode-bidi"; + static const char aSVGStrWordSpacing[] = "word-spacing"; + static const char aSVGStrTspan[] = "tspan"; + static const char aSVGStrTref[] = "tref"; + static const char aSVGStrTextPath[] = "textPath"; + static const char aSVGStrStartOffset[] = "startOffset"; + static const char aSVGStrMethod[] = "method"; + static const char aSVGStrSpacing[] = "spacing"; + static const char aSVGStrTextAlign[] = "text-align"; + static const char aSVGStrPathLength[] = "pathLength"; + static const char aSVGStrType[] = "type"; + static const char aSVGStrClass[] = "class"; + static const char aSVGStrTextAnchor[] = "text-anchor"; + static const char aSVGStrXmlSpace[] = "xml:space"; + static const char aSVGStrColor[] = "color"; + static const char aSVGStrClipPathNode[] = "clipPath"; + static const char aSVGStrClipPathProperty[] = "clip-path"; + static const char aSVGStrMask[] = "mask"; + static const char aSVGStrClipPathUnits[] = "clipPathUnits"; + static const char aSVGStrMaskUnits[] = "maskUnits"; + static const char aSVGStrMaskContentUnits[] = "maskContentUnits"; + static const char aSVGStrClipRule[] = "clip-rule"; + static const char aSVGStrMarker[] = "marker"; + static const char aSVGStrMarkerStart[] = "marker-start"; + static const char aSVGStrMarkerMid[] = "marker-mid"; + static const char aSVGStrMarkerEnd[] = "marker-end"; + static const char aSVGStrRefX[] = "refX"; + static const char aSVGStrRefY[] = "refY"; + static const char aSVGStrMarkerUnits[] = "markerUnits"; + static const char aSVGStrMarkerWidth[] = "markerWidth"; + static const char aSVGStrMarkerHeight[] = "markerHeight"; + static const char aSVGStrOrient[] = "orient"; + static const char aSVGStrPattern[] = "pattern"; + static const char aSVGStrPatternUnits[] = "patternUnits"; + static const char aSVGStrPatternContentUnits[] = "patternContentUnits"; + static const char aSVGStrPatternTransform[] = "patternTransform"; + static const char aSVGStrOpacity[] = "opacity"; + static const char aSVGStrVisibility[] = "visibility"; + static const char aSVGStrTitle[] = "title"; + static const char aSVGStrDesc[] = "desc"; + + static const char aSVGStrPreserveAspectRatio[] = "preserveAspectRatio"; + static const char aSVGStrDefer[] = "defer"; + static const char aSVGStrNone[] = "none"; + static const char aSVGStrXMinYMin[] = "xMinYMin"; + static const char aSVGStrXMidYMin[] = "xMidYMin"; + static const char aSVGStrXMaxYMin[] = "xMaxYMin"; + static const char aSVGStrXMinYMid[] = "xMinYMid"; + static const char aSVGStrXMidYMid[] = "xMidYMid"; + static const char aSVGStrXMaxYMid[] = "xMaxYMid"; + static const char aSVGStrXMinYMax[] = "xMinYMax"; + static const char aSVGStrXMidYMax[] = "xMidYMax"; + static const char aSVGStrXMaxYMax[] = "xMaxYMax"; + static const char aSVGStrMeet[] = "meet"; + static const char aSVGStrSlice[] = "slice"; + + static const char aSVGStrDefs[] = "defs"; + static const char aSVGStrG[] = "g"; + static const char aSVGStrSvg[] = "svg"; + static const char aSVGStrSymbol[] = "symbol"; + static const char aSVGStrUse[] = "use"; + static const char aSVGStrA[] = "a"; + + static const char aSVGStrCircle[] = "circle"; + static const char aSVGStrEllipse[] = "ellipse"; + static const char aSVGStrLine[] = "line"; + static const char aSVGStrPath[] = "path"; + static const char aSVGStrPolygon[] = "polygon"; + static const char aSVGStrPolyline[] = "polyline"; + static const char aSVGStrRect[] = "rect"; + static const char aSVGStrImage[] = "image"; + + static const char aSVGStrLinearGradient[] = "linearGradient"; + static const char aSVGStrRadialGradient[] = "radialGradient"; + static const char aSVGStrStop[] = "stop"; + static const char aSVGStrOffset[] = "offset"; + static const char aSVGStrX1[] = "x1"; + static const char aSVGStrY1[] = "y1"; + static const char aSVGStrX2[] = "x2"; + static const char aSVGStrY2[] = "y2"; + static const char aSVGStrCx[] = "cx"; + static const char aSVGStrCy[] = "cy"; + static const char aSVGStrFx[] = "fx"; + static const char aSVGStrFy[] = "fy"; + static const char aSVGStrR[] = "r"; + static const char aSVGStrGradientUnits[] = "gradientUnits"; + static const char aSVGStrGradientTransform[] = "gradientTransform"; + static const char aSVGStrSpreadMethod[] = "spreadMethod"; + static const char aSVGStrXlinkHref[] = "xlink:href"; + static const char aSVGStrStopColor[] = "stop-color"; + static const char aSVGStrStopOpacity[] = "stop-opacity"; + + static const char aSVGStrFill[] = "fill"; + static const char aSVGStrFillOpacity[] = "fill-opacity"; + static const char aSVGStrFillRule[] = "fill-rule"; + + static const char aSVGStrStroke[] = "stroke"; + static const char aSVGStrStrokeDasharray[] = "stroke-dasharray"; + static const char aSVGStrStrokeDashoffset[] = "stroke-dashoffset"; + static const char aSVGStrStrokeLinecap[] = "stroke-linecap"; + static const char aSVGStrStrokeLinejoin[] = "stroke-linejoin"; + static const char aSVGStrStrokeMiterlimit[] = "stroke-miterlimit"; + static const char aSVGStrStrokeOpacity[] = "stroke-opacity"; + static const char aSVGStrStrokeWidth[] = "stroke-width"; + + static const char aSVGStrText[] = "text"; + static const char aSVGStrBaselineShift[] = "baseline-shift"; + + static const char aSVGStrFlowRoot[] = "flowRoot"; + + SVGToken StrToSVGToken(const OUString& rStr, bool bCaseIndependent) + { + typedef std::unordered_map< OUString, SVGToken > SVGTokenMapper; + typedef std::pair< OUString, SVGToken > SVGTokenValueType; + static SVGTokenMapper aSVGTokenMapperList { + { aSVGStrWidth, SVGTokenWidth }, + { aSVGStrHeight, SVGTokenHeight }, + { aSVGStrViewBox, SVGTokenViewBox }, + { aSVGStrTransform, SVGTokenTransform }, + { aSVGStrStyle, SVGTokenStyle }, + { aSVGStrDisplay, SVGTokenDisplay }, // #i121656# + { aSVGStrD, SVGTokenD }, + { aSVGStrX, SVGTokenX }, + { aSVGStrY, SVGTokenY }, + { aSVGStrXmlns, SVGTokenXmlns }, + { aSVGStrVersion, SVGTokenVersion }, + { aSVGStrId, SVGTokenId }, + { aSVGStrRx, SVGTokenRx }, + { aSVGStrRy, SVGTokenRy }, + { aSVGStrPoints, SVGTokenPoints }, + { aSVGStrDx, SVGTokenDx }, + { aSVGStrDy, SVGTokenDy }, + { aSVGStrRotate, SVGTokenRotate }, + { aSVGStrTextLength, SVGTokenTextLength }, + { aSVGStrLengthAdjust, SVGTokenLengthAdjust }, + { aSVGStrFont, SVGTokenFont }, + { aSVGStrFontFamily, SVGTokenFontFamily }, + { aSVGStrFontSize, SVGTokenFontSize }, + { aSVGStrFontSizeAdjust, SVGTokenFontSizeAdjust }, + { aSVGStrFontStretch, SVGTokenFontStretch }, + { aSVGStrFontStyle, SVGTokenFontStyle }, + { aSVGStrFontVariant, SVGTokenFontVariant }, + { aSVGStrFontWeight, SVGTokenFontWeight }, + { aSVGStrDirection, SVGTokenDirection }, + { aSVGStrLetterSpacing, SVGTokenLetterSpacing }, + { aSVGStrTextDecoration, SVGTokenTextDecoration }, + { aSVGStrUnicodeBidi, SVGTokenUnicodeBidi }, + { aSVGStrWordSpacing, SVGTokenWordSpacing }, + { aSVGStrTspan, SVGTokenTspan }, + { aSVGStrTref, SVGTokenTref }, + { aSVGStrTextPath, SVGTokenTextPath }, + { aSVGStrStartOffset, SVGTokenStartOffset }, + { aSVGStrMethod, SVGTokenMethod }, + { aSVGStrSpacing, SVGTokenSpacing }, + { aSVGStrTextAlign, SVGTokenTextAlign }, + { aSVGStrPathLength, SVGTokenPathLength }, + { aSVGStrType, SVGTokenType }, + { aSVGStrClass, SVGTokenClass }, + { aSVGStrTextAnchor, SVGTokenTextAnchor }, + { aSVGStrXmlSpace, SVGTokenXmlSpace }, + { aSVGStrColor, SVGTokenColor }, + { aSVGStrClipPathNode, SVGTokenClipPathNode }, + { aSVGStrClipPathProperty, SVGTokenClipPathProperty }, + { aSVGStrMask, SVGTokenMask }, + { aSVGStrClipPathUnits, SVGTokenClipPathUnits }, + { aSVGStrMaskUnits, SVGTokenMaskUnits }, + { aSVGStrMaskContentUnits, SVGTokenMaskContentUnits }, + { aSVGStrClipRule, SVGTokenClipRule }, + { aSVGStrMarker, SVGTokenMarker }, + { aSVGStrMarkerStart, SVGTokenMarkerStart }, + { aSVGStrMarkerMid, SVGTokenMarkerMid }, + { aSVGStrMarkerEnd, SVGTokenMarkerEnd }, + { aSVGStrRefX, SVGTokenRefX }, + { aSVGStrRefY, SVGTokenRefY }, + { aSVGStrMarkerUnits, SVGTokenMarkerUnits }, + { aSVGStrMarkerWidth, SVGTokenMarkerWidth }, + { aSVGStrMarkerHeight, SVGTokenMarkerHeight }, + { aSVGStrOrient, SVGTokenOrient }, + { aSVGStrPattern, SVGTokenPattern }, + { aSVGStrPatternUnits, SVGTokenPatternUnits }, + { aSVGStrPatternContentUnits, SVGTokenPatternContentUnits }, + { aSVGStrPatternTransform, SVGTokenPatternTransform }, + { aSVGStrOpacity, SVGTokenOpacity }, + { aSVGStrVisibility, SVGTokenVisibility }, + { aSVGStrTitle, SVGTokenTitle }, + { aSVGStrDesc, SVGTokenDesc }, + + { aSVGStrPreserveAspectRatio, SVGTokenPreserveAspectRatio }, + { aSVGStrDefer, SVGTokenDefer }, + { aSVGStrNone, SVGTokenNone }, + { aSVGStrXMinYMin, SVGTokenXMinYMin }, + { aSVGStrXMidYMin, SVGTokenXMidYMin }, + { aSVGStrXMaxYMin, SVGTokenXMaxYMin }, + { aSVGStrXMinYMid, SVGTokenXMinYMid }, + { aSVGStrXMidYMid, SVGTokenXMidYMid }, + { aSVGStrXMaxYMid, SVGTokenXMaxYMid }, + { aSVGStrXMinYMax, SVGTokenXMinYMax }, + { aSVGStrXMidYMax, SVGTokenXMidYMax }, + { aSVGStrXMaxYMax, SVGTokenXMaxYMax }, + { aSVGStrMeet, SVGTokenMeet }, + { aSVGStrSlice, SVGTokenSlice }, + + { aSVGStrDefs, SVGTokenDefs }, + { aSVGStrG, SVGTokenG }, + { aSVGStrSvg, SVGTokenSvg }, + { aSVGStrSymbol, SVGTokenSymbol }, + { aSVGStrUse, SVGTokenUse }, + { aSVGStrA, SVGTokenA }, + + { aSVGStrCircle, SVGTokenCircle }, + { aSVGStrEllipse, SVGTokenEllipse }, + { aSVGStrLine, SVGTokenLine }, + { aSVGStrPath, SVGTokenPath }, + { aSVGStrPolygon, SVGTokenPolygon }, + { aSVGStrPolyline, SVGTokenPolyline }, + { aSVGStrRect, SVGTokenRect }, + { aSVGStrImage, SVGTokenImage }, + + { aSVGStrLinearGradient, SVGTokenLinearGradient }, + { aSVGStrRadialGradient, SVGTokenRadialGradient }, + { aSVGStrStop, SVGTokenStop }, + { aSVGStrOffset, SVGTokenOffset }, + { aSVGStrX1, SVGTokenX1 }, + { aSVGStrY1, SVGTokenY1 }, + { aSVGStrX2, SVGTokenX2 }, + { aSVGStrY2, SVGTokenY2 }, + { aSVGStrCx, SVGTokenCx }, + { aSVGStrCy, SVGTokenCy }, + { aSVGStrFx, SVGTokenFx }, + { aSVGStrFy, SVGTokenFy }, + { aSVGStrR, SVGTokenR }, + { aSVGStrGradientUnits, SVGTokenGradientUnits }, + { aSVGStrGradientTransform, SVGTokenGradientTransform }, + { aSVGStrSpreadMethod, SVGTokenSpreadMethod }, + { aSVGStrXlinkHref, SVGTokenXlinkHref }, + { aSVGStrStopColor, SVGTokenStopColor }, + { aSVGStrStopOpacity, SVGTokenStopOpacity }, + + { aSVGStrFill, SVGTokenFill }, + { aSVGStrFillOpacity, SVGTokenFillOpacity }, + { aSVGStrFillRule, SVGTokenFillRule }, + + { aSVGStrStroke, SVGTokenStroke }, + { aSVGStrStrokeDasharray, SVGTokenStrokeDasharray }, + { aSVGStrStrokeDashoffset, SVGTokenStrokeDashoffset }, + { aSVGStrStrokeLinecap, SVGTokenStrokeLinecap }, + { aSVGStrStrokeLinejoin, SVGTokenStrokeLinejoin }, + { aSVGStrStrokeMiterlimit, SVGTokenStrokeMiterlimit }, + { aSVGStrStrokeOpacity, SVGTokenStrokeOpacity }, + { aSVGStrStrokeWidth, SVGTokenStrokeWidth }, + + { aSVGStrText, SVGTokenText }, + { aSVGStrBaselineShift, SVGTokenBaselineShift }, + { aSVGStrFlowRoot, SVGTokenFlowRoot } + }; + + const SVGTokenMapper::const_iterator aResult(aSVGTokenMapperList.find(rStr.startsWith("svg:") ? rStr.copy(4) : rStr)); + + if(aResult == aSVGTokenMapperList.end()) + { + if(bCaseIndependent) + { + static SVGTokenMapper aCaseLindependentSVGTokenMapperList; + + if(aCaseLindependentSVGTokenMapperList.empty()) + { + for(const auto& rCurrent : aSVGTokenMapperList) + { + aCaseLindependentSVGTokenMapperList.insert( + SVGTokenValueType( + rCurrent.first.toAsciiLowerCase(), + rCurrent.second)); + } + } + + const SVGTokenMapper::const_iterator aResult2(aCaseLindependentSVGTokenMapperList.find(rStr.toAsciiLowerCase())); + + if(aResult2 == aCaseLindependentSVGTokenMapperList.end()) + { + return SVGTokenUnknown; + } + else + { + return aResult2->second; + } + } + + return SVGTokenUnknown; + } + else + { + return aResult->second; + } + } + + OUString getStrTitle() + { + return aSVGStrTitle; + } + + OUString getStrDesc() + { + return aSVGStrDesc; + } +} // end of namespace svgio + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtools.cxx b/svgio/source/svgreader/svgtools.cxx new file mode 100644 index 000000000..0c628511d --- /dev/null +++ b/svgio/source/svgreader/svgtools.cxx @@ -0,0 +1,1691 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtools.hxx> +#include <sal/log.hxx> +#include <osl/diagnose.h> +#include <tools/color.hxx> +#include <rtl/math.hxx> +#include <basegfx/matrix/b2dhommatrix.hxx> +#include <basegfx/matrix/b2dhommatrixtools.hxx> +#include <svgtoken.hxx> +#include <unordered_map> + +namespace svgio::svgreader +{ + // common non-token strings + const OUString commonStrings::aStrUserSpaceOnUse("userSpaceOnUse"); + const OUString commonStrings::aStrObjectBoundingBox("objectBoundingBox"); + const OUString commonStrings::aStrNonzero("nonzero"); + const OUString commonStrings::aStrEvenOdd("evenodd"); + + basegfx::B2DHomMatrix SvgAspectRatio::createLinearMapping(const basegfx::B2DRange& rTarget, const basegfx::B2DRange& rSource) + { + basegfx::B2DHomMatrix aRetval; + const double fSWidth(rSource.getWidth()); + const double fSHeight(rSource.getHeight()); + const bool bNoSWidth(basegfx::fTools::equalZero(fSWidth)); + const bool bNoSHeight(basegfx::fTools::equalZero(fSHeight)); + + // transform from source state to unit range + aRetval.translate(-rSource.getMinX(), -rSource.getMinY()); + aRetval.scale( + (bNoSWidth ? 1.0 : 1.0 / fSWidth) * rTarget.getWidth(), + (bNoSHeight ? 1.0 : 1.0 / fSHeight) * rTarget.getHeight()); + + // transform from unit rage to target range + aRetval.translate(rTarget.getMinX(), rTarget.getMinY()); + + return aRetval; + } + + basegfx::B2DHomMatrix SvgAspectRatio::createMapping(const basegfx::B2DRange& rTarget, const basegfx::B2DRange& rSource) const + { + // removed !isSet() from below. Due to correct defaults in the constructor an instance + // of this class is perfectly useful without being set by any importer + if(Align_none == getSvgAlign()) + { + // create linear mapping (default) + return createLinearMapping(rTarget, rSource); + } + + basegfx::B2DHomMatrix aRetval; + + const double fSWidth(rSource.getWidth()); + const double fSHeight(rSource.getHeight()); + const bool bNoSWidth(basegfx::fTools::equalZero(fSWidth)); + const bool bNoSHeight(basegfx::fTools::equalZero(fSHeight)); + const double fScaleX((bNoSWidth ? 1.0 : 1.0 / fSWidth) * rTarget.getWidth()); + const double fScaleY((bNoSHeight ? 1.0 : 1.0 / fSHeight) * rTarget.getHeight()); + const double fScale(isMeetOrSlice() ? std::min(fScaleX, fScaleY) : std::max(fScaleX, fScaleY)); + + // remove source translation, apply scale + aRetval.translate(-rSource.getMinX(), -rSource.getMinY()); + aRetval.scale(fScale, fScale); + + // evaluate horizontal alignment + const double fNewWidth(fSWidth * fScale); + double fTransX(0.0); + + switch(getSvgAlign()) + { + case Align_xMidYMin: + case Align_xMidYMid: + case Align_xMidYMax: + { + // centerX + const double fFreeSpace(rTarget.getWidth() - fNewWidth); + fTransX = fFreeSpace * 0.5; + break; + } + case Align_xMaxYMin: + case Align_xMaxYMid: + case Align_xMaxYMax: + { + // Right align + const double fFreeSpace(rTarget.getWidth() - fNewWidth); + fTransX = fFreeSpace; + break; + } + default: break; + } + + // evaluate vertical alignment + const double fNewHeight(fSHeight * fScale); + double fTransY(0.0); + + switch(getSvgAlign()) + { + case Align_xMinYMid: + case Align_xMidYMid: + case Align_xMaxYMid: + { + // centerY + const double fFreeSpace(rTarget.getHeight() - fNewHeight); + fTransY = fFreeSpace * 0.5; + break; + } + case Align_xMinYMax: + case Align_xMidYMax: + case Align_xMaxYMax: + { + // Bottom align + const double fFreeSpace(rTarget.getHeight() - fNewHeight); + fTransY = fFreeSpace; + break; + } + default: break; + } + + // add target translation + aRetval.translate( + rTarget.getMinX() + fTransX, + rTarget.getMinY() + fTransY); + + return aRetval; + } + + double SvgNumber::solveNonPercentage(const InfoProvider& rInfoProvider) const + { + if(isSet()) + { + switch(meUnit) + { + case Unit_em: + { + return mfNumber * rInfoProvider.getCurrentFontSizeInherited(); + } + case Unit_ex: + { + return mfNumber * rInfoProvider.getCurrentXHeightInherited() * 0.5; + } + case Unit_px: + { + return mfNumber; + } + case Unit_pt: + case Unit_pc: + case Unit_cm: + case Unit_mm: + case Unit_in: + { + double fRetval(mfNumber); + + switch(meUnit) + { + case Unit_pt: fRetval *= F_SVG_PIXEL_PER_INCH / 72.0; break; + case Unit_pc: fRetval *= F_SVG_PIXEL_PER_INCH / 6.0; break; + case Unit_cm: fRetval *= F_SVG_PIXEL_PER_INCH / 2.54; break; + case Unit_mm: fRetval *= 0.1 * F_SVG_PIXEL_PER_INCH / 2.54; break; + case Unit_in: fRetval *= F_SVG_PIXEL_PER_INCH; break; + default: break; + } + + return fRetval; + } + case Unit_none: + { + SAL_WARN("svgio", "Design error, this case should have been handled in the caller"); + return mfNumber; + } + default: + { + OSL_ENSURE(false, "Do not use with percentage! "); + return 0.0; + } + } + } + + /// not set + OSL_ENSURE(false, "SvgNumber not set (!)"); + return 0.0; + } + + double SvgNumber::solve(const InfoProvider& rInfoProvider, NumberType aNumberType) const + { + if(isSet()) + { + switch(meUnit) + { + case Unit_px: + { + return mfNumber; + } + case Unit_pt: + case Unit_pc: + case Unit_cm: + case Unit_mm: + case Unit_in: + case Unit_em: + case Unit_ex: + case Unit_none: + { + return solveNonPercentage( rInfoProvider); + } + case Unit_percent: + { + double fRetval(mfNumber * 0.01); + basegfx::B2DRange aViewPort = rInfoProvider.getCurrentViewPort(); + + if ( aViewPort.isEmpty() ) + { + SAL_WARN("svgio", "Design error, this case should have been handled in the caller"); + // no viewPort, assume a normal page size (A4) + aViewPort = basegfx::B2DRange( + 0.0, + 0.0, + 210.0 * F_SVG_PIXEL_PER_INCH / 2.54, + 297.0 * F_SVG_PIXEL_PER_INCH / 2.54); + + } + + if ( !aViewPort.isEmpty() ) + { + if(xcoordinate == aNumberType) + { + // it's a x-coordinate, relative to current width (w) + fRetval *= aViewPort.getWidth(); + } + else if(ycoordinate == aNumberType) + { + // it's a y-coordinate, relative to current height (h) + fRetval *= aViewPort.getHeight(); + } + else // length + { + // it's a length, relative to sqrt(w*w + h*h)/sqrt(2) + const double fCurrentWidth(aViewPort.getWidth()); + const double fCurrentHeight(aViewPort.getHeight()); + const double fCurrentLength( + sqrt(fCurrentWidth * fCurrentWidth + fCurrentHeight * fCurrentHeight)/sqrt(2.0)); + + fRetval *= fCurrentLength; + } + } + + return fRetval; + } + default: + { + break; + } + } + } + + /// not set + OSL_ENSURE(false, "SvgNumber not set (!)"); + return 0.0; + } + + bool SvgNumber::isPositive() const + { + return basegfx::fTools::moreOrEqual(mfNumber, 0.0); + } + + void skip_char(const OUString& rCandidate, sal_Unicode nChar, sal_Int32& nPos, const sal_Int32 nLen) + { + while(nPos < nLen && nChar == rCandidate[nPos]) + { + nPos++; + } + } + + void skip_char(const OUString& rCandidate, sal_Unicode nCharA, sal_Unicode nCharB, sal_Int32& nPos, const sal_Int32 nLen) + { + while(nPos < nLen && (nCharA == rCandidate[nPos] || nCharB == rCandidate[nPos])) + { + nPos++; + } + } + + void copySign(const OUString& rCandidate, sal_Int32& nPos, OUStringBuffer& rTarget, const sal_Int32 nLen) + { + if(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + if('+' == aChar || '-' == aChar) + { + rTarget.append(aChar); + nPos++; + } + } + } + + void copyNumber(const OUString& rCandidate, sal_Int32& nPos, OUStringBuffer& rTarget, const sal_Int32 nLen) + { + bool bOnNumber(true); + + while(bOnNumber && nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + bOnNumber = ('0' <= aChar && '9' >= aChar) || '.' == aChar; + + if(bOnNumber) + { + rTarget.append(aChar); + nPos++; + } + } + } + + void copyHex(const OUString& rCandidate, sal_Int32& nPos, OUStringBuffer& rTarget, const sal_Int32 nLen) + { + bool bOnHex(true); + + while(bOnHex && nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + bOnHex = ('0' <= aChar && '9' >= aChar) + || ('A' <= aChar && 'F' >= aChar) + || ('a' <= aChar && 'f' >= aChar); + + if(bOnHex) + { + rTarget.append(aChar); + nPos++; + } + } + } + + void copyString(const OUString& rCandidate, sal_Int32& nPos, OUStringBuffer& rTarget, const sal_Int32 nLen) + { + bool bOnChar(true); + + while(bOnChar && nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + bOnChar = ('a' <= aChar && 'z' >= aChar) + || ('A' <= aChar && 'Z' >= aChar) + || '-' == aChar; + + if(bOnChar) + { + rTarget.append(aChar); + nPos++; + } + } + } + + void copyToLimiter(const OUString& rCandidate, sal_Unicode nLimiter, sal_Int32& nPos, OUStringBuffer& rTarget, const sal_Int32 nLen) + { + while(nPos < nLen && nLimiter != rCandidate[nPos]) + { + rTarget.append(rCandidate[nPos]); + nPos++; + } + } + + bool readNumber(const OUString& rCandidate, sal_Int32& nPos, double& fNum, const sal_Int32 nLen) + { + if(nPos < nLen) + { + OUStringBuffer aNum; + + copySign(rCandidate, nPos, aNum, nLen); + copyNumber(rCandidate, nPos, aNum, nLen); + + if(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + if('e' == aChar || 'E' == aChar) + { + // try to read exponential number, but be careful. I had + // a case where dx="2em" was used, thus the 'e' was consumed + // by error. First try if there are numbers after the 'e', + // safe current state + nPos++; + const OUStringBuffer aNum2(aNum); + const sal_Int32 nPosAfterE(nPos); + + aNum.append(aChar); + copySign(rCandidate, nPos, aNum, nLen); + copyNumber(rCandidate, nPos, aNum, nLen); + + if(nPosAfterE == nPos) + { + // no number after 'e', go back. Do not + // return false, it's still a valid integer number + aNum = aNum2; + nPos--; + } + } + } + + if(!aNum.isEmpty()) + { + rtl_math_ConversionStatus eStatus; + + fNum = rtl::math::stringToDouble( + aNum.makeStringAndClear(), '.', ',', + &eStatus); + + return eStatus == rtl_math_ConversionStatus_Ok; + } + } + + return false; + } + + SvgUnit readUnit(const OUString& rCandidate, sal_Int32& nPos, const sal_Int32 nLen) + { + SvgUnit aRetval(Unit_px); + + if(nPos < nLen) + { + const sal_Unicode aCharA(rCandidate[nPos]); + + if(nPos + 1 < nLen) + { + const sal_Unicode aCharB(rCandidate[nPos + 1]); + bool bTwoCharValid(false); + + switch(aCharA) + { + case u'e' : + { + if('m' == aCharB) + { + // 'em' Relative to current font size + aRetval = Unit_em; + bTwoCharValid = true; + } + else if('x' == aCharB) + { + // 'ex' Relative to current font x-height + aRetval = Unit_ex; + bTwoCharValid = true; + } + break; + } + case u'p' : + { + if('x' == aCharB) + { + // 'px' UserUnit (default) + bTwoCharValid = true; + } + else if('t' == aCharB) + { + // 'pt' == 4/3 px + aRetval = Unit_pt; + bTwoCharValid = true; + } + else if('c' == aCharB) + { + // 'pc' == 16 px + aRetval = Unit_pc; + bTwoCharValid = true; + } + break; + } + case u'i' : + { + if('n' == aCharB) + { + // 'in' == 96 px, since CSS 2.1 + aRetval = Unit_in; + bTwoCharValid = true; + } + break; + } + case u'c' : + { + if('m' == aCharB) + { + // 'cm' == 37.79527559 px + aRetval = Unit_cm; + bTwoCharValid = true; + } + break; + } + case u'm' : + { + if('m' == aCharB) + { + // 'mm' == 3.779528 px + aRetval = Unit_mm; + bTwoCharValid = true; + } + break; + } + } + + if(bTwoCharValid) + { + nPos += 2; + } + } + else + { + if('%' == aCharA) + { + // percent used, relative to current + nPos++; + aRetval = Unit_percent; + } + } + } + + return aRetval; + } + + bool readNumberAndUnit(const OUString& rCandidate, sal_Int32& nPos, SvgNumber& aNum, const sal_Int32 nLen) + { + double fNum(0.0); + + if(readNumber(rCandidate, nPos, fNum, nLen)) + { + skip_char(rCandidate, ' ', nPos, nLen); + aNum = SvgNumber(fNum, readUnit(rCandidate, nPos, nLen)); + + return true; + } + + return false; + } + + bool readAngle(const OUString& rCandidate, sal_Int32& nPos, double& fAngle, const sal_Int32 nLen) + { + if(readNumber(rCandidate, nPos, fAngle, nLen)) + { + skip_char(rCandidate, ' ', nPos, nLen); + + enum DegreeType + { + deg, + grad, + rad + } aType(deg); // degrees is default + + if(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + static const char aStrGrad[] = "grad"; + static const char aStrRad[] = "rad"; + + switch(aChar) + { + case u'g' : + case u'G' : + { + if(rCandidate.matchIgnoreAsciiCase(aStrGrad, nPos)) + { + // angle in grad + nPos += strlen(aStrGrad); + aType = grad; + } + break; + } + case u'r' : + case u'R' : + { + if(rCandidate.matchIgnoreAsciiCase(aStrRad, nPos)) + { + // angle in radians + nPos += strlen(aStrRad); + aType = rad; + } + break; + } + } + } + + // convert to radians + if(deg == aType) + { + fAngle = basegfx::deg2rad(fAngle); + } + else if(grad == aType) + { + // looks like 100 grad is 90 degrees + fAngle *= F_PI / 200.0; + } + + return true; + } + + return false; + } + + sal_Int32 read_hex(sal_Unicode nChar) + { + if(nChar >= '0' && nChar <= '9') + { + return nChar - u'0'; + } + else if(nChar >= 'A' && nChar <= 'F') + { + return 10 + sal_Int32(nChar - u'A'); + } + else if(nChar >= 'a' && nChar <= 'f') + { + return 10 + sal_Int32(nChar - u'a'); + } + else + { + // error + return 0; + } + } + + bool match_colorKeyword(basegfx::BColor& rColor, const OUString& rName, bool bCaseIndependent) + { + typedef std::unordered_map< OUString, Color > ColorTokenMapper; + typedef std::pair< OUString, Color > ColorTokenValueType; + static const ColorTokenMapper aColorTokenMapperList { + { ColorTokenValueType(OUString("aliceblue"), Color(240, 248, 255)) }, + { ColorTokenValueType(OUString("antiquewhite"), Color(250, 235, 215) ) }, + { ColorTokenValueType(OUString("aqua"), Color( 0, 255, 255) ) }, + { ColorTokenValueType(OUString("aquamarine"), Color(127, 255, 212) ) }, + { ColorTokenValueType(OUString("azure"), Color(240, 255, 255) ) }, + { ColorTokenValueType(OUString("beige"), Color(245, 245, 220) ) }, + { ColorTokenValueType(OUString("bisque"), Color(255, 228, 196) ) }, + { ColorTokenValueType(OUString("black"), Color( 0, 0, 0) ) }, + { ColorTokenValueType(OUString("blanchedalmond"), Color(255, 235, 205) ) }, + { ColorTokenValueType(OUString("blue"), Color( 0, 0, 255) ) }, + { ColorTokenValueType(OUString("blueviolet"), Color(138, 43, 226) ) }, + { ColorTokenValueType(OUString("brown"), Color(165, 42, 42) ) }, + { ColorTokenValueType(OUString("burlywood"), Color(222, 184, 135) ) }, + { ColorTokenValueType(OUString("cadetblue"), Color( 95, 158, 160) ) }, + { ColorTokenValueType(OUString("chartreuse"), Color(127, 255, 0) ) }, + { ColorTokenValueType(OUString("chocolate"), Color(210, 105, 30) ) }, + { ColorTokenValueType(OUString("coral"), Color(255, 127, 80) ) }, + { ColorTokenValueType(OUString("cornflowerblue"), Color(100, 149, 237) ) }, + { ColorTokenValueType(OUString("cornsilk"), Color(255, 248, 220) ) }, + { ColorTokenValueType(OUString("crimson"), Color(220, 20, 60) ) }, + { ColorTokenValueType(OUString("cyan"), Color( 0, 255, 255) ) }, + { ColorTokenValueType(OUString("darkblue"), Color( 0, 0, 139) ) }, + { ColorTokenValueType(OUString("darkcyan"), Color( 0, 139, 139) ) }, + { ColorTokenValueType(OUString("darkgoldenrod"), Color(184, 134, 11) ) }, + { ColorTokenValueType(OUString("darkgray"), Color(169, 169, 169) ) }, + { ColorTokenValueType(OUString("darkgreen"), Color( 0, 100, 0) ) }, + { ColorTokenValueType(OUString("darkgrey"), Color(169, 169, 169) ) }, + { ColorTokenValueType(OUString("darkkhaki"), Color(189, 183, 107) ) }, + { ColorTokenValueType(OUString("darkmagenta"), Color(139, 0, 139) ) }, + { ColorTokenValueType(OUString("darkolivegreen"), Color( 85, 107, 47) ) }, + { ColorTokenValueType(OUString("darkorange"), Color(255, 140, 0) ) }, + { ColorTokenValueType(OUString("darkorchid"), Color(153, 50, 204) ) }, + { ColorTokenValueType(OUString("darkred"), Color(139, 0, 0) ) }, + { ColorTokenValueType(OUString("darksalmon"), Color(233, 150, 122) ) }, + { ColorTokenValueType(OUString("darkseagreen"), Color(143, 188, 143) ) }, + { ColorTokenValueType(OUString("darkslateblue"), Color( 72, 61, 139) ) }, + { ColorTokenValueType(OUString("darkslategray"), Color( 47, 79, 79) ) }, + { ColorTokenValueType(OUString("darkslategrey"), Color( 47, 79, 79) ) }, + { ColorTokenValueType(OUString("darkturquoise"), Color( 0, 206, 209) ) }, + { ColorTokenValueType(OUString("darkviolet"), Color(148, 0, 211) ) }, + { ColorTokenValueType(OUString("deeppink"), Color(255, 20, 147) ) }, + { ColorTokenValueType(OUString("deepskyblue"), Color( 0, 191, 255) ) }, + { ColorTokenValueType(OUString("dimgray"), Color(105, 105, 105) ) }, + { ColorTokenValueType(OUString("dimgrey"), Color(105, 105, 105) ) }, + { ColorTokenValueType(OUString("dodgerblue"), Color( 30, 144, 255) ) }, + { ColorTokenValueType(OUString("firebrick"), Color(178, 34, 34) ) }, + { ColorTokenValueType(OUString("floralwhite"), Color(255, 250, 240) ) }, + { ColorTokenValueType(OUString("forestgreen"), Color( 34, 139, 34) ) }, + { ColorTokenValueType(OUString("fuchsia"), Color(255, 0, 255) ) }, + { ColorTokenValueType(OUString("gainsboro"), Color(220, 220, 220) ) }, + { ColorTokenValueType(OUString("ghostwhite"), Color(248, 248, 255) ) }, + { ColorTokenValueType(OUString("gold"), Color(255, 215, 0) ) }, + { ColorTokenValueType(OUString("goldenrod"), Color(218, 165, 32) ) }, + { ColorTokenValueType(OUString("gray"), Color(128, 128, 128) ) }, + { ColorTokenValueType(OUString("grey"), Color(128, 128, 128) ) }, + { ColorTokenValueType(OUString("green"), Color(0, 128, 0) ) }, + { ColorTokenValueType(OUString("greenyellow"), Color(173, 255, 47) ) }, + { ColorTokenValueType(OUString("honeydew"), Color(240, 255, 240) ) }, + { ColorTokenValueType(OUString("hotpink"), Color(255, 105, 180) ) }, + { ColorTokenValueType(OUString("indianred"), Color(205, 92, 92) ) }, + { ColorTokenValueType(OUString("indigo"), Color( 75, 0, 130) ) }, + { ColorTokenValueType(OUString("ivory"), Color(255, 255, 240) ) }, + { ColorTokenValueType(OUString("khaki"), Color(240, 230, 140) ) }, + { ColorTokenValueType(OUString("lavender"), Color(230, 230, 250) ) }, + { ColorTokenValueType(OUString("lavenderblush"), Color(255, 240, 245) ) }, + { ColorTokenValueType(OUString("lawngreen"), Color(124, 252, 0) ) }, + { ColorTokenValueType(OUString("lemonchiffon"), Color(255, 250, 205) ) }, + { ColorTokenValueType(OUString("lightblue"), Color(173, 216, 230) ) }, + { ColorTokenValueType(OUString("lightcoral"), Color(240, 128, 128) ) }, + { ColorTokenValueType(OUString("lightcyan"), Color(224, 255, 255) ) }, + { ColorTokenValueType(OUString("lightgoldenrodyellow"), Color(250, 250, 210) ) }, + { ColorTokenValueType(OUString("lightgray"), Color(211, 211, 211) ) }, + { ColorTokenValueType(OUString("lightgreen"), Color(144, 238, 144) ) }, + { ColorTokenValueType(OUString("lightgrey"), Color(211, 211, 211) ) }, + { ColorTokenValueType(OUString("lightpink"), Color(255, 182, 193) ) }, + { ColorTokenValueType(OUString("lightsalmon"), Color(255, 160, 122) ) }, + { ColorTokenValueType(OUString("lightseagreen"), Color( 32, 178, 170) ) }, + { ColorTokenValueType(OUString("lightskyblue"), Color(135, 206, 250) ) }, + { ColorTokenValueType(OUString("lightslategray"), Color(119, 136, 153) ) }, + { ColorTokenValueType(OUString("lightslategrey"), Color(119, 136, 153) ) }, + { ColorTokenValueType(OUString("lightsteelblue"), Color(176, 196, 222) ) }, + { ColorTokenValueType(OUString("lightyellow"), Color(255, 255, 224) ) }, + { ColorTokenValueType(OUString("lime"), Color( 0, 255, 0) ) }, + { ColorTokenValueType(OUString("limegreen"), Color( 50, 205, 50) ) }, + { ColorTokenValueType(OUString("linen"), Color(250, 240, 230) ) }, + { ColorTokenValueType(OUString("magenta"), Color(255, 0, 255) ) }, + { ColorTokenValueType(OUString("maroon"), Color(128, 0, 0) ) }, + { ColorTokenValueType(OUString("mediumaquamarine"), Color(102, 205, 170) ) }, + { ColorTokenValueType(OUString("mediumblue"), Color( 0, 0, 205) ) }, + { ColorTokenValueType(OUString("mediumorchid"), Color(186, 85, 211) ) }, + { ColorTokenValueType(OUString("mediumpurple"), Color(147, 112, 219) ) }, + { ColorTokenValueType(OUString("mediumseagreen"), Color( 60, 179, 113) ) }, + { ColorTokenValueType(OUString("mediumslateblue"), Color(123, 104, 238) ) }, + { ColorTokenValueType(OUString("mediumspringgreen"), Color( 0, 250, 154) ) }, + { ColorTokenValueType(OUString("mediumturquoise"), Color( 72, 209, 204) ) }, + { ColorTokenValueType(OUString("mediumvioletred"), Color(199, 21, 133) ) }, + { ColorTokenValueType(OUString("midnightblue"), Color( 25, 25, 112) ) }, + { ColorTokenValueType(OUString("mintcream"), Color(245, 255, 250) ) }, + { ColorTokenValueType(OUString("mistyrose"), Color(255, 228, 225) ) }, + { ColorTokenValueType(OUString("moccasin"), Color(255, 228, 181) ) }, + { ColorTokenValueType(OUString("navajowhite"), Color(255, 222, 173) ) }, + { ColorTokenValueType(OUString("navy"), Color( 0, 0, 128) ) }, + { ColorTokenValueType(OUString("oldlace"), Color(253, 245, 230) ) }, + { ColorTokenValueType(OUString("olive"), Color(128, 128, 0) ) }, + { ColorTokenValueType(OUString("olivedrab"), Color(107, 142, 35) ) }, + { ColorTokenValueType(OUString("orange"), Color(255, 165, 0) ) }, + { ColorTokenValueType(OUString("orangered"), Color(255, 69, 0) ) }, + { ColorTokenValueType(OUString("orchid"), Color(218, 112, 214) ) }, + { ColorTokenValueType(OUString("palegoldenrod"), Color(238, 232, 170) ) }, + { ColorTokenValueType(OUString("palegreen"), Color(152, 251, 152) ) }, + { ColorTokenValueType(OUString("paleturquoise"), Color(175, 238, 238) ) }, + { ColorTokenValueType(OUString("palevioletred"), Color(219, 112, 147) ) }, + { ColorTokenValueType(OUString("papayawhip"), Color(255, 239, 213) ) }, + { ColorTokenValueType(OUString("peachpuff"), Color(255, 218, 185) ) }, + { ColorTokenValueType(OUString("peru"), Color(205, 133, 63) ) }, + { ColorTokenValueType(OUString("pink"), Color(255, 192, 203) ) }, + { ColorTokenValueType(OUString("plum"), Color(221, 160, 221) ) }, + { ColorTokenValueType(OUString("powderblue"), Color(176, 224, 230) ) }, + { ColorTokenValueType(OUString("purple"), Color(128, 0, 128) ) }, + { ColorTokenValueType(OUString("red"), Color(255, 0, 0) ) }, + { ColorTokenValueType(OUString("rosybrown"), Color(188, 143, 143) ) }, + { ColorTokenValueType(OUString("royalblue"), Color( 65, 105, 225) ) }, + { ColorTokenValueType(OUString("saddlebrown"), Color(139, 69, 19) ) }, + { ColorTokenValueType(OUString("salmon"), Color(250, 128, 114) ) }, + { ColorTokenValueType(OUString("sandybrown"), Color(244, 164, 96) ) }, + { ColorTokenValueType(OUString("seagreen"), Color( 46, 139, 87) ) }, + { ColorTokenValueType(OUString("seashell"), Color(255, 245, 238) ) }, + { ColorTokenValueType(OUString("sienna"), Color(160, 82, 45) ) }, + { ColorTokenValueType(OUString("silver"), Color(192, 192, 192) ) }, + { ColorTokenValueType(OUString("skyblue"), Color(135, 206, 235) ) }, + { ColorTokenValueType(OUString("slateblue"), Color(106, 90, 205) ) }, + { ColorTokenValueType(OUString("slategray"), Color(112, 128, 144) ) }, + { ColorTokenValueType(OUString("slategrey"), Color(112, 128, 144) ) }, + { ColorTokenValueType(OUString("snow"), Color(255, 250, 250) ) }, + { ColorTokenValueType(OUString("springgreen"), Color( 0, 255, 127) ) }, + { ColorTokenValueType(OUString("steelblue"), Color( 70, 130, 180) ) }, + { ColorTokenValueType(OUString("tan"), Color(210, 180, 140) ) }, + { ColorTokenValueType(OUString("teal"), Color( 0, 128, 128) ) }, + { ColorTokenValueType(OUString("thistle"), Color(216, 191, 216) ) }, + { ColorTokenValueType(OUString("tomato"), Color(255, 99, 71) ) }, + { ColorTokenValueType(OUString("turquoise"), Color( 64, 224, 208) ) }, + { ColorTokenValueType(OUString("violet"), Color(238, 130, 238) ) }, + { ColorTokenValueType(OUString("wheat"), Color(245, 222, 179) ) }, + { ColorTokenValueType(OUString("white"), Color(255, 255, 255) ) }, + { ColorTokenValueType(OUString("whitesmoke"), Color(245, 245, 245) ) }, + { ColorTokenValueType(OUString("yellow"), Color(255, 255, 0) ) }, + { ColorTokenValueType(OUString("yellowgreen"), Color(154, 205, 50) ) }, + }; + + ColorTokenMapper::const_iterator aResult(aColorTokenMapperList.find(rName)); + + if(bCaseIndependent && aResult == aColorTokenMapperList.end()) + { + // also try case independent match (e.g. for Css styles) + aResult = aColorTokenMapperList.find(rName.toAsciiLowerCase()); + } + + if(aResult == aColorTokenMapperList.end()) + { + return false; + } + else + { + rColor = aResult->second.getBColor(); + return true; + } + } + + bool read_color(const OUString& rCandidate, basegfx::BColor& rColor, bool bCaseIndependent, SvgNumber& rOpacity) + { + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + const sal_Unicode aChar(rCandidate[0]); + const double fFactor(1.0 / 255.0); + + if(aChar == '#') + { + // hex definition + OUStringBuffer aNum; + sal_Int32 nPos(1); + + copyHex(rCandidate, nPos, aNum, nLen); + const sal_Int32 nLength(aNum.getLength()); + + if(3 == nLength) + { + const sal_Int32 nR(read_hex(aNum[0])); + const sal_Int32 nG(read_hex(aNum[1])); + const sal_Int32 nB(read_hex(aNum[2])); + + rColor.setRed((nR | (nR << 4)) * fFactor); + rColor.setGreen((nG | (nG << 4)) * fFactor); + rColor.setBlue((nB | (nB << 4)) * fFactor); + + return true; + } + else if(6 == nLength) + { + const sal_Int32 nR1(read_hex(aNum[0])); + const sal_Int32 nR2(read_hex(aNum[1])); + const sal_Int32 nG1(read_hex(aNum[2])); + const sal_Int32 nG2(read_hex(aNum[3])); + const sal_Int32 nB1(read_hex(aNum[4])); + const sal_Int32 nB2(read_hex(aNum[5])); + + rColor.setRed((nR2 | (nR1 << 4)) * fFactor); + rColor.setGreen((nG2 | (nG1 << 4)) * fFactor); + rColor.setBlue((nB2 | (nB1 << 4)) * fFactor); + + return true; + } + } + else + { + static const char aStrRgb[] = "rgb"; + + if(rCandidate.matchIgnoreAsciiCase(aStrRgb, 0)) + { + // rgb/rgba definition + sal_Int32 nPos(strlen(aStrRgb)); + bool bIsRGBA = false; + + if('a' == rCandidate[nPos]) + { + //Delete the 'a' from 'rbga' + skip_char(rCandidate, 'a', nPos, nPos + 1); + bIsRGBA = true; + } + + skip_char(rCandidate, ' ', '(', nPos, nLen); + double fR(0.0); + + if(readNumber(rCandidate, nPos, fR, nLen)) + { + skip_char(rCandidate, ' ', nPos, nLen); + + if(nPos < nLen) + { + const sal_Unicode aPercentChar(rCandidate[nPos]); + const bool bIsPercent('%' == aPercentChar); + double fG(0.0); + + if(bIsPercent) + { + skip_char(rCandidate, '%', nPos, nLen); + } + + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumber(rCandidate, nPos, fG, nLen)) + { + double fB(0.0); + + if(bIsPercent) + { + skip_char(rCandidate, '%', nPos, nLen); + } + + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumber(rCandidate, nPos, fB, nLen)) + { + double fA(1.0); + + if(bIsPercent) + { + skip_char(rCandidate, '%', nPos, nLen); + } + + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumber(rCandidate, nPos, fA, nLen)) + { + if(bIsRGBA) + { + const double fFac(bIsPercent ? 0.01 : 1); + rOpacity = SvgNumber(fA * fFac); + + if(bIsPercent) + { + skip_char(rCandidate, '%', nPos, nLen); + } + } + else + { + return false; + } + } + + const double fFac(bIsPercent ? 0.01 : fFactor); + + rColor.setRed(fR * fFac); + rColor.setGreen(fG * fFac); + rColor.setBlue(fB * fFac); + + skip_char(rCandidate, ' ', ')', nPos, nLen); + return true; + } + } + } + } + } + else + { + // color keyword + if(match_colorKeyword(rColor, rCandidate, bCaseIndependent)) + { + return true; + } + } + } + } + + return false; + } + + basegfx::B2DRange readViewBox(const OUString& rCandidate, InfoProvider const & rInfoProvider) + { + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + SvgNumber aMinX; + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aMinX, nLen)) + { + SvgNumber aMinY; + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aMinY, nLen)) + { + SvgNumber aWidth; + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aWidth, nLen)) + { + SvgNumber aHeight; + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aHeight, nLen)) + { + double fX(aMinX.solve(rInfoProvider, xcoordinate)); + double fY(aMinY.solve(rInfoProvider, ycoordinate)); + double fW(aWidth.solve(rInfoProvider,xcoordinate)); + double fH(aHeight.solve(rInfoProvider,ycoordinate)); + return basegfx::B2DRange(fX,fY,fX+fW,fY+fH); + } + } + } + } + } + + return basegfx::B2DRange(); + } + + basegfx::B2DHomMatrix readTransform(const OUString& rCandidate, InfoProvider const & rInfoProvider) + { + basegfx::B2DHomMatrix aMatrix; + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + while(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + const sal_Int32 nInitPos(nPos); + static const char aStrMatrix[] = "matrix"; + static const char aStrTranslate[] = "translate"; + static const char aStrScale[] = "scale"; + static const char aStrRotate[] = "rotate"; + static const char aStrSkewX[] = "skewX"; + static const char aStrSkewY[] = "skewY"; + + switch(aChar) + { + case u'm' : + { + if(rCandidate.match(aStrMatrix, nPos)) + { + // matrix element + nPos += strlen(aStrMatrix); + skip_char(rCandidate, ' ', '(', nPos, nLen); + SvgNumber aVal; + basegfx::B2DHomMatrix aNew; + + if(readNumberAndUnit(rCandidate, nPos, aVal, nLen)) + { + aNew.set(0, 0, aVal.solve(rInfoProvider)); // Element A + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aVal, nLen)) + { + aNew.set(1, 0, aVal.solve(rInfoProvider)); // Element B + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aVal, nLen)) + { + aNew.set(0, 1, aVal.solve(rInfoProvider)); // Element C + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aVal, nLen)) + { + aNew.set(1, 1, aVal.solve(rInfoProvider)); // Element D + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aVal, nLen)) + { + aNew.set(0, 2, aVal.solve(rInfoProvider, xcoordinate)); // Element E + skip_char(rCandidate, ' ', ',', nPos, nLen); + + if(readNumberAndUnit(rCandidate, nPos, aVal, nLen)) + { + aNew.set(1, 2, aVal.solve(rInfoProvider, ycoordinate)); // Element F + skip_char(rCandidate, ' ', ')', nPos, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + // caution: String is evaluated from left to right, but matrix multiplication + // in SVG is right to left, so put the new transformation before the current + // one by multiplicating from the right side + aMatrix = aMatrix * aNew; + } + } + } + } + } + } + } + break; + } + case u't' : + { + if(rCandidate.match(aStrTranslate, nPos)) + { + // translate element + nPos += strlen(aStrTranslate); + skip_char(rCandidate, ' ', '(', nPos, nLen); + SvgNumber aTransX; + + if(readNumberAndUnit(rCandidate, nPos, aTransX, nLen)) + { + skip_char(rCandidate, ' ', ',', nPos, nLen); + SvgNumber aTransY; + readNumberAndUnit(rCandidate, nPos, aTransY, nLen); + skip_char(rCandidate, ' ', ')', nPos, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + aMatrix = aMatrix * basegfx::utils::createTranslateB2DHomMatrix( + aTransX.solve(rInfoProvider, xcoordinate), + aTransY.solve(rInfoProvider, ycoordinate)); + } + } + break; + } + case u's' : + { + if(rCandidate.match(aStrScale, nPos)) + { + // scale element + nPos += strlen(aStrScale); + skip_char(rCandidate, ' ', '(', nPos, nLen); + SvgNumber aScaleX; + + if(readNumberAndUnit(rCandidate, nPos, aScaleX, nLen)) + { + skip_char(rCandidate, ' ', ',', nPos, nLen); + SvgNumber aScaleY(aScaleX); + readNumberAndUnit(rCandidate, nPos, aScaleY, nLen); + skip_char(rCandidate, ' ', ')', nPos, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + aMatrix = aMatrix * basegfx::utils::createScaleB2DHomMatrix( + aScaleX.solve(rInfoProvider), + aScaleY.solve(rInfoProvider)); + } + } + else if(rCandidate.match(aStrSkewX, nPos)) + { + // skewx element + nPos += strlen(aStrSkewX); + skip_char(rCandidate, ' ', '(', nPos, nLen); + double fSkewX(0.0); + + if(readAngle(rCandidate, nPos, fSkewX, nLen)) + { + skip_char(rCandidate, ' ', ')', nPos, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + aMatrix = aMatrix * basegfx::utils::createShearXB2DHomMatrix(tan(fSkewX)); + } + } + else if(rCandidate.match(aStrSkewY, nPos)) + { + // skewy element + nPos += strlen(aStrSkewY); + skip_char(rCandidate, ' ', '(', nPos, nLen); + double fSkewY(0.0); + + if(readAngle(rCandidate, nPos, fSkewY, nLen)) + { + skip_char(rCandidate, ' ', ')', nPos, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + aMatrix = aMatrix * basegfx::utils::createShearYB2DHomMatrix(tan(fSkewY)); + } + } + break; + } + case u'r' : + { + if(rCandidate.match(aStrRotate, nPos)) + { + // rotate element + nPos += strlen(aStrRotate); + skip_char(rCandidate, ' ', '(', nPos, nLen); + double fAngle(0.0); + + if(readAngle(rCandidate, nPos, fAngle, nLen)) + { + skip_char(rCandidate, ' ', ',', nPos, nLen); + SvgNumber aX; + readNumberAndUnit(rCandidate, nPos, aX, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + SvgNumber aY; + readNumberAndUnit(rCandidate, nPos, aY, nLen); + skip_char(rCandidate, ' ', ')', nPos, nLen); + skip_char(rCandidate, ' ', ',', nPos, nLen); + + const double fX(aX.isSet() ? aX.solve(rInfoProvider, xcoordinate) : 0.0); + const double fY(aY.isSet() ? aY.solve(rInfoProvider, ycoordinate) : 0.0); + + if(!basegfx::fTools::equalZero(fX) || !basegfx::fTools::equalZero(fY)) + { + // rotate around point + aMatrix = aMatrix * basegfx::utils::createRotateAroundPoint(fX, fY, fAngle); + } + else + { + // rotate + aMatrix = aMatrix * basegfx::utils::createRotateB2DHomMatrix(fAngle); + } + } + } + break; + } + } + + if(nInitPos == nPos) + { + OSL_ENSURE(false, "Could not interpret on current position (!)"); + nPos++; + } + } + } + + return aMatrix; + } + + bool readSingleNumber(const OUString& rCandidate, SvgNumber& aNum) + { + const sal_Int32 nLen(rCandidate.getLength()); + sal_Int32 nPos(0); + + return readNumberAndUnit(rCandidate, nPos, aNum, nLen); + } + + bool readLocalUrl(const OUString& rCandidate, OUString& rURL) + { + static const char aStrUrl[] = "url"; + + if(rCandidate.startsWith(aStrUrl)) + { + const sal_Int32 nLen(rCandidate.getLength()); + sal_Int32 nPos(strlen(aStrUrl)); + + skip_char(rCandidate, '(', '#', nPos, nLen); + OUStringBuffer aTokenValue; + copyToLimiter(rCandidate, ')', nPos, aTokenValue, nLen); + rURL = aTokenValue.makeStringAndClear(); + + return true; + } + + return false; + } + + bool readSvgPaint(const OUString& rCandidate, SvgPaint& rSvgPaint, + OUString& rURL, bool bCaseIndependent, SvgNumber& rOpacity) + { + if( !rCandidate.isEmpty() ) + { + basegfx::BColor aColor; + + if(read_color(rCandidate, aColor, bCaseIndependent, rOpacity)) + { + rSvgPaint = SvgPaint(aColor, true, true); + return true; + } + else + { + if(rCandidate.startsWith("none")) + { + rSvgPaint = SvgPaint(aColor, true, false, false); + return true; + } + else if(readLocalUrl(rCandidate, rURL)) + { + /// Url is copied to rURL, but needs to be solved outside this helper + return false; + } + else if(rCandidate.startsWith("currentColor")) + { + rSvgPaint = SvgPaint(aColor, true, true, true); + return true; + } + } + } + + return false; + } + + bool readSvgNumberVector(const OUString& rCandidate, SvgNumberVector& rSvgNumberVector) + { + const sal_Int32 nLen(rCandidate.getLength()); + rSvgNumberVector.clear(); + + if(nLen) + { + sal_Int32 nPos(0); + SvgNumber aNum; + skip_char(rCandidate, ' ', ',', nPos, nLen); + + while(readNumberAndUnit(rCandidate, nPos, aNum, nLen)) + { + rSvgNumberVector.push_back(aNum); + skip_char(rCandidate, ' ', ',', nPos, nLen); + } + + return !rSvgNumberVector.empty(); + } + + return false; + } + + SvgAspectRatio readSvgAspectRatio(const OUString& rCandidate) + { + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + SvgAlign aSvgAlign(Align_xMidYMid); + bool bMeetOrSlice(true); + bool bChanged(false); + + while(nPos < nLen) + { + const sal_Int32 nInitPos(nPos); + skip_char(rCandidate, ' ', nPos, nLen); + OUStringBuffer aTokenName; + copyString(rCandidate, nPos, aTokenName, nLen); + + if(!aTokenName.isEmpty()) + { + switch(StrToSVGToken(aTokenName.makeStringAndClear(), false)) + { + case SVGTokenDefer: + { + bChanged = true; + break; + } + case SVGTokenNone: + { + aSvgAlign = Align_none; + bChanged = true; + break; + } + case SVGTokenXMinYMin: + { + aSvgAlign = Align_xMinYMin; + bChanged = true; + break; + } + case SVGTokenXMidYMin: + { + aSvgAlign = Align_xMidYMin; + bChanged = true; + break; + } + case SVGTokenXMaxYMin: + { + aSvgAlign = Align_xMaxYMin; + bChanged = true; + break; + } + case SVGTokenXMinYMid: + { + aSvgAlign = Align_xMinYMid; + bChanged = true; + break; + } + case SVGTokenXMidYMid: + { + aSvgAlign = Align_xMidYMid; + bChanged = true; + break; + } + case SVGTokenXMaxYMid: + { + aSvgAlign = Align_xMaxYMid; + bChanged = true; + break; + } + case SVGTokenXMinYMax: + { + aSvgAlign = Align_xMinYMax; + bChanged = true; + break; + } + case SVGTokenXMidYMax: + { + aSvgAlign = Align_xMidYMax; + bChanged = true; + break; + } + case SVGTokenXMaxYMax: + { + aSvgAlign = Align_xMaxYMax; + bChanged = true; + break; + } + case SVGTokenMeet: + { + bMeetOrSlice = true; + bChanged = true; + break; + } + case SVGTokenSlice: + { + bMeetOrSlice = false; + bChanged = true; + break; + } + default: + { + break; + } + } + } + + if(nInitPos == nPos) + { + OSL_ENSURE(false, "Could not interpret on current position (!)"); + nPos++; + } + } + + if(bChanged) + { + return SvgAspectRatio(aSvgAlign, bMeetOrSlice); + } + } + + return SvgAspectRatio(); + } + + bool readSvgStringVector(const OUString& rCandidate, SvgStringVector& rSvgStringVector) + { + rSvgStringVector.clear(); + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + OUStringBuffer aTokenValue; + skip_char(rCandidate, ' ', ',', nPos, nLen); + + while(nPos < nLen) + { + copyToLimiter(rCandidate, ',', nPos, aTokenValue, nLen); + skip_char(rCandidate, ',', ' ', nPos, nLen); + const OUString aString = aTokenValue.makeStringAndClear(); + + if(!aString.isEmpty()) + { + rSvgStringVector.push_back(aString); + } + } + } + + return !rSvgStringVector.empty(); + } + + void readImageLink(const OUString& rCandidate, OUString& rXLink, OUString& rUrl, OUString& rMimeType, OUString& rData) + { + rXLink.clear(); + rUrl.clear(); + rMimeType.clear(); + rData.clear(); + + if('#' == rCandidate[0]) + { + // local link + rXLink = rCandidate.copy(1); + } + else + { + static const char aStrData[] = "data:"; + + if(rCandidate.match(aStrData, 0)) + { + // embedded data + sal_Int32 nPos(strlen(aStrData)); + sal_Int32 nLen(rCandidate.getLength()); + OUStringBuffer aBuffer; + + // read mime type + skip_char(rCandidate, ' ', nPos, nLen); + copyToLimiter(rCandidate, ';', nPos, aBuffer, nLen); + skip_char(rCandidate, ' ', ';', nPos, nLen); + rMimeType = aBuffer.makeStringAndClear(); + + if(!rMimeType.isEmpty() && nPos < nLen) + { + if(rMimeType.startsWith("image")) + { + // image data + OUString aData(rCandidate.copy(nPos)); + static const char aStrBase64[] = "base64"; + + if(aData.startsWith(aStrBase64)) + { + // base64 encoded + nPos = strlen(aStrBase64); + nLen = aData.getLength(); + + skip_char(aData, ' ', ',', nPos, nLen); + + if(nPos < nLen) + { + rData = aData.copy(nPos); + } + } + } + } + } + else + { + // Url (path and filename) + rUrl = rCandidate; + } + } + } + + OUString convert(const OUString& rCandidate, sal_Unicode nPattern, sal_Unicode nNew, bool bRemove) + { + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + OUStringBuffer aBuffer; + bool bChanged(false); + + while(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + if(nPattern == aChar) + { + bChanged = true; + + if(!bRemove) + { + aBuffer.append(nNew); + } + } + else + { + aBuffer.append(aChar); + } + + nPos++; + } + + if(bChanged) + { + return aBuffer.makeStringAndClear(); + } + } + + return rCandidate; + } + + // #i125325# + OUString removeBlockComments(const OUString& rCandidate) + { + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + OUStringBuffer aBuffer; + bool bChanged(false); + sal_Int32 nInsideComment(0); + const sal_Unicode aCommentSlash('/'); + const sal_Unicode aCommentStar('*'); + + while(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + const bool bStart(aCommentSlash == aChar && nPos + 1 < nLen && aCommentStar == rCandidate[nPos + 1]); + const bool bEnd(aCommentStar == aChar && nPos + 1 < nLen && aCommentSlash == rCandidate[nPos + 1]); + + if(bStart) + { + nPos += 2; + nInsideComment++; + bChanged = true; + } + else if(bEnd) + { + nPos += 2; + nInsideComment--; + } + else + { + if(!nInsideComment) + { + aBuffer.append(aChar); + } + + nPos++; + } + } + + if(bChanged) + { + return aBuffer.makeStringAndClear(); + } + } + + return rCandidate; + } + + OUString consolidateContiguousSpace(const OUString& rCandidate) + { + const sal_Int32 nLen(rCandidate.getLength()); + + if(nLen) + { + sal_Int32 nPos(0); + OUStringBuffer aBuffer; + bool bInsideSpace(false); + const sal_Unicode aSpace(' '); + + while(nPos < nLen) + { + const sal_Unicode aChar(rCandidate[nPos]); + + if(aSpace == aChar) + { + bInsideSpace = true; + } + else + { + if(bInsideSpace) + { + bInsideSpace = false; + aBuffer.append(aSpace); + } + + aBuffer.append(aChar); + } + + nPos++; + } + + if(bInsideSpace) + { + aBuffer.append(aSpace); + } + + if(aBuffer.getLength() != nLen) + { + return aBuffer.makeStringAndClear(); + } + } + + return rCandidate; + } + + OUString whiteSpaceHandlingDefault(const OUString& rCandidate) + { + const sal_Unicode aNewline('\n'); + const sal_Unicode aTab('\t'); + const sal_Unicode aSpace(' '); + + // remove all newline characters + OUString aRetval(convert(rCandidate, aNewline, aNewline, true)); + + // convert tab to space + aRetval = convert(aRetval, aTab, aSpace, false); + + // strip of all leading and trailing spaces + aRetval = aRetval.trim(); + + // consolidate contiguous space + aRetval = consolidateContiguousSpace(aRetval); + + return aRetval; + } + + OUString whiteSpaceHandlingPreserve(const OUString& rCandidate) + { + const sal_Unicode aNewline('\n'); + const sal_Unicode aTab('\t'); + const sal_Unicode aSpace(' '); + + // convert newline to space + convert(rCandidate, aNewline, aSpace, false); + + // convert tab to space + convert(rCandidate, aTab, aSpace, false); + + return rCandidate; + } + + ::std::vector< double > solveSvgNumberVector(const SvgNumberVector& rInput, const InfoProvider& rInfoProvider) + { + ::std::vector< double > aRetval; + + if(!rInput.empty()) + { + const double nCount(rInput.size()); + aRetval.reserve(nCount); + + for(sal_uInt32 a(0); a < nCount; a++) + { + aRetval.push_back(rInput[a].solve(rInfoProvider)); + } + } + + return aRetval; + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtrefnode.cxx b/svgio/source/svgreader/svgtrefnode.cxx new file mode 100644 index 000000000..b4b08d45c --- /dev/null +++ b/svgio/source/svgreader/svgtrefnode.cxx @@ -0,0 +1,83 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtrefnode.hxx> +#include <svgdocument.hxx> + +namespace svgio::svgreader +{ + SvgTrefNode::SvgTrefNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenTref, rDocument, pParent), + maSvgStyleAttributes(*this), + maXLink() + { + } + + SvgTrefNode::~SvgTrefNode() + { + } + + const SvgStyleAttributes* SvgTrefNode::getSvgStyleAttributes() const + { + return &maSvgStyleAttributes; + } + + void SvgTrefNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenXlinkHref: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen && '#' == aContent[0]) + { + maXLink = aContent.copy(1); + } + break; + } + default: + { + break; + } + } + } + + const SvgTextNode* SvgTrefNode::getReferencedSvgTextNode() const + { + return dynamic_cast< const SvgTextNode* >(getDocument().findSvgNodeById(maXLink)); + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgtspannode.cxx b/svgio/source/svgreader/svgtspannode.cxx new file mode 100644 index 000000000..f9b298dda --- /dev/null +++ b/svgio/source/svgreader/svgtspannode.cxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgtspannode.hxx> + +namespace svgio::svgreader +{ + SvgTspanNode::SvgTspanNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenTspan, rDocument, pParent), + maSvgStyleAttributes(*this), + maSvgTextPositions() + { + } + + SvgTspanNode::~SvgTspanNode() + { + } + + const SvgStyleAttributes* SvgTspanNode::getSvgStyleAttributes() const + { + // #i125293# Need to support CssStyles in tspan text sections + return checkForCssStyle("tspan", maSvgStyleAttributes); + } + + void SvgTspanNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // read text position attributes + maSvgTextPositions.parseTextPositionAttributes(aSVGToken, aContent); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + default: + { + break; + } + } + } + + double SvgTspanNode::getCurrentFontSize() const + { + return getCurrentFontSizeInherited(); + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgusenode.cxx b/svgio/source/svgreader/svgusenode.cxx new file mode 100644 index 000000000..4d71af3cf --- /dev/null +++ b/svgio/source/svgreader/svgusenode.cxx @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <svgusenode.hxx> +#include <drawinglayer/primitive2d/transformprimitive2d.hxx> +#include <svgdocument.hxx> + +namespace svgio::svgreader +{ + SvgUseNode::SvgUseNode( + SvgDocument& rDocument, + SvgNode* pParent) + : SvgNode(SVGTokenUse, rDocument, pParent), + maSvgStyleAttributes(*this), + maX(), + maY(), + maWidth(), + maHeight(), + maXLink(), + mbDecomposingSvgNode(false) + { + } + + SvgUseNode::~SvgUseNode() + { + } + + const SvgStyleAttributes* SvgUseNode::getSvgStyleAttributes() const + { + return checkForCssStyle("use", maSvgStyleAttributes); + } + + void SvgUseNode::parseAttribute(const OUString& rTokenName, SVGToken aSVGToken, const OUString& aContent) + { + // call parent + SvgNode::parseAttribute(rTokenName, aSVGToken, aContent); + + // read style attributes + maSvgStyleAttributes.parseStyleAttribute(aSVGToken, aContent, false); + + // parse own + switch(aSVGToken) + { + case SVGTokenStyle: + { + readLocalCssStyle(aContent); + break; + } + case SVGTokenTransform: + { + const basegfx::B2DHomMatrix aMatrix(readTransform(aContent, *this)); + + if(!aMatrix.isIdentity()) + { + setTransform(&aMatrix); + } + break; + } + case SVGTokenX: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maX = aNum; + } + break; + } + case SVGTokenY: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + maY = aNum; + } + break; + } + case SVGTokenWidth: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maWidth = aNum; + } + } + break; + } + case SVGTokenHeight: + { + SvgNumber aNum; + + if(readSingleNumber(aContent, aNum)) + { + if(aNum.isPositive()) + { + maHeight = aNum; + } + } + break; + } + case SVGTokenXlinkHref: + { + const sal_Int32 nLen(aContent.getLength()); + + if(nLen && '#' == aContent[0]) + { + maXLink = aContent.copy(1); + } + break; + } + default: + { + break; + } + } + } + + void SvgUseNode::decomposeSvgNode(drawinglayer::primitive2d::Primitive2DContainer& rTarget, bool /*bReferenced*/) const + { + // try to access link to content + const SvgNode* pXLink = getDocument().findSvgNodeById(maXLink); + + if (!(pXLink && Display_none != pXLink->getDisplay() && !mbDecomposingSvgNode)) + return; + + // decompose children + drawinglayer::primitive2d::Primitive2DContainer aNewTarget; + + // todo: in case mpXLink is a SVGTokenSvg or SVGTokenSymbol the + // SVG docs want the getWidth() and getHeight() from this node + // to be valid for the subtree. + mbDecomposingSvgNode = true; + const_cast< SvgNode* >(pXLink)->setAlternativeParent(this); + pXLink->decomposeSvgNode(aNewTarget, true); + const_cast< SvgNode* >(pXLink)->setAlternativeParent(); + mbDecomposingSvgNode = false; + + if(aNewTarget.empty()) + return; + + basegfx::B2DHomMatrix aTransform; + + if(getX().isSet() || getY().isSet()) + { + aTransform.translate( + getX().solve(*this, xcoordinate), + getY().solve(*this, ycoordinate)); + } + + if(getTransform()) + { + aTransform = *getTransform() * aTransform; + } + + if(!aTransform.isIdentity()) + { + const drawinglayer::primitive2d::Primitive2DReference xRef( + new drawinglayer::primitive2d::TransformPrimitive2D( + aTransform, + aNewTarget)); + + rTarget.push_back(xRef); + } + else + { + rTarget.append(aNewTarget); + } + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svgreader/svgvisitor.cxx b/svgio/source/svgreader/svgvisitor.cxx new file mode 100644 index 000000000..1f2ea975c --- /dev/null +++ b/svgio/source/svgreader/svgvisitor.cxx @@ -0,0 +1,165 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#include <sal/config.h> + +#include <svgrectnode.hxx> +#include <svgsvgnode.hxx> +#include <svggnode.hxx> +#include <svgpathnode.hxx> +#include <svggradientnode.hxx> + +#include <svgvisitor.hxx> + +namespace svgio::svgreader +{ +SvgDrawVisitor::SvgDrawVisitor() + : mpDrawRoot(std::make_shared<gfx::DrawRoot>()) + , mpCurrent(mpDrawRoot) +{ +} + +void SvgDrawVisitor::visit(svgio::svgreader::SvgNode const& rNode) +{ + switch (rNode.getType()) + { + case svgio::svgreader::SVGTokenSvg: + { + auto const& rSvgNode = static_cast<svgio::svgreader::SvgSvgNode const&>(rNode); + + basegfx::B2DRange aRange = rSvgNode.getCurrentViewPort(); + + static_cast<gfx::DrawRoot*>(mpCurrent.get())->maRectangle = aRange; + } + break; + case svgio::svgreader::SVGTokenG: + { + auto const& rGNode = static_cast<svgio::svgreader::SvgGNode const&>(rNode); + + if (rGNode.getTransform() != nullptr) + { + basegfx::B2DHomMatrix rMatrix = *rGNode.getTransform(); + + printf("G [%f %f %f - %f %f %f - %f %f %f]\n", rMatrix.get(0, 0), rMatrix.get(0, 1), + rMatrix.get(0, 2), rMatrix.get(1, 0), rMatrix.get(1, 1), rMatrix.get(1, 2), + rMatrix.get(2, 0), rMatrix.get(2, 1), rMatrix.get(2, 2)); + } + } + break; + case svgio::svgreader::SVGTokenRect: + { + auto const& rRectNode = static_cast<svgio::svgreader::SvgRectNode const&>(rNode); + + double x = rRectNode.getX().getNumber(); + double y = rRectNode.getY().getNumber(); + double w = rRectNode.getWidth().getNumber(); + double h = rRectNode.getHeight().getNumber(); + + auto pRectangle + = std::make_shared<gfx::DrawRectangle>(basegfx::B2DRange(x, y, x + w, y + h)); + pRectangle->mnRx = rRectNode.getRx().getNumber(); + pRectangle->mnRy = rRectNode.getRy().getNumber(); + + pRectangle->mnStrokeWidth + = rRectNode.getSvgStyleAttributes()->getStrokeWidth().getNumber(); + + pRectangle->mnOpacity = rRectNode.getSvgStyleAttributes()->getOpacity().getNumber(); + + const basegfx::BColor* pFillColor = rRectNode.getSvgStyleAttributes()->getFill(); + const SvgGradientNode* pFillGradient + = rRectNode.getSvgStyleAttributes()->getSvgGradientNodeFill(); + if (pFillColor) + { + pRectangle->mpFillColor = std::make_shared<basegfx::BColor>(*pFillColor); + } + else if (pFillGradient) + { + drawinglayer::primitive2d::SvgGradientEntryVector aSvgGradientEntryVector; + pFillGradient->collectGradientEntries(aSvgGradientEntryVector); + if (!aSvgGradientEntryVector.empty()) + { + auto aGradientInfo = std::make_shared<gfx::LinearGradientInfo>(); + + aGradientInfo->x1 = pFillGradient->getX1().getNumber(); + aGradientInfo->y1 = pFillGradient->getY1().getNumber(); + aGradientInfo->x2 = pFillGradient->getX2().getNumber(); + aGradientInfo->y2 = pFillGradient->getY2().getNumber(); + + const basegfx::B2DHomMatrix* pGradientTransform + = pFillGradient->getGradientTransform(); + if (pGradientTransform) + { + aGradientInfo->maMatrix = *pGradientTransform; + } + + pRectangle->mpFillGradient = aGradientInfo; + + for (auto const& rEntry : aSvgGradientEntryVector) + { + gfx::GradientStop aStop; + aStop.maColor = rEntry.getColor(); + aStop.mfOffset = rEntry.getOffset(); + aStop.mfOpacity = rEntry.getOpacity(); + pRectangle->mpFillGradient->maGradientStops.push_back(aStop); + } + } + } + + const basegfx::BColor* pStrokeColor = rRectNode.getSvgStyleAttributes()->getStroke(); + if (pStrokeColor) + pRectangle->mpStrokeColor = std::make_shared<basegfx::BColor>(*pStrokeColor); + + mpCurrent->maChildren.push_back(pRectangle); + } + break; + case svgio::svgreader::SVGTokenPath: + { + auto const& rPathNode = static_cast<svgio::svgreader::SvgPathNode const&>(rNode); + + auto pPath = rPathNode.getPath(); + if (pPath) + { + auto pDrawPath = std::make_shared<gfx::DrawPath>(*pPath); + + pDrawPath->mnStrokeWidth + = rPathNode.getSvgStyleAttributes()->getStrokeWidth().getNumber(); + + pDrawPath->mnOpacity = rPathNode.getSvgStyleAttributes()->getOpacity().getNumber(); + + const basegfx::BColor* pFillColor = rPathNode.getSvgStyleAttributes()->getFill(); + if (pFillColor) + pDrawPath->mpFillColor = std::make_shared<basegfx::BColor>(*pFillColor); + + const basegfx::BColor* pStrokeColor + = rPathNode.getSvgStyleAttributes()->getStroke(); + if (pStrokeColor) + pDrawPath->mpStrokeColor = std::make_shared<basegfx::BColor>(*pStrokeColor); + + mpCurrent->maChildren.push_back(pDrawPath); + } + } + break; + + default: + break; + } + goToChildren(rNode); +} + +void SvgDrawVisitor::goToChildren(svgio::svgreader::SvgNode const& rNode) +{ + for (auto& rChild : rNode.getChildren()) + { + rChild->accept(*this); + } +} +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svguno/svguno.cxx b/svgio/source/svguno/svguno.cxx new file mode 100644 index 000000000..05baa2cb6 --- /dev/null +++ b/svgio/source/svguno/svguno.cxx @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <cppuhelper/factory.hxx> +#include <cppuhelper/implementationentry.hxx> +#include <sal/types.h> + +#include "xsvgparser.hxx" + +namespace { + +static cppu::ImplementationEntry const services[] = { + { &svgio::svgreader::XSvgParser_createInstance, + &svgio::svgreader::XSvgParser_getImplementationName, + &svgio::svgreader::XSvgParser_getSupportedServiceNames, + &cppu::createSingleComponentFactory, nullptr, 0 }, + { nullptr, nullptr, nullptr, nullptr, nullptr, 0 } }; + +} + +extern "C" SAL_DLLPUBLIC_EXPORT void * svgio_component_getFactory( + char const * pImplName, void * pServiceManager, void * pRegistryKey) +{ + return cppu::component_getFactoryHelper( + pImplName, pServiceManager, pRegistryKey, services); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svguno/xsvgparser.cxx b/svgio/source/svguno/xsvgparser.cxx new file mode 100644 index 000000000..f48d04cd1 --- /dev/null +++ b/svgio/source/svguno/xsvgparser.cxx @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <com/sun/star/graphic/XSvgParser.hpp> +#include <com/sun/star/lang/XServiceInfo.hpp> +#include <com/sun/star/lang/XInitialization.hpp> +#include <cppuhelper/implbase2.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <comphelper/sequence.hxx> +#include <com/sun/star/xml/sax/XParser.hpp> +#include <com/sun/star/xml/sax/Parser.hpp> +#include <com/sun/star/xml/sax/InputSource.hpp> +#include <svgdocumenthandler.hxx> +#include <tools/diagnose_ex.h> + +#include <svgvisitor.hxx> + +#include "xsvgparser.hxx" + +using namespace ::com::sun::star; + +namespace svgio::svgreader +{ + namespace { + + class XSvgParser : public ::cppu::WeakAggImplHelper2< graphic::XSvgParser, lang::XServiceInfo > + { + private: + std::shared_ptr<SvgDrawVisitor> mpVisitor; + + uno::Reference< uno::XComponentContext > context_; + bool parseSvgXML(uno::Reference<io::XInputStream> const & xSVGStream, + uno::Reference<xml::sax::XDocumentHandler> const & xSvgDocHdl); + public: + explicit XSvgParser( + uno::Reference< uno::XComponentContext > const & context); + XSvgParser(const XSvgParser&) = delete; + XSvgParser& operator=(const XSvgParser&) = delete; + + // XSvgParser + virtual uno::Sequence< uno::Reference< ::graphic::XPrimitive2D > > SAL_CALL getDecomposition( + const uno::Reference< ::io::XInputStream >& xSVGStream, + const OUString& aAbsolutePath) override; + + virtual uno::Any SAL_CALL getDrawCommands( + uno::Reference<io::XInputStream> const & xSvgStream, + const OUString& aAbsolutePath) override; + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService(const OUString&) override; + virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + }; + + } +} // end of namespace svgio::svgreader + +// uno functions +namespace svgio::svgreader +{ + uno::Sequence< OUString > XSvgParser_getSupportedServiceNames() + { + return uno::Sequence< OUString > { "com.sun.star.graphic.SvgTools" }; + } + + OUString XSvgParser_getImplementationName() + { + return "svgio::svgreader::XSvgParser"; + } + + uno::Reference< uno::XInterface > XSvgParser_createInstance(const uno::Reference< uno::XComponentContext >& context) + { + return static_cast< ::cppu::OWeakObject* >(new XSvgParser(context)); + } +} // end of namespace svgio::svgreader + +namespace svgio::svgreader +{ + XSvgParser::XSvgParser( + uno::Reference< uno::XComponentContext > const & context): + context_(context) + { + } + + bool XSvgParser::parseSvgXML(uno::Reference<io::XInputStream> const & xSVGStream, uno::Reference<xml::sax::XDocumentHandler> const & xSvgDocHdl) + { + try + { + // prepare ParserInputSrouce + xml::sax::InputSource myInputSource; + myInputSource.aInputStream = xSVGStream; + + // get parser + uno::Reference< xml::sax::XParser > xParser( + xml::sax::Parser::create(context_)); + // fdo#60471 need to enable internal entities because + // certain ... popular proprietary products write SVG files + // that use entities to define XML namespaces. + uno::Reference<lang::XInitialization> const xInit(xParser, + uno::UNO_QUERY_THROW); + uno::Sequence<uno::Any> args(1); + args[0] <<= OUString("DoSmeplease"); + xInit->initialize(args); + + // connect parser and filter + xParser->setDocumentHandler(xSvgDocHdl); + + // finally, parse the stream to a hierarchy of + // SVGGraphicPrimitive2D which will be embedded to the + // primitive sequence. Their decompositions will in the + // end create local low-level primitives, thus SVG will + // be processable from all our processors + xParser->parseStream(myInputSource); + } + catch(const uno::Exception&) + { + TOOLS_INFO_EXCEPTION( "svg", "Parse error"); + return false; + } + + return true; + } + + uno::Sequence< uno::Reference< ::graphic::XPrimitive2D > > XSvgParser::getDecomposition( + const uno::Reference< ::io::XInputStream >& xSVGStream, + const OUString& aAbsolutePath ) + { + drawinglayer::primitive2d::Primitive2DContainer aRetval; + + if(xSVGStream.is()) + { + // local document handler + SvgDocHdl* pSvgDocHdl = new SvgDocHdl(aAbsolutePath); + uno::Reference<xml::sax::XDocumentHandler> xSvgDocHdl(pSvgDocHdl); + parseSvgXML(xSVGStream, xSvgDocHdl); + + // decompose to primitives + for(std::unique_ptr<SvgNode> const & pCandidate : pSvgDocHdl->getSvgDocument().getSvgNodeVector()) + { + if(Display_none != pCandidate->getDisplay()) + { + pCandidate->decomposeSvgNode(aRetval, false); + } + } + } + else + { + OSL_ENSURE(false, "Invalid stream (!)"); + } + + return comphelper::containerToSequence(aRetval); + } + + uno::Any SAL_CALL XSvgParser::getDrawCommands( + uno::Reference<io::XInputStream> const & xSvgStream, + const OUString& aAbsolutePath) + { + uno::Any aAnyResult; + + if (!xSvgStream.is()) + return aAnyResult; + + SvgDocHdl* pSvgDocHdl = new SvgDocHdl(aAbsolutePath); + uno::Reference<xml::sax::XDocumentHandler> xSvgDocHdl(pSvgDocHdl); + parseSvgXML(xSvgStream, xSvgDocHdl); + + // decompose to primitives + for (std::unique_ptr<SvgNode> const & pCandidate : pSvgDocHdl->getSvgDocument().getSvgNodeVector()) + { + if (Display_none != pCandidate->getDisplay()) + { + mpVisitor = std::make_shared<SvgDrawVisitor>(); + pCandidate->accept(*mpVisitor); + std::shared_ptr<gfx::DrawRoot> pDrawRoot(mpVisitor->getDrawRoot()); + sal_uInt64 nPointer = reinterpret_cast<sal_uInt64>(pDrawRoot.get()); + aAnyResult <<= sal_uInt64(nPointer); + } + } + + return aAnyResult; + } + + OUString SAL_CALL XSvgParser::getImplementationName() + { + return XSvgParser_getImplementationName(); + } + + sal_Bool SAL_CALL XSvgParser::supportsService(const OUString& rServiceName) + { + return cppu::supportsService(this, rServiceName); + } + + uno::Sequence< OUString > SAL_CALL XSvgParser::getSupportedServiceNames() + { + return XSvgParser_getSupportedServiceNames(); + } + +} // end of namespace svgio::svgreader + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/svgio/source/svguno/xsvgparser.hxx b/svgio/source/svguno/xsvgparser.hxx new file mode 100644 index 000000000..158b3dd13 --- /dev/null +++ b/svgio/source/svguno/xsvgparser.hxx @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_SVGIO_SOURCE_SVGUNO_XSVGPARSER_HXX +#define INCLUDED_SVGIO_SOURCE_SVGUNO_XSVGPARSER_HXX + +#include <sal/config.h> + +#include <com/sun/star/uno/Reference.hxx> +#include <com/sun/star/uno/Sequence.hxx> + +namespace com::sun::star { + namespace uno { + class XComponentContext; + class XInterface; + } +} + +namespace svgio::svgreader { + +css::uno::Reference< css::uno::XInterface > +XSvgParser_createInstance( css::uno::Reference< css::uno::XComponentContext > const &); + +OUString XSvgParser_getImplementationName(); + +css::uno::Sequence< OUString > +XSvgParser_getSupportedServiceNames(); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |