Krita Source Code Documentation
Loading...
Searching...
No Matches
kis_tool_ellipse.cc
Go to the documentation of this file.
1/*
2 * kis_tool_ellipse.cc - part of Krayon
3 *
4 * SPDX-FileCopyrightText: 2000 John Califf <jcaliff@compuzone.net>
5 * SPDX-FileCopyrightText: 2002 Patrick Julien <freak@codepimps.org>
6 * SPDX-FileCopyrightText: 2004 Boudewijn Rempt <boud@valdyas.org>
7 * SPDX-FileCopyrightText: 2004 Clarence Dang <dang@kde.org>
8 * SPDX-FileCopyrightText: 2009 Lukáš Tvrdý <lukast.dev@gmail.com>
9 * SPDX-FileCopyrightText: 2010 Cyrille Berger <cberger@cberger.net>
10 *
11 * SPDX-License-Identifier: GPL-2.0-or-later
12 */
13
14#include "kis_tool_ellipse.h"
15#include <KoCanvasBase.h>
16#include <KoPathShape.h>
17#include <KoShapeStroke.h>
18
19#include <QBrush>
20#include <QFormLayout>
21#include <QHBoxLayout>
22#include <QIcon>
23#include <QLineF>
24#include <QPen>
25#include <QPixmap>
26
28#include <KisViewManager.h>
29#include <KoGroupButton.h>
30#include <KoPointerEvent.h>
31#include <canvas/kis_canvas2.h>
33#include <kis_icon.h>
37#include <ksharedconfig.h>
41
42#include <cmath>
43
44namespace
45{
46constexpr qreal MinAxisLength = 1.0;
47
48QPointF rotate90(const QPointF &point)
49{
50 return QPointF(-point.y(), point.x());
51}
52}
53
55 : KisToolEllipseBase(canvas, KisToolEllipseBase::PAINT, KisCursor::loadWithSize("tool_ellipse_cursor.svg", 32, 32, 6, 6))
56{
57 setObjectName("tool_ellipse");
60
61 KisCanvas2 *kritaCanvas = dynamic_cast<KisCanvas2*>(canvas);
62
63 connect(kritaCanvas->viewManager()->canvasResourceProvider(), SIGNAL(sigEffectiveCompositeOpChanged()), SLOT(resetCursorStyle()));
64}
65
69
71{
73
74 QWidget *widget = new QWidget();
75 widget->setObjectName("PlacementModeWidget");
76
77 KisOptionButtonStrip *placementStrip = new KisOptionButtonStrip(widget);
78 KoGroupButton *boundingBoxButton = placementStrip->addButton(i18nc("Ellipse tool placement mode", "Bounding Box"));
79 KoGroupButton *threePointButton = placementStrip->addButton(i18nc("Ellipse tool placement mode", "3-Point"));
80 boundingBoxButton->setToolTip(i18n("Place the ellipse inside a bounding box"));
81 threePointButton->setToolTip(i18n("Place the ellipse by setting the major axis and width"));
82
83 KConfigGroup cfg = KSharedConfig::openConfig()->group(toolId());
84 m_placementMode = static_cast<PlacementMode>(cfg.readEntry("placementMode", int(BoundingBoxPlacement)));
87 }
88 placementStrip->button(int(m_placementMode))->setChecked(true);
89
90 connect(placementStrip, SIGNAL(buttonToggled(int,bool)), SLOT(slotPlacementModeChanged(int,bool)));
91
96 Q_FOREACH (QPointer<QWidget> other, widgets) {
97 if (qobject_cast<KisRectangleConstraintWidget*>(other)) {
98 connect(placementStrip,
99 qOverload<int, bool>(&KisOptionButtonStrip::buttonToggled),
100 other,
101 [other](int mode, bool checked) {
102 if (!checked)
103 return;
104 other->setEnabled(static_cast<PlacementMode>(mode) == BoundingBoxPlacement);
105 });
106 other->setEnabled(m_placementMode == BoundingBoxPlacement);
107 break;
108 }
109 }
110
111 QHBoxLayout *hLayout = new QHBoxLayout(widget);
112 hLayout->addWidget(new QLabel(i18nc("Ellipse tool placement mode option label", "Placement:")), 0, Qt::AlignLeft);
113 hLayout->addWidget(placementStrip, 1, Qt::AlignRight);
114 widgets.prepend(widget);
115
116 return widgets;
117}
118
120{
121 if (!checked) {
122 return;
123 }
124
126 setStatusText(QString());
128
129 KConfigGroup cfg = KSharedConfig::openConfig()->group(toolId());
130 cfg.writeEntry("placementMode", int(m_placementMode));
131}
132
134{
138 return;
139 }
140
142 useCursor(KisCursor::loadWithSize("tool_ellipse_eraser_cursor.svg", 32, 32, 6, 6));
143 } else {
145 }
146
148}
149
154
156{
157 NodePaintAbility paintability = nodePaintAbility();
158 if (!nodeEditable() || paintability == UNPAINTABLE || paintability == KisToolPaint::CLONE || paintability == KisToolPaint::MYPAINTBRUSH_UNPAINTABLE) {
159 if (paintability == KisToolPaint::CLONE) {
160 KisCanvas2 *kiscanvas = static_cast<KisCanvas2*>(canvas());
161 kiscanvas->viewManager()->showFloatingMessage(
162 i18n("This tool cannot paint on clone layers. Please select a paint or vector layer or mask."),
163 koIcon("object-locked"));
164 }
165
166 if (paintability == KisToolPaint::MYPAINTBRUSH_UNPAINTABLE) {
167 KisCanvas2 *kiscanvas = static_cast<KisCanvas2*>(canvas());
168 kiscanvas->viewManager()->showFloatingMessage(
169 i18n("The MyPaint Brush Engine is not available for this colorspace"),
170 koIcon("object-locked"));
171 }
172
173 event->ignore();
174 return false;
175 }
176
177 return true;
178}
179
181{
182 return m_threePointHandles.size() == 3;
183}
184
189
190int KisToolEllipse::threePointHandleAt(const QPointF &pos) const
191{
192 const QPointF viewPos = pixelToView(pos);
193 const qreal radius = qMax<qreal>(grabSensitivity(), handleRadius() + 3);
194
195 for (int i = m_threePointHandles.size() - 1; i >= 0; --i) {
196 if (QLineF(viewPos, pixelToView(m_threePointHandles[i])).length() <= radius) {
197 return i;
198 }
199 }
200
201 return -1;
202}
203
205{
206 static const QCursor cursor = [] {
207 QPixmap pixmap(42, 32);
208 pixmap.fill(Qt::transparent);
209
210 QPainter painter(&pixmap);
211 painter.drawPixmap(0, 0, QIcon(QStringLiteral(":/tool_ellipse_cursor.svg")).pixmap(32, 32));
212 painter.setRenderHint(QPainter::Antialiasing, true);
213
214 QPainterPath checkPath;
215 checkPath.moveTo(31.0, 23.0);
216 checkPath.lineTo(34.0, 26.0);
217 checkPath.lineTo(41.0, 17.0);
218
219 QPen outlinePen(Qt::white, 4.0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
220 painter.setPen(outlinePen);
221 painter.drawPath(checkPath);
222
223 QPen checkPen(Qt::black, 2.0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
224 painter.setPen(checkPen);
225 painter.drawPath(checkPath);
226 painter.end();
227
228 return QCursor(pixmap, 6, 6);
229 }();
230
231 return cursor;
232}
233
244
246{
247 if (!isThreePointPlacement()) {
249 return;
250 }
251
252 if (!canStartThreePointEllipse(event)) {
253 return;
254 }
255
261 event->accept();
262 return;
263 } else {
265 }
266 }
267
269 event->accept();
270}
271
273{
274 if (!isThreePointPlacement()) {
276 return;
277 }
278
280 event->accept();
281 return;
282 }
283
285 const QPointF pos = convertToPixelCoordAndSnap(event, QPointF(), false);
287 const QRectF oldRect = threePointUpdateRect();
290 } else if (!hasCompleteThreePointEllipse()) {
292 }
294}
295
297{
298 if (!isThreePointPlacement()) {
300 return;
301 }
302
306 event->accept();
307 return;
308 }
309
311
312 if (!event->spontaneous()) {
314 event->accept();
315 return;
316 }
317
318 const QPointF pos = convertToPixelCoordAndSnap(event, QPointF(), false);
320
322 const QRectF oldRect = threePointUpdateRect();
327 event->accept();
328 return;
329 }
330
332 beginShape();
334 }
335
337 if (!m_threePointHandles.isEmpty()) {
339 }
340 m_threePointHandles.append(pos);
343
344 if (m_threePointHandles.size() == 1) {
345 setStatusText(i18n("Click to place the other end of the ellipse axis."));
346 } else if (m_threePointHandles.size() == 2) {
347 setStatusText(i18n("Click to set the ellipse width."));
348 } else {
349 setStatusText(i18n("Drag handles to adjust the ellipse. Press Enter to apply or Esc to cancel."));
351 }
352 }
353
354 event->accept();
355}
356
358{
361 return;
362 }
363
365 updateThreePointPreview(convertToPixelCoordAndSnap(event, QPointF(), false));
366 } else {
367 updateThreePointCursor(convertToPixelCoordAndSnap(event, QPointF(), false));
368 }
370}
371
372void KisToolEllipse::paint(QPainter &gc, const KoViewConverter &converter)
373{
374 if (!isThreePointPlacement()) {
375 KisToolEllipseBase::paint(gc, converter);
376 return;
377 }
378
380 KisToolPaint::paint(gc, converter);
381}
382
391
403
413
422
424{
425 const QRectF oldRect = threePointUpdateRect();
428}
429
440
450
452{
454 return;
455 }
456
457 QPainterPath path;
459 return;
460 }
461
462 const QRectF updateRect = threePointUpdateRect().united(path.boundingRect());
463 updateCanvasPixelRect(updateRect);
464
465 // The painting helper starts a stroke, which re-emits requestStrokeEnd().
466 // Clear the pending preview before painting to avoid recursive commits.
471
472 updateCanvasPixelRect(updateRect);
473}
474
476{
478 return;
479 }
480
481 QPainterPath path;
482 const QPointF firstPoint = pixelToView(m_threePointHandles[0]);
483
484 if (m_threePointHandles.size() == 1) {
485 path.addPath(drawX(firstPoint));
486 path.moveTo(firstPoint);
488 } else {
489 QPainterPath ellipsePath;
490 if (threePointEllipsePath(threePointPreviewPoint(), &ellipsePath)) {
491 path.addPath(pixelToView(ellipsePath));
492 } else {
493 path.moveTo(firstPoint);
494 path.lineTo(pixelToView(m_threePointHandles[1]));
495 }
496 }
497
498 paintToolOutline(&gc, path);
500}
501
503{
504 gc.save();
505 gc.setRenderHint(QPainter::Antialiasing, true);
507 gc.setPen(QPen(palette.black, 1.0));
508 gc.setBrush(QBrush(palette.white));
509
510 const qreal radius = qMax<qreal>(3.0, handleRadius() * 0.75);
511 for (const QPointF &point : m_threePointHandles) {
512 const QPointF viewPoint = pixelToView(point);
513 gc.drawEllipse(QRectF(viewPoint - QPointF(radius, radius), QSizeF(radius * 2.0, radius * 2.0)));
514 }
515
516 gc.restore();
517}
518
519bool KisToolEllipse::threePointEllipsePath(const QPointF &thirdPoint, QPainterPath *path) const
520{
521 if (m_threePointHandles.size() < 2) {
522 return false;
523 }
524
525 const QPointF p1 = m_threePointHandles[0];
526 const QPointF p2 = m_threePointHandles[1];
527 const QPointF center = (p1 + p2) * 0.5;
528 const QPointF majorVector = p2 - p1;
529 const qreal majorLength = std::hypot(majorVector.x(), majorVector.y());
530
531 if (majorLength < MinAxisLength) {
532 return false;
533 }
534
535 const qreal semiMajor = majorLength * 0.5;
536 const QPointF majorUnit = majorVector / majorLength;
537 const QPointF minorUnit = rotate90(majorUnit);
538 const QPointF localPoint = thirdPoint - center;
539 const qreal localX = QPointF::dotProduct(localPoint, majorUnit);
540 const qreal localY = QPointF::dotProduct(localPoint, minorUnit);
541 const qreal divisor = 1.0 - (localX * localX) / (semiMajor * semiMajor);
542
543 if (divisor <= 0.0 || qFuzzyIsNull(localY)) {
544 return false;
545 }
546
547 const qreal semiMinor = qAbs(localY) / std::sqrt(divisor);
548 if (semiMinor <= 0.0) {
549 return false;
550 }
551
552 QPainterPath canonicalPath;
553 canonicalPath.addEllipse(QPointF(0, 0), semiMajor, semiMinor);
554
555 QTransform ellipseTransform(majorUnit.x(), majorUnit.y(),
556 minorUnit.x(), minorUnit.y(),
557 center.x(), center.y());
558
559 *path = ellipseTransform.map(canonicalPath);
560 return true;
561}
562
564{
565 QRectF rect;
566
567 for (const QPointF &point : m_threePointHandles) {
568 rect |= QRectF(point, QSizeF(1.0, 1.0));
569 }
570
571 rect |= QRectF(m_threePointHoverPoint, QSizeF(1.0, 1.0));
572
573 QPainterPath path;
575 rect |= path.boundingRect();
576 }
577
578 return rect.adjusted(-20.0, -20.0, 20.0, 20.0);
579}
580
581void KisToolEllipse::addThreePointEllipsePath(const QPainterPath &path)
582{
583 const KisToolShape::ShapeAddInfo info =
585
586 if (!info.shouldAddShape) {
587 KisFigurePaintingToolHelper helper(kundo2_i18n("Draw Ellipse"),
588 image(),
589 currentNode(),
590 canvas()->resourceManager(),
591 strokeStyle(),
592 fillStyle(),
593 fillTransform());
594 helper.paintPainterPath(path);
595 } else {
596 QPainterPath documentPath = path;
597 if (image()) {
598 QTransform pixelToDocument;
599 pixelToDocument.scale(1.0 / image()->xRes(), 1.0 / image()->yRes());
600 documentPath = pixelToDocument.map(path);
601 }
602
605 if (info.shouldAddSelectionShape) {
606 shape->normalize();
607 addShape(shape);
608 } else {
609 addPathShape(shape, kundo2_i18n("Draw Ellipse"));
610 }
611 }
612}
613
614void KisToolEllipse::finishRect(const QRectF& rect, qreal roundCornersX, qreal roundCornersY)
615{
616 Q_UNUSED(roundCornersX);
617 Q_UNUSED(roundCornersY);
618
619 if (rect.isEmpty())
620 return;
621
622 const KisToolShape::ShapeAddInfo info =
624
625 if (!info.shouldAddShape) {
626 KisFigurePaintingToolHelper helper(kundo2_i18n("Draw Ellipse"),
627 image(),
628 currentNode(),
629 canvas()->resourceManager(),
630 strokeStyle(),
631 fillStyle(),
632 fillTransform());
633 QPainterPath path;
634 path.addEllipse(rect);
635 getRotatedPath(path, rect.center(), getRotationAngle());
636 helper.paintPainterPath(path);
637 } else {
638 KisResourcesSnapshot resources(image(),
639 currentNode(),
640 canvas()->resourceManager());
641 QRectF r = convertToPt(rect);
643 shape->rotate(qRadiansToDegrees(getRotationAngle()));
645 shape->setStroke(border);
646
648
649 addShape(shape);
650 }
651}
652
654{
655 return true;
656}
QPointF rotate90(const QPointF &p)
Definition Ellipse.cc:58
QPointF p2
QPointF p1
KoColorDisplayRendererInterface * displayRendererInterface() const override
displayRendererInterface The display renderer interface has a number of color conversion functions wh...
KisViewManager * viewManager() const
static QCursor loadWithSize(const QString &cursorName, int width, int height, int hotspotX=-1, int hotspotY=-1)
static QCursor pointingHandCursor()
void paintPainterPath(const QPainterPath &path)
Provides a list of consecutive tool buttons.
void buttonToggled(KoGroupButton *button, bool checked)
KoGroupButton * addButton(const QIcon &icon, const QString &text=QString())
KoGroupButton * button(int index) const
The PopupWidgetInterface abstract class defines the basic interface that will be used by all popup wi...
The KisResourcesSnapshot class takes a snapshot of the various resources like colors and settings use...
static KoShape * createEllipseShape(const QRectF &rect)
QVector< QPointF > m_threePointHandles
~KisToolEllipse() override
bool supportsPaintingAssistants() const override
bool threePointEllipsePath(const QPointF &thirdPoint, QPainterPath *path) const
KisToolEllipse(KoCanvasBase *canvas)
void finishRect(const QRectF &rect, qreal roundCornersX, qreal roundCornersY) override
void mouseMoveEvent(KoPointerEvent *event) override
void resetCursorStyle() override
void updateThreePointPreview(const QPointF &pos)
QPointF m_threePointHoverPoint
QPointF threePointPreviewPoint() const
bool canStartThreePointEllipse(KoPointerEvent *event)
PlacementMode m_placementMode
bool isThreePointPlacement() const
QRectF threePointUpdateRect() const
QList< QPointer< QWidget > > createOptionWidgets() override
bool m_threePointCommittedOnPress
bool hasCompleteThreePointEllipse() const
void endPrimaryAction(KoPointerEvent *event) override
QCursor threePointConfirmCursor() const
void paintThreePointHandles(QPainter &gc)
void beginPrimaryAction(KoPointerEvent *event) override
void addThreePointEllipsePath(const QPainterPath &path)
KisPopupWidgetInterface * popupWidget() override
void updateThreePointCursor(const QPointF &pos)
void deactivate() override
bool m_threePointCommitInProgress
void slotPlacementModeChanged(int mode, bool checked)
int threePointHandleAt(const QPointF &pos) const
void paintThreePointEllipse(QPainter &gc)
void requestStrokeEnd() override
void paint(QPainter &gc, const KoViewConverter &converter) override
void continuePrimaryAction(KoPointerEvent *event) override
void requestStrokeCancellation() override
void setSupportOutline(bool supportOutline)
virtual void requestUpdateOutline(const QPointF &outlineDocPoint, const KoPointerEvent *event)
void paint(QPainter &gc, const KoViewConverter &converter) override
void setMode(ToolMode mode) override
bool isEraser() const
void mouseMoveEvent(KoPointerEvent *event) override
void getRotatedPath(QPainterPath &path, const QPointF &center, const qreal &angle)
QPainterPath drawX(const QPointF &pt)
KisToolShapeUtils::StrokeStyle strokeStyle()
ShapeAddInfo shouldAddShape(KisNodeSP currentNode) const
virtual void beginShape()
qreal currentStrokeWidth() const
void addPathShape(KoPathShape *pathShape, const KUndo2MagicString &name)
QTransform fillTransform()
void addShape(KoShape *shape)
KisToolShapeUtils::FillStyle fillStyle()
KisCanvasResourceProvider * canvasResourceProvider()
void showFloatingMessage(const QString &message, const QIcon &icon, int timeout=4500, KisFloatingMessage::Priority priority=KisFloatingMessage::Medium, int alignment=Qt::AlignCenter|Qt::TextWordWrap)
shows a floating message in the top right corner of the canvas
virtual KisHandlePalette handlePaletteForDisplayColorSpace() const =0
handlePaletteForDisplayColorSpace
void toQColor(QColor *c) const
a convenience method for the above.
Definition KoColor.cpp:198
The position of a path point within a path shape.
Definition KoPathShape.h:63
virtual QPointF normalize()
Normalizes the path data.
static KoPathShape * createShapeFromPainterPath(const QPainterPath &path)
Creates path shape from given QPainterPath.
bool spontaneous() const
return if this event was spontaneous (see QMouseEvent::spontaneous())
QPointF point
The point in document coordinates.
void rotate(qreal angle)
Rotate the shape (relative)
Definition KoShape.cpp:223
virtual void setStroke(KoShapeStrokeModelSP stroke)
Definition KoShape.cpp:902
virtual void requestStrokeCancellation()
virtual KisPopupWidgetInterface * popupWidget()
Definition KoToolBase.h:340
Q_INVOKABLE QString toolId() const
virtual QList< QPointer< QWidget > > createOptionWidgets()
int grabSensitivity() const
Convenience function to get the current grab sensitivity.
void setStatusText(const QString &statusText)
void setIsOpacityPresetMode(bool value)
int handleRadius() const
Convenience function to get the current handle radius.
void useCursor(const QCursor &cursor)
virtual void mouseMoveEvent(KoPointerEvent *event)=0
virtual void deactivate()
virtual void requestStrokeEnd()
virtual void paint(QPainter &painter, const KoViewConverter &converter)=0
static bool qFuzzyIsNull(half h)
#define koIcon(name)
Use these macros for icons without any issues.
Definition kis_icon.h:25
#define CHECK_MODE_SANITY_OR_RETURN(_mode)
Definition kis_tool.h:27
KUndo2MagicString kundo2_i18n(const char *text)
void markAsSelectionShapeIfNeeded(KoShape *shape) const
virtual ToolMode mode() const
Definition kis_tool.cc:407
void updateCanvasPixelRect(const QRectF &pixelRect)
Update the canvas for the given rectangle in image pixel coordinates.
Definition kis_tool.cc:322
KisTool::NodePaintAbility nodePaintAbility()
Definition kis_tool.cc:539
virtual void resetCursorStyle()
Definition kis_tool.cc:613
bool nodeEditable()
Checks checks if the current node is editable.
Definition kis_tool.cc:651
virtual void beginPrimaryAction(KoPointerEvent *event)
Definition kis_tool.cc:431
QPointF pixelToView(const QPoint &pixelCoord) const
Definition kis_tool.cc:269
KisNodeSP currentNode() const
Definition kis_tool.cc:370
virtual void endPrimaryAction(KoPointerEvent *event)
Definition kis_tool.cc:446
virtual void continuePrimaryAction(KoPointerEvent *event)
Definition kis_tool.cc:441
bool overrideCursorIfNotEditable()
Override the cursor appropriately if current node is not editable.
Definition kis_tool.cc:618
void paintToolOutline(QPainter *painter, const KisOptimizedBrushOutline &path)
Definition kis_tool.cc:589
QRectF convertToPt(const QRectF &rect)
Definition kis_tool.cc:252
KisImageWSP image() const
Definition kis_tool.cc:332
@ PAINT_MODE
Definition kis_tool.h:304
@ HOVER_MODE
Definition kis_tool.h:303
QPointF convertToPixelCoordAndSnap(KoPointerEvent *e, const QPointF &offset=QPointF(), bool useModifiers=true)
Definition kis_tool.cc:214
QCursor cursor
Definition kis_tool.cc:64
NodePaintAbility
Definition kis_tool.h:152
@ MYPAINTBRUSH_UNPAINTABLE
Definition kis_tool.h:157
@ UNPAINTABLE
Definition kis_tool.h:156
KisCanvas2 * canvas