File indexing completed on 2024-04-14 03:59:29

0001 /*
0002     SPDX-FileCopyrightText: 2008-2010 Stefan Majewsky <majewsky@gmx.net>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "diamond.h"
0008 
0009 #include <QGraphicsSceneMouseEvent>
0010 
0011 QString colorKey(KDiamond::Color color)
0012 {
0013     QString colors[] = {
0014         QLatin1String("kdiamond-selection"),
0015         QLatin1String("kdiamond-red"),
0016         QLatin1String("kdiamond-green"),
0017         QLatin1String("kdiamond-blue"),
0018         QLatin1String("kdiamond-yellow"),
0019         QLatin1String("kdiamond-white"),
0020         QLatin1String("kdiamond-black"),
0021         QLatin1String("kdiamond-orange")
0022     };
0023     return colors[(color < 0 || color >= KDiamond::ColorsCount) ? 0 : color];
0024 }
0025 
0026 Diamond::Diamond(KDiamond::Color color, KGameGraphicsViewRenderer *renderer, QGraphicsItem *parent)
0027     : KGameRenderedGraphicsObject(renderer, colorKey(color), parent)
0028     , m_color(color)
0029 {
0030     //selection markers do not react to mouse events; they should also appear behind diamonds
0031     if (color == KDiamond::Selection) {
0032         setAcceptedMouseButtons({});
0033         setZValue(-1);
0034     } else {
0035         setAcceptedMouseButtons(Qt::LeftButton);
0036     }
0037 }
0038 
0039 KDiamond::Color Diamond::color() const
0040 {
0041     return m_color;
0042 }
0043 
0044 void Diamond::mousePressEvent(QGraphicsSceneMouseEvent *event)
0045 {
0046     m_mouseDown = true;
0047     m_mouseDownPos = event->pos();
0048 }
0049 
0050 void Diamond::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
0051 {
0052     if (m_mouseDown) {
0053         //check if diamond was dragged onto another one
0054         const QPointF pos = event->pos();
0055         const qreal dx = pos.x() - m_mouseDownPos.x(), dy = pos.y() - m_mouseDownPos.y();
0056         const QSizeF diamondSize = boundingRect().size();
0057         static const qreal draggingFuzziness = 2.0 / 3.0;
0058         if (qAbs(dx) > qAbs(dy)) {
0059             if (qAbs(dx) >= diamondSize.width() * draggingFuzziness) {
0060                 Q_EMIT dragged(QPoint(dx < 0 ? -1 : 1, 0));
0061                 m_mouseDown = false; //mouse action has been handled
0062             }
0063         } else {
0064             if (qAbs(dy) >= diamondSize.height() * draggingFuzziness) {
0065                 Q_EMIT dragged(QPoint(0, dy < 0 ? -1 : 1));
0066                 m_mouseDown = false;
0067             }
0068         }
0069     }
0070 }
0071 
0072 void Diamond::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
0073 {
0074     if (m_mouseDown && boundingRect().contains(event->pos())) {
0075         Q_EMIT clicked();
0076         m_mouseDown = false;
0077     }
0078 }
0079 
0080 #include "moc_diamond.cpp"