/
pi_coder
/
ByteMachine
Обзор
Документация
Войти
/
pi_coder
/
ByteMachine
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/nodes/paint_node.cpp
453 строки
15 KB
pimenov-and
Перенос функциональности из старого проекта, в основном это описания узлов
19 июл 2026, 20:13
19 июл 2026, 20:13
cb3c51b
Код
Авторство
О чём код?
//////////////////////////////////////////////////////////////// // ByteMachine // Узел для вывода графики //////////////////////////////////////////////////////////////// #include "paint_node.h" #include "node_name_manager.h" #include "undo/undo_change_object_prop_value.h" #include "qt_helper.h" #include "colors.h" #include <QPainter> #include <QDomDocument> //============================================================== using std::size_t; //============================================================== // Конструктор с параметрами //============================================================== PaintNode::PaintNode(QUndoStack *undoStack, QObject *parent) : BaseNode{undoStack, parent} { name_ = nodeNameManager()->addName("paint"); Q_ASSERT(!name_.isEmpty()); createInputPin(); createOutputPin(); // Задание начальной высоты const int width = PaintNode::minWidth(); const int height = PaintNode::minHeight(); setUndo(true); BaseNode::setWidth(width); BaseNode::setHeight(height); setUndo(false); PaintNode::updateStateInfo(); } //============================================================== // Чтение из XML //============================================================== void PaintNode::readFromXml(const QDomElement &elem) { Q_ASSERT(!elem.isNull()); } //============================================================== // Запись в XML //============================================================== void PaintNode::writeToXml(QDomDocument &doc, QDomElement &elem) const { Q_ASSERT(!doc.isNull()); Q_ASSERT(!elem.isNull()); } //============================================================== // Функция вывода //============================================================== void PaintNode::draw(QPainter *painter, ColorThemes theme) const { Q_ASSERT(painter != nullptr); Q_ASSERT(!isUnknown(theme)); drawHighlight(painter, theme); drawBody(painter, theme); drawPins(painter, theme); drawStateArea(painter, theme); drawResizebleMarker(painter, theme); drawComments(painter, theme); } //============================================================== // Получение копии узла //============================================================== ShPtrBaseNode PaintNode::clone() const { const ShPtrPaintNode cloneNode = ShPtrPaintNode::create( undoStack(), parent()); cloneNode->setUndo(true); cloneNode->setLeft(left()); cloneNode->setTop(top()); cloneNode->setWidth(width()); cloneNode->setHeight(height()); cloneNode->setScaleInNode(scaleInNode()); cloneNode->setBypass(isBypass()); cloneNode->setComment(comment()); cloneNode->setUndo(false); return cloneNode; } //============================================================== // Получение текста подсказки //============================================================== QString PaintNode::tooltipText() const { QString text{}; text += QString{"%1: \"%2\"\n"}.arg(tr("Name"), name()); text += QString{"%1: %2%\n"}.arg(tr("Scale in node")).arg(scaleInNode()); text += QString{"%1: %2\n"}.arg(tr("Bypass"), boolToStrTr(isBypass())); text += QString{"%1: \"%2\""}.arg(tr("Comment"), comment()); return text; } //============================================================== // Получение размера данных //============================================================== size_t PaintNode::dataSize() const { if (stateInfo_.isError()) { return 0; } return inputDataSize(); } //============================================================== // Получение байта данных //============================================================== quint8 PaintNode::dataByte(size_t index) const { Q_ASSERT_X(index < dataSize(), "Check index", qPrintable(QString{"index: %1, dataSize: %2"}.arg(index).arg(dataSize()))); return inputPin_->dataByte(index); } //============================================================== // Получение блока данных //============================================================== ByteList PaintNode::dataBlock(size_t index, size_t count) const { // Q_ASSERT_X(index >= 0, "Check index", qPrintable(QString::number(index))); // Q_ASSERT_X(count >= 0, "Check count", qPrintable(QString::number(count))); // Q_ASSERT_X(static_cast<qint64>(index) + count <= dataSize(), "Check index and count", // qPrintable(QString{"index: %1, count: %2, dataSize: %3"}.arg(index).arg(count).arg(dataSize()))); return inputPin_->dataBlock(index, count); } //============================================================== // Функция вызывается при изменении данных //============================================================== void PaintNode::dataChanged() { updateStateInfo(); outputPin_->dataChanged(); } //============================================================== // Получение входных пинов //============================================================== QVector<ShPtrInputPin> PaintNode::inputPins() { return QVector<ShPtrInputPin>{inputPin_}; } //============================================================== // Получение входных пинов (2 вариант) //============================================================== QVector<ShPtrConstInputPin> PaintNode::inputPins() const { return QVector<ShPtrConstInputPin>{inputPin_}; } //============================================================== // Получение выходных пинов //============================================================== QVector<ShPtrOutputPin> PaintNode::outputPins() { return QVector<ShPtrOutputPin>{outputPin_}; } //============================================================== // Получение выходных пинов (константный вариант) //============================================================== QVector<ShPtrConstOutputPin> PaintNode::outputPins() const { return QVector<ShPtrConstOutputPin>{outputPin_}; } //============================================================== // Задание масштаба в узле //============================================================== void PaintNode::setScaleInNode(int scale) { scale = correctScaleInNode(scale); if (scaleInNode_ != scale) { const int oldScale = scaleInNode_; scaleInNode_ = scale; const PropValue value{"scaleInNode", scaleInNode_}; emit sigChangedProp(value); if (!isUndo_) { Q_ASSERT(undoStack_ != nullptr); const auto undoCmd = new UndoChangeObjectPropValue{this, "scaleInNode", scaleInNode_, oldScale}; undoStack_->push(undoCmd); } startHighlightTimer(); } } //============================================================== // Сброс масштаба в узле //============================================================== void PaintNode::resetScaleInNode() { setScaleInNode(100); } //============================================================== // Задание признака пропуска узла //============================================================== void PaintNode::setBypass(bool bypass) { if (isBypass_ != bypass) { const bool oldBypass = isBypass_; isBypass_ = bypass; const PropValue value{"bypass", isBypass_}; emit sigChangedProp(value); if (!isUndo_) { Q_ASSERT(undoStack_ != nullptr); const auto undoCmd = new UndoChangeObjectPropValue{this, "bypass", isBypass_, oldBypass}; undoStack_->push(undoCmd); } startHighlightTimer(); } } //============================================================== // Сброс признака вывода изображения в узле //============================================================== void PaintNode::resetBypass() { setBypass(false); } //============================================================== // Функция получения имени свойства из графического // интерфейса по его системному имени //============================================================== QString PaintNode::getUiPropertyName(const QString &systemName) { const QMap<QString, QString> map { {"name", tr("Name")}, {"left", tr("Left")}, {"top", tr("Top")}, {"width", tr("Width")}, {"height", tr("Height")}, {"topLeft", tr("Top and left")}, {"size", tr("Size")}, {"comment", tr("Comment")}, {"scaleInNode", tr("Scale in node")}, {"bypass", tr("Bypass")} }; return map.value(systemName, tr("Unknown")); } //============================================================== // Функция перевода //============================================================== void PaintNode::retranslate() { updateStateInfo(); } //============================================================== // Функция вызывается при подключении выходного пина //============================================================== void PaintNode::slotOutputPinConnectChanged(ConnectStates state, InputPin *pin) { Q_ASSERT(!isUnknown(state)); Q_ASSERT(pin != nullptr); dataChanged(); const int conNodeId = pin->parentNode()->id(); const int conPinIndex = pin->parentNode()->indexOfInputPin(pin); const bool isCon = ::isConnect(state); emit sigChangedConnect(0, conNodeId, conPinIndex, isCon); } //============================================================== // Создание входного пина //============================================================== void PaintNode::createInputPin() { inputPin_ = ShPtrInputPin::create(this, 0); } //============================================================== // Создание выходного пина //============================================================== void PaintNode::createOutputPin() { outputPin_ = ShPtrOutputPin::create(this, 0); connect(outputPin_.get(), &OutputPin::sigConnectChanged, this, &PaintNode::slotOutputPinConnectChanged); } //============================================================== // Обновление состояния узла //============================================================== void PaintNode::updateStateInfo() { const NodeStateInfo oldStateInfo = stateInfo_; if (!isConnectedInputPin()) { const QString msg = tr("Not connected input pin"); stateInfo_ = NodeStateInfo{NodeStates::Error, msg}; } else if (isErrorInParent(this)) { const QString msg = tr("Parent error"); stateInfo_ = NodeStateInfo{NodeStates::Error, msg}; } else if (inputDataSize() == 0) { const QString msg = tr("No data"); stateInfo_ = NodeStateInfo{NodeStates::Warning, msg}; } else { stateInfo_ = NodeStateInfo{NodeStates::Success, QString{}}; } if (stateInfo_ != oldStateInfo) { emit sigChangedState(stateInfo_); } } //============================================================== // Получение признака подключения входного пина //============================================================== bool PaintNode::isConnectedInputPin() const { return inputPin_->isConnected(); } //============================================================== // Получение размера входные данных //============================================================== size_t PaintNode::inputDataSize() const { return isConnectedInputPin()? inputPin_->dataSize() : 0; } //============================================================== // Вывод тела //============================================================== void PaintNode::drawBody(QPainter *painter, ColorThemes theme) const { Q_ASSERT(painter != nullptr); Q_ASSERT(!isUnknown(theme)); // Вывод основы painter->setPen(Qt::transparent); painter->setBrush(Colors::nodeBack(theme)); painter->drawRect(rect().adjusted(-2, -2, 2, 2)); // основа чуть больше для создания внешней рамки // Вывод типа узла painter->setPen(Colors::nodeText(theme)); painter->drawText(left(), top(), width(), headerHeight(), Qt::AlignCenter, strType()); // Вывод разделительной линии painter->setPen(Colors::nodeBorder(theme)); painter->drawLine(left() + 1, top() + headerHeight(), right() - 2, top() + headerHeight()); // Вывод данных if (stateInfo_.isError()) { painter->setPen(Colors::nodeText(theme)); const QString strState = nodeStateToStr(stateInfo().state()); painter->drawText(left(), top() + headerHeight(), width(), height() - headerHeight(), Qt::AlignCenter, strState); } // Обводка контура QPen borderPen{currentBorderColor(theme), 2}; borderPen.setJoinStyle(Qt::MiterJoin); painter->setPen(borderPen); painter->setBrush(Qt::transparent); painter->drawRect(rect()); } //============================================================== // Вывод комментариев //============================================================== void PaintNode::drawComments(QPainter *painter, ColorThemes theme) const { Q_ASSERT(painter != nullptr); Q_ASSERT(!isUnknown(theme)); if (isCommentsVisible()) { QString comments{}; comments += QString{" <<< %1: \"%2\"\n"}.arg(tr("Name"), name()); comments += QString{" %1: %2%\n"}.arg(tr("Scale in node")).arg(scaleInNode()); comments += QString{" %1: %2\n"}.arg(tr("Bypass"), boolToStrTr(isBypass())); comments += QString{" %1: \"%2\"\n"}.arg(tr("Comment"), comment()); #ifdef QT_DEBUG comments += " -\n"; comments += QString{" %1: %2\n"}.arg("Id").arg(id()); #endif // QT_DEBUG const int commentsLeft = right(); const int commentsTop = top() + (headerHeight() - charHeight()) / 2; const int commentsFlags = Qt::AlignLeft | Qt::AlignTop | Qt::TextDontClip; const QRect commentsRect{commentsLeft, commentsTop, 0, 0}; painter->setPen(Colors::nodeText(theme)); painter->drawText(commentsRect, commentsFlags, comments); } } //============================================================== // Корректировка масштаба в узле //============================================================== /* static */ int PaintNode::correctScaleInNode(int scale) { if (scale < 0) { return 0; } else if (scale > 100) { return 100; } else { return scale; } }