Krita Source Code Documentation
Loading...
Searching...
No Matches
SvgTextTool.cpp
Go to the documentation of this file.
1/* This file is part of the KDE project
2
3 SPDX-FileCopyrightText: 2017 Boudewijn Rempt <boud@valdyas.org>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6*/
7
8#include "SvgTextTool.h"
10#include "KoSvgTextShape.h"
16#include "SvgInlineSizeHelper.h"
17#include "SvgMoveTextCommand.h"
18#include "SvgMoveTextStrategy.h"
20#include "SvgTextEditor.h"
23#include "SvgTextShortCuts.h"
25
26#include <QPainterPath>
27#include <QDesktopServices>
28#include <QApplication>
29#include <QStyle>
30#include <QDockWidget>
31#include <QQuickItem>
32
33#include <klocalizedstring.h>
34
35#include <KisPart.h>
36#include <kis_canvas2.h>
37#include <KSharedConfig>
38#include "kis_assert.h"
40
41#include <KoFileDialog.h>
42#include <KoIcon.h>
43#include <KoCanvasBase.h>
44#include <KoSelection.h>
45#include <KoShapeManager.h>
46#include <KoShapeController.h>
47#include <KoShapeRegistry.h>
48#include <KoShapeFactoryBase.h>
49#include <KoPointerEvent.h>
50#include <KoProperties.h>
52#include "KoToolManager.h"
53#include <KoShapeFillWrapper.h>
55#include <KoPathShape.h>
56#include <KoPathSegment.h>
57
59#include <KoCssStylePreset.h>
61#include <KoColorBackground.h>
62#include <KisResourceModel.h>
63
65#include <KisViewManager.h>
66#include <KisQQuickWidget.h>
67#include <QQmlError>
68#include <KisMainWindow.h>
69
71#include "kis_tool_utils.h"
72#include "kis_debug.h"
74
75
77
78constexpr double INLINE_SIZE_DASHES_PATTERN_A = 4.0;
79constexpr double INLINE_SIZE_DASHES_PATTERN_B = 8.0;
81constexpr double INLINE_SIZE_HANDLE_THICKNESS = 1.0;
82
83
84static bool debugEnabled()
85{
86 static const bool debugEnabled = !qEnvironmentVariableIsEmpty("KRITA_DEBUG_TEXTTOOL");
87 return debugEnabled;
88}
89
91 : KoToolBase(canvas)
92 , m_textCursor(canvas)
93 , m_optionManager(new SvgTextToolOptionsManager(this))
94{
95 // TODO: figure out whether we should use system config for this, Windows and GTK have values for it, but Qt and MacOS don't(?).
96 int cursorFlashLimit = 5000;
97 m_textCursor.setCaretSetting(QApplication::style()->pixelMetric(QStyle::PM_TextCursorWidth)
98 , qApp->cursorFlashTime()
99 , cursorFlashLimit);
100 connect(&m_textCursor, SIGNAL(updateCursorDecoration(QRectF)), this, SLOT(slotUpdateCursorDecoration(QRectF)));
101
102 Q_FOREACH(const QString name, SvgTextShortCuts::possibleActions()) {
103 QAction *a = action(name);
105 dbgTools << "registered" << name << a->shortcut();
106 }
107 }
108
109 const QStringList extraActions = {
110 "svg_insert_special_character",
111 "svg_paste_rich_text",
112 "svg_paste_plain_text"
113 };
114 connect(&m_textCursor, SIGNAL(sigOpenGlyphPalette()), this, SLOT(showGlyphPalette()));
115 Q_FOREACH (const QString name, extraActions) {
116 QAction *a = action(name);
117 if (a) {
119 qWarning() << "could not register" << name << a->shortcut();
120 }
121 }
122 }
123
125 const QMap<QString, int> convertActions {
126 {"text_type_preformatted", KoSvgTextShape::PreformattedText},
127 {"text_type_inline_wrap", KoSvgTextShape::InlineWrap},
128 {"text_type_pre_positioned", KoSvgTextShape::PrePositionedText}
129 };
130 Q_FOREACH(const QString name, convertActions.keys()) {
131 QAction *a = action(name);
132 connect(a, SIGNAL(triggered()), m_textTypeSignalsMapper.data(), SLOT(map()));
133 m_textTypeSignalsMapper->setMapping(a, convertActions.value(name));
134 }
135
136 m_base_cursor = QCursor(QPixmap(":/tool_text_basic.xpm"), 7, 7);
137 m_text_inline_horizontal = QCursor(QPixmap(":/tool_text_inline_horizontal.xpm"), 7, 7);
138 m_text_inline_vertical = QCursor(QPixmap(":/tool_text_inline_vertical.xpm"), 7, 7);
139 m_text_on_path = QCursor(QPixmap(":/tool_text_on_path.xpm"), 7, 7);
140 m_text_in_shape = QCursor(QPixmap(":/tool_text_in_shape.xpm"), 7, 7);
141 m_ibeam_horizontal = QCursor(QPixmap(":/tool_text_i_beam_horizontal.xpm"), 11, 11);
142 m_ibeam_vertical = QCursor(QPixmap(":/tool_text_i_beam_vertical.xpm"), 11, 11);
143 m_ibeam_horizontal_done = QCursor(QPixmap(":/tool_text_i_beam_horizontal_done.xpm"), 5, 11);
144}
145
147{
148 if(m_editor) {
149 m_editor->close();
150 }
151 if(m_glyphPalette) {
152 m_glyphPalette->close();
153 }
154}
155
156void SvgTextTool::activate(const QSet<KoShape *> &shapes)
157{
158 KoToolBase::activate(shapes);
159 m_canvasConnections.addConnection(canvas()->selectedShapesProxy(), SIGNAL(selectionChanged()), this, SLOT(slotShapeSelectionChanged()));
160
161 const KisCanvas2 *canvas2 = qobject_cast<const KisCanvas2 *>(this->canvas());
162 if (canvas2) {
164 QDockWidget *docker = canvas2->viewManager()->mainWindow()->dockWidget("TextProperties");
165 if (docker && m_optionManager) {
166 m_optionManager->setTextPropertiesOpen(docker->isVisible());
167 }
168 }
169
170 connect(m_textTypeSignalsMapper.data(), SIGNAL(mapped(int)), this, SLOT(slotConvertType(int)));
171
174
176}
177
179{
182 m_textCursor.setShape(nullptr);
183 const KisCanvas2 *canvas2 = qobject_cast<const KisCanvas2 *>(this->canvas());
184 if (canvas2) {
186 }
187 // Exiting text editing mode is handled by requestStrokeEnd
188 disconnect(m_textTypeSignalsMapper.data(), 0, this, 0);
189
190 m_hoveredShapeHighlightRect = QPainterPath();
191
193}
194
196{
197 return nullptr;
198}
199
200QVariant SvgTextTool::inputMethodQuery(Qt::InputMethodQuery query) const
201{
202 if (canvas()) {
203 return m_textCursor.inputMethodQuery(query);
204 } else {
205 return KoToolBase::inputMethodQuery(query);
206 }
207}
208
209void SvgTextTool::inputMethodEvent(QInputMethodEvent *event)
210{
212}
213
215{
216 KisQQuickWidget *optionWidget = new KisQQuickWidget();
217 optionWidget->setMinimumWidth(100);
218 optionWidget->setMinimumHeight(100);
219
220 optionWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
221 optionWidget->setSource(QUrl("qrc:/SvgTextToolOptions.qml"));
222
223 m_optionManager->setShowDebug(debugEnabled());
224 if (optionWidget->errors().isEmpty()) {
225 optionWidget->rootObject()->setProperty("manager", QVariant::fromValue(m_optionManager.data()));
226 optionWidget->connectMinimumHeightToRootObject();
227 } else {
228 qWarning() << optionWidget->errors();
229 }
230
231
232 connect(m_optionManager.data(), SIGNAL(openTextEditor()), SLOT(showEditor()));
233 connect(m_optionManager.data(), SIGNAL(openGlyphPalette()), SLOT(showGlyphPalette()));
234
235 connect(m_optionManager.data(), SIGNAL(convertTextType(int)), SLOT(slotConvertType(int)));
236 connect(m_optionManager->optionsModel(), SIGNAL(useVisualBidiCursorChanged(bool)), this, SLOT(slotUpdateVisualCursor()));
237 connect(m_optionManager->optionsModel(), SIGNAL(pasteRichtTextByDefaultChanged(bool)), this, SLOT(slotUpdateTextPasteBehaviour()));
238 const KisCanvas2 *canvas2 = qobject_cast<const KisCanvas2 *>(this->canvas());
239 if (canvas2 && canvas2->viewManager()->mainWindow()) {
240 QDockWidget *docker = canvas2->viewManager()->mainWindow()->dockWidget("TextProperties");
241 m_optionManager->setShowTextPropertyButton((docker));
242 if (docker) {
243 optionWidget->setPalette(docker->palette());
244 m_optionManager->setTextPropertiesOpen(docker->isVisible());
246 docker->setVisible(!docker->isVisible());
247 });
248 // Once we have docker toggling actions, we should revisit this.
249 }
250 }
254
255
256 return optionWidget;
257}
258
266
268{
270 KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(canvas()->selectedShapesProxy(), 0);
271
273 if (shapes.isEmpty()) return 0;
274
275 KoSvgTextShape *textShape = dynamic_cast<KoSvgTextShape*>(shapes.first());
276
277 return textShape;
278}
279
281{
282 KoSvgTextShape *shape = selectedShape();
283 if (!shape) return;
284
285 if (!m_editor) {
286 m_editor = new SvgTextEditor(QApplication::activeWindow());
287 m_editor->setWindowTitle(i18nc("@title:window", "Krita - Edit Text"));
288 m_editor->setWindowModality(Qt::ApplicationModal);
289 m_editor->setAttribute( Qt::WA_QuitOnClose, false );
290
291 connect(m_editor, SIGNAL(textUpdated(KoSvgTextShape*,QString,QString)), SLOT(textUpdated(KoSvgTextShape*,QString,QString)));
292 connect(m_editor, SIGNAL(textEditorClosed()), SLOT(slotTextEditorClosed()));
293
294 m_editor->activateWindow(); // raise on creation only
295 }
296 if (!m_editor->isVisible()) {
297 m_editor->setInitialShape(shape);
298#ifdef Q_OS_ANDROID
299 // for window manager
300 m_editor->setWindowFlags(Qt::Dialog);
301 m_editor->menuBar()->setNativeMenuBar(false);
302#endif
303 m_editor->show();
304 }
305}
306
307void SvgTextTool::textUpdated(KoSvgTextShape *shape, const QString &svg, const QString &defs)
308{
309 SvgTextChangeCommand *cmd = new SvgTextChangeCommand(shape, svg, defs);
310 canvas()->addCommand(cmd);
311}
312
314{
315 if (!m_glyphPalette) {
316 m_glyphPalette = new GlyphPaletteDialog(QApplication::activeWindow());
317 m_glyphPalette->setAttribute( Qt::WA_QuitOnClose, false );
318
319 connect(&m_textCursor, SIGNAL(selectionChanged()), this, SLOT(updateGlyphPalette()));
320 connect(m_glyphPalette, SIGNAL(signalInsertRichText(KoSvgTextShape*, bool)), this, SLOT(insertRichText(KoSvgTextShape*, bool)));
321
322 m_glyphPalette->activateWindow();
323 }
324 if (!m_glyphPalette->isVisible()) {
325 m_glyphPalette->show();
327 }
328}
329
331{
332 if (m_glyphPalette && m_glyphPalette->isVisible()) {
333 QString grapheme = QString();
334 if (m_textCursor.shape()) {
335 int pos = m_textCursor.getPos();
336 int pos2 = pos > 0? m_textCursor.shape()->posLeft(pos, false): m_textCursor.shape()->posRight(pos, false);
337 int start = m_textCursor.shape()->indexForPos(qMin(pos, pos2));
338 int end = m_textCursor.shape()->indexForPos(qMax(pos, pos2));
339 grapheme = m_textCursor.shape()->plainText().mid(start, end-start);
340 }
341 m_glyphPalette->setGlyphModelFromProperties(m_textCursor.currentTextProperties(), grapheme);
342 }
343}
344
353
355{
356 // change tools to the shape selection tool when we close the text editor to allow moving and further editing of the object.
357 // most of the time when we edit text, the shape selection tool is where we left off anyway
358 KoToolManager::instance()->switchToolRequested("InteractionTool");
359}
360
362{
363 QStringList propStrings;
364 QMap<QString, QString> paraProps = properties.convertParagraphProperties();
365 for (auto it = paraProps.constBegin(); it != paraProps.constEnd(); it++) {
366 propStrings.append(QString("%1: %2;").arg(it.key()).arg(it.value()));
367 }
368 paraProps = properties.convertToSvgTextAttributes();
369 for (auto it = paraProps.constBegin(); it != paraProps.constEnd(); it++) {
370 propStrings.append(QString("%1: %2;").arg(it.key()).arg(it.value()));
371 }
372
373 return QString("<defs>\n <style>\n text {\n %1\n }\n </style>\n</defs>").arg(propStrings.join("\n "));
374}
375
377{
378 const bool useCurrent = m_optionManager->optionsModel()->useCurrentTextProperties();
379 const QString presetName = m_optionManager->optionsModel()->cssStylePresetName();
380
382 if (useCurrent || presetName.isEmpty()) {
384 props = textData.commonProperties;
385 } else {
387 QVector<KoResourceSP> res = model->resourcesForName(presetName);
388 if (res.first()) {
389 KoCssStylePresetSP style = res.first().staticCast<KoCssStylePreset>();
390 qreal dpi = 72;
391 KisCanvas2 *canvas2 = qobject_cast<KisCanvas2 *>(this->canvas());
392 if (canvas2) {
393 dpi = canvas2->image()->xRes() * 72.0;
394 }
395 if (style) {
396 props = style->properties(dpi, true);
397 }
398 }
399 }
400
401 QColor fontColor = (canvas()->resourceManager()->isUsingOtherColor()
402 ? canvas()->resourceManager()->backgroundColor()
403 : canvas()->resourceManager()->foregroundColor()).toQColor();
405 bg->setColor(fontColor);
407 props.setProperty(KoSvgTextProperties::FillId, QVariant::fromValue(bgProp));
408 return props;
409}
410
412{
414 if (shapes.size() == 1) {
415 KoSvgTextShape *textShape = selectedShape();
416 if (!textShape) {
418 return;
419 }
420 } else if (shapes.size() > 1) {
421 KoSvgTextShape *foundTextShape = nullptr;
422
423 Q_FOREACH (KoShape *shape, shapes) {
424 KoSvgTextShape *textShape = dynamic_cast<KoSvgTextShape*>(shape);
425 if (textShape) {
426 foundTextShape = textShape;
427 break;
428 }
429 }
430
432 if (foundTextShape) {
433 koSelection()->select(foundTextShape);
434 }
435 return;
436 }
437 KoSvgTextShape *const shape = selectedShape();
438 if (shape != m_textCursor.shape()) {
439 m_textCursor.setShape(shape);
440 if (shape) {
441 setTextMode(true);
442 } else {
443 setTextMode(false);
444 }
445 }
447}
448
450{
452}
453
458
460{
461 return m_textCursor.paste();
462}
463
468
475
480
485
487{
488 if (!isActivated()) return;
492 m_interactionStrategy->cancelInteraction();
493 m_interactionStrategy = nullptr;
494 useCursor(Qt::ArrowCursor);
495 } else if (isInTextMode()) {
497 }
498 }
499}
500
509
511{
512 if (canvas()) {
513 canvas()->updateCanvas(updateRect);
514 }
515}
516
518 if (selectedShape()) {
519 if (index == selectedShape()->textType()) return;
521 KUndo2Command *parentCommand = new KUndo2Command();
524 parentCommand->setText(cmd->text());
526 canvas()->addCommand(parentCommand);
528 }
529}
530
532{
533 m_textCursor.setVisualMode(m_optionManager->optionsModel()->useVisualBidiCursor());
534}
535
537{
538 m_textCursor.setPasteRichTextByDefault(m_optionManager->optionsModel()->pasteRichtTextByDefault());
539}
540
542{
543 KoSvgTextShape *shape = selectedShape();
544 if (m_optionManager) {
545 if (shape) {
546 m_optionManager->convertToTextType(int(shape->textType()));
547 action("text_type_preformatted")->setEnabled(true);
548 action("text_type_pre_positioned")->setEnabled(true);
549 action("text_type_inline_wrap")->setEnabled(true);
550 action("text_type_preformatted")->setChecked(shape->textType() == KoSvgTextShape::PreformattedText);
551 action("text_type_pre_positioned")->setChecked(shape->textType() == KoSvgTextShape::PrePositionedText);
552 action("text_type_inline_wrap")->setChecked(shape->textType() == KoSvgTextShape::InlineWrap);
553 } else {
554 m_optionManager->convertToTextType(-1);
555 action("text_type_preformatted")->setEnabled(false);
556 action("text_type_pre_positioned")->setEnabled(false);
557 action("text_type_inline_wrap")->setEnabled(false);
558 }
559 }
560}
561
563{
564 QRectF rect;
565 KoSvgTextShape *const shape = selectedShape();
566 if (shape) {
567 rect |= shape->boundingRect();
568
569 const QPointF anchor = shape->absoluteTransformation().map(QPointF());
570 rect |= kisGrowRect(QRectF(anchor, anchor), handleRadius());
571
572 qreal pxlToPt = canvas()->viewConverter()->viewToDocumentX(1.0);
574
575 if (std::optional<InlineSizeInfo> info = InlineSizeInfo::fromShape(shape, length * pxlToPt)) {
576 rect |= kisGrowRect(info->boundingRect(), handleRadius() * 2);
577 }
578
579 if (canvas()->snapGuide()->isSnapping()) {
581 }
582 }
583
584 rect |= m_hoveredShapeHighlightRect.boundingRect();
585
586 return rect;
587}
588
589void SvgTextTool::paint(QPainter &gc, const KoViewConverter &converter)
590{
591 if (!isActivated()) return;
592
594 m_interactionStrategy->paint(gc, converter);
595 }
596
597 KoSvgTextShape *shape = selectedShape();
598 if (shape) {
599 KisHandlePainterHelper handlePainter =
601
604 QPainterPath path;
605 path.addRect(shape->outlineRect());
606 handlePainter.drawPath(path);
607 }
608
609
610 qreal pxlToPt = canvas()->viewConverter()->viewToDocumentX(1.0);
612 if (std::optional<InlineSizeInfo> info = InlineSizeInfo::fromShape(shape, length * pxlToPt)) {
614 handlePainter.drawConnectionLine(info->baselineLineLocal());
615
619 }
621 handlePainter.drawHandleLine(info->startLineLocal());
622 handlePainter.drawHandleLine(info->startLineDashes(), INLINE_SIZE_HANDLE_THICKNESS, dashPattern, INLINE_SIZE_DASHES_PATTERN_A);
623
628 }
629 handlePainter.drawHandleLine(info->endLineLocal());
630 handlePainter.drawHandleLine(info->endLineDashes(), INLINE_SIZE_HANDLE_THICKNESS, dashPattern, INLINE_SIZE_DASHES_PATTERN_A);
631 }
632
635 } else {
637 }
638 handlePainter.drawHandleCircle(QPointF(), KoToolBase::handleRadius() * 0.75);
639 }
640
641 gc.setTransform(converter.documentToView(), true);
642 {
644 if (!m_hoveredShapeHighlightRect.isEmpty()) {
646 QPainterPath path;
647 path.addPath(m_hoveredShapeHighlightRect);
648 handlePainter.drawPath(path);
649 }
650 }
651 if (shape) {
652 m_textCursor.paintDecorations(gc, qApp->palette().color(QPalette::Highlight), decorationThickness());
653 }
655 gc.save();
656 canvas()->snapGuide()->paint(gc, converter);
657 gc.restore();
658 }
659
660 // Paint debug outline
661 if (debugEnabled() && shape) {
662 gc.save();
663 using Element = KoSvgTextShape::DebugElement;
664 KoSvgTextShape::DebugElements el{};
665 if (m_optionManager->showCharacterDebug()) {
666 el |= Element::CharBbox;
667 }
668 if (m_optionManager->showLineDebug()) {
669 el |= Element::LineBox;
670 }
671
672 gc.setTransform(shape->absoluteTransformation(), true);
673 shape->paintDebug(gc, el);
674 gc.restore();
675 }
676}
677
679{
681
682 if (selectedShape) {
686 event->accept();
687 return;
691 event->accept();
692 return;
696 event->accept();
697 return;
698 }
699 }
700
701 KoSvgTextShape *hoveredShape = dynamic_cast<KoSvgTextShape *>(canvas()->shapeManager()->shapeAt(event->point));
702 QString shapeType;
703 QPainterPath hoverPath = KisToolUtils::shapeHoverInfoCrossLayer(canvas(), event->point, shapeType);
704 bool crossLayerPossible = !hoverPath.isEmpty() && shapeType == KoSvgTextShape_SHAPEID;
705
706 if (!selectedShape && !hoveredShape && !crossLayerPossible) {
707 QPointF point = canvas()->snapGuide()->snap(event->point, event->modifiers());
708 m_interactionStrategy.reset(new SvgCreateTextStrategy(this, point));
710 event->accept();
711 } else if (hoveredShape) {
712 if (hoveredShape != selectedShape) {
714 canvas()->shapeManager()->selection()->select(hoveredShape);
715 m_hoveredShapeHighlightRect = QPainterPath();
716 }
719 event->accept();
720 } else if (crossLayerPossible) {
724 m_hoveredShapeHighlightRect = QPainterPath();
725 } else {
727 }
728 event->accept();
729 } else { // if there's a selected shape but no hovered shape...
731 event->accept();
732 }
733
735}
736
737static inline Qt::CursorShape angleToCursor(const QVector2D unit)
738{
739 constexpr float SIN_PI_8 = 0.382683432;
740 if (unit.y() < SIN_PI_8 && unit.y() > -SIN_PI_8) {
741 return Qt::SizeHorCursor;
742 } else if (unit.x() < SIN_PI_8 && unit.x() > -SIN_PI_8) {
743 return Qt::SizeVerCursor;
744 } else if ((unit.x() > 0 && unit.y() > 0) || (unit.x() < 0 && unit.y() < 0)) {
745 return Qt::SizeFDiagCursor;
746 } else {
747 return Qt::SizeBDiagCursor;
748 }
749}
750
751static inline Qt::CursorShape lineToCursor(const QLineF line, const KoCanvasBase *const canvas)
752{
753 const KisCanvas2 *const canvas2 = qobject_cast<const KisCanvas2 *>(canvas);
754 KIS_ASSERT(canvas2);
755 const KisCoordinatesConverter *const converter = canvas2->coordinatesConverter();
756 QLineF wdgLine = converter->flakeToWidget(line);
757 return angleToCursor(QVector2D(wdgLine.p2() - wdgLine.p1()).normalized());
758}
759
761{
762 m_lastMousePos = event->point;
763 m_hoveredShapeHighlightRect = QPainterPath();
764
765
767 m_interactionStrategy->handleMouseMove(event->point, event->modifiers());
770 if (c && c->draggingInlineSize()) {
771 if (this->writingMode() == KoSvgText::HorizontalTB) {
773 } else {
775 }
776 } else {
778 }
779 } else if (m_dragging == DragMode::Select && this->selectedShape()) {
781 // Todo: replace with something a little less hacky.
782 if (selectedShape->writingMode() == KoSvgText::HorizontalTB) {
784 } else {
786 }
787 }
788 event->accept();
789 } else {
792 QCursor cursor = m_base_cursor;
793 if (selectedShape) {
795 const qreal sensitivity = grabSensitivityInPt();
796
797 if (std::optional<InlineSizeInfo> info = InlineSizeInfo::fromShape(selectedShape)) {
798 const QPolygonF zone = info->endLineGrabRect(sensitivity);
799 const QPolygonF startZone = info->startLineGrabRect(sensitivity);
800 if (zone.containsPoint(event->point, Qt::OddEvenFill)) {
802 cursor = lineToCursor(info->baselineLine(), canvas());
803 } else if (startZone.containsPoint(event->point, Qt::OddEvenFill)){
805 cursor = lineToCursor(info->baselineLine(), canvas());
806 }
807 }
808
810 const QPolygonF textOutline = selectedShape->absoluteTransformation().map(selectedShape->outlineRect());
811 const QPolygonF moveBorderRegion = selectedShape->absoluteTransformation().map(kisGrowRect(selectedShape->outlineRect(),
812 sensitivity * 2));
813 if (moveBorderRegion.containsPoint(event->point, Qt::OddEvenFill) && !textOutline.containsPoint(event->point, Qt::OddEvenFill)) {
815 cursor = Qt::SizeAllCursor;
816 }
817 }
818 }
819
820 QString shapeType;
821 bool isHorizontal = true;
822 const KoSvgTextShape *hoveredShape = dynamic_cast<KoSvgTextShape *>(canvas()->shapeManager()->shapeAt(event->point));
823 QPainterPath hoverPath = KisToolUtils::shapeHoverInfoCrossLayer(canvas(), event->point, shapeType, &isHorizontal);
824 if (selectedShape && selectedShape == hoveredShape && m_highlightItem == HighlightItem::None) {
827 } else {
829 }
830 } else if (hoveredShape) {
831 if (!hoveredShape->shapesInside().isEmpty()) {
832 QPainterPath paths;
833 Q_FOREACH(KoShape *s, hoveredShape->shapesInside()) {
834 KoPathShape *path = dynamic_cast<KoPathShape *>(s);
835 if (path) {
836 paths.addPath(hoveredShape->absoluteTransformation().map(path->absoluteTransformation().map(path->outline())));
837 }
838 }
839 if (!paths.isEmpty()) {
841 }
842 } else {
843 m_hoveredShapeHighlightRect.addRect(hoveredShape->boundingRect());
844 }
845 if (hoveredShape->writingMode() == KoSvgText::HorizontalTB) {
847 } else {
849 }
850 } else if (!hoverPath.isEmpty() && shapeType == KoSvgTextShape_SHAPEID && m_highlightItem == HighlightItem::None) {
851 m_hoveredShapeHighlightRect = hoverPath;
852 if (isHorizontal) {
854 } else {
856 }
857 }
858#if 0
861 KoPathShape *shape = dynamic_cast<KoPathShape *>(canvas()->shapeManager()->shapeAt(event->point));
862 if (shape) {
863 if (shape->subpathCount() > 0) {
864 if (shape->isClosedSubpath(0)) {
866 }
867 }
868 KoPathSegment segment = segmentAtPoint(event->point, shape, handleGrabRect(event->point));
869 if (segment.isValid()) {
871 }
872 m_hoveredShapeHighlightRect.addPath(shape->absoluteTransformation().map(shape->outline()));
873 } else {
874 m_hoveredShapeHighlightRect = QPainterPath();
875 }
876 }
877#endif
879 event->ignore();
880 }
881
883}
884
886{
888 m_interactionStrategy->finishInteraction(event->modifiers());
889 KUndo2Command *const command = m_interactionStrategy->createCommand();
890 if (command) {
892 canvas()->addCommand(command);
894 }
895 m_interactionStrategy = nullptr;
898 }
900 event->accept();
901 } else {
903 }
904 event->accept();
905}
906
907void SvgTextTool::keyPressEvent(QKeyEvent *event)
908{
910 && (event->key() == Qt::Key_Control || event->key() == Qt::Key_Alt || event->key() == Qt::Key_Shift
911 || event->key() == Qt::Key_Meta)) {
912 m_interactionStrategy->handleMouseMove(m_lastMousePos, event->modifiers());
913 event->accept();
914 return;
915 } else if (event->key() == Qt::Key_Escape) {
917 } else if (selectedShape()) {
919 }
920
921 event->ignore();
922}
923
924void SvgTextTool::keyReleaseEvent(QKeyEvent *event)
925{
927 && (event->key() == Qt::Key_Control || event->key() == Qt::Key_Alt || event->key() == Qt::Key_Shift
928 || event->key() == Qt::Key_Meta)) {
929 m_interactionStrategy->handleMouseMove(m_lastMousePos, event->modifiers());
930 event->accept();
931 } else {
932 event->ignore();
933 }
934}
935
936void SvgTextTool::focusInEvent(QFocusEvent *event)
937{
939 event->accept();
940}
941
942void SvgTextTool::focusOutEvent(QFocusEvent *event)
943{
945 event->accept();
946}
947
949{
950 if (canvas()->shapeManager()->shapeAt(event->point) != selectedShape()) {
951 event->ignore(); // allow the event to be used by another
952 return;
953 } else {
954 m_textCursor.setPosToPoint(event->point, true);
957 }
958 const QRectF updateRect = std::exchange(m_hoveredShapeHighlightRect, QPainterPath()).boundingRect();
959 canvas()->updateCanvas(kisGrowRect(updateRect, 100));
960 event->accept();
961}
962
964{
965 if (canvas()->shapeManager()->shapeAt(event->point) == selectedShape()) {
966 // TODO: Consider whether we want to use sentence based selection instead:
967 // QTextBoundaryFinder allows us to find sentences if necessary.
970 event->accept();
971 }
972}
973
975{
976 const int sensitivity = grabSensitivity();
977 return canvas()->viewConverter()->viewToDocumentX(sensitivity);
978}
979
985
qreal length(const QPointF &vec)
Definition Ellipse.cc:82
#define KoSvgTextShape_SHAPEID
connect(this, SIGNAL(optionsChanged()), this, SLOT(saveOptions()))
constexpr double INLINE_SIZE_DASHES_PATTERN_A
static Qt::CursorShape lineToCursor(const QLineF line, const KoCanvasBase *const canvas)
constexpr int INLINE_SIZE_DASHES_PATTERN_LENGTH
Size of the hidden part of the inline-size handle dashes.
constexpr double INLINE_SIZE_HANDLE_THICKNESS
Total amount of trailing dashes on inline-size handles.
constexpr double INLINE_SIZE_DASHES_PATTERN_B
Size of the visible part of the inline-size handle dashes.
static Qt::CursorShape angleToCursor(const QVector2D unit)
static bool debugEnabled()
Linethickness.
The GlyphPaletteDialog class.
void setText(const KUndo2MagicString &text)
The KisAllresourcesModel class provides access to the cache database for a particular resource type....
QVector< KoResourceSP > resourcesForName(const QString &name) const
KisCoordinatesConverter * coordinatesConverter
KisImageWSP image() const
KisViewManager * viewManager() const
_Private::Traits< T >::Result flakeToWidget(const T &obj) const
The KisHandlePainterHelper class is a special helper for painting handles around objects....
void drawPath(const QPainterPath &path)
void drawConnectionLine(const QLineF &line)
void setHandleStyle(const KisHandleStyle &style)
void drawHandleLine(const QLineF &line, qreal width=1.0, QVector< qreal > dashPattern={}, qreal dashOffset=0.0)
void drawHandleCircle(const QPointF &center, qreal radius)
static KisHandleStyle & highlightedPrimaryHandlesWithSolidOutline()
static KisHandleStyle & highlightedPrimaryHandles()
static KisHandleStyle & partiallyHighlightedPrimaryHandles()
static KisHandleStyle & secondarySelection()
static KisHandleStyle & primarySelection()
double xRes() const
QDockWidget * dockWidget(const QString &id)
The PopupWidgetInterface abstract class defines the basic interface that will be used by all popup wi...
The KisQQuickWidget class.
void connectMinimumHeightToRootObject()
connectMinimumHeightToRootObject By default we scale rootObject to widget, but in some situations we ...
static KisAllResourcesModel * resourceModel(const QString &resourceType)
void addConnection(Sender sender, Signal signal, Receiver receiver, Method method, Qt::ConnectionType type=Qt::AutoConnection)
The KisSignalMapper class bundles signals from identifiable senders.
void setTextPropertiesInterface(KoSvgTextPropertiesInterface *interface)
setTextPropertiesInterface set the text properties interface. This should be done on tool activation....
KisMainWindow * mainWindow() const
KisTextPropertiesManager * textPropertyManager() const
KoSnapGuide * snapGuide
virtual KoShapeManager * shapeManager() const =0
virtual const KoViewConverter * viewConverter() const =0
virtual void updateCanvas(const QRectF &rc)=0
virtual void addCommand(KUndo2Command *command)=0
QPointer< KoCanvasResourceProvider > resourceManager
virtual KoSelectedShapesProxy * selectedShapesProxy() const =0
selectedShapesProxy() is a special interface for keeping a persistent connections to selectionChanged...
A simple solid color shape background.
The KoCssStylePreset class.
A KoPathSegment consist of two neighboring KoPathPoints.
bool isValid() const
Returns if segment is valid, e.g. has two valid points.
The position of a path point within a path shape.
Definition KoPathShape.h:63
bool isClosedSubpath(int subpathIndex) const
Checks if a subpath is closed.
QPainterPath outline() const override
reimplemented
int subpathCount() const
Returns the number of subpaths in the path.
Qt::KeyboardModifiers modifiers() const
QPointF point
The point in document coordinates.
virtual KoSelection * selection()=0
void deselectAll()
clear the selections list
void select(KoShape *shape)
const QList< KoShape * > selectedEditableShapes() const
KoShape * shapeAt(const QPointF &position, KoFlake::ShapeSelection selection=KoFlake::ShapeOnTop, bool omitHiddenShapes=true)
KoSelection * selection
QTransform absoluteTransformation() const
Definition KoShape.cpp:382
static KisHandlePainterHelper createHandlePainterHelperView(QPainter *painter, KoShape *shape, const KoViewConverter &converter, qreal handleRadius=0.0, int decorationThickness=1)
Definition KoShape.cpp:1177
void paint(QPainter &painter, const KoViewConverter &converter)
paints the guide
QPointF snap(const QPointF &mousePosition, Qt::KeyboardModifiers modifiers)
snaps the mouse position, returns if mouse was snapped
QRectF boundingRect()
returns the bounding rect of the guide
The SvgConvertTextTypeCommand class This command allows textshapes to be converted between preformatt...
@ FillId
KoSvgText::BackgroundProperty.
@ WritingModeId
KoSvgText::WritingMode.
QMap< QString, QString > convertToSvgTextAttributes() const
QMap< QString, QString > convertParagraphProperties() const
convertParagraphProperties some properties only apply to the root shape, so we write those separately...
void setProperty(PropertyId id, const QVariant &value)
QVariant propertyOrDefault(PropertyId id) const
int posLeft(int pos, bool visual=false)
QRectF boundingRect() const override
Get the bounding box of the shape.
int indexForPos(int pos) const
indexForPos get the string index for a given cursor position.
@ PreformattedText
Text-on-Path falls under this or PrePositionedText depending on collapse of lines.
@ InlineWrap
Uses inline size to wrap and preserves spaces.
QList< KoShape * > shapesInside
TextType textType() const
textType This enum gives an indication of what kind of text this shape is. The different text types a...
int posRight(int pos, bool visual=false)
void paintDebug(QPainter &painter, DebugElements elements) const
KoSvgText::WritingMode writingMode() const
writingMode There's a number of places we need to check the writing mode to provide proper controls.
QRectF outlineRect() const override
KoCanvasBase * canvas() const
Returns the canvas the tool is working on.
void selectionChanged(bool hasSelection)
QCursor cursor() const
return the last emitted cursor
int grabSensitivity() const
Convenience function to get the current grab sensitivity.
void setTextMode(bool value)
virtual void repaintDecorations()
int handleRadius() const
Convenience function to get the current handle radius.
void useCursor(const QCursor &cursor)
virtual void activate(const QSet< KoShape * > &shapes)
bool isInTextMode() const
QRectF handleGrabRect(const QPointF &position) const
virtual void deactivate()
QAction * action(const QString &name) const
bool isActivated() const
virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const
int decorationThickness() const
decorationThickness The minimum thickness for tool decoration lines, this is derived from the screen ...
void switchToolRequested(const QString &id)
static KoToolManager * instance()
Return the toolmanager singleton.
virtual qreal viewToDocumentX(qreal viewX) const
virtual QPointF documentToView(const QPointF &documentPoint) const
static QStringList possibleActions()
The SvgTextToolOptionsManager class.
void openTextPropertiesDocker(bool open)
void activate(const QSet< KoShape * > &shapes) override
reimplemented from KoToolBase
void mouseTripleClickEvent(KoPointerEvent *event) override
reimplemented from KoToolBase
void copy() const override
reimplemented from superclass
bool selectAll() override
selectAll select all data the tool can select.
KisSignalAutoConnectionsStore m_canvasConnections
~SvgTextTool() override
void requestStrokeCancellation() override
void inputMethodEvent(QInputMethodEvent *event) override
QScopedPointer< KisSignalMapper > m_textTypeSignalsMapper
void mouseMoveEvent(KoPointerEvent *event) override
reimplemented from KoToolBase
std::unique_ptr< KoInteractionStrategy > m_interactionStrategy
void keyPressEvent(QKeyEvent *event) override
void requestStrokeEnd() override
void slotTextTypeUpdated()
slotTextTypeUpdated Update the text type in the tool options.
QPointer< GlyphPaletteDialog > m_glyphPalette
QScopedPointer< SvgTextToolOptionsManager > m_optionManager
QCursor m_base_cursor
KoSelection * koSelection() const
DragMode m_dragging
void mouseReleaseEvent(KoPointerEvent *event) override
reimplemented from KoToolBase
void slotUpdateVisualCursor()
slotUpdateVisualCursor update the visual cursor mode on the text cursor.
QString generateDefs(const KoSvgTextProperties &properties=KoSvgTextProperties())
generateDefs This generates a defs section with the appropriate css and css strings assigned.
qreal grabSensitivityInPt() const
void deleteSelection() override
reimplemented from superclass
QCursor m_text_inline_horizontal
QCursor m_ibeam_horizontal
KoSvgTextShape * selectedShape() const
QPointF m_lastMousePos
QCursor m_ibeam_horizontal_done
SvgTextTool(KoCanvasBase *canvas)
QVariant inputMethodQuery(Qt::InputMethodQuery query) const override
void slotShapeSelectionChanged()
selectionChanged called when the canvas selection is changed.
void showGlyphPalette()
showGlyphPalette Shows the glyph palette dialog.
void slotTextEditorClosed()
QCursor m_text_inline_vertical
QPainterPath m_hoveredShapeHighlightRect
void focusInEvent(QFocusEvent *event) override
bool hasSelection() override
reimplemented from superclass
KoSvgTextProperties propertiesForNewText() const
propertiesForNewText get the text properties that should be used for new text.
void updateGlyphPalette()
updateGlyphPalette update the glyph palette dialog from the current selection.
void mouseDoubleClickEvent(KoPointerEvent *event) override
reimplemented from superclass
bool m_strategyAddingCommand
KisPopupWidgetInterface * popupWidget() override
HighlightItem m_highlightItem
void focusOutEvent(QFocusEvent *event) override
KoToolSelection * selection() override
reimplemented from superclass
void slotUpdateTextPasteBehaviour()
slotUpdateTextPasteBehaviour update the default text paste behaviour.
void deselect() override
deselect the tool should clear the selection if it has one.
QCursor m_ibeam_vertical
virtual QWidget * createOptionWidget() override
reimplemented from KoToolBase
void insertRichText(KoSvgTextShape *richText, bool replaceLastGlyph=false)
insertRichText Insert a rich text shape, used by the glyph palette..
QCursor m_text_in_shape
void textUpdated(KoSvgTextShape *shape, const QString &svg, const QString &defs)
void deactivate() override
reimplemented from KoToolBase
void mousePressEvent(KoPointerEvent *event) override
reimplemented from KoToolBase
void slotUpdateCursorDecoration(QRectF updateRect)
updateCursor update the canvas decorations in a particular update rect for the text cursor.
QCursor m_text_on_path
void showEditor()
friend class SvgCreateTextStrategy
Definition SvgTextTool.h:36
void paint(QPainter &gc, const KoViewConverter &converter) override
reimplemented from KoToolBase
SvgTextCursor m_textCursor
KoSvgText::WritingMode writingMode() const
QRectF decorationsRect() const override
reimplemented from KoToolBase
bool paste() override
reimplemented from superclass
void slotConvertType(int index)
slotConvertType
QPointer< SvgTextEditor > m_editor
void keyReleaseEvent(QKeyEvent *event) override
#define KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:129
#define KIS_ASSERT(cond)
Definition kis_assert.h:33
#define dbgTools
Definition kis_debug.h:48
T kisGrowRect(const T &rect, U offset)
Definition kis_global.h:186
bool selectShapeCrossLayer(KoCanvasBase *canvas, const QPointF &point, const QString &shapeType, bool skipCurrentShapes)
selectShapeCrossLayer Tries to select a shape under the cursor regardless of which layer it is on,...
QPainterPath shapeHoverInfoCrossLayer(KoCanvasBase *canvas, const QPointF &point, QString &shapeType, bool *isHorizontal, bool skipCurrentShapes)
shapeHoverInfoCrossLayer get hover info of shapes on all layers.
@ SvgTextPropertyData
KoSvgTextPropertyDataStruct.
@ HorizontalTB
Definition KoSvgText.h:38
const QString CssStyles
The KoSvgTextPropertyData struct.
KoSvgTextProperties commonProperties
The properties common between all the selected text.
BackgroundProperty is a special wrapper around KoShapeBackground for managing it in KoSvgTextProperti...
Definition KoSvgText.h:714
void setVisualMode(const bool visualMode=true)
setVisualMode set whether the navigation mode is visual or logical. This right now primarily affects ...
void keyPressEvent(QKeyEvent *event)
Handle the cursor-related key events.
KoSvgTextPropertiesInterface * textPropertyInterface()
void setCaretSetting(int cursorWidth=1, int cursorFlash=1000, int cursorFlashLimit=5000)
setCaretSetting Set the caret settings for the cursor. Qt has some standard functionality associated,...
QPair< KoSvgTextProperties, KoSvgTextProperties > currentTextProperties() const
currentTextProperties
bool hasSelection() override
return true if the tool currently has something selected that can be copied or deleted.
void setPos(int pos, int anchor)
Set the pos and the anchor.
void insertRichText(KoSvgTextShape *insert)
Insert rich text at getPos();.
void inputMethodEvent(QInputMethodEvent *event)
void setPosToPoint(QPointF point, bool moveAnchor=true)
Set the pos from a point. This currently does a search inside the text shape.
void moveCursor(MoveMode mode, bool moveAnchor=true)
Move the cursor, and, if you don't want a selection, move the anchor.
void setPasteRichTextByDefault(const bool pasteRichText=true)
setPasteRichText
QVariant inputMethodQuery(Qt::InputMethodQuery query) const
void removeSelection()
removeSelection if there's a selection, creates a text-removal command.
int getPos()
Get the current position.
void focusOut()
Stops blinking cursor.
bool registerPropertyAction(QAction *action, const QString &name)
Register an action.
void focusIn()
Turns on blinking cursor.
void paintDecorations(QPainter &gc, QColor selectionColor, int decorationThickness=1)
bool paste()
paste pastes plain text in the clipboard at pos. Uses pasteRichTextByDefault to determine whether to ...
void setShape(KoSvgTextShape *textShape)
setShape
KoSvgTextShape * shape
void copy() const
copy copies plain text into the clipboard between anchor and pos.