CmvrControlStation/src/jointfloweditor.cpp

806 lines
30 KiB
C++
Raw Normal View History

#include "jointfloweditor.h"
#include "uiicons.h"
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QGraphicsSceneHoverEvent>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QEvent>
#include <QFormLayout>
#include <QFrame>
#include <QJsonObject>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMouseEvent>
#include <QPainter>
#include <QPen>
#include <QPushButton>
#include <QScrollBar>
#include <QSignalBlocker>
#include <QSpinBox>
#include <QTimer>
#include <QVBoxLayout>
#include <QUuid>
#include <algorithm>
#include <functional>
namespace {
constexpr qreal kNodeWidth = 190.0;
constexpr qreal kNodeHeight = 76.0;
class NodeEditDialog final : public QDialog
{
public:
NodeEditDialog(const QString &title, QWidget *parent)
: QDialog(parent, Qt::Tool | Qt::FramelessWindowHint)
{
setObjectName(QStringLiteral("jointFlowChildDialog"));
setAttribute(Qt::WA_TranslucentBackground);
QVBoxLayout *outerLayout = new QVBoxLayout(this);
outerLayout->setContentsMargins(12, 12, 12, 12);
outerLayout->setSpacing(0);
QFrame *surface = new QFrame(this);
surface->setObjectName(QStringLiteral("jointFlowChildSurface"));
QVBoxLayout *surfaceLayout = new QVBoxLayout(surface);
surfaceLayout->setContentsMargins(0, 0, 0, 0);
surfaceLayout->setSpacing(0);
m_titleBar = new QWidget(surface);
m_titleBar->setObjectName(QStringLiteral("jointFlowChildTitleBar"));
m_titleBar->setFixedHeight(44);
QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBar);
titleLayout->setContentsMargins(12, 0, 0, 0);
titleLayout->setSpacing(9);
QLabel *mark = new QLabel(QStringLiteral("C"), m_titleBar);
mark->setObjectName(QStringLiteral("jointFlowDialogMark"));
mark->setAlignment(Qt::AlignCenter);
mark->setFixedSize(24, 24);
QLabel *titleLabel = new QLabel(title, m_titleBar);
titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle"));
QPushButton *closeButton = new QPushButton(m_titleBar);
closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton"));
closeButton->setFixedSize(46, 43);
closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"),
QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#4f5964"))));
titleLayout->addWidget(mark);
titleLayout->addWidget(titleLabel);
titleLayout->addStretch(1);
titleLayout->addWidget(closeButton);
surfaceLayout->addWidget(m_titleBar);
QWidget *content = new QWidget(surface);
content->setObjectName(QStringLiteral("jointFlowChildContent"));
m_contentLayout = new QVBoxLayout(content);
m_contentLayout->setContentsMargins(18, 16, 18, 16);
m_contentLayout->setSpacing(12);
surfaceLayout->addWidget(content, 1);
outerLayout->addWidget(surface);
m_titleBar->installEventFilter(this);
titleLabel->installEventFilter(this);
mark->installEventFilter(this);
connect(closeButton, &QPushButton::clicked, this, &QDialog::reject);
}
QVBoxLayout *contentLayout() const { return m_contentLayout; }
protected:
bool eventFilter(QObject *watched, QEvent *event) override
{
if ((watched == m_titleBar || (watched && watched->parent() == m_titleBar)) && event) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton) {
m_dragging = true;
m_dragOffset = mouseEvent->globalPos() - frameGeometry().topLeft();
return true;
}
} else if (event->type() == QEvent::MouseMove && m_dragging) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
move(mouseEvent->globalPos() - m_dragOffset);
return true;
} else if (event->type() == QEvent::MouseButtonRelease) {
m_dragging = false;
}
}
return QDialog::eventFilter(watched, event);
}
private:
QWidget *m_titleBar = nullptr;
QVBoxLayout *m_contentLayout = nullptr;
QPoint m_dragOffset;
bool m_dragging = false;
};
class FlowGraphicsView final : public QGraphicsView
{
public:
explicit FlowGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr)
: QGraphicsView(scene, parent)
{
}
protected:
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::RightButton) {
m_panning = true;
m_lastPosition = event->pos();
viewport()->setCursor(Qt::ClosedHandCursor);
event->accept();
return;
}
QGraphicsView::mousePressEvent(event);
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (m_panning) {
const QPoint delta = event->pos() - m_lastPosition;
m_lastPosition = event->pos();
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x());
verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y());
event->accept();
return;
}
QGraphicsView::mouseMoveEvent(event);
}
void mouseReleaseEvent(QMouseEvent *event) override
{
if (event->button() == Qt::RightButton && m_panning) {
m_panning = false;
viewport()->unsetCursor();
event->accept();
return;
}
QGraphicsView::mouseReleaseEvent(event);
}
private:
bool m_panning = false;
QPoint m_lastPosition;
};
class FlowCardItem final : public QGraphicsItem
{
public:
FlowCardItem(QString id, QString title, QString subtitle, bool loop, bool active,
bool collapsed,
std::function<void(const QString &, const QPointF &)> moved,
std::function<void(const QString &)> edit,
std::function<void(const QString &)> toggleCollapsed)
: m_id(std::move(id)), m_title(std::move(title)), m_subtitle(std::move(subtitle)),
m_loop(loop), m_active(active), m_collapsed(collapsed),
m_moved(std::move(moved)), m_edit(std::move(edit)),
m_toggleCollapsed(std::move(toggleCollapsed))
{
setFlags(ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges);
setAcceptHoverEvents(true);
setCursor(Qt::OpenHandCursor);
setZValue(2.0);
}
QRectF boundingRect() const override { return QRectF(0, 0, kNodeWidth, kNodeHeight); }
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
{
painter->setRenderHint(QPainter::Antialiasing);
const QColor fill = m_loop ? QColor("#f4efff") : QColor("#ffffff");
const QColor border = m_active ? QColor("#20a36a")
: (isSelected() ? QColor("#1b6ef3") : QColor("#cbd6e2"));
painter->setPen(QPen(border, m_active ? 3.0 : 1.5));
painter->setBrush(fill);
painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), 10, 10);
painter->setPen(QColor("#25313d"));
QFont titleFont = painter->font();
titleFont.setBold(true);
painter->setFont(titleFont);
painter->drawText(QRectF(14, 10, kNodeWidth - (m_loop ? 58 : 28), 25),
Qt::AlignLeft | Qt::AlignVCenter,
m_title);
if (m_loop) {
const QColor buttonFill = m_collapsePressed ? QColor("#d8e9ff")
: m_collapseHovered ? QColor("#e8f2ff") : QColor("#ffffff");
const QColor buttonBorder = m_collapseHovered || m_collapsePressed
? QColor("#1b6ef3") : QColor("#b8c7d8");
painter->setPen(QPen(buttonBorder, 1.4));
painter->setBrush(buttonFill);
painter->drawRoundedRect(collapseButtonRect(), 5, 5);
painter->setPen(QPen(QColor("#286fc2"), 1.8,
Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
const QPointF center = collapseButtonRect().center();
QPolygonF arrow;
if (m_collapsed) {
arrow << QPointF(center.x() - 3.5, center.y() - 5)
<< QPointF(center.x() + 2.0, center.y())
<< QPointF(center.x() - 3.5, center.y() + 5);
} else {
arrow << QPointF(center.x() - 5, center.y() - 3.0)
<< QPointF(center.x(), center.y() + 2.5)
<< QPointF(center.x() + 5, center.y() - 3.0);
}
painter->drawPolyline(arrow);
}
painter->setFont(QFont());
painter->setPen(QColor("#687684"));
painter->drawText(QRectF(14, 38, kNodeWidth - 28, 26), Qt::AlignLeft | Qt::AlignVCenter,
m_subtitle);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
{
if (m_loop && event->button() == Qt::LeftButton
&& collapseButtonRect().contains(event->pos())) {
m_collapsePressed = true;
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
event->accept();
return;
}
setCursor(Qt::ClosedHandCursor);
QGraphicsItem::mousePressEvent(event);
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
{
if (m_collapsePressed) {
const bool activate = collapseButtonRect().contains(event->pos());
m_collapsePressed = false;
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
if (activate && m_toggleCollapsed)
m_toggleCollapsed(m_id);
event->accept();
return;
}
setCursor(Qt::OpenHandCursor);
QGraphicsItem::mouseReleaseEvent(event);
if (m_moved)
m_moved(m_id, pos());
}
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override
{
if (m_edit)
m_edit(m_id);
event->accept();
}
void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override
{
const bool overButton = m_loop && collapseButtonRect().contains(event->pos());
if (m_collapseHovered != overButton) {
m_collapseHovered = overButton;
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
}
setCursor(overButton ? Qt::PointingHandCursor : Qt::OpenHandCursor);
QGraphicsItem::hoverMoveEvent(event);
}
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override
{
if (m_collapseHovered) {
m_collapseHovered = false;
update(collapseButtonRect().adjusted(-2, -2, 2, 2));
}
setCursor(Qt::OpenHandCursor);
QGraphicsItem::hoverLeaveEvent(event);
}
private:
QRectF collapseButtonRect() const { return QRectF(kNodeWidth - 34, 9, 22, 22); }
QString m_id;
QString m_title;
QString m_subtitle;
bool m_loop = false;
bool m_active = false;
bool m_collapsed = false;
bool m_collapseHovered = false;
bool m_collapsePressed = false;
std::function<void(const QString &, const QPointF &)> m_moved;
std::function<void(const QString &)> m_edit;
std::function<void(const QString &)> m_toggleCollapsed;
};
}
JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent)
{
setObjectName(QStringLiteral("jointFlowEditor"));
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
m_scene = new QGraphicsScene(this);
m_scene->setBackgroundBrush(QColor("#f4f7fa"));
m_view = new FlowGraphicsView(m_scene, this);
m_view->setObjectName(QStringLiteral("jointFlowCanvas"));
m_view->setRenderHint(QPainter::Antialiasing);
m_view->setDragMode(QGraphicsView::RubberBandDrag);
m_view->setMinimumHeight(230);
layout->addWidget(m_view);
connect(m_scene, &QGraphicsScene::selectionChanged, this, [this]() {
for (QGraphicsItem *item : m_scene->selectedItems()) {
const QString id = item->data(0).toString();
if (!id.isEmpty()) {
m_selectedNodeId = id;
if (const Node *selected = nodeById(id))
m_insertionParentId = selected->parentId;
notifyInsertionContext();
return;
}
}
m_selectedNodeId.clear();
notifyInsertionContext();
});
}
JointFlowEditor::~JointFlowEditor()
{
// The scene is deleted by QObject after our selection/node members are gone.
// Do not let its selectionChanged callback access those destroyed members.
disconnect(m_scene, nullptr, this, nullptr);
}
void JointFlowEditor::addSingleNode(const QString &nodeName, const QString &pointName,
double intervalSeconds)
{
if (nodeName.trimmed().isEmpty() || pointName.isEmpty())
return;
Node node;
node.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
node.type = SingleNode;
node.nodeName = nodeName.trimmed();
node.pointName = pointName;
node.intervalSeconds = qMax(0.0, intervalSeconds);
const Node *insertionParent = nodeById(m_insertionParentId);
node.parentId = insertionParent && insertionParent->type == LoopNode
? insertionParent->id : QString();
node.order = insertionOrder(node.parentId);
makeRoomForInsertion(node.parentId, node.order);
node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100));
m_nodes.append(node);
m_selectedNodeId = node.id;
layoutSiblings(QString());
rebuildScene();
emit changed();
}
void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount,
double intervalSeconds)
{
if (nodeName.trimmed().isEmpty())
return;
Node node;
node.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
node.type = LoopNode;
node.nodeName = nodeName.trimmed();
node.loopCount = qMax(1, loopCount);
node.intervalSeconds = qMax(0.0, intervalSeconds);
const Node *insertionParent = nodeById(m_insertionParentId);
node.parentId = insertionParent && insertionParent->type == LoopNode
? insertionParent->id : QString();
node.order = insertionOrder(node.parentId);
makeRoomForInsertion(node.parentId, node.order);
node.position = QPointF(40 + node.order * 220, 40 + (node.parentId.isEmpty() ? 0 : 100));
m_nodes.append(node);
m_selectedNodeId = node.id;
layoutSiblings(QString());
rebuildScene();
emit changed();
}
void JointFlowEditor::removeSelectedNode()
{
const QString id = selectedNodeId();
if (id.isEmpty())
return;
QStringList removing{id};
for (int i = 0; i < removing.size(); ++i) {
for (const Node &node : m_nodes)
if (node.parentId == removing.at(i))
removing.append(node.id);
}
QString parentId;
if (const Node *node = nodeById(id))
parentId = node->parentId;
for (int i = m_nodes.size() - 1; i >= 0; --i)
if (removing.contains(m_nodes.at(i).id))
m_nodes.removeAt(i);
if (removing.contains(m_insertionParentId))
setInsertionAtRoot();
m_selectedNodeId.clear();
normalizeOrders(parentId);
layoutSiblings(QString());
rebuildScene();
emit changed();
}
void JointFlowEditor::removePointReferences(const QStringList &pointNames)
{
for (int i = m_nodes.size() - 1; i >= 0; --i)
if (m_nodes.at(i).type == SingleNode && pointNames.contains(m_nodes.at(i).pointName))
m_nodes.removeAt(i);
rebuildScene();
emit changed();
}
bool JointFlowEditor::isEmpty() const { return m_nodes.isEmpty(); }
QList<JointFlowEditor::ExecutionStep> JointFlowEditor::expandedSteps(
QString *error, int maximumSteps) const
{
QList<ExecutionStep> result;
for (const Node *node : childrenOf(QString())) {
if (!appendExecution(*node, result, error, maximumSteps))
return {};
}
return result;
}
bool JointFlowEditor::appendExecution(const Node &node, QList<ExecutionStep> &steps,
QString *error, int maximumSteps) const
{
if (node.type == SingleNode) {
if (steps.size() >= maximumSteps) {
if (error) *error = QStringLiteral("展开后的流程超过 %1 步").arg(maximumSteps);
return false;
}
steps.append({node.pointName, node.intervalSeconds, node.id});
return true;
}
const QList<const Node *> children = childrenOf(node.id);
if (children.isEmpty()) {
if (error) *error = QStringLiteral("存在没有子节点的循环节点");
return false;
}
for (int repeat = 0; repeat < node.loopCount; ++repeat)
for (const Node *child : children)
if (!appendExecution(*child, steps, error, maximumSteps)) return false;
if (!steps.isEmpty())
steps.last().intervalSeconds += node.intervalSeconds;
return true;
}
QJsonArray JointFlowEditor::toJson() const
{
QJsonArray array;
for (const Node &node : m_nodes)
appendJsonNode(array, node);
return array;
}
void JointFlowEditor::appendJsonNode(QJsonArray &target, const Node &node) const
{
QJsonObject object;
object.insert(QStringLiteral("id"), node.id);
object.insert(QStringLiteral("type"), node.type == LoopNode ? QStringLiteral("loop")
: QStringLiteral("single"));
object.insert(QStringLiteral("nodeName"), node.nodeName);
object.insert(QStringLiteral("pointName"), node.pointName);
object.insert(QStringLiteral("loopCount"), node.loopCount);
object.insert(QStringLiteral("intervalSeconds"), node.intervalSeconds);
object.insert(QStringLiteral("parentId"), node.parentId);
object.insert(QStringLiteral("order"), node.order);
object.insert(QStringLiteral("x"), node.position.x());
object.insert(QStringLiteral("y"), node.position.y());
object.insert(QStringLiteral("collapsed"), node.collapsed);
target.append(object);
}
bool JointFlowEditor::fromJson(const QJsonArray &array)
{
QList<Node> loaded;
for (const QJsonValue &value : array) {
const QJsonObject object = value.toObject();
Node node;
node.id = object.value(QStringLiteral("id")).toString();
if (node.id.isEmpty()) return false;
node.type = object.value(QStringLiteral("type")).toString() == QStringLiteral("loop")
? LoopNode : SingleNode;
node.nodeName = object.value(QStringLiteral("nodeName")).toString().trimmed();
node.pointName = object.value(QStringLiteral("pointName")).toString();
if (node.nodeName.isEmpty())
node.nodeName = node.type == LoopNode ? QStringLiteral("循环节点") : node.pointName;
node.loopCount = qMax(1, object.value(QStringLiteral("loopCount")).toInt(1));
node.intervalSeconds = qMax(0.0, object.value(QStringLiteral("intervalSeconds")).toDouble());
node.parentId = object.value(QStringLiteral("parentId")).toString();
node.order = object.value(QStringLiteral("order")).toInt();
node.position = QPointF(object.value(QStringLiteral("x")).toDouble(),
object.value(QStringLiteral("y")).toDouble());
node.collapsed = object.value(QStringLiteral("collapsed")).toBool(false);
loaded.append(node);
}
m_nodes = loaded;
m_selectedNodeId.clear();
m_insertionParentId.clear();
rebuildScene();
return true;
}
void JointFlowEditor::clear()
{
m_nodes.clear();
m_selectedNodeId.clear();
m_insertionParentId.clear();
rebuildScene();
}
void JointFlowEditor::setActiveNode(const QString &nodeId) { m_activeNodeId = nodeId; rebuildScene(); }
void JointFlowEditor::setAvailablePointNames(const QStringList &pointNames)
{
m_availablePointNames = pointNames;
m_availablePointNames.removeDuplicates();
}
void JointFlowEditor::setInsertionAtRoot()
{
const QSignalBlocker sceneBlocker(m_scene);
m_scene->clearSelection();
m_selectedNodeId.clear();
m_insertionParentId.clear();
notifyInsertionContext();
}
bool JointFlowEditor::useSelectedLoopAsInsertionParent()
{
const Node *selected = nodeById(selectedNodeId());
if (!selected || selected->type != LoopNode)
return false;
const QSignalBlocker sceneBlocker(m_scene);
m_scene->clearSelection();
m_insertionParentId = selected->id;
m_selectedNodeId.clear();
notifyInsertionContext();
return true;
}
JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id)
{ for (Node &node : m_nodes) if (node.id == id) return &node; return nullptr; }
const JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id) const
{ for (const Node &node : m_nodes) if (node.id == id) return &node; return nullptr; }
QList<const JointFlowEditor::Node *> JointFlowEditor::childrenOf(const QString &parentId) const
{
QList<const Node *> result;
for (const Node &node : m_nodes) if (node.parentId == parentId) result.append(&node);
std::sort(result.begin(), result.end(), [](const Node *a, const Node *b) {
return a->order < b->order;
});
return result;
}
QString JointFlowEditor::selectedNodeId() const
{
for (QGraphicsItem *item : m_scene->selectedItems())
if (!item->data(0).toString().isEmpty()) return item->data(0).toString();
return m_selectedNodeId;
}
void JointFlowEditor::editNode(const QString &id)
{
Node *node = nodeById(id);
if (!node) return;
NodeEditDialog dialog(node->type == SingleNode
? QStringLiteral("编辑单步节点") : QStringLiteral("编辑循环节点"), this);
dialog.setMinimumWidth(420);
QVBoxLayout *dialogLayout = dialog.contentLayout();
QFormLayout *form = new QFormLayout;
QLineEdit *nameEdit = new QLineEdit(node->nodeName, &dialog);
form->addRow(QStringLiteral("节点名称"), nameEdit);
QComboBox *pointCombo = nullptr;
QSpinBox *loopCountSpin = nullptr;
if (node->type == SingleNode) {
QStringList pointNames = m_availablePointNames;
if (!pointNames.contains(node->pointName))
pointNames.prepend(node->pointName);
pointCombo = new QComboBox(&dialog);
pointCombo->addItems(pointNames);
pointCombo->setCurrentText(node->pointName);
form->addRow(QStringLiteral("执行点位"), pointCombo);
} else {
loopCountSpin = new QSpinBox(&dialog);
loopCountSpin->setRange(1, 10000);
loopCountSpin->setValue(node->loopCount);
form->addRow(QStringLiteral("循环次数"), loopCountSpin);
}
QDoubleSpinBox *intervalSpin = new QDoubleSpinBox(&dialog);
intervalSpin->setRange(0.0, 3600.0);
intervalSpin->setDecimals(1);
intervalSpin->setSingleStep(0.1);
intervalSpin->setSuffix(QStringLiteral(" s"));
intervalSpin->setValue(node->intervalSeconds);
form->addRow(node->type == LoopNode ? QStringLiteral("循环结束后等待")
: QStringLiteral("执行结束后等待"),
intervalSpin);
dialogLayout->addLayout(form);
QDialogButtonBox *buttons = new QDialogButtonBox(
QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("保存"));
buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消"));
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
dialogLayout->addWidget(buttons);
if (dialog.exec() != QDialog::Accepted || nameEdit->text().trimmed().isEmpty())
return;
node->nodeName = nameEdit->text().trimmed();
if (pointCombo)
node->pointName = pointCombo->currentText();
if (loopCountSpin)
node->loopCount = loopCountSpin->value();
node->intervalSeconds = intervalSpin->value();
rebuildScene();
emit changed();
}
void JointFlowEditor::toggleLoopCollapsed(const QString &id)
{
Node *node = nodeById(id);
if (!node || node->type != LoopNode)
return;
node->collapsed = !node->collapsed;
QTimer::singleShot(0, this, [this]() {
rebuildScene();
emit changed();
});
}
void JointFlowEditor::moveNode(const QString &id, const QPointF &position)
{
Node *node = nodeById(id);
if (!node) return;
const QString parentId = node->parentId;
const qreal droppedCenterX = position.x() + kNodeWidth / 2.0;
QList<Node *> siblings;
for (Node &candidate : m_nodes)
if (candidate.parentId == parentId && candidate.id != id)
siblings.append(&candidate);
std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) {
return a->order < b->order;
});
int targetOrder = 0;
for (const Node *sibling : siblings) {
if (droppedCenterX > sibling->position.x() + kNodeWidth / 2.0)
++targetOrder;
}
siblings.insert(targetOrder, node);
for (int order = 0; order < siblings.size(); ++order)
siblings.at(order)->order = order;
layoutSiblings(QString());
rebuildScene();
emit changed();
}
int JointFlowEditor::insertionOrder(const QString &parentId) const
{
const Node *selected = nodeById(selectedNodeId());
if (selected && selected->parentId == parentId)
return selected->order + 1;
return childrenOf(parentId).size();
}
void JointFlowEditor::makeRoomForInsertion(const QString &parentId, int order)
{
for (Node &candidate : m_nodes)
if (candidate.parentId == parentId && candidate.order >= order)
++candidate.order;
}
qreal JointFlowEditor::layoutSiblings(const QString &parentId)
{
QList<Node *> siblings;
for (Node &candidate : m_nodes)
if (candidate.parentId == parentId)
siblings.append(&candidate);
std::sort(siblings.begin(), siblings.end(), [](const Node *a, const Node *b) {
return a->order < b->order;
});
qreal startX = 40.0;
qreal y = 40.0;
if (!parentId.isEmpty()) {
const Node *parent = nodeById(parentId);
if (parent) {
startX = parent->position.x() + 40.0;
y = parent->position.y() + 112.0;
} else {
y = 140.0;
}
}
qreal right = startX;
for (int order = 0; order < siblings.size(); ++order) {
Node *sibling = siblings.at(order);
sibling->order = order;
sibling->position = QPointF(startX, y);
right = startX + kNodeWidth;
// Reserve the entire subtree before placing the next sibling, so
// adjacent expanded loops cannot put their child cards on top of each other.
if (sibling->type == LoopNode)
right = qMax(right, layoutSiblings(sibling->id));
startX = right + 30.0;
}
return right;
}
void JointFlowEditor::notifyInsertionContext()
{
const Node *parent = nodeById(m_insertionParentId);
const QString container = parent && parent->type == LoopNode
? parent->nodeName : QStringLiteral("根流程");
const Node *selected = nodeById(selectedNodeId());
if (selected && selected->parentId == (parent ? parent->id : QString())) {
emit insertionContextChanged(QStringLiteral("%1(插入到“%2”之后)")
.arg(container, selected->nodeName));
return;
}
emit insertionContextChanged(QStringLiteral("%1(末尾)").arg(container));
}
void JointFlowEditor::normalizeOrders(const QString &parentId)
{
int order = 0;
for (const Node *child : childrenOf(parentId))
if (Node *node = nodeById(child->id)) node->order = order++;
}
void JointFlowEditor::rebuildScene()
{
const QSignalBlocker sceneBlocker(m_scene);
m_scene->clear();
QHash<QString, FlowCardItem *> cards;
for (const Node &node : m_nodes) {
bool hiddenByCollapsedAncestor = false;
const Node *ancestor = node.parentId.isEmpty() ? nullptr : nodeById(node.parentId);
while (ancestor) {
if (ancestor->collapsed) {
hiddenByCollapsedAncestor = true;
break;
}
ancestor = ancestor->parentId.isEmpty() ? nullptr : nodeById(ancestor->parentId);
}
if (hiddenByCollapsedAncestor)
continue;
const QString title = node.nodeName;
const QString executionUnit = node.type == LoopNode
? QStringLiteral("循环 × %1").arg(node.loopCount) : node.pointName;
const QString subtitle = QStringLiteral("执行:%1 · 等待 %2 s")
.arg(executionUnit).arg(node.intervalSeconds, 0, 'f', 1);
auto *card = new FlowCardItem(node.id, title, subtitle, node.type == LoopNode,
node.id == m_activeNodeId, node.collapsed,
[this](const QString &id, const QPointF &pos) { moveNode(id, pos); },
[this](const QString &id) { editNode(id); },
[this](const QString &id) { toggleLoopCollapsed(id); });
card->setData(0, node.id);
card->setPos(node.position);
m_scene->addItem(card);
if (node.id == m_selectedNodeId)
card->setSelected(true);
cards.insert(node.id, card);
}
for (const Node &node : m_nodes) {
if (node.parentId.isEmpty() || !cards.contains(node.parentId) || !cards.contains(node.id))
continue;
const QPointF from = cards.value(node.parentId)->sceneBoundingRect().center();
const QPointF to = cards.value(node.id)->sceneBoundingRect().center();
m_scene->addLine(QLineF(from, to), QPen(QColor("#9aabc0"), 2.0));
}
QStringList parentIds{QString()};
for (const Node &node : m_nodes)
if (!parentIds.contains(node.parentId)) parentIds.append(node.parentId);
for (const QString &parentId : parentIds) {
const QList<const Node *> siblings = childrenOf(parentId);
for (int i = 1; i < siblings.size(); ++i) {
const Node *previous = siblings.at(i - 1);
const Node *current = siblings.at(i);
if (!cards.contains(previous->id) || !cards.contains(current->id)) continue;
const QPointF from = cards.value(previous->id)->sceneBoundingRect().center();
const QPointF to = cards.value(current->id)->sceneBoundingRect().center();
m_scene->addLine(QLineF(from, to), QPen(QColor("#5a91cf"), 1.5, Qt::DashLine));
}
}
m_scene->setSceneRect(m_scene->itemsBoundingRect().adjusted(-60, -60, 60, 60));
notifyInsertionContext();
}