1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
|
//===-- qlogo/canvas.cpp - Canvas class implementation -------*- C++ -*-===//
//
// Copyright 2017-2024 Jason Sikes
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the conditions specified in the
// license found in the LICENSE file in the project root.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file contains the implementation of the Canvas class, which is the
/// graphics portion of the user interface.
///
//===----------------------------------------------------------------------===//
#define _USE_MATH_DEFINES
#include "gui/canvas.h"
#include "math.h"
#include "sharedconstants.h"
#include <QBuffer>
#include <QColor>
#include <QMouseEvent>
#include <QSvgGenerator>
Arc::Arc(QPointF center, qreal a, qreal span, qreal radius)
{
rectangle = QRectF(center.x() - radius, center.y() - radius, radius * 2, radius * 2);
startAngle = (a - 90) * 16;
spanAngle = span * -16;
}
Canvas::Canvas(QWidget *parent) : QWidget(parent)
{
boundsX = Config::get().initialBoundX;
boundsY = Config::get().initialBoundY;
backgroundColor = Config::get().initialCanvasBackgroundColor;
foregroundColor = Config::get().initialCanvasForegroundColor;
currentWriteInfo.pen = QPen(foregroundColor);
currentWriteInfo.pen.setCapStyle(Qt::RoundCap);
currentWriteInfo.pen.setJoinStyle(Qt::RoundJoin);
currentWriteInfo.composingMode = QPainter::CompositionMode_SourceOver;
turtleMatrix = QTransform();
turtleIsVisible = true;
initDrawingElementList();
initTurtleImage();
}
void Canvas::initDrawingElementList()
{
drawingElementList.push_back({DrawingElementIDTurtle, DrawingElementVariant(currentWriteInfo)});
if (penIsDown)
lineGroup.push_back(pointFromTurtle());
}
/// @brief Initialize the turtle image.
void Canvas::initTurtleImage()
{
qreal multiplier = 5;
qreal height = 7 * multiplier * 2; // vertical distance from origin to head
qreal halfwidth = 3 * multiplier * 2; // horizontal distance from origin to edge
qreal aft = -2 * multiplier * 2; // vertical distance from origin to butt
QPolygonF turtlePolygon;
turtlePolygon << QPointF(0, 0) // Origin open
<< QPointF(halfwidth, aft) // Right aft
<< QPointF(0, height) // Head
<< QPointF(-halfwidth, aft) // Left aft
<< QPointF(0, 0) // Origin close
;
turtleImage =
QImage(halfwidth * 2 + multiplier * 2, height - aft + multiplier * 2, QImage::Format_ARGB32_Premultiplied);
turtleImage.fill(Qt::transparent);
QPainter painter(&turtleImage);
painter.translate(halfwidth + multiplier, multiplier - aft);
QPen pen = QPen(Config::get().initialCanvasForegroundColor, multiplier * 2);
pen.setCapStyle(Qt::RoundCap);
pen.setJoinStyle(Qt::RoundJoin);
painter.setPen(pen);
painter.setBrush(QBrush(Config::get().initialCanvasBackgroundColor));
painter.drawPolygon(turtlePolygon);
// Whenever we draw the turtle, transform a bit.
turtleImageMatrix.scale(0.5 / multiplier, 0.5 / multiplier);
turtleImageMatrix.translate(-halfwidth - multiplier, aft);
}
void Canvas::clearScreen()
{
drawingElementList.clear();
lineGroup.clear();
initDrawingElementList();
update();
}
// Call this when we are about to add something to the DrawingElementList.
// (Except LineGroup, of course.)
void Canvas::pushLineGroup()
{
if (lineGroup.size() > 1)
{
drawingElementList.push_back({DrawingElementIDPolyline, DrawingElementVariant(lineGroup)});
lineGroup.clear();
if (penIsDown)
lineGroup.push_back(pointFromTurtle());
}
}
void Canvas::setBounds(qreal x, qreal y)
{
boundsX = x;
boundsY = y;
updateMatrix();
update();
}
void Canvas::setLastWriteInfo()
{
Q_ASSERT(drawingElementList.size() > 0);
int lastElementID = drawingElementList.last().elementID;
// If the last drawing element is not a TurtleWriteInfo, then create it and
// push it onto the list.
if (lastElementID != DrawingElementIDTurtle)
{
drawingElementList.push_back({DrawingElementIDTurtle, DrawingElementVariant(currentWriteInfo)});
}
else
{
// replace the drawing element at the end of the list.
std::get<TurtleWriteInfo>(drawingElementList.last().element) = currentWriteInfo;
}
}
void Canvas::setPenIsDown(bool aPenIsDown)
{
if (aPenIsDown == penIsDown)
return;
penIsDown = aPenIsDown;
if (penIsDown)
{
Q_ASSERT(lineGroup.size() < 2);
lineGroup.clear();
lineGroup.push_back(pointFromTurtle());
}
else
{
pushLineGroup();
}
}
void Canvas::setPenmode(PenModeEnum newMode)
{
if (newMode == penMode)
return;
pushLineGroup();
penMode = newMode;
currentWriteInfo.composingMode =
(penMode == penModeReverse) ? QPainter::CompositionMode_Difference : QPainter::CompositionMode_SourceOver;
currentWriteInfo.pen.setColor(colorForCurrentPenmode());
setLastWriteInfo();
}
void Canvas::setPensize(qreal aSize)
{
if (currentWriteInfo.pen.widthF() == aSize)
return;
pushLineGroup();
currentWriteInfo.pen.setWidthF(aSize);
setLastWriteInfo();
}
const QColor &Canvas::colorForCurrentPenmode()
{
if (penMode == penModePaint)
return foregroundColor;
if (penMode == penModeErase)
return backgroundColor;
// Else it must be penModeReverse. Return white for full reverse effect.
return QColorConstants::White;
}
void Canvas::setLabelFontName(QString name)
{
labelFont.setFamily(name);
}
void Canvas::setLabelFontSize(qreal aSize)
{
labelFont.setPointSizeF(aSize);
}
void Canvas::addLabel(QString aText)
{
// The "minus-dy" is because we have to flip the coordinate system when
// drawing text. This is the most efficient place to do it.
Label l(aText, QPointF(turtleMatrix.dx(), -turtleMatrix.dy()), labelFont);
pushLineGroup();
drawingElementList.push_back({DrawingElementIDLabel, DrawingElementVariant(l)});
update();
}
void Canvas::addArc(qreal angle, qreal radius)
{
if (!penIsDown)
return;
qreal s = turtleMatrix.m21();
qreal c = turtleMatrix.m11();
qreal a = atan2(s, c) * 180 / M_PI;
if (radius < 0)
{
radius *= -1;
a = 180 - a;
}
Arc arc(pointFromTurtle(), a, angle, radius);
pushLineGroup();
drawingElementList.push_back({DrawingElementIDArc, DrawingElementVariant(arc)});
update();
}
void Canvas::setTurtleIsVisible(bool isVisible)
{
if (turtleIsVisible != isVisible)
{
turtleIsVisible = isVisible;
update();
}
}
void Canvas::setTurtleMatrix(const QTransform &aTurtleMatrix)
{
turtleMatrix = aTurtleMatrix;
update();
}
void Canvas::setBackgroundColor(const QColor &c)
{
backgroundColor = c;
update();
}
void Canvas::setForegroundColor(const QColor &c)
{
if (foregroundColor == c)
return;
pushLineGroup();
foregroundColor = c;
currentWriteInfo.pen.setColor(colorForCurrentPenmode());
setLastWriteInfo();
}
void Canvas::setBackgroundImage(QImage image)
{
backgroundImage = image;
update();
}
QImage Canvas::getImage()
{
QImage retval(boundsX * 2, boundsY * 2, QImage::Format_ARGB32_Premultiplied);
QPainter imagePainter = QPainter(&retval);
retval.fill(backgroundColor);
painter = &imagePainter;
painter->translate(boundsX, boundsY);
painter->scale(1, -1);
drawCanvas();
return retval;
}
QByteArray Canvas::getSvg()
{
QByteArray retval;
QBuffer bufferStream(&retval);
QSvgGenerator generator;
generator.setOutputDevice(&bufferStream);
generator.setSize(QSize(boundsX * 2, boundsY * 2));
QPainter svgPainter = QPainter(&generator);
painter = &svgPainter;
painter->translate(boundsX, boundsY);
painter->scale(1, -1);
drawCanvas();
return retval;
}
void Canvas::paintEvent(QPaintEvent *event)
{
// If any of our dimensions are zero then we can't draw.
if ((width() == 0) || (height() == 0) || (boundsX == 0) || (boundsY == 0))
return;
QPainter eventPainter = QPainter(this);
painter = &eventPainter;
if (!canvasIsBounded)
elementListDrawUnboundedBackground();
painter->setWorldTransform(drawingMatrix);
if (canvasIsBounded)
elementListDrawBoundedBackground();
drawCanvas();
}
void Canvas::drawCanvas()
{
painter->setRenderHint(QPainter::Antialiasing);
elementListDrawBackgroundImage();
for (auto &drawCommand : drawingElementList)
{
switch (drawCommand.elementID)
{
case DrawingElementIDLabel:
elementListDrawLabel(std::get<Label>(drawCommand.element));
break;
case DrawingElementIDTurtle:
elementListSetWriteInfo(std::get<TurtleWriteInfo>(drawCommand.element));
break;
case DrawingElementIDPolyline:
elementListDrawPolyline(std::get<QPolygonF>(drawCommand.element));
break;
case DrawingElementIDPolygon:
elementListDrawPolygon(std::get<Polygon>(drawCommand.element));
break;
case DrawingElementIDArc:
elementListDrawArc(std::get<Arc>(drawCommand.element));
break;
default:
Q_ASSERT(false);
}
}
// Draw the in-progress line group.
painter->drawPolyline(lineGroup);
elementListDrawTurtle();
}
void Canvas::elementListDrawUnboundedBackground()
{
painter->fillRect(rect(), backgroundColor);
}
void Canvas::elementListDrawBoundedBackground()
{
QRectF rect(-boundsX, -boundsY, 2 * boundsX, 2 * boundsY);
painter->setClipRect(rect);
painter->fillRect(rect, backgroundColor);
}
void Canvas::elementListDrawBackgroundImage()
{
if (backgroundImage.isNull())
return;
QRectF rect(-boundsX, -boundsY, 2 * boundsX, 2 * boundsY);
painter->scale(1, -1);
painter->drawImage(rect, backgroundImage);
painter->scale(1, -1);
}
void Canvas::elementListDrawLabel(const Label &label)
{
painter->setFont(label.font);
painter->scale(1, -1);
painter->drawStaticText(label.position, label.text);
painter->scale(1, -1);
}
void Canvas::elementListDrawPolyline(const QPolygonF &polyLine)
{
painter->drawPolyline(polyLine);
}
void Canvas::elementListDrawPolygon(const Polygon &p)
{
static QPen noPen = QPen();
noPen.setStyle(Qt::NoPen);
QPen pen = painter->pen();
painter->setPen(noPen);
painter->setBrush(QBrush(p.color));
painter->drawPolygon(p.points);
painter->setPen(pen);
}
void Canvas::elementListDrawArc(const Arc &a)
{
painter->drawArc(a.rectangle, a.startAngle, a.spanAngle);
}
void Canvas::elementListDrawTurtle()
{
if (turtleIsVisible)
{
painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
painter->save();
painter->setTransform(turtleMatrix, true);
painter->setTransform(turtleImageMatrix, true);
painter->drawImage(QPointF(0, 0), turtleImage);
painter->restore();
}
}
// The pen controls composition mode, color and size
void Canvas::elementListSetWriteInfo(const TurtleWriteInfo &info)
{
painter->setPen(info.pen);
painter->setCompositionMode(info.composingMode);
}
void Canvas::emitVertex()
{
if (penIsDown)
lineGroup << pointFromTurtle();
if (isConstructingPolygon)
polygonGroup << pointFromTurtle();
update();
}
void Canvas::updateMatrix(void)
{
// Set coordinate system so that background box fits in widget and fills
// without stretching.
qreal widgetHWRatio = (qreal)height() / (qreal)width();
qreal boundsHWRatio = boundsY / boundsX;
qreal hwRatio;
if (widgetHWRatio > boundsHWRatio)
{
// the bounds are hugging the left and right edges
hwRatio = width() / boundsX / 2;
}
else
{
// the bounds are hugging the top and bottom edges
hwRatio = height() / boundsY / 2;
}
drawingMatrix.reset();
drawingMatrix.translate(width() / 2.0, height() / 2.0);
drawingMatrix.scale(hwRatio, -hwRatio);
inverseDrawingMatrix = drawingMatrix.inverted();
}
QPointF Canvas::pointFromTurtle()
{
return QPointF(turtleMatrix.dx(), turtleMatrix.dy());
}
void Canvas::beginPolygon(const QColor &color)
{
Q_ASSERT(isConstructingPolygon == false);
Q_ASSERT(polygonGroup.size() == 0);
isConstructingPolygon = true;
polygonColor = (penMode == penModeReverse) ? QColorConstants::White : color;
polygonGroup << pointFromTurtle();
}
void Canvas::endPolygon()
{
Q_ASSERT(isConstructingPolygon == true);
// A polygon needs at least three vertices.
if (polygonGroup.size() >= 3)
{
pushLineGroup();
drawingElementList.push_back(
{DrawingElementIDPolygon, DrawingElementVariant(Polygon({polygonColor, polygonGroup}))});
}
polygonGroup.clear();
isConstructingPolygon = false;
}
void Canvas::resizeEvent(QResizeEvent *event)
{
updateMatrix();
}
void Canvas::mousePressEvent(QMouseEvent *event)
{
int buttonID = 0;
Qt::MouseButton button = event->button();
if (button & Qt::MiddleButton)
buttonID = 3;
if (button & Qt::RightButton)
buttonID = 2;
if (button & Qt::LeftButton)
buttonID = 1;
QPointF mousePos = inverseDrawingMatrix.map(event->position());
if (!canvasIsBounded || ((mousePos.x() <= boundsX) && (mousePos.y() <= boundsY) && (mousePos.x() >= -boundsX) &&
(mousePos.y() >= -boundsY)))
{
mouseButtonPressed = true;
emit sendMouseclickedSignal(mousePos, buttonID);
}
}
void Canvas::mouseMoveEvent(QMouseEvent *event)
{
QPointF mousePos = inverseDrawingMatrix.map(event->position());
if (mouseButtonPressed || !canvasIsBounded ||
((mousePos.x() <= boundsX) && (mousePos.y() <= boundsY) && (mousePos.x() >= -boundsX) &&
(mousePos.y() >= -boundsY)))
emit sendMousemovedSignal(mousePos);
}
void Canvas::mouseReleaseEvent(QMouseEvent *)
{
if (mouseButtonPressed)
{
mouseButtonPressed = false;
emit sendMouseReleasedSignal();
}
}
|