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++
Initial implementation typesetting mode.
Wolthera van Hövell tot Westerfliercc31ff609d76
diff --git a/libs/command/kis_command_ids.h b/libs/command/kis_command_ids.hindex 4ce7488e04..33bbe407eb 100644--- a/libs/command/kis_command_ids.h+++ b/libs/command/kis_command_ids.h@@ -42,7 +42,8 @@ enum CommandId {ChangePaintOrderCommand,SvgTextMergePropertiesRangeCommand,KoShapeMergeTextPropertiesCommandId,- ImageAnimSettingCommandId+ ImageAnimSettingCommandId,+ SvgTextChangeTransformsOnRangeCommandId,};}diff --git a/libs/flake/text/KoSvgTextShape.cpp b/libs/flake/text/KoSvgTextShape.cppindex 83485c69e5..17ac7765a6 100644--- a/libs/flake/text/KoSvgTextShape.cpp+++ b/libs/flake/text/KoSvgTextShape.cpp@@ -882,12 +882,17 @@ KoSvgTextProperties KoSvgTextShape::propertiesForPos(const int pos, bool inherit}KoSvgTextProperties inheritProperties(KisForest<KoSvgTextContentElement>::depth_first_tail_iterator it) {- KoSvgTextProperties props = it->properties;+ QList<KisForest<KoSvgTextContentElement>::hierarchy_iterator> hierarchy;for (auto parentIt = KisForestDetail::hierarchyBegin(siblingCurrent(it));parentIt != KisForestDetail::hierarchyEnd(siblingCurrent(it)); parentIt++) {- KoSvgTextProperties parentProps = parentIt->properties;- parentProps.setAllButNonInheritableProperties(props);- props = parentProps;+ hierarchy.append(parentIt);+ }+ KoSvgTextProperties props = KoSvgTextProperties::defaultProperties();+ while (!hierarchy.isEmpty()) {+ auto it = hierarchy.takeLast();+ KoSvgTextProperties p = it->properties;+ p.inheritFrom(props, true);+ props = p;}return props;}@@ -1099,6 +1104,192 @@ void KoSvgTextShape::cleanUp()shapeChangedPriv(ContentChanged);}+bool KoSvgTextShape::setCharacterTransformsOnRange(const int startPos, const int endPos, const QVector<QPointF> positions, const QVector<qreal> rotateDegrees, const bool deltaPosition)+{+ if ((startPos < 0 && startPos == endPos) || d->cursorPos.isEmpty()) {+ return false;+ }+ const int finalPos = d->cursorPos.size()-1;+ const int startIndex = d->cursorPos.at(qBound(0, qMin(startPos, endPos), finalPos)).index;+ int endIndex = d->cursorPos.at(qBound(0, qMax(startPos, endPos), finalPos)).index;+ if (startIndex == endIndex) {+ endIndex += 1;+ while(d->result.at(endIndex).middle) {+ endIndex += 1;+ if (endIndex > d->result.size()) break;+ }+ }++ bool changed = false;++ QVector<KoSvgText::CharTransformation> resolvedTransforms = Private::resolvedTransformsForTree(d->textData, !shapesInside().isEmpty(), true);+ Private::removeTransforms(d->textData, startIndex, endIndex-startIndex);+ QPointF totalStartDelta;+ QPointF anchorAbsolute;+ QPointF anchorCssPos;++ if (deltaPosition) {+ for (int i = 0; i< startIndex; i++) {+ KoSvgText::CharTransformation tf = resolvedTransforms.value(i);+ if (tf.xPos) {+ totalStartDelta.setX(0);+ anchorAbsolute.setX(*tf.xPos);+ }+ if (tf.yPos) {+ totalStartDelta.setY(0);+ anchorAbsolute.setY(*tf.yPos);+ }+ if (tf.startsNewChunk()) {+ anchorCssPos = d->result.value(i).cssPosition;+ }+ totalStartDelta += tf.relativeOffset();+ }+ }++ int currentIndex = 0;+ QPointF accumulatedOffset;+ for (auto it = d->textData.depthFirstTailBegin(); it != d->textData.depthFirstTailEnd(); it++) {+ if (KoSvgTextShape::Private::childCount(siblingCurrent(it)) > 0) {+ continue;+ // TODO: also skip textpaths, their transforms aren't read.+ }++ int endContentElement = it->finalResultIndex;++ if (endContentElement >= startIndex && currentIndex <= endIndex) {++ QVector<KoSvgText::CharTransformation> transforms;+ int addressableOffset = 0;+ for (int i = currentIndex; (i < endContentElement); i++) {+ const CharacterResult res = d->result.value(i);+ if (!res.addressable) {+ addressableOffset += 1;+ continue;+ }++ int transformIndex = (i - startIndex) - addressableOffset;+ KoSvgText::CharTransformation tf = resolvedTransforms.value(i, KoSvgText::CharTransformation());+ if (i < startIndex) {+ if (!deltaPosition) {+ const QPointF p = res.finalPosition - res.textPathAndAnchoringOffset;+ if (!tf.xPos) {+ tf.xPos = p.x();+ }+ if (!tf.yPos) {+ tf.yPos = p.y();+ }+ }+ transforms << tf;+ continue;+ }+ if (i >= endIndex) {+ if (i == endIndex) {+ // Counter transform to keep unselected characters at the same pos.+ if (deltaPosition && !tf.startsNewChunk()) {+ QPointF delta = res.finalPosition - (res.textPathAndAnchoringOffset + anchorAbsolute + res.textLengthOffset);+ delta -= (totalStartDelta + accumulatedOffset + (res.cssPosition-anchorCssPos));+ tf.dxPos = delta.x();+ tf.dyPos = delta.y();+ } else {+ const QPointF p = res.finalPosition - res.textPathAndAnchoringOffset;+ tf.xPos = p.x();+ tf.yPos = p.y();+ }+ }+ transforms << tf;+ continue;+ }++ if (rotateDegrees.size()+startIndex > i) {+ tf.rotate = kisDegreesToRadians(rotateDegrees.value(transformIndex, tf.rotate? *tf.rotate: rotateDegrees.last()));+ }+ if (positions.size()+startIndex > i) {+ const QPointF pos = positions.value(transformIndex, QPointF());+++ if (deltaPosition) {+ if (tf.startsNewChunk()) {+ anchorAbsolute = tf.absolutePos();+ totalStartDelta = tf.relativeOffset();+ anchorCssPos = res.cssPosition;+ }++ QPointF delta = pos - (res.textPathAndAnchoringOffset + anchorAbsolute + res.textLengthOffset);+ delta -= (totalStartDelta + accumulatedOffset + (res.cssPosition-anchorCssPos));+ tf.dxPos = delta.x();+ tf.dyPos = delta.y();+ if (tf.startsNewChunk()) {+ accumulatedOffset = QPointF();+ totalStartDelta = tf.relativeOffset();+ } else {+ accumulatedOffset += tf.relativeOffset();+ }+ } else {+ const QPointF delta = pos - res.textPathAndAnchoringOffset;+ tf.xPos = delta.x();+ tf.yPos = delta.y();+ }+ }++ transforms << tf;+ }+ it->localTransformations = transforms;+ changed = true;+ }+ currentIndex = it->finalResultIndex;+ if (currentIndex > endIndex) {+ break;+ }+ }++ if (changed) {+ KoSvgTextShape::Private::cleanUp(d->textData);+ notifyChanged();+ shapeChangedPriv(ContentChanged);+ }++ return changed;+}++KoSvgTextCharacterInfo infoFromCharacterResult(const CharacterResult &res, const int index) {+ KoSvgTextCharacterInfo info;+ info.finalPos = res.finalPosition;+ info.rotateDeg = kisRadiansToDegrees(res.rotate);+ info.visualIndex = res.visualIndex;+ info.middle = res.middle;+ info.advance = res.advance;+ info.logicalIndex = index;+ info.rtl = res.cursorInfo.rtl;+ info.metrics = res.metrics;+ return info;+}++QList<KoSvgTextCharacterInfo> KoSvgTextShape::getPositionsAndRotationsForRange(const int startPos, const int endPos) const+{+ QList<KoSvgTextCharacterInfo> infos;+ if ((startPos < 0 && startPos == endPos) || d->cursorPos.isEmpty()) {+ return infos;+ }+ const int finalPos = d->cursorPos.size()-1;+ const int startIndex = d->cursorPos.at(qBound(0, qMin(startPos, endPos), finalPos)).index;+ const int endIndex = d->cursorPos.at(qBound(0, qMax(startPos, endPos), finalPos)).index;++ for (int i = startIndex; i < endIndex; i++) {+ CharacterResult res = d->result.value(i);+ if (!res.addressable) continue;+ infos << infoFromCharacterResult(res, i);+ }++ if (endIndex == startIndex) {+ CharacterResult resFinal = d->result.value(startIndex);+ if (resFinal.addressable) {+ infos << infoFromCharacterResult(resFinal, startIndex);+ }+ }++ return infos;+}+KisForest<KoSvgTextContentElement>::child_iterator findNodeIndexForPropertyIdImpl(KisForest<KoSvgTextContentElement>::child_iterator parent, KoSvgTextProperties::PropertyId propertyId) {for (auto child = KisForestDetail::childBegin(parent); child != KisForestDetail::childEnd(parent); child++) {if (child->properties.hasProperty(propertyId)) {@@ -1709,9 +1900,14 @@ KoSvgTextShape::TextType KoSvgTextShape::textType() consttextSpaceCollapse = true;break;}+ if (!it->localTransformations.isEmpty()) {+ textSpaceCollapse = true;+ break;+ }}return textSpaceCollapse? TextType::PrePositionedText: TextType::PreformattedText;}+ return TextType::PrePositionedText;}void KoSvgTextShape::setShapesInside(QList<KoShape *> shapesInside)diff --git a/libs/flake/text/KoSvgTextShape.h b/libs/flake/text/KoSvgTextShape.hindex 78c0566174..e9081df9c4 100644--- a/libs/flake/text/KoSvgTextShape.h+++ b/libs/flake/text/KoSvgTextShape.h@@ -19,6 +19,7 @@class KoSvgTextShapeMemento;class KoSvgTextNodeIndex;+struct KoSvgTextCharacterInfo;typedef QSharedPointer<KoSvgTextShapeMemento> KoSvgTextShapeMementoSP;#define KoSvgTextShape_SHAPEID "KoSvgTextShapeID"@@ -373,6 +374,28 @@ public:/// Cleans up the internal text data. Used by undo commands.void cleanUp();+ /**+ * @brief setCharacterTransformsOnRange+ * Set SVG 1.1 style character transforms on the given range. Will not work+ * when the shape is auto wrapping.+ * @param startPos -- start of range+ * @param endPos -- end of range+ * @param positions -- positions, in shape coordinates.+ * @param rotations -- rotations, in degrees.+ * @param deltaPosition -- whether to calculate and set the delta positions.+ * @return whether successful.+ */+ bool setCharacterTransformsOnRange(const int startPos, const int endPos, const QVector<QPointF> positions, const QVector<qreal> rotateDegrees, const bool deltaPosition = true);++ /**+ * @brief getPositionsAndRotationsForRange+ * @param startPos -- start of range.+ * @param endPos -- end of range, not inclusive.+ * @param includeLastAdvance -- include a transform at the end that represents the last transform+advance.+ * @return list of qpairs, with the first value being the final position, and the second the final rotation.+ */+ QList<KoSvgTextCharacterInfo> getPositionsAndRotationsForRange(const int startPos, const int endPos) const;+/****************************************************************************** KoSvgTextNodeIndex functions.*@@ -600,6 +623,41 @@ private:};+/**+ * @brief The KoSvgTextCharacterInfo class+ * This is a small struct to convey information about+ * character positioning inside a textShape.+ * It's functionally a simplified readonly version+ * of CharacterResult inside the TextShape.+ *+ * Currently used for character transform adjustments.+ */+struct KoSvgTextCharacterInfo {+ QPointF finalPos;+ QPointF advance;+ qreal rotateDeg; // Rotation in radians.+ int visualIndex = -1;+ int logicalIndex = -1;+ bool rtl = false;+ bool middle = false; /// <Whether the character is in the middle of a cluster.+ KoSvgText::FontMetrics metrics;++ // For use with std::sort+ static bool visualLessThan(const KoSvgTextCharacterInfo &a, const KoSvgTextCharacterInfo &b) {+ bool compare = false;+ if (a.visualIndex >= 0+ && b.visualIndex >= 0) {+ compare = a.visualIndex < b.visualIndex;+ } else {+ compare = a.logicalIndex < b.logicalIndex;+ }+ return compare;+ }+ static bool logicalLessThan(const KoSvgTextCharacterInfo &a, const KoSvgTextCharacterInfo &b) {+ return a.logicalIndex < b.logicalIndex;+ }+};+class KoSvgTextShapeFactory : public KoShapeFactoryBase{diff --git a/libs/flake/text/KoSvgTextShape_p.h b/libs/flake/text/KoSvgTextShape_p.hindex 58212c1bc8..e351f155b5 100644--- a/libs/flake/text/KoSvgTextShape_p.h+++ b/libs/flake/text/KoSvgTextShape_p.h@@ -108,6 +108,8 @@ struct CharacterResult {int visualIndex = -1;int plaintTextIndex = -1;QPointF cssPosition = QPointF(); ///< the position in accordance with the CSS specs, as opossed to the SVG spec.+ QPointF textLengthOffset = QPointF(); ///< offset caused by textLength+ QPointF textPathAndAnchoringOffset = QPointF(); ///< Offset caused by textPath and anchoring.QPointF dominantBaselineOffset = QPointF(); // Shift caused by aligning glyphs to dominant baseline.QPointF baselineOffset = QPointF(); ///< The computed baseline offset, will be applied///< when calculating the line-offset during line breaking.@@ -700,7 +702,7 @@ public:* @param alsoCollapseLowSurrogate -- whether to mark utf16 surrogates as collapsed too.* @return list of collapsed characters*/- static QVector<bool> collapsedWhiteSpacesForText(KisForest<KoSvgTextContentElement> &tree, QString &allText, const bool alsoCollapseLowSurrogate = false) {+ static QVector<bool> collapsedWhiteSpacesForText(KisForest<KoSvgTextContentElement> &tree, QString &allText, const bool alsoCollapseLowSurrogate = false, bool includeBidiControls = false) {QMap<int, KoSvgText::TextSpaceCollapse> collapseModes;QList<KoSvgTextProperties> parentProps = {KoSvgTextProperties::defaultProperties()};@@ -713,6 +715,14 @@ public:const int children = childCount(siblingCurrent(it));if (children == 0) {QString text = it->text;+ if (includeBidiControls) {+ KoSvgText::UnicodeBidi bidi = KoSvgText::UnicodeBidi(parentProps.last().propertyOrDefault(KoSvgTextProperties::UnicodeBidiId).toInt());+ KoSvgText::Direction direction = KoSvgText::Direction(parentProps.last().propertyOrDefault(KoSvgTextProperties::DirectionId).toInt());+ QVector<QPair<int, int>> positions;+ QString text = KoCssTextUtils::getBidiOpening(direction, bidi);+ text += it->getTransformedString(positions, parentProps.last());+ text += KoCssTextUtils::getBidiClosing(bidi);+ }KoSvgText::TextSpaceCollapse collapse = KoSvgText::TextSpaceCollapse(parentProps.last().propertyOrDefault(KoSvgTextProperties::TextCollapseId).toInt());collapseModes.insert(allText.size(), collapse);allText += text;@@ -773,6 +783,7 @@ public:int transformOffsetEnd = 0;for (int i = globalIndex; i < globalIndex + currentLength; i++) {+ if (i >= collapsedCharacters.size()) break;if (i < start) {transformOffset += collapsedCharacters.at(i)? 0: 1;}@@ -783,7 +794,8 @@ public:}}if (transformOffset < currentTextElement->localTransformations.size()) {- currentTextElement->localTransformations.remove(transformOffset, transformOffsetEnd-transformOffset);+ currentTextElement->localTransformations.remove(transformOffset,+ qBound(0, transformOffsetEnd-transformOffset, currentTextElement->localTransformations.size()));}}@@ -913,16 +925,9 @@ public:}}- /**- * @brief insertNewLinesAtAnchors- * Resolves character transforms and then inserts new lines at each- * transform that creates a new chunk.- * @param tree -- tree to apply to.- * @param shapesInside -- whether we're wrapping in shape.- */- static void insertNewLinesAtAnchors(KisForest<KoSvgTextContentElement> &tree, bool shapesInside = false) {+ static QVector<KoSvgText::CharTransformation> resolvedTransformsForTree(KisForest<KoSvgTextContentElement> &tree, bool shapesInside = false, bool includeBidiControls = false) {QString all;- QVector<bool> collapsed = collapsedWhiteSpacesForText(tree, all, false);+ QVector<bool> collapsed = collapsedWhiteSpacesForText(tree, all, false, includeBidiControls);QVector<CharacterResult> result(all.size());int globalIndex = 0;KoSvgTextProperties props = tree.childBegin()->properties;@@ -937,6 +942,18 @@ public:isHorizontal, isWrapped, false, resolvedTransforms,collapsed, KoSvgTextProperties::defaultProperties(),false);+ return resolvedTransforms;+ }++ /**+ * @brief insertNewLinesAtAnchors+ * Resolves character transforms and then inserts new lines at each+ * transform that creates a new chunk.+ * @param tree -- tree to apply to.+ * @param shapesInside -- whether we're wrapping in shape.+ */+ static void insertNewLinesAtAnchors(KisForest<KoSvgTextContentElement> &tree, bool shapesInside = false) {+ QVector<KoSvgText::CharTransformation> resolvedTransforms = resolvedTransformsForTree(tree, shapesInside);auto end = std::make_reverse_iterator(tree.childBegin());auto begin = std::make_reverse_iterator(tree.childEnd());diff --git a/libs/flake/text/KoSvgTextShape_p_layout.cpp b/libs/flake/text/KoSvgTextShape_p_layout.cppindex bced35c1f8..8e87a036b0 100644--- a/libs/flake/text/KoSvgTextShape_p_layout.cpp+++ b/libs/flake/text/KoSvgTextShape_p_layout.cpp@@ -1009,6 +1009,7 @@ void KoSvgTextShape::Private::applyTextLength(KisForest<KoSvgTextContentElement>CharacterResult cr = result[visualToLogical.value(k)];if (cr.addressable) {cr.finalPosition += shift;+ cr.textLengthOffset += shift;if (spacingAndGlyphs) {QPointF scale(d.x() != 0 ? (d.x() / cr.advance.x()) + 1 : 1.0, d.y() != 0 ? (d.y() / cr.advance.y()) + 1 : 1.0);cr.scaleCharacterResult(scale.x(), scale.y());@@ -1690,6 +1691,7 @@ void KoSvgTextShape::Private::applyAnchoring(QVector<CharacterResult> &result, bfor (int j = start; j < end; j++) {result[j].finalPosition += shiftP;+ result[j].textPathAndAnchoringOffset += shiftP;}start = end;}@@ -1877,6 +1879,7 @@ void KoSvgTextShape::Private::applyTextPath(KisForest<KoSvgTextContentElement>::tAngle = 0 - (360 - tAngle);}const QPointF vectorT(qCos(qDegreesToRadians(tAngle)), -qSin(qDegreesToRadians(tAngle)));+ const QPointF originalPos = cr.finalPosition;if (isHorizontal) {cr.rotate -= qDegreesToRadians(tAngle);QPointF vectorN(-vectorT.y(), vectorT.x());@@ -1888,6 +1891,7 @@ void KoSvgTextShape::Private::applyTextPath(KisForest<KoSvgTextContentElement>::const qreal o = (cr.advance.y() * 0.5);cr.finalPosition = pos - (o * vectorT) + (cr.finalPosition.x() * vectorN);}+ cr.textPathAndAnchoringOffset += (cr.finalPosition - originalPos);// FIXME: What about other glyph formats?if (stretch && outlineGlyph) {const QTransform tf = cr.finalTransform();@@ -1911,6 +1915,7 @@ void KoSvgTextShape::Private::applyTextPath(KisForest<KoSvgTextContentElement>::afterPath = false;} else {cr.finalPosition += pathEnd;+ cr.textPathAndAnchoringOffset += pathEnd;result[i] = cr;}}diff --git a/plugins/tools/svgtexttool/CMakeLists.txt b/plugins/tools/svgtexttool/CMakeLists.txtindex 64c5160db2..87e0415e2d 100644--- a/plugins/tools/svgtexttool/CMakeLists.txt+++ b/plugins/tools/svgtexttool/CMakeLists.txt@@ -26,6 +26,8 @@ set (SvgTextTool_SRCSSvgTextToolOptionsData.cppSvgTextToolOptionsModel.cppSvgTextToolOptionsManager.cpp+ SvgTextChangeTransformsOnRange.cpp+ SvgTextTypeSettingStrategy.cppglyphpalette/GlyphPaletteDialog.cppglyphpalette/GlyphPaletteProxyModel.cppdiff --git a/plugins/tools/svgtexttool/SvgTextChangeTransformsOnRange.cpp b/plugins/tools/svgtexttool/SvgTextChangeTransformsOnRange.cppnew file mode 100644index 0000000000..c150625b2e--- /dev/null+++ b/plugins/tools/svgtexttool/SvgTextChangeTransformsOnRange.cpp@@ -0,0 +1,139 @@+/*+ * SPDX-FileCopyrightText: 2025 Wolthera van Hövell tot Westerflier <[email protected]>+ *+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#include "SvgTextChangeTransformsOnRange.h"+#include "kis_command_ids.h"++SvgTextChangeTransformsOnRange::SvgTextChangeTransformsOnRange(KoSvgTextShape *shape, int startPos, int endPos, QVector<QPointF> positions, QVector<qreal> rotations, bool calculateDeltaPositions, KUndo2Command *parentCommand)+ : KUndo2Command(parentCommand)+ , m_textShape(shape)+ , m_startPos(startPos)+ , m_endPos(endPos)+ , m_positions(positions)+ , m_rotations(rotations)+ , m_calculateDeltaPositions(calculateDeltaPositions)+ , m_textData(shape->getMemento())+{+ setText(kundo2_i18n("Adjust character transforms on text."));+}++SvgTextChangeTransformsOnRange::SvgTextChangeTransformsOnRange(KoSvgTextShape *shape, int startPos, int endPos, QPointF delta, OffsetType type, bool calculateDeltaPositions, KUndo2Command *parentCommand)+ : KUndo2Command(parentCommand)+ , m_textShape(shape)+ , m_startPos(startPos)+ , m_endPos(endPos)+ , m_calculateDeltaPositions(calculateDeltaPositions)+ , m_textData(shape->getMemento())+{+ setText(kundo2_i18n("Adjust character transforms on text."));++ QVector<QPointF> positions;+ QVector<qreal> rotations;++ QList<KoSvgTextCharacterInfo> originalTf = shape->getPositionsAndRotationsForRange(startPos, endPos);++ if (type == OffsetAll) {+ while (!originalTf.isEmpty()) {+ KoSvgTextCharacterInfo tf = originalTf.takeFirst();+ positions.append(tf.finalPos + delta);+ rotations.append(tf.rotateDeg);+ }+ } else {+ const int lineEnd = qMin(shape->lineEnd(qMin(startPos, endPos)), qMax(startPos, endPos));+ QList<KoSvgTextCharacterInfo> infos =+ shape->getPositionsAndRotationsForRange(qMin(startPos, endPos), lineEnd);+ if (infos.size() < 1) return;+ const bool rtl = infos.first().rtl;+ KoSvgTextCharacterInfo first = infos.first();+ KoSvgTextCharacterInfo last = infos.last();+ if (infos.size() > 1) {+ std::sort(infos.begin(), infos.end(), KoSvgTextCharacterInfo::visualLessThan);+ for (auto it = infos.begin(); it != infos.end(); it++) {+ if (it->visualIndex >= 0) {+ first = *it;+ break;+ }+ }+ for (auto it = infos.rbegin(); it != infos.rend(); it++) {+ if (it->visualIndex >= 0) {+ last = *it;+ break;+ }+ }+ }+ QTransform t = QTransform::fromTranslate(last.finalPos.x(), last.finalPos.y());+ t.rotate(last.rotateDeg);+ last.finalPos = t.map(last.advance);++ const QLineF originalLine(rtl? last.finalPos: first.finalPos, rtl? first.finalPos: last.finalPos);+ QLineF newLine(originalLine.p1(), originalLine.p2() + delta);++ const qreal scale = newLine.length()/originalLine.length();+ QTransform origin = QTransform::fromTranslate(originalLine.p1().x(), originalLine.p1().y());+ qreal angle = originalLine.angle() - newLine.angle();++ QTransform deltaTf = origin.inverted();+ deltaTf *= QTransform::fromScale(scale, scale);+ deltaTf *= QTransform().rotate(angle);+ deltaTf *= origin;++ while (!originalTf.isEmpty()) {+ KoSvgTextCharacterInfo tf = originalTf.takeFirst();+ if (type != RotateOnly) {+ positions.append(deltaTf.map(tf.finalPos));+ } else {+ positions.append(tf.finalPos);+ }+ if (type != ScaleOnly) {+ rotations.append(tf.rotateDeg + (angle));+ } else {+ rotations.append(tf.rotateDeg);+ }+ }+ }++ m_positions = positions;+ m_rotations = rotations;++}++void SvgTextChangeTransformsOnRange::undo()+{+ QRectF updateRect = m_textShape->boundingRect();++ m_textShape->setMemento(m_textData);++ updateRect |= m_textShape->boundingRect();+ m_textShape->notifyCursorPosChanged(m_startPos, m_endPos);+ m_textShape->updateAbsolute(updateRect);+}++void SvgTextChangeTransformsOnRange::redo()+{+ QRectF updateRect = m_textShape->boundingRect();++ m_textShape->setCharacterTransformsOnRange(m_startPos, m_endPos, m_positions, m_rotations, m_calculateDeltaPositions);++ updateRect |= m_textShape->boundingRect();+ m_textShape->notifyCursorPosChanged(m_startPos, m_endPos);+ m_textShape->updateAbsolute(updateRect);+}++int SvgTextChangeTransformsOnRange::id() const+{+ return KisCommandUtils::SvgTextChangeTransformsOnRangeCommandId;+}++bool SvgTextChangeTransformsOnRange::mergeWith(const KUndo2Command *otherCommand) {+ const SvgTextChangeTransformsOnRange *other = dynamic_cast<const SvgTextChangeTransformsOnRange *>(otherCommand);++ if (!other || other->m_textShape != m_textShape || other->m_startPos != m_startPos || other->m_endPos != m_endPos || other->m_calculateDeltaPositions != m_calculateDeltaPositions) {+ return false;+ }++ m_positions = other->m_positions;+ m_rotations = other->m_rotations;+ return true;+}diff --git a/plugins/tools/svgtexttool/SvgTextChangeTransformsOnRange.h b/plugins/tools/svgtexttool/SvgTextChangeTransformsOnRange.hnew file mode 100644index 0000000000..0a2fa22674--- /dev/null+++ b/plugins/tools/svgtexttool/SvgTextChangeTransformsOnRange.h@@ -0,0 +1,41 @@+/*+ * SPDX-FileCopyrightText: 2025 Wolthera van Hövell tot Westerflier <[email protected]>+ *+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#ifndef SVGTEXTCHANGETRANSFORMSONRANGE_H+#define SVGTEXTCHANGETRANSFORMSONRANGE_H++#include <kundo2command.h>+#include <KoSvgTextShape.h>+++class SvgTextChangeTransformsOnRange : public KUndo2Command+{+public:+ SvgTextChangeTransformsOnRange(KoSvgTextShape *shape, int startPos, int endPos, QVector<QPointF> positions, QVector<qreal> rotations, bool calculateDeltaPositions, KUndo2Command *parentCommand = nullptr);++ enum OffsetType{+ OffsetAll,+ ScaleAndRotate,+ ScaleOnly,+ RotateOnly+ };++ SvgTextChangeTransformsOnRange(KoSvgTextShape *shape, int startPos, int endPos, QPointF delta, OffsetType type, bool calculateDeltaPositions, KUndo2Command *parentCommand = nullptr);+ ~SvgTextChangeTransformsOnRange() = default;+ void undo() override;+ void redo() override;+ int id() const override;+ bool mergeWith(const KUndo2Command *other) override;+private:+ KoSvgTextShape *m_textShape = nullptr;+ int m_startPos = -1;+ int m_endPos = -1;+ QVector<QPointF> m_positions;+ QVector<qreal> m_rotations;+ bool m_calculateDeltaPositions = false;+ KoSvgTextShapeMementoSP m_textData;+};++#endif // SVGTEXTCHANGETRANSFORMSONRANGE_Hdiff --git a/plugins/tools/svgtexttool/SvgTextCursor.cpp b/plugins/tools/svgtexttool/SvgTextCursor.cppindex 19011d2576..8d2f8b97b7 100644--- a/plugins/tools/svgtexttool/SvgTextCursor.cpp+++ b/plugins/tools/svgtexttool/SvgTextCursor.cpp@@ -25,6 +25,7 @@#include "KoCanvasController.h"#include "KoCanvasResourceProvider.h"#include <kis_signal_compressor.h>+#include <KisHandlePainterHelper.h>#include "kundo2command.h"#include <QTimer>@@ -103,6 +104,26 @@ struct IMEDecorationInfo {}};+struct TypeSettingDecorInfo {+ QPair<QPointF, QPointF> handles;+ bool handlesEnabled;++ QMap<SvgTextCursor::TypeSettingModeHandle, QPainterPath> paths;++ QRectF boundingRect(qreal handleRadius) {+ QRectF total;+ for (int i = 0; i< paths.values().size(); i++) {+ total |= paths.values().at(i).boundingRect();+ }+ QRectF rect(0, 0, handleRadius, handleRadius);+ rect.moveCenter(handles.first);+ total |= rect;+ rect.moveCenter(handles.second);+ total |= rect;+ return total;+ }+};+struct Q_DECL_HIDDEN SvgTextCursor::Private {KoCanvasBase *canvas;bool isAddingCommand = false;@@ -131,6 +152,13 @@ struct Q_DECL_HIDDEN SvgTextCursor::Private {bool visualNavigation = true;bool pasteRichText = true;+ bool typeSettingMode = false;+ SvgTextCursor::TypeSettingModeHandle hoveredTypeSettingHandle = SvgTextCursor::NoHandle;+ bool drawTypeSettingHandle = true;+ qreal handleRadius = 7;+ QRectF oldTypeSettingRect;+ TypeSettingDecorInfo typeSettingDecor;+SvgTextInsertCommand *preEditCommand {nullptr}; ///< PreEdit string as an command provided by the input method.int preEditStart = -1; ///< Start of the preEdit string as a cursor pos.int preEditLength = -1; ///< Length of the preEditString.@@ -181,6 +209,8 @@ void SvgTextCursor::setShape(KoSvgTextShape *textShape)d->shape->addShapeChangeListener(this);updateInputMethodItemTransform();d->pos = d->shape->posForIndex(d->shape->plainText().size());+ d->typeSettingDecor.handlesEnabled = (d->shape->textType() == KoSvgTextShape::PreformattedText+ || d->shape->textType() == KoSvgTextShape::PrePositionedText);} else {d->pos = 0;}@@ -208,6 +238,12 @@ void SvgTextCursor::setPasteRichTextByDefault(const bool pasteRichText)d->pasteRichText = pasteRichText;}+void SvgTextCursor::setTypeSettingModeActive(bool activate)+{+ d->typeSettingMode = activate;+ updateTypeSettingDecoration();+}+int SvgTextCursor::getPos(){return d->pos;@@ -252,6 +288,35 @@ void SvgTextCursor::setPosToPoint(QPointF point, bool moveAnchor)}}+SvgTextCursor::TypeSettingModeHandle SvgTextCursor::typeSettingHandleAtPos(const QRectF regionOfInterest)+{+ SvgTextCursor::TypeSettingModeHandle handle = SvgTextCursor::NoHandle;++ if (!(d->typeSettingMode && d->shape && d->canvas && d->shape->boundingRect().contains(regionOfInterest))) return handle;++ const QRectF roiInShape = d->shape->absoluteTransformation().inverted().mapRect(regionOfInterest);++ if (d->typeSettingDecor.handlesEnabled) {+ if (roiInShape.contains(d->typeSettingDecor.handles.first)) {+ handle = SvgTextCursor::StartPos;+ } else if (roiInShape.contains(d->typeSettingDecor.handles.second)) {+ handle = SvgTextCursor::EndPos;+ }+ }++ return handle;+}++void SvgTextCursor::setTypeSettingHandleHovered(TypeSettingModeHandle hovered)+{+ d->hoveredTypeSettingHandle = hovered;+}++void SvgTextCursor::setDrawTypeSettingHandle(bool draw)+{+ d->drawTypeSettingHandle = draw;+}+void SvgTextCursor::moveCursor(MoveMode mode, bool moveAnchor){if (d->shape) {@@ -482,12 +547,13 @@ static QColor bgColorForCaret(QColor c) {return KisPaintingTweaks::luminosityCoarse(c) > 0.8? QColor(0, 0, 0, 64) : QColor(255, 255, 255, 64);}-void SvgTextCursor::paintDecorations(QPainter &gc, QColor selectionColor, int decorationThickness)+void SvgTextCursor::paintDecorations(QPainter &gc, QColor selectionColor, int decorationThickness, qreal handleRadius){if (d->shape) {gc.save();gc.setTransform(d->shape->absoluteTransformation(), true);- if (d->pos != d->anchor) {++ if (d->pos != d->anchor && !d->typeSettingMode) {gc.save();gc.setOpacity(0.5);QBrush brush(selectionColor);@@ -509,6 +575,7 @@ void SvgTextCursor::paintDecorations(QPainter &gc, QColor selectionColor, int de}}+if (d->preEditCommand) {gc.save();QBrush brush(selectionColor);@@ -516,6 +583,35 @@ void SvgTextCursor::paintDecorations(QPainter &gc, QColor selectionColor, int degc.fillPath(d->IMEDecoration, brush);gc.restore();}+ if (d->typeSettingMode && d->drawTypeSettingHandle) {+ d->handleRadius = handleRadius;+ QTransform painterTf = gc.transform();+ KisHandlePainterHelper helper(&gc, handleRadius, decorationThickness);+ const KisHandleStyle highlight = KisHandleStyle::partiallyHighlightedPrimaryHandles();+ const KisHandleStyle regular = KisHandleStyle::secondarySelection();++ Q_FOREACH(SvgTextCursor::TypeSettingModeHandle handle, d->typeSettingDecor.paths.keys()) {+ const QPainterPath p = d->typeSettingDecor.paths.value(handle);+ if (d->hoveredTypeSettingHandle == handle) {+ helper.setHandleStyle(highlight);+ helper.drawPath(p);+ } else {+ gc.save();+ gc.setPen(selectionColor);+ gc.setOpacity(0.5);+ gc.drawPath(painterTf.map(p));+ gc.restore();+ }+ }++ if (d->typeSettingDecor.handlesEnabled) {+ helper.setHandleStyle(d->hoveredTypeSettingHandle == EndPos? highlight: regular);+ helper.drawHandleCircle(d->typeSettingDecor.handles.second);+ helper.setHandleStyle(d->hoveredTypeSettingHandle == StartPos? highlight: regular);+ helper.drawHandleRect(d->typeSettingDecor.handles.first);+ }++ }gc.restore();}}@@ -1280,6 +1376,7 @@ void SvgTextCursor::updateCursor(bool firstUpdate)d->posIndex = d->shape->indexForPos(d->pos);d->anchorIndex = d->shape->indexForPos(d->anchor);emit selectionChanged();+ updateTypeSettingDecoration();}d->cursorColor = QColor();d->cursorShape = d->shape? d->shape->cursorForPos(d->pos, d->cursorCaret, d->cursorColor): QPainterPath();@@ -1342,6 +1439,83 @@ void SvgTextCursor::updateIMEDecoration()}}+void SvgTextCursor::updateTypeSettingDecoration()+{+ QRectF updateRect;+ if (d->shape && d->typeSettingMode) {++ QList<KoSvgTextCharacterInfo> infos =+ d->shape->getPositionsAndRotationsForRange(d->pos, d->anchor);+ if (infos.size() < 1) return;++ const bool rtl = infos.first().rtl;++ KoSvgTextCharacterInfo first = infos.first();+ KoSvgTextCharacterInfo last = infos.last();+ if (infos.size() > 1) {+ std::sort(infos.begin(), infos.end(), KoSvgTextCharacterInfo::visualLessThan);+ for (auto it = infos.begin(); it != infos.end(); it++) {+ if (it->visualIndex >= 0) {+ first = *it;+ break;+ }+ }+ for (auto it = infos.rbegin(); it != infos.rend(); it++) {+ if (it->visualIndex >= 0) {+ last = *it;+ break;+ }+ }+ }++ QTransform t = QTransform::fromTranslate(last.finalPos.x(), last.finalPos.y());+ t.rotate(last.rotateDeg);+ last.finalPos = t.map(last.advance);++ //+ d->typeSettingDecor.handles.first = rtl? last.finalPos: first.finalPos;+ d->typeSettingDecor.handles.second = rtl? first.finalPos: last.finalPos;++ // Slightly cursed...+ // It'd be better if we could get KoSvgTextNodeIndex for a pos, but that one is only implemented in shape branch...+ d->typeSettingDecor.paths = QMap<SvgTextCursor::TypeSettingModeHandle, QPainterPath>();+ for (auto it = infos.begin(); it != infos.end(); it++) {+ const KoSvgTextProperties props = d->shape->propertiesForPos(d->shape->posForIndex(it->logicalIndex), true);+ KoSvgText::FontMetrics metrics = it->metrics;+ const bool isHorizontal = d->shape->writingMode() == KoSvgText::HorizontalTB;++ const qreal scaleMetrics = props.fontSize().value/qreal(metrics.fontSize);++ QTransform t = QTransform::fromTranslate(it->finalPos.x(), it->finalPos.y());+ t.rotate(it->rotateDeg);++ const QMap<SvgTextCursor::TypeSettingModeHandle, int> types {+ {BaselineShift, 0},+ {Ascender, metrics.ascender},+ {Descender, metrics.descender},+ {BaselineAlphabetic, metrics.alphabeticBaseline},+ {BaselineIdeographic, metrics.ideographicUnderBaseline},+ {BaselineHanging, metrics.hangingBaseline},+ {BaselineMathematic, metrics.mathematicalBaseline},+ {BaselineMiddle, metrics.xHeight/2}+ };++ Q_FOREACH(SvgTextCursor::TypeSettingModeHandle handle, types.keys()) {+ const int metric = types.value(handle);+ QPointF offset = isHorizontal? QPointF(0, -(metric*scaleMetrics)): QPointF(metric*scaleMetrics, 0);+ QPainterPath p = d->typeSettingDecor.paths.value(handle);+ p.moveTo(t.map(offset));+ p.lineTo(t.map(offset+it->advance));+ d->typeSettingDecor.paths.insert(handle, p);+ }+ }++ updateRect = d->shape->shapeToDocument(d->typeSettingDecor.boundingRect(d->handleRadius));+ }+ Q_EMIT updateCursorDecoration(updateRect | d->oldTypeSettingRect);+ d->oldTypeSettingRect = updateRect;+}+void SvgTextCursor::addCommandToUndoAdapter(KUndo2Command *cmd){if (d->canvas) {diff --git a/plugins/tools/svgtexttool/SvgTextCursor.h b/plugins/tools/svgtexttool/SvgTextCursor.hindex d47e3fbf46..befc6f3dbc 100644--- a/plugins/tools/svgtexttool/SvgTextCursor.h+++ b/plugins/tools/svgtexttool/SvgTextCursor.h@@ -66,6 +66,21 @@ public:ParagraphEnd,};+ enum TypeSettingModeHandle {+ NoHandle,+ StartPos,+ EndPos,+ Ascender,+ BaselineShift,+ Descender,++ BaselineAlphabetic,+ BaselineIdeographic,+ BaselineMiddle,+ BaselineHanging,+ BaselineMathematic+ };+~SvgTextCursor();/**@@ -103,6 +118,8 @@ public:*/void setPasteRichTextByDefault(const bool pasteRichText = true);+ void setTypeSettingModeActive(bool activate);+/// Get the current position.int getPos();@@ -115,6 +132,11 @@ public:/// Set the pos from a point. This currently does a search inside the text shape.void setPosToPoint(QPointF point, bool moveAnchor = true);+ /// Get typeSettingMode handle for text;+ TypeSettingModeHandle typeSettingHandleAtPos(const QRectF regionOfInterest);+ void setTypeSettingHandleHovered(TypeSettingModeHandle hovered = TypeSettingModeHandle::NoHandle);+ void setDrawTypeSettingHandle(bool draw);+/// Move the cursor, and, if you don't want a selection, move the anchor.void moveCursor(MoveMode mode, bool moveAnchor = true);@@ -171,7 +193,7 @@ public:void deselectText();- void paintDecorations(QPainter &gc, QColor selectionColor, int decorationThickness = 1);+ void paintDecorations(QPainter &gc, QColor selectionColor, int decorationThickness = 1, qreal handleRadius = 5.0);QVariant inputMethodQuery(Qt::InputMethodQuery query) const;void inputMethodEvent(QInputMethodEvent *event);@@ -249,6 +271,7 @@ private:void updateCursor(bool firstUpdate = false);void updateSelection();void updateIMEDecoration();+ void updateTypeSettingDecoration();void addCommandToUndoAdapter(KUndo2Command *cmd);int moveModeResult(MoveMode &mode, int &pos, bool visual = false) const;diff --git a/plugins/tools/svgtexttool/SvgTextTool.action b/plugins/tools/svgtexttool/SvgTextTool.actionindex 1c0be477a5..54c230088d 100644--- a/plugins/tools/svgtexttool/SvgTextTool.action+++ b/plugins/tools/svgtexttool/SvgTextTool.action@@ -222,5 +222,50 @@<isCheckable>false</isCheckable><text>Paste Plain Text</text></Action>++ <Action name="svg_type_setting_move_selection_start_down_1_px">+ <iconText>Move Text Selection Down</iconText>+ <text>Move Text Selection Down By 1 Pixel</text>+ <shortcut></shortcut>+ <toolTip>When type setting mode is active, move the start of the selection down by one pixel.</toolTip>+ <icon></icon>+ <whatsThis/>+ <statusTip/>+ <isCheckable>false</isCheckable>+ </Action>++ <Action name="svg_type_setting_move_selection_start_up_1_px">+ <iconText>Move Text Selection Up</iconText>+ <text>Move Text Selection Up By 1 Pixel</text>+ <shortcut></shortcut>+ <toolTip>When type setting mode is active, move the start of the selection up by one pixel.</toolTip>+ <icon></icon>+ <whatsThis/>+ <statusTip/>+ <isCheckable>false</isCheckable>+ </Action>++ <Action name="svg_type_setting_move_selection_start_left_1_px">+ <iconText>Move Text Selection Left</iconText>+ <text>Move Text Selection Left By 1 Pixel</text>+ <shortcut></shortcut>+ <toolTip>When type setting mode is active, move the start of the selection left by one pixel.</toolTip>+ <icon></icon>+ <whatsThis/>+ <statusTip/>+ <isCheckable>false</isCheckable>+ </Action>++ <Action name="svg_type_setting_move_selection_start_right_1_px">+ <iconText>Move Text Selection Right</iconText>+ <text>Move Text Selection Right By 1 Pixel</text>+ <shortcut></shortcut>+ <toolTip>When type setting mode is active, move the start of the selection reft by one pixel.</toolTip>+ <icon></icon>+ <whatsThis/>+ <statusTip/>+ <isCheckable>false</isCheckable>+ </Action>+</Actions></ActionCollection>diff --git a/plugins/tools/svgtexttool/SvgTextTool.cpp b/plugins/tools/svgtexttool/SvgTextTool.cppindex 7c62e9190d..51af6107b7 100644--- a/plugins/tools/svgtexttool/SvgTextTool.cpp+++ b/plugins/tools/svgtexttool/SvgTextTool.cpp@@ -22,6 +22,8 @@#include "KoSvgConvertTextTypeCommand.h"#include "SvgTextShortCuts.h"#include "SvgTextToolOptionsModel.h"+#include "SvgTextTypeSettingStrategy.h"+#include "SvgTextChangeTransformsOnRange.h"#include <QPainterPath>#include <QDesktopServices>@@ -137,6 +139,19 @@ SvgTextTool::SvgTextTool(KoCanvasBase *canvas)m_textTypeSignalsMapper->setMapping(a, convertActions.value(name));}+ m_typeSettingMovementMapper.reset(new KisSignalMapper(this));+ const QMap<QString, int> typeSetActions {+ {"svg_type_setting_move_selection_start_down_1_px", Qt::Key_Down},+ {"svg_type_setting_move_selection_start_up_1_px", Qt::Key_Up},+ {"svg_type_setting_move_selection_start_left_1_px", Qt::Key_Left},+ {"svg_type_setting_move_selection_start_right_1_px", Qt::Key_Right}+ };+ Q_FOREACH(const QString name, typeSetActions.keys()) {+ QAction *a = action(name);+ connect(a, SIGNAL(triggered()), m_typeSettingMovementMapper.data(), SLOT(map()));+ m_typeSettingMovementMapper->setMapping(a, typeSetActions.value(name));+ }+m_base_cursor = QCursor(QPixmap(":/tool_text_basic.xpm"), 7, 7);m_text_inline_horizontal = QCursor(QPixmap(":/tool_text_inline_horizontal.xpm"), 7, 7);m_text_inline_vertical = QCursor(QPixmap(":/tool_text_inline_vertical.xpm"), 7, 7);@@ -172,6 +187,7 @@ void SvgTextTool::activate(const QSet<KoShape *> &shapes)}connect(m_textTypeSignalsMapper.data(), SIGNAL(mapped(int)), this, SLOT(slotConvertType(int)));+ connect(m_typeSettingMovementMapper.data(), SIGNAL(mapped(int)), this, SLOT(slotMoveTextSelection(int)));useCursor(m_base_cursor);slotShapeSelectionChanged();@@ -190,6 +206,7 @@ void SvgTextTool::deactivate()}// Exiting text editing mode is handled by requestStrokeEnddisconnect(m_textTypeSignalsMapper.data(), 0, this, 0);+ disconnect(m_typeSettingMovementMapper.data(), 0, this, 0);m_hoveredShapeHighlightRect = QPainterPath();@@ -237,6 +254,7 @@ QWidget *SvgTextTool::createOptionWidget()connect(m_optionManager.data(), SIGNAL(openGlyphPalette()), SLOT(showGlyphPalette()));connect(m_optionManager.data(), SIGNAL(convertTextType(int)), SLOT(slotConvertType(int)));+ connect(m_optionManager.data(), SIGNAL(typeSettingModeChanged()), SLOT(slotUpdateTypeSettingMode()));connect(m_optionManager->optionsModel(), SIGNAL(useVisualBidiCursorChanged(bool)), this, SLOT(slotUpdateVisualCursor()));connect(m_optionManager->optionsModel(), SIGNAL(pasteRichtTextByDefaultChanged(bool)), this, SLOT(slotUpdateTextPasteBehaviour()));const KisCanvas2 *canvas2 = qobject_cast<const KisCanvas2 *>(this->canvas());@@ -554,12 +572,60 @@ void SvgTextTool::slotTextTypeUpdated()action("text_type_preformatted")->setChecked(shape->textType() == KoSvgTextShape::PreformattedText);action("text_type_pre_positioned")->setChecked(shape->textType() == KoSvgTextShape::PrePositionedText);action("text_type_inline_wrap")->setChecked(shape->textType() == KoSvgTextShape::InlineWrap);+} else {m_optionManager->convertToTextType(-1);action("text_type_preformatted")->setEnabled(false);action("text_type_pre_positioned")->setEnabled(false);action("text_type_inline_wrap")->setEnabled(false);}+ Q_FOREACH(QObject *obj, m_typeSettingMovementMapper->children()) {+ QAction *a = qobject_cast<QAction*>(obj);+ if (a && shape) {+ a->setEnabled(m_optionManager->typeSettingMode());+ }+ }+ }+}++void SvgTextTool::slotMoveTextSelection(int index)+{+ KoSvgTextShape *shape = selectedShape();+ if (!shape) return;+ QPointF offset;+ // test type setting mode.+ if (index == Qt::Key_Down) {+ offset = QPointF(0, 1);+ } else if (index == Qt::Key_Up) {+ offset = QPointF(0, -1);+ } else if (index == Qt::Key_Right) {+ offset = QPointF(-1, 0);+ } else if (index == Qt::Key_Left) {+ offset = QPointF(1, 0);+ } else {+ return;+ }+ const KisCanvas2 *canvas2 = qobject_cast<const KisCanvas2 *>(this->canvas());+ if (canvas2) {+ offset = canvas2->coordinatesConverter()->imageToDocumentTransform().map(offset);+ }+ KUndo2Command *parentCommand = new KUndo2Command();+ new KoKeepShapesSelectedCommand({selectedShape()}, {}, canvas()->selectedShapesProxy(), KisCommandUtils::FlipFlopCommand::State::INITIALIZING, parentCommand);+ KUndo2Command *cmd = new SvgTextChangeTransformsOnRange(shape, m_textCursor.getPos(), m_textCursor.getAnchor(), offset, SvgTextChangeTransformsOnRange::OffsetAll, true, parentCommand);+ new KoKeepShapesSelectedCommand({}, {selectedShape()}, canvas()->selectedShapesProxy(), KisCommandUtils::FlipFlopCommand::State::FINALIZING, parentCommand);+ parentCommand->setText(cmd->text());+ canvas()->addCommand(parentCommand);+}++void SvgTextTool::slotUpdateTypeSettingMode()+{+ m_textCursor.setTypeSettingModeActive(m_optionManager->typeSettingMode());+ KoSvgTextShape *shape = selectedShape();+ Q_FOREACH(QObject *obj, m_typeSettingMovementMapper->children()) {+ QAction *a = qobject_cast<QAction*>(obj);+ if (a && shape) {+ a->setEnabled(m_optionManager->typeSettingMode());+ }}}@@ -594,7 +660,7 @@ void SvgTextTool::paint(QPainter &gc, const KoViewConverter &converter){if (!isActivated()) return;- if (m_dragging == DragMode::Create) {+ if (m_interactionStrategy) {m_interactionStrategy->paint(gc, converter);}@@ -653,7 +719,7 @@ void SvgTextTool::paint(QPainter &gc, const KoViewConverter &converter)}}if (shape) {- m_textCursor.paintDecorations(gc, qApp->palette().color(QPalette::Highlight), decorationThickness());+ m_textCursor.paintDecorations(gc, qApp->palette().color(QPalette::Highlight), decorationThickness(), handleRadius());}if (m_interactionStrategy) {gc.save();@@ -718,7 +784,12 @@ void SvgTextTool::mousePressEvent(KoPointerEvent *event)canvas()->shapeManager()->selection()->select(hoveredShape);m_hoveredShapeHighlightRect = QPainterPath();}- m_interactionStrategy.reset(new SvgSelectTextStrategy(this, &m_textCursor, event->point));+ if (m_textCursor.typeSettingHandleAtPos(handleGrabRect(event->point)) != SvgTextCursor::NoHandle && hoveredShape == selectedShape) {+ m_interactionStrategy.reset(new SvgTextTypeSettingStrategy(this, selectedShape, &m_textCursor, handleGrabRect(event->point)));+ m_textCursor.setDrawTypeSettingHandle(false);+ } else {+ m_interactionStrategy.reset(new SvgSelectTextStrategy(this, &m_textCursor, event->point));+ }m_dragging = DragMode::Select;event->accept();} else if (crossLayerPossible) {@@ -826,10 +897,12 @@ void SvgTextTool::mouseMoveEvent(KoPointerEvent *event)const KoSvgTextShape *hoveredShape = dynamic_cast<KoSvgTextShape *>(canvas()->shapeManager()->shapeAt(event->point));QPainterPath hoverPath = KisToolUtils::shapeHoverInfoCrossLayer(canvas(), event->point, shapeType, &isHorizontal);if (selectedShape && selectedShape == hoveredShape && m_highlightItem == HighlightItem::None) {- if (selectedShape->writingMode() == KoSvgText::HorizontalTB) {- cursor = m_ibeam_horizontal;+ SvgTextCursor::TypeSettingModeHandle handle = m_textCursor.typeSettingHandleAtPos(handleGrabRect(event->point));+ m_textCursor.setTypeSettingHandleHovered(handle);+ if (handle != SvgTextCursor::NoHandle) {+ cursor = Qt::ArrowCursor;} else {- cursor = m_ibeam_vertical;+ cursor = selectedShape->writingMode() == KoSvgText::HorizontalTB? m_ibeam_horizontal: m_ibeam_vertical;}} else if (hoveredShape) {if (!hoveredShape->shapesInside().isEmpty()) {@@ -901,6 +974,7 @@ void SvgTextTool::mouseReleaseEvent(KoPointerEvent *event)useCursor(m_base_cursor);}m_dragging = DragMode::None;+ m_textCursor.setDrawTypeSettingHandle(true);event->accept();} else {useCursor(m_base_cursor);diff --git a/plugins/tools/svgtexttool/SvgTextTool.h b/plugins/tools/svgtexttool/SvgTextTool.hindex b253347095..c6da412b60 100644--- a/plugins/tools/svgtexttool/SvgTextTool.h+++ b/plugins/tools/svgtexttool/SvgTextTool.h@@ -173,6 +173,15 @@ private Q_SLOTS:*/void slotTextTypeUpdated();+ /**+ * @brief slotMoveTextSelection+ * Move the start of the selection in typesetting mode by image 1 pix.+ * @param index -- Qt key for a direction.+ */+ void slotMoveTextSelection(int index);++ void slotUpdateTypeSettingMode();+private:enum class DragMode {None = 0,@@ -198,6 +207,7 @@ private:bool m_strategyAddingCommand {false};QScopedPointer<KisSignalMapper> m_textTypeSignalsMapper;+ QScopedPointer<KisSignalMapper> m_typeSettingMovementMapper;SvgTextCursor m_textCursor;diff --git a/plugins/tools/svgtexttool/SvgTextToolFactory.cpp b/plugins/tools/svgtexttool/SvgTextToolFactory.cppindex afc4e4a866..7749376624 100644--- a/plugins/tools/svgtexttool/SvgTextToolFactory.cpp+++ b/plugins/tools/svgtexttool/SvgTextToolFactory.cpp@@ -46,6 +46,11 @@ QList<QAction *> SvgTextToolFactory::createActionsImpl()actions << KisActionRegistry::instance()->makeQAction("text_type_preformatted", this);actions << KisActionRegistry::instance()->makeQAction("text_type_pre_positioned", this);actions << KisActionRegistry::instance()->makeQAction("text_type_inline_wrap", this);++ actions << KisActionRegistry::instance()->makeQAction("svg_type_setting_move_selection_start_down_1_px", this);+ actions << KisActionRegistry::instance()->makeQAction("svg_type_setting_move_selection_start_up_1_px", this);+ actions << KisActionRegistry::instance()->makeQAction("svg_type_setting_move_selection_start_left_1_px", this);+ actions << KisActionRegistry::instance()->makeQAction("svg_type_setting_move_selection_start_right_1_px", this);return actions;}diff --git a/plugins/tools/svgtexttool/SvgTextToolOptions.qml b/plugins/tools/svgtexttool/SvgTextToolOptions.qmlindex e88b92fcfc..5cb677d00e 100644--- a/plugins/tools/svgtexttool/SvgTextToolOptions.qml+++ b/plugins/tools/svgtexttool/SvgTextToolOptions.qml@@ -16,9 +16,14 @@ Control {property SvgTextToolOptionsManager manager: SvgTextToolOptionsManager{};onManagerChanged: {+ if (typeof manager == "undefined") return;updateTextProperties()textType.updateTextTypes();- updatePresetName()+ updatePresetName();++ btnTypeSettingMode.checked = manager.typeSettingMode;+ chkVisualBidiCursor.checked = manager.optionsModel.useVisualBidiCursor;+ chkPasteRichTextByDefault.checked = manager.optionsModel.pasteRichtTextByDefault;}Connections {@@ -29,6 +34,9 @@ Control {function onTextTypeChanged() {textType.updateTextTypes();}+ function onTypeSettingModeChanged() {+ btnTypeSettingMode.checked = manager.typeSettingMode;+ }}Connections {@@ -166,6 +174,27 @@ Control {Layout.fillWidth: true;}+ Kis.ToolSeparatorBase {+ orientation: Qt.Horizontal;+ Layout.fillWidth: true;+ }+ Button {+ id: btnTypeSettingMode;+ text: i18nc("@label:button", "Type Setting Mode");+ checkable: true;+ hoverEnabled: true;+ onCheckedChanged: {+ manager.typeSettingMode = checked;+ }+ Layout.fillWidth: true;++ Kis.ToolTipBase {+ parent: btnTypeSettingMode;+ text: i18nc("@info:tooltip", "Enable type setting mode.");+ visible: parent.hovered;+ }+ }+Kis.ToolSeparatorBase {orientation: Qt.Horizontal;Layout.fillWidth: true;diff --git a/plugins/tools/svgtexttool/SvgTextToolOptionsManager.cpp b/plugins/tools/svgtexttool/SvgTextToolOptionsManager.cppindex a45532ca41..2a889dfe78 100644--- a/plugins/tools/svgtexttool/SvgTextToolOptionsManager.cpp+++ b/plugins/tools/svgtexttool/SvgTextToolOptionsManager.cpp@@ -17,6 +17,8 @@ struct SvgTextToolOptionsManager::Privatebool textPropertiesDockerOpen = false;bool showTextPropertyButton = false;++ bool typeSettingMode = false;};SvgTextToolOptionsManager::SvgTextToolOptionsManager(QObject *parent)@@ -114,6 +116,18 @@ void SvgTextToolOptionsManager::setShowTextPropertyButton(const bool show)Q_EMIT showTextPropertyButtonChanged();}+bool SvgTextToolOptionsManager::typeSettingMode() const+{+ return d->typeSettingMode;+}++void SvgTextToolOptionsManager::setTypeSettingMode(const bool activate)+{+ if (d->typeSettingMode == activate) return;+ d->typeSettingMode = activate;+ Q_EMIT typeSettingModeChanged();+}+void SvgTextToolOptionsManager::emitOpenTextEditor(){Q_EMIT openTextEditor();diff --git a/plugins/tools/svgtexttool/SvgTextToolOptionsManager.h b/plugins/tools/svgtexttool/SvgTextToolOptionsManager.hindex 395c585954..0ccc913010 100644--- a/plugins/tools/svgtexttool/SvgTextToolOptionsManager.h+++ b/plugins/tools/svgtexttool/SvgTextToolOptionsManager.h@@ -22,6 +22,7 @@ class SvgTextToolOptionsManager : public QObjectQ_PROPERTY(int textType READ textType WRITE convertToTextType NOTIFY convertTextType)Q_PROPERTY(bool textPropertiesOpen READ textPropertiesOpen WRITE setTextPropertiesOpen NOTIFY openTextPropertiesDocker)Q_PROPERTY(bool showTextPropertyButton READ showTextPropertyButton WRITE setShowTextPropertyButton NOTIFY showTextPropertyButtonChanged)+ Q_PROPERTY(bool typeSettingMode READ typeSettingMode WRITE setTypeSettingMode NOTIFY typeSettingModeChanged)/* Debug options */Q_PROPERTY(bool showDebug READ showDebug WRITE setShowDebug NOTIFY showDebugChanged)@@ -77,6 +78,9 @@ public:bool showTextPropertyButton() const;void setShowTextPropertyButton(const bool show);+ bool typeSettingMode() const;+ void setTypeSettingMode(const bool activate);+public Q_SLOTS:/*** @brief emitOpenTextEditor@@ -103,6 +107,8 @@ Q_SIGNALS:void showDebugCharacterChanged();void showLineDebugChanged();+ void typeSettingModeChanged();+private:struct Private;QScopedPointer<Private> d;diff --git a/plugins/tools/svgtexttool/SvgTextTypeSettingStrategy.cpp b/plugins/tools/svgtexttool/SvgTextTypeSettingStrategy.cppnew file mode 100644index 0000000000..6579b49bd6--- /dev/null+++ b/plugins/tools/svgtexttool/SvgTextTypeSettingStrategy.cpp@@ -0,0 +1,118 @@+/*+ * SPDX-FileCopyrightText: 2025 Wolthera van Hövell tot Westerflier <[email protected]>+ *+ * SPDX-License-Identifier: GPL-3.0-or-later+ */++#include "SvgTextTypeSettingStrategy.h"+#include "SvgTextCursor.h"+#include "SvgTextChangeTransformsOnRange.h"+#include "SvgTextShapeManagerBlocker.h"++#include <KoToolBase.h>+#include <KoCanvasBase.h>+#include "KoSnapGuide.h"+#include <kis_algebra_2d.h>+#include <QDebug>+#include <KoViewConverter.h>++SvgTextTypeSettingStrategy::SvgTextTypeSettingStrategy(KoToolBase *tool, KoSvgTextShape *textShape, SvgTextCursor *textCursor, const QRectF ®ionOfInterest)+ : KoInteractionStrategy(tool)+ , m_shape(textShape)+ , m_dragStart(regionOfInterest.center())+{++ m_cursorPos = textCursor->getPos();+ m_cursorAnchor = textCursor->getAnchor();+ qDebug() << Q_FUNC_INFO << regionOfInterest << m_cursorPos << m_cursorAnchor;+ m_editingType = textCursor->typeSettingHandleAtPos(regionOfInterest);+}++void SvgTextTypeSettingStrategy::paint(QPainter &painter, const KoViewConverter &converter)+{+ /*+ if (!m_shape) return;+ const int lineStart = qMax(m_shape->lineStart(m_cursorAnchor), qMin(m_cursorPos, m_cursorAnchor));+ QList<QPair<QPointF, qreal>> firstTf = m_shape->getPositionsAndRotationsForRange(lineStart, qMax(m_cursorPos, m_cursorAnchor), false);+ if (firstTf.size() < 2) return;+ QLineF originalLine(firstTf.first().first, firstTf.last().first);+ QPointF delta = m_dragCurrent - m_dragStart;+ QLineF newLine(originalLine.p1(), originalLine.p2() + delta);+ painter.save();+ painter.setPen(Qt::blue);+ painter.setTransform(converter.documentToView(), true);+ painter.drawPoint(m_dragStart);+ painter.drawPoint(m_dragCurrent);+ painter.setTransform(m_shape->absoluteTransformation(), true);+ painter.setPen(Qt::red);+ painter.setOpacity(0.3);+ painter.drawPoint(originalLine.p1());+ painter.drawLine(originalLine);+ painter.drawLine(newLine);+ painter.restore();+ */+}++void SvgTextTypeSettingStrategy::handleMouseMove(const QPointF &mouseLocation, Qt::KeyboardModifiers modifiers)+{+ QPointF delta = mouseLocation - m_dragStart;++ if (modifiers & Qt::ShiftModifier) {+ delta = snapToClosestAxis(delta);+ m_dragCurrent = m_dragStart + delta;+ m_currentDelta = delta;+ } else {+ m_dragCurrent =+ tool()->canvas()->snapGuide()->snap(mouseLocation, modifiers);+ m_currentDelta = m_dragCurrent - m_dragStart;+ }++ if (m_editingType != int(SvgTextCursor::NoHandle)) {+ SvgTextShapeManagerBlocker blocker(tool()->canvas()->shapeManager());+ QRectF updateRect = m_shape->boundingRect();+ if (m_previousCmd) {+ m_previousCmd->undo();+ }+ m_previousCmd.reset(createCommand());+ if (m_previousCmd) {+ m_previousCmd->redo();+ }+ updateRect |= m_shape->boundingRect();+ blocker.unlock();+ m_shape->updateAbsolute(updateRect);+ }+}++KUndo2Command *SvgTextTypeSettingStrategy::createCommand()+{+ if (m_editingType == int(SvgTextCursor::NoHandle)) return nullptr;+ QPointF delta = m_currentDelta;++ QList<KoSvgTextCharacterInfo> originalTf = m_shape->getPositionsAndRotationsForRange(m_cursorPos, m_cursorAnchor);+ if (originalTf.isEmpty()) return nullptr;++ KUndo2Command *cmd = nullptr;+ if (m_editingType == int(SvgTextCursor::StartPos) || m_editingType == int(SvgTextCursor::EndPos)) {+ if (m_shape->textType() != KoSvgTextShape::PreformattedText && m_shape->textType() != KoSvgTextShape::PrePositionedText) return nullptr;+ SvgTextChangeTransformsOnRange::OffsetType type = m_editingType == int(SvgTextCursor::StartPos)? SvgTextChangeTransformsOnRange::OffsetAll: SvgTextChangeTransformsOnRange::ScaleAndRotate;++ cmd = new SvgTextChangeTransformsOnRange(m_shape, m_cursorPos, m_cursorAnchor, delta, type, true, nullptr);+ }+ return cmd;+}++void SvgTextTypeSettingStrategy::cancelInteraction()+{+ if (m_previousCmd) {+ m_previousCmd->undo();+ }+ tool()->repaintDecorations();+}++void SvgTextTypeSettingStrategy::finishInteraction(Qt::KeyboardModifiers modifiers)+{+ if (m_previousCmd) {+ m_previousCmd->undo();+ }+ tool()->repaintDecorations();+}diff --git a/plugins/tools/svgtexttool/SvgTextTypeSettingStrategy.h b/plugins/tools/svgtexttool/SvgTextTypeSettingStrategy.hnew file mode 100644index 0000000000..ef132234d5--- /dev/null+++ b/plugins/tools/svgtexttool/SvgTextTypeSettingStrategy.h@@ -0,0 +1,49 @@+/*+ * SPDX-FileCopyrightText: 2025 Wolthera van Hövell tot Westerflier <[email protected]>+ *+ * SPDX-License-Identifier: GPL-3.0-or-later+ */++#ifndef SVGTEXTTYPESETTINGSTRATEGY_H+#define SVGTEXTTYPESETTINGSTRATEGY_H++#include <KoInteractionStrategy.h>+#include <QPointF>+#include <KoSvgTextShape.h>++class SvgTextCursor;+class KoSvgTextShape;+class QRectF;+class QPointF;++/**+ * @brief The SvgTextTypeSettingStrategy class+ * This class encompasses the typesetting mode.+ */+class SvgTextTypeSettingStrategy: public KoInteractionStrategy+{+public:+ SvgTextTypeSettingStrategy(KoToolBase *tool, KoSvgTextShape *textShape, SvgTextCursor *textCursor, const QRectF ®ionOfInterest);++ // KoInteractionStrategy interface+public:+ void paint(QPainter &painter, const KoViewConverter &converter) override;+ void handleMouseMove(const QPointF &mouseLocation, Qt::KeyboardModifiers modifiers) override;+ KUndo2Command *createCommand() override;+ void cancelInteraction() override;+ void finishInteraction(Qt::KeyboardModifiers modifiers) override;++private:+ KoSvgTextShape *m_shape;+ QPointF m_dragStart;+ QPointF m_dragCurrent;+ QPointF m_currentDelta;++ int m_cursorPos;+ int m_cursorAnchor;+ int m_editingType;++ QScopedPointer<KUndo2Command> m_previousCmd;+};++#endif // SVGTEXTTYPESETTINGSTRATEGY_H