File indexing completed on 2024-12-22 04:16:45

0001 /*
0002  * SPDX-FileCopyrightText: 2023 Wolthera van Hövell tot Westerflier <griffinvalley@gmail.com>
0003  *
0004  * SPDX-License-Identifier: GPL-3.0-or-later
0005  */
0006 #include "SvgTextInsertCommand.h"
0007 #include "KoSvgTextShape.h"
0008 #include "KoSvgTextShapeMarkupConverter.h"
0009 
0010 #include "kis_command_ids.h"
0011 SvgTextInsertCommand::SvgTextInsertCommand(KoSvgTextShape *shape, int pos, int anchor, QString text, KUndo2Command *parent)
0012     : KUndo2Command(parent)
0013     , m_shape(shape)
0014     , m_pos(pos)
0015     , m_anchor(anchor)
0016     , m_text(text)
0017 {
0018     setText(kundo2_i18n("Insert Text"));
0019 
0020     QRegExp exp;
0021     // This replaces...
0022     // - carriage return
0023     // - linefeed-carriage return
0024     // - carriage return-linefeed
0025     // - line seperator
0026     // - paragraph seperator
0027     // - vertical tab/line tab
0028     // with a single linefeed to avoid them from being added to the textShape.
0029     exp.setPattern("[\\r|\\r\\n|\\x2029|\\x2028\\x000b]");
0030     text.replace(exp, "\n");
0031     m_text = text;
0032 }
0033 
0034 void SvgTextInsertCommand::redo()
0035 {
0036     QRectF updateRect = m_shape->boundingRect();
0037     // Index defaults to -1 when there's no text in the shape.
0038     int oldIndex = qMax(0, m_shape->indexForPos(m_pos));
0039 
0040     KoSvgTextShapeMarkupConverter converter(m_shape);
0041     converter.convertToSvg(&m_oldSvg, &m_oldDefs);
0042     m_shape->insertText(m_pos, m_text);
0043     m_shape->updateAbsolute( updateRect| m_shape->boundingRect());
0044 
0045     int pos = m_shape->posForIndex(oldIndex + m_text.size(), false, false);
0046     m_shape->notifyCursorPosChanged(pos, pos);
0047 
0048 }
0049 
0050 void SvgTextInsertCommand::undo()
0051 {
0052     QRectF updateRect = m_shape->boundingRect();
0053     KoSvgTextShapeMarkupConverter converter(m_shape);
0054     // Hardcoded resolution?
0055     converter.convertFromSvg(m_oldSvg, m_oldDefs, m_shape->boundingRect(), 72.0);
0056     m_shape->updateAbsolute( updateRect| m_shape->boundingRect());
0057 
0058     m_shape->notifyCursorPosChanged(m_pos, m_anchor);
0059 }
0060 
0061 int SvgTextInsertCommand::id() const
0062 {
0063     return KisCommandUtils::SvgInsertTextCommand;
0064 }
0065 
0066 bool SvgTextInsertCommand::mergeWith(const KUndo2Command *other)
0067 {
0068     const SvgTextInsertCommand *command = dynamic_cast<const SvgTextInsertCommand*>(other);
0069 
0070 
0071     if (!command || command->m_shape != m_shape) {
0072         return false;
0073     }
0074     int oldIndex = m_shape->indexForPos(m_pos);
0075     int otherOldIndex = m_shape->indexForPos(command->m_pos);
0076     if (oldIndex + m_text.size() != otherOldIndex) {
0077         return false;
0078     }
0079 
0080     m_text += command->m_text;
0081     return true;
0082 }