Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
Create basic KoResource to handle style presets for text properties.
Wolthera van Hövell tot Westerflier56b6331e4628
diff --git a/libs/flake/CMakeLists.txt b/libs/flake/CMakeLists.txtindex ce8cb1d61f..f24b749ec1 100644--- a/libs/flake/CMakeLists.txt+++ b/libs/flake/CMakeLists.txt@@ -251,6 +251,7 @@ set(kritaflake_SRCSresources/KoGamutMask.cppresources/KoFontFamily.cppresources/KoFontStorage.cpp+ resources/KoCssStylePreset.cppFlakeDebug.cpptests/MockShapes.cppdiff --git a/libs/flake/resources/KoCssStylePreset.cpp b/libs/flake/resources/KoCssStylePreset.cppnew file mode 100644index 0000000000..8fca5f9341--- /dev/null+++ b/libs/flake/resources/KoCssStylePreset.cpp@@ -0,0 +1,200 @@+/*+ * SPDX-FileCopyrightText: 2025 Wolthera van Hövell tot Westerflier <[email protected]>+ *+ * SPDX-License-Identifier: GPL-2.0-or-later+ */+#include "KoCssStylePreset.h"++#include <KoShapePainter.h>+#include <KoSvgTextShape.h>+#include <KoDocumentResourceManager.h>++#include <SvgWriter.h>+#include <SvgParser.h>++#include <QDomDocument>+#include <QBuffer>+#include <QFileInfo>++#include <FlakeDebug.h>++const QString TITLE = "title";+const QString DESCRIPTION = "description";+const QString DESC = "desc";+const QString SAMPLE_SVG = "sample_svg";+const QString STYLE_TYPE = "style_type";++struct KoCssStylePreset::Private {++ Private()+ : shape(new KoSvgTextShape())+ {+ }+ ~Private() {}++ QScopedPointer<KoSvgTextShape> shape;+};++KoCssStylePreset::KoCssStylePreset(const QString &filename)+ : KoResource(filename)+ , d(new Private())+{+ setName(name().replace("_", " "));+ if (name().endsWith(defaultFileExtension())) {+ const QFileInfo f(name());+ setName(f.completeBaseName());+ }+}++KoCssStylePreset::KoCssStylePreset(const KoCssStylePreset &rhs)+ : KoResource(rhs)+ , d(new Private())+{+ d->shape.reset(dynamic_cast<KoSvgTextShape*>(rhs.d->shape.data()->cloneShape()));+ setTitle(rhs.title());+ setDescription(rhs.description());+ setValid(true);+}++KoCssStylePreset::~KoCssStylePreset()+{++}++KoSvgTextProperties KoCssStylePreset::properties()+{+ const QVector<int> treeIndex = d->shape->findTreeIndexForPropertyId(KoSvgTextProperties::KraTextStyleType);+ return d->shape->propertiesForTreeIndex(treeIndex);+}++void KoCssStylePreset::setProperties(const KoSvgTextProperties &properties)+{+ const QVector<int> treeIndex = d->shape->findTreeIndexForPropertyId(KoSvgTextProperties::KraTextStyleType);+ if (d->shape->propertiesForTreeIndex(treeIndex) == properties) return;+ d->shape->setPropertiesAtTreeIndex(treeIndex, properties);+}++QString KoCssStylePreset::title() const+{+ return d->shape->additionalAttribute(TITLE);+}++void KoCssStylePreset::setTitle(QString title)+{+ d->shape->setAdditionalAttribute(TITLE, title);+}++QString KoCssStylePreset::description() const+{+ QMap<QString, QVariant> m = metadata();+ return m[DESCRIPTION].toString();+}++void KoCssStylePreset::setDescription(QString description)+{+ d->shape->setAdditionalAttribute(DESC, description);+ addMetaData(DESCRIPTION, description);+}++KoResourceSP KoCssStylePreset::clone() const+{+ return KoResourceSP(new KoCssStylePreset(*this));+}++bool KoCssStylePreset::loadFromDevice(QIODevice *dev, KisResourcesInterfaceSP resourcesInterface)+{+ if (!dev->isOpen()) dev->open(QIODevice::ReadOnly);+ QString errorMsg;+ int errorLine = 0;+ int errorColumn = 0;+ QDomDocument xmlDocument = SvgParser::createDocumentFromSvg(dev, &errorMsg, &errorLine, &errorColumn);+ if (xmlDocument.isNull()) {++ errorFlake << "Parsing error in " << filename() << "! Aborting!" << Qt::endl+ << " In line: " << errorLine << ", column: " << errorColumn << Qt::endl+ << " Error message: " << errorMsg << Qt::endl;+ errorFlake << "Parsing error in the main document at line" << errorLine+ << ", column" << errorColumn << Qt::endl+ << "Error message: " << errorMsg;++ return false;+ }++ KoDocumentResourceManager manager;+ SvgParser parser(&manager);+ parser.setResolution(QRectF(0,0,100,100), 72); // initialize with default values+ QSizeF fragmentSize;++ QList<KoShape*> shapes = parser.parseSvg(xmlDocument.documentElement(), &fragmentSize);++ Q_FOREACH(KoShape *shape, shapes) {+ KoSvgTextShape *textShape = dynamic_cast<KoSvgTextShape*>(shape);+ if (textShape) {+ d->shape.reset(textShape);+ setName(d->shape->additionalAttribute(TITLE));+ addMetaData(DESCRIPTION, d->shape->additionalAttribute(DESC));+ QVector<int> treeIndex = d->shape->findTreeIndexForPropertyId(KoSvgTextProperties::KraTextStyleType);+ qDebug() << "style found at..." << treeIndex;+ QString styleType = "paragraph";+ if (!treeIndex.isEmpty()) {+ KoSvgTextProperties props = d->shape->propertiesForTreeIndex(treeIndex);+ styleType = props.propertyOrDefault(KoSvgTextProperties::KraTextStyleType).toString();+ }++ addMetaData(STYLE_TYPE, styleType);++ qDebug() << "type..." << styleType;+ updateThumbnail();+ setValid(true);+ return true;+ }+ }+++ return false;+}++bool KoCssStylePreset::saveToDevice(QIODevice *dev) const+{+ if (!d->shape) return false;+ SvgWriter writer({d->shape.data()});+ return writer.save(dev, d->shape->boundingRect().size());+}++QString KoCssStylePreset::defaultFileExtension() const+{+ return ".svg";+}++QString generateSVG(const KoSvgTextShape *shape) {++ SvgWriter writer({shape->textOutline()});+ QBuffer buffer;+ buffer.open(QIODevice::WriteOnly);+ writer.save(buffer, shape->boundingRect().size());+ buffer.close();++ return QString::fromUtf8(buffer.data());+}++void KoCssStylePreset::updateThumbnail()+{+ QImage img(256,+ 256,+ QImage::Format_ARGB32);+ img.fill(Qt::white);++ KoShapePainter painter;+ painter.setShapes({d->shape.data()});+ painter.paint(img);++ /// generate SVG sample.+ addMetaData(SAMPLE_SVG, generateSVG(d->shape.data()));++ setImage(img);+}++QPair<QString, QString> KoCssStylePreset::resourceType() const+{+ return QPair<QString, QString>(ResourceType::CssStyles, "");+}diff --git a/libs/flake/resources/KoCssStylePreset.h b/libs/flake/resources/KoCssStylePreset.hnew file mode 100644index 0000000000..bd02517af0--- /dev/null+++ b/libs/flake/resources/KoCssStylePreset.h@@ -0,0 +1,56 @@+/*+ * SPDX-FileCopyrightText: 2025 Wolthera van Hövell tot Westerflier <[email protected]>+ *+ * SPDX-License-Identifier: GPL-2.0-or-later+ */+#ifndef KOCSSSTYLEPRESET_H+#define KOCSSSTYLEPRESET_H++#include <KoResource.h>+#include <KoSvgTextProperties.h>+#include <kritaflake_export.h>++class KoCssStylePreset;+typedef QSharedPointer<KoCssStylePreset> KoCssStylePresetSP;++/**+ * @brief The KoCssStylePreset class+ *+ * This is a Resource that represents style data.+ * Internally, the style data is stored inside a text shape,+ * allowing us to showcase the style data in context.+ */+class KRITAFLAKE_EXPORT KoCssStylePreset : public KoResource+{+public:+ KoCssStylePreset(const QString &filename);+ KoCssStylePreset(const KoCssStylePreset &rhs);+ KoCssStylePreset &operator=(const KoCssStylePreset &rhs) = delete;+ ~KoCssStylePreset();++ KoSvgTextProperties properties();+ void setProperties(const KoSvgTextProperties &properties);++ /// The proper title of the style.+ QString title() const;+ void setTitle(QString title);++ /// The description associated with this style.+ QString description() const;+ void setDescription(QString description);++ // KoResource interface+public:+ KoResourceSP clone() const override;+ bool loadFromDevice(QIODevice *dev, KisResourcesInterfaceSP resourcesInterface) override;+ bool saveToDevice(QIODevice *dev) const override;+ QString defaultFileExtension() const override;+ void updateThumbnail() override;+ QPair<QString, QString> resourceType() const override;+private:+ struct Private;+ QScopedPointer<Private> d;++};++#endif // KOCSSSTYLEPRESET_Hdiff --git a/libs/flake/text/KoSvgTextContentElement.cpp b/libs/flake/text/KoSvgTextContentElement.cppindex ead3adae17..9c7cc769a6 100644--- a/libs/flake/text/KoSvgTextContentElement.cpp+++ b/libs/flake/text/KoSvgTextContentElement.cpp@@ -157,6 +157,8 @@ KoSvgTextProperties adjustPropertiesForFontSizeWorkaround(const KoSvgTextPropert}+const QString TEXT_STYLE_TYPE = "krita:style-type";+bool KoSvgTextContentElement::loadSvg(const QDomElement &e, SvgLoadingContext &context, bool rootNode){SvgGraphicsContext *gc = context.currentGC();@@ -229,6 +231,10 @@ bool KoSvgTextContentElement::loadSvg(const QDomElement &e, SvgLoadingContext &c}}+ if (e.hasAttribute(TEXT_STYLE_TYPE.toLatin1().data())) {+ properties.setProperty(KoSvgTextProperties::KraTextStyleType, e.attribute(TEXT_STYLE_TYPE.toLatin1().data()));+ }+return true;}@@ -351,6 +357,10 @@ bool KoSvgTextContentElement::saveSvg(SvgSavingContext &context,context.shapeWriter().addAttribute("style", styleString);}+ if (properties.hasProperty(KoSvgTextProperties::KraTextStyleType)) {+ context.shapeWriter().addAttribute(TEXT_STYLE_TYPE.toLatin1().data(), properties.property(KoSvgTextProperties::KraTextStyleType).toString());+ }+if (saveText) {context.shapeWriter().addTextNode(text);}diff --git a/libs/flake/text/KoSvgTextProperties.h b/libs/flake/text/KoSvgTextProperties.hindex df854c962e..13b964f367 100644--- a/libs/flake/text/KoSvgTextProperties.h+++ b/libs/flake/text/KoSvgTextProperties.h@@ -116,7 +116,8 @@ public:TextRenderingId, ///< Enum- KraTextVersionId ///< Int, used for handling incorrectly saved files.+ KraTextVersionId, ///< Int, used for handling incorrectly saved files.+ KraTextStyleType, ///< string, used to identify the style preset type (character or paragraph).};KoSvgTextProperties();diff --git a/libs/flake/text/KoSvgTextShape.cpp b/libs/flake/text/KoSvgTextShape.cppindex d93a148715..0048b9a333 100644--- a/libs/flake/text/KoSvgTextShape.cpp+++ b/libs/flake/text/KoSvgTextShape.cpp@@ -1049,6 +1049,80 @@ void KoSvgTextShape::cleanUp()shapeChangedPriv(ContentChanged);}+QVector<int> findTreeIndexForPropertyIdImpl(KisForest<KoSvgTextContentElement>::child_iterator parent, KoSvgTextProperties::PropertyId propertyId) {+ int count = 0;+ for (auto child = KisForestDetail::childBegin(parent); child != KisForestDetail::childEnd(parent); child++) {+ if (child->properties.hasProperty(propertyId)) {+ return QVector<int>({count});+ } else if (KisForestDetail::childBegin(child) != KisForestDetail::childEnd(child)) {+ QVector current = QVector<int>({count});+ QVector childIndex = findTreeIndexForPropertyIdImpl(child, propertyId);+ if (!childIndex.isEmpty()) {+ current.append(childIndex);+ return current;+ }+ }+ count += 1;+ }+ return QVector<int>();+}++QVector<int> KoSvgTextShape::findTreeIndexForPropertyId(KoSvgTextProperties::PropertyId propertyId)+{+ QVector<int> treeIndex;++ for (auto it = d->textData.childBegin(); it != d->textData.childEnd(); it++) {+ treeIndex = findTreeIndexForPropertyIdImpl(it, propertyId);+ treeIndex.insert(0, 0);+ }++ return treeIndex;+}++KoSvgTextProperties KoSvgTextShape::propertiesForTreeIndex(const QVector<int> &treeIndex) const+{+ if (treeIndex.isEmpty()) return KoSvgTextProperties();+ QVector<int> idx = treeIndex;+ idx.removeFirst();+ for (auto it = d->textData.childBegin(); it != d->textData.childEnd(); it++) {+ if (idx.isEmpty()) {+ if (it != d->textData.childEnd()) {+ return it->properties;+ } else {+ return KoSvgTextProperties();+ }+ }+ auto child = d->iteratorForTreeIndex(idx, it);+ if (child != d->textData.childEnd()) {+ return child->properties;+ }+ }+ return KoSvgTextProperties();+}++bool KoSvgTextShape::setPropertiesAtTreeIndex(const QVector<int> treeIndex, const KoSvgTextProperties props)+{+ QVector<int> idx = treeIndex;+ if (treeIndex.isEmpty()) return false;+ idx.removeFirst();+ for (auto it = d->textData.childBegin(); it != d->textData.childEnd(); it++) {+ if (idx.isEmpty()) {+ if (it != d->textData.childEnd()) {+ it->properties = props;+ return true;+ } else {+ return false;+ }+ }+ auto child = d->iteratorForTreeIndex(idx, it);+ if (child != d->textData.childEnd()) {+ child->properties = props;+ return true;+ }+ }+ return false;+}+KoSvgTextProperties KoSvgTextShape::textProperties() const{return KisForestDetail::size(d->textData)? d->textData.childBegin()->properties: KoSvgTextProperties();diff --git a/libs/flake/text/KoSvgTextShape.h b/libs/flake/text/KoSvgTextShape.hindex 5196847694..bbb1a6253f 100644--- a/libs/flake/text/KoSvgTextShape.h+++ b/libs/flake/text/KoSvgTextShape.h@@ -352,6 +352,28 @@ public:/// Cleans up the internal text data. Used by undo commands.void cleanUp();+ /**+ * @brief findTreeIndexForPropertyId+ * @return the tree index of the first content element found with a given property id.+ * Empty vector means none was found.+ * @propertyId -- id to search for.+ */+ QVector<int> findTreeIndexForPropertyId(KoSvgTextProperties::PropertyId propertyId);++ /**+ * @brief propertiesForTreeIndex+ * @param treeIndex -- vector representing the tree index.+ * @return properties at the given tree index. If the tree index is wrong, empty properties will be returned.+ */+ KoSvgTextProperties propertiesForTreeIndex(const QVector<int> &treeIndex) const;++ /**+ * @brief setPropertiesAtTreeIndex+ * @param treeIndex -- set text properties at given tree index.+ * @return if successful.+ */+ bool setPropertiesAtTreeIndex(const QVector<int> treeIndex, const KoSvgTextProperties props);+/*--------------- Properties ---------------*/KoSvgTextProperties textProperties() const;@@ -362,6 +384,7 @@ public:QVector<PaintOrder> paintOrder() const override;void setPaintOrder(PaintOrder first, PaintOrder second) override;+/*** @brief plainText* plain text of all text inside this text shape,diff --git a/libs/flake/text/KoSvgTextShape_p.h b/libs/flake/text/KoSvgTextShape_p.hindex 970ce1fc92..b3662c08fe 100644--- a/libs/flake/text/KoSvgTextShape_p.h+++ b/libs/flake/text/KoSvgTextShape_p.h@@ -739,6 +739,23 @@ public:}}}++ static KisForest<KoSvgTextContentElement>::child_iterator iteratorForTreeIndex(const QVector<int> treeIndex, KisForest<KoSvgTextContentElement>::child_iterator parent) {+ if (treeIndex.isEmpty()) return parent;+ QVector<int> idx = treeIndex;+ int count = idx.takeFirst();+ for (auto child = KisForestDetail::childBegin(parent); child != KisForestDetail::childEnd(parent); child++) {+ if (count == 0) {+ if ((KisForestDetail::childBegin(child) != KisForestDetail::childEnd(child))) {+ return iteratorForTreeIndex(idx, child);+ } else {+ return child;+ }+ }+ count -= 1;+ }+ return KisForestDetail::childEnd(parent);+ }};#endif // KO_SVG_TEXT_SHAPE_P_Hdiff --git a/libs/resources/KisResourceTypes.cpp b/libs/resources/KisResourceTypes.cppindex 418cfc5991..5e8e0911fa 100644--- a/libs/resources/KisResourceTypes.cpp+++ b/libs/resources/KisResourceTypes.cpp@@ -26,6 +26,7 @@ namespace ResourceType {const QString TaskSets {QStringLiteral("tasksets")};const QString LayerStyles {QStringLiteral("layerstyles")};const QString FontFamilies {QStringLiteral("fontfamilies")};+ const QString CssStyles {QStringLiteral("css_styles")};}namespace ResourceSubType {@@ -56,6 +57,7 @@ namespace ResourceName {const KLocalizedString TaskSets = ki18nc("resource type", "Task Sets");const KLocalizedString LayerStyles = ki18nc("resource type", "Layer Styles");const KLocalizedString FontFamilies = ki18nc("resource type", "Font Families");+ const KLocalizedString CssStyles = ki18nc("resource type", "Style Presets");}QString ResourceName::resourceTypeToName(const QString &resourceType)@@ -80,6 +82,7 @@ QString ResourceName::resourceTypeToName(const QString &resourceType)typeMap[ResourceType::TaskSets] = ResourceName::TaskSets.toString();typeMap[ResourceType::LayerStyles] = ResourceName::LayerStyles.toString();typeMap[ResourceType::FontFamilies] = ResourceName::FontFamilies.toString();+ typeMap[ResourceType::CssStyles] = ResourceName::CssStyles.toString();return typeMap;}();diff --git a/libs/resources/KisResourceTypes.h b/libs/resources/KisResourceTypes.hindex 6c2fe6d8b6..54af5fadd4 100644--- a/libs/resources/KisResourceTypes.h+++ b/libs/resources/KisResourceTypes.h@@ -29,6 +29,7 @@ namespace ResourceType {KRITARESOURCES_EXPORT extern const QString TaskSets;KRITARESOURCES_EXPORT extern const QString LayerStyles;KRITARESOURCES_EXPORT extern const QString FontFamilies;+ KRITARESOURCES_EXPORT extern const QString CssStyles;}namespace ResourceSubType {@@ -59,6 +60,7 @@ namespace ResourceName {KRITARESOURCES_EXPORT extern const KLocalizedString TaskSets;KRITARESOURCES_EXPORT extern const KLocalizedString LayerStyles;KRITARESOURCES_EXPORT extern const KLocalizedString FontFamilies;+ KRITARESOURCES_EXPORT extern const KLocalizedString CssStyles;KRITARESOURCES_EXPORT QString resourceTypeToName(const QString &resourceType);diff --git a/libs/ui/KisApplication.cpp b/libs/ui/KisApplication.cppindex af01303855..d9148efd46 100644--- a/libs/ui/KisApplication.cpp+++ b/libs/ui/KisApplication.cpp@@ -99,6 +99,7 @@#include <KisSessionResource.h>#include <resources/KoSvgSymbolCollectionResource.h>#include <resources/KoFontFamily.h>+#include <resources/KoCssStylePreset.h>#include "widgets/KisScreenColorSampler.h"#include "KisDlgInternalColorSelector.h"@@ -398,6 +399,7 @@ bool KisApplication::registerResources()QStringList() << "application/x-photoshop-style"));reg->add(new KisResourceLoader<KoFontFamily>(ResourceType::FontFamilies, ResourceType::FontFamilies, i18n("Font Families"), QStringList() << "application/x-font-ttf" << "application/x-font-otf"));+ reg->add(new KisResourceLoader<KoCssStylePreset>(ResourceType::CssStyles, ResourceType::CssStyles, i18n("Style Presets"), QStringList() << "image/svg+xml"));reg->registerFixup(10, new KisBrushTypeMetaDataFixup());diff --git a/libs/widgets/KoResourceServerProvider.cpp b/libs/widgets/KoResourceServerProvider.cppindex 7b045ca0cd..5aa928c776 100644--- a/libs/widgets/KoResourceServerProvider.cpp+++ b/libs/widgets/KoResourceServerProvider.cpp@@ -104,6 +104,7 @@ struct Q_DECL_HIDDEN KoResourceServerProvider::PrivateKoResourceServer<KoColorSet> *paletteServer;KoResourceServer<KoSvgSymbolCollectionResource> *svgSymbolCollectionServer;KoResourceServer<KoGamutMask> *gamutMaskServer;+ KoResourceServer<KoCssStylePreset> *stylePresetServer;#if defined HAVE_SEEXPRKoResourceServer<KisSeExprScript>* seExprScriptServer;#endif@@ -116,6 +117,7 @@ KoResourceServerProvider::KoResourceServerProvider() : d(new Private)d->paletteServer = new KoResourceServer<KoColorSet>(ResourceType::Palettes);d->svgSymbolCollectionServer = new KoResourceServer<KoSvgSymbolCollectionResource>(ResourceType::Symbols);d->gamutMaskServer = new KoResourceServer<KoGamutMask>(ResourceType::GamutMasks);+ d->stylePresetServer = new KoResourceServer<KoCssStylePreset>(ResourceType::CssStyles);#if defined HAVE_SEEXPRd->seExprScriptServer = new KoResourceServer<KisSeExprScript>(ResourceType::SeExprScripts);#endif@@ -128,6 +130,7 @@ KoResourceServerProvider::~KoResourceServerProvider()delete d->paletteServer;delete d->svgSymbolCollectionServer;delete d->gamutMaskServer;+ delete d->stylePresetServer;#if defined HAVE_SEEXPRdelete d->seExprScriptServer;#endif@@ -167,6 +170,11 @@ KoResourceServer<KoGamutMask> *KoResourceServerProvider::gamutMaskServer()return KoResourceServerProvider::instance()->d->gamutMaskServer;}+KoResourceServer<KoCssStylePreset> *KoResourceServerProvider::stylePresetServer()+{+ return KoResourceServerProvider::instance()->d->stylePresetServer;+}+#if defined HAVE_SEEXPRKoResourceServer<KisSeExprScript> *KoResourceServerProvider::seExprScriptServer(){diff --git a/libs/widgets/KoResourceServerProvider.h b/libs/widgets/KoResourceServerProvider.hindex 8454786e37..faaeda5d1c 100644--- a/libs/widgets/KoResourceServerProvider.h+++ b/libs/widgets/KoResourceServerProvider.h@@ -22,6 +22,7 @@#include <resources/KoColorSet.h>#include <resources/KoSvgSymbolCollectionResource.h>#include <resources/KoGamutMask.h>+#include <resources/KoCssStylePreset.h>#include <config-seexpr.h>#if defined HAVE_SEEXPR#include <resources/KisSeExprScript.h>@@ -45,6 +46,7 @@ public:static KoResourceServer<KoColorSet> *paletteServer();static KoResourceServer<KoSvgSymbolCollectionResource> *svgSymbolCollectionServer();static KoResourceServer<KoGamutMask> *gamutMaskServer();+ static KoResourceServer<KoCssStylePreset> *stylePresetServer();#if defined HAVE_SEEXPRstatic KoResourceServer<KisSeExprScript> *seExprScriptServer();#endif