CmvrControlStation/src/jointfloweditor.cpp

812 lines
36 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "jointfloweditor.h"
#include "uiicons.h"
#include "workflowcanvas.h"
#include "workflowgraph.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 <QWheelEvent>
#include <QPainter>
#include <QPen>
#include <QPushButton>
#include <QScrollBar>
#include <QSignalBlocker>
#include <QSpinBox>
#include <QTimer>
#include <QVBoxLayout>
#include <QUuid>
#include <algorithm>
#include <cmath>
#include <functional>
namespace {
constexpr qreal kNodeWidth = 300.0;
constexpr qreal kNodeHeight = 110.0;
using FlowGraphicsView = WorkflowCanvas;
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
{
workflowCardPaint(painter,boundingRect(),m_title,m_subtitle,
m_active?QColor("#20a36a"):m_loop?QColor("#a086d7"):QColor("#557799"),isSelected(),m_loop?25:0,
m_loop?QStringLiteral("loop"):QStringLiteral("arm"));
if(m_loop) {
painter->setPen(QColor("#73849a"));
painter->drawText(collapseButtonRect(),Qt::AlignCenter,m_collapsed?QStringLiteral("+"):QStringLiteral("−"));
}
}
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);
m_dragStart = pos();
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 (pos()!=m_dragStart && 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;
QPointF m_dragStart;
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);
auto *canvasTools = static_cast<WorkflowCanvas *>(m_view)->tools(this);
layout->addWidget(canvasTools);
auto *workspace = new QSplitter(Qt::Horizontal, this);
auto *inspector = new QWidget(workspace);
m_inspector = inspector;
auto *form = new QFormLayout(inspector);
auto *title = new QLabel(QStringLiteral("节点参数"), inspector);
title->setObjectName(QStringLiteral("sectionTitle"));
auto *nodeName = new QLineEdit(inspector);
auto *point = new QComboBox(inspector);
auto *wait = new QDoubleSpinBox(inspector);
wait->setRange(0,2147483.647);wait->setDecimals(3);wait->setSuffix(QStringLiteral(" s"));
auto *count = new QSpinBox(inspector); count->setRange(1,10000);
auto *apply = new QPushButton(QStringLiteral("保存参数"), inspector);
apply->setObjectName(QStringLiteral("primaryButton"));
auto *note = new QLabel(QStringLiteral("选择节点编辑参数。点位从左侧点位库拖入;循环通过工具栏添加。"), inspector);
note->setWordWrap(true);
form->addRow(title);form->addRow(QStringLiteral("名称"),nodeName);
form->addRow(QStringLiteral("点位"),point);form->addRow(QStringLiteral("等待"),wait);
form->addRow(QStringLiteral("循环次数"),count);form->addRow(apply);form->addRow(note);
const auto updateInspector = [this,nodeName,point,wait,count,apply] {
const auto *node=nodeById(selectedNodeId());
const auto extra=WorkflowGraph::node(m_graph,selectedNodeId());const bool sleep=extra.value("type")=="sleep";
nodeName->setText(node ? node->nodeName : QString());
point->clear();point->addItems(m_availablePointNames);
if(node && !m_availablePointNames.contains(node->pointName))
point->addItem(node->pointName);
if(node)point->setCurrentText(node->pointName);
wait->setValue(node ? (m_graph.isEmpty()?node->intervalSeconds:WorkflowGraph::postWait(m_graph,node->id)/1000.) : 0);
count->setValue(node ? node->loopCount : 1);
if(sleep){nodeName->setText(extra.value("properties").toObject().value("name").toString());wait->setValue(WorkflowGraph::delay(extra)/1000.);}
nodeName->setEnabled(node||sleep); wait->setEnabled(node||sleep);apply->setEnabled(node||sleep);
point->setEnabled(node && node->type==SingleNode);count->setEnabled(node && node->type==LoopNode);
};
connect(apply,&QPushButton::clicked,this,[this,nodeName,point,wait,count] {
if(WorkflowGraph::node(m_graph,selectedNodeId()).value("type")=="sleep") {
WorkflowGraph::editDelay(m_graph,selectedNodeId(),nodeName->text().trimmed(),qRound(wait->value()*1000));rebuildScene();emit changed();return;
}
auto *node=nodeById(selectedNodeId());if(!node || nodeName->text().trimmed().isEmpty())return;
node->nodeName=nodeName->text().trimmed();node->intervalSeconds=wait->value();
if(!m_graph.isEmpty())if(WorkflowGraph::postWait(m_graph,node->id)!=qRound(wait->value()*1000))WorkflowGraph::setWait(m_graph,node->id,qRound(wait->value()*1000));
if(node->type==LoopNode)node->loopCount=count->value();
else {if(point->currentText().isEmpty())return;node->pointName=point->currentText();}
rebuildScene();emit changed();
});
connect(m_scene,&QGraphicsScene::selectionChanged,this,updateInspector);
connect(this,&JointFlowEditor::changed,this,updateInspector);
connect(this,&JointFlowEditor::selectionDetailsChanged,this,updateInspector);
m_refreshInspector = updateInspector;
updateInspector();
auto *inspectorScroll = new QScrollArea(workspace);
inspectorScroll->setWidgetResizable(true);
inspectorScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
inspectorScroll->setFrameShape(QFrame::NoFrame);
inspectorScroll->setWidget(inspector);
auto *toggleInspector = new QPushButton(QStringLiteral("节点参数"),canvasTools);
toggleInspector->setCheckable(true);toggleInspector->setChecked(false);
toggleInspector->setObjectName(QStringLiteral("secondaryButton"));
static_cast<QHBoxLayout *>(canvasTools->layout())->insertWidget(0,toggleInspector);
connect(toggleInspector,&QPushButton::toggled,inspectorScroll,&QWidget::setVisible);
inspectorScroll->hide();
connect(m_scene,&QGraphicsScene::selectionChanged,this,[this,toggleInspector] {
if(!m_scene->selectedItems().isEmpty())toggleInspector->setChecked(true);
});
workspace->addWidget(m_view);workspace->addWidget(inspectorScroll);
workspace->setStretchFactor(0,1);workspace->setSizes({800,240});
inspector->setMinimumWidth(210);
layout->addWidget(workspace,1);
static_cast<WorkflowCanvas *>(m_view)->componentDropped=[this](const QString &key) {
if(!m_view->isInteractive())return;
if(key=="loop"){addLoopNode(QStringLiteral("循环"),1,0);return;}
if(key=="sleep"){auto *canvas=static_cast<WorkflowCanvas *>(m_view);WorkflowGraph::addSleep(m_graph,canvas->dropContainer,canvas->dropPosition);rebuildScene();emit changed();return;}
if(!key.startsWith(QStringLiteral("point:")))return;
const QString name=key.mid(6);if(!m_availablePointNames.contains(name))return;
auto *canvas=static_cast<WorkflowCanvas *>(m_view);
if(canvas->droppingFromPalette)m_insertionParentId=canvas->dropContainer;
addSingleNode(name,name,0);
if(canvas->droppingFromPalette){auto *node=nodeById(m_selectedNodeId);if(node){node->position=canvas->dropPosition-QPointF(kNodeWidth/2,kNodeHeight/2);WorkflowGraph::position(m_graph,node->id,canvas->dropPosition);rebuildScene();emit changed();}}
};
for(const auto &key:{QStringLiteral("loop"),QStringLiteral("sleep")}) {
auto *button=new QPushButton(key=="loop"?QStringLiteral("添加循环"):QStringLiteral("添加等待"),canvasTools);
button->setObjectName(QStringLiteral("secondaryButton"));static_cast<QHBoxLayout *>(canvasTools->layout())->insertWidget(0,button);
connect(button,&QPushButton::clicked,this,[this,key]{if(!m_view->isInteractive())return;auto *canvas=static_cast<WorkflowCanvas *>(m_view);canvas->dropPosition=canvas->mapToScene(canvas->viewport()->rect().center());canvas->dropContainer=m_insertionParentId;canvas->componentDropped(key);});
}
static_cast<WorkflowCanvas *>(m_view)->connectionRequested=[this](const QString &from,const QString &to,QString &error) {
if(!m_view->isInteractive())return false;
if(!WorkflowGraph::connect(m_graph,from,to,error))return false;
QString graphError;WorkflowGraph::order(m_graph,graphError);
if(graphError.isEmpty()) {
const auto waits=WorkflowGraph::waits(m_graph,graphError);
if(graphError.isEmpty())for(auto &node:m_nodes)node.intervalSeconds=waits.value(node.id);
}
rebuildScene();emit changed();return true;
};
auto *pointCanvas=static_cast<WorkflowCanvas *>(m_view);
pointCanvas->copyNodes=[this](const QSet<QString> &selection) {
QSet<QString> ids=selection;bool added=true;
while(added){added=false;for(const auto &n:m_nodes)if(!ids.contains(n.id)&&ids.contains(n.parentId)){ids.insert(n.id);added=true;}}
auto part=WorkflowGraph::fragment(m_graph,ids);QJsonArray records;
for(const auto &n:m_nodes)if(ids.contains(n.id)) {
QJsonArray single;appendJsonNode(single,n);auto record=single.first().toObject();
if(!ids.contains(n.parentId))record.remove("parentId");
records.append(record);
}
if(records.isEmpty()&&part.value("nodes").toArray().isEmpty())return QJsonObject();
part.insert("editor",QStringLiteral("points"));part.insert("pointNodes",records);return part;
};
pointCanvas->pasteNodes=[this](const QJsonObject &data,const QPointF &offset) {
if(!m_view->isInteractive()||data.value("editor")!="points")return false;
for(const auto &v:data.value("pointNodes").toArray()) {
const auto n=v.toObject();
if(n.value("type")!="loop"&&!m_availablePointNames.contains(n.value("pointName").toString()))return false;
}
QHash<QString,QString> ids;
auto part=WorkflowGraph::cloneFragment(data,offset,ids);
for(const auto &v:data.value("pointNodes").toArray()) {
const auto record=v.toObject();const QString oldId=record.value("id").toString();
if(!ids.contains(oldId))ids[oldId]=QUuid::createUuid().toString(QUuid::WithoutBraces);
}
for(const auto &v:data.value("pointNodes").toArray()) {
const auto record=v.toObject();Node n;
n.id=ids.value(record.value("id").toString());
n.type=record.value("type")=="loop"?LoopNode:SingleNode;
n.nodeName=record.value("nodeName").toString();n.pointName=record.value("pointName").toString();
n.parentId=ids.value(record.value("parentId").toString());n.order=record.value("order").toInt();
n.loopCount=record.value("loopCount").toInt(1);n.intervalSeconds=record.value("intervalSeconds").toDouble();
n.collapsed=record.value("collapsed").toBool();
n.position=QPointF(record.value("x").toDouble(),record.value("y").toDouble())+offset;
m_nodes.append(n);m_selectedNodeId=n.id;
}
if(!m_graph.isEmpty()||!part.value("nodes").toArray().isEmpty())m_graph=WorkflowGraph::appendFragment(m_graph,part);
rebuildScene();emit changed();
m_scene->clearSelection();
for(auto *item:m_scene->items())if(ids.values().contains(item->data(7010).toString())&&(item->flags()&QGraphicsItem::ItemIsSelectable))item->setSelected(true);
return true;
};
static_cast<WorkflowCanvas *>(m_view)->connectionRemoved=[this](const QString &from,const QString &to) {
if(!m_view->isInteractive())return;WorkflowGraph::disconnect(m_graph,from,to);rebuildScene();emit changed();
};
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 (!m_view->isInteractive() || 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();
m_view->ensureVisible(QRectF(nodeById(node.id)->position, QSizeF(kNodeWidth, kNodeHeight)), 24, 24);
emit changed();
}
void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount,
double intervalSeconds)
{
if (!m_view->isInteractive() || 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();
m_view->ensureVisible(QRectF(nodeById(node.id)->position, QSizeF(kNodeWidth, kNodeHeight)), 24, 24);
emit changed();
}
void JointFlowEditor::removeSelectedNode()
{
if (!m_view->isInteractive()) return;
const QString id = selectedNodeId();
if (id.isEmpty())
return;
WorkflowGraph::removeNode(m_graph,id);
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 { if(!m_nodes.isEmpty())return false;for(const auto &v:m_graph.value("nodes").toArray())if(v.toObject().value("type")=="sleep")return false;return true; }
QList<JointFlowEditor::ExecutionStep> JointFlowEditor::expandedSteps(
QString *error, int maximumSteps) const
{
QString graphError;
if(!m_graph.isEmpty()) {
m_executionOrder=WorkflowGraph::order(m_graph,graphError);
if(graphError.isEmpty())m_executionWaits=WorkflowGraph::waits(m_graph,graphError);
if(!graphError.isEmpty()){if(error)*error=graphError;return {};}
}
const QScopedValueRollback<bool> orderGuard(m_useExecutionOrder,!m_graph.isEmpty());
QList<ExecutionStep> result;
const int initial=WorkflowGraph::leadingWait(m_graph,QString());if(initial)result.append({QString(),initial/1000.,QString()});
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, m_useExecutionOrder?m_executionWaits.value(node.id):node.intervalSeconds, node.id});
return true;
}
const QList<const Node *> children = childrenOf(node.id);
const int initial=m_useExecutionOrder?WorkflowGraph::leadingWait(m_graph,node.id):0;
if (children.isEmpty()&&!initial) {
if (error) *error = QStringLiteral("存在没有子节点的循环节点");
return false;
}
for (int repeat = 0; repeat < node.loopCount; ++repeat) {
if(initial){if(steps.size()>=maximumSteps){if(error)*error=QStringLiteral("流程展开超过步数限制");return false;}steps.append({QString(),initial/1000.,node.id});}
for (const Node *child : children)
if (!appendExecution(*child, steps, error, maximumSteps)) return false;
}
if (!steps.isEmpty()) {
steps.last().intervalSeconds += m_useExecutionOrder?m_executionWaits.value(node.id):node.intervalSeconds;
if(steps.last().intervalSeconds>2147483.647){if(error)*error=QStringLiteral("累计等待超出计时器范围");return false;}
}
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();
resetView();
QTimer::singleShot(0, this, &JointFlowEditor::resetView);
return true;
}
void JointFlowEditor::clear()
{
m_nodes.clear();
m_selectedNodeId.clear();
m_insertionParentId.clear();
rebuildScene();
resetView();
}
void JointFlowEditor::resetView()
{
m_view->resetTransform();
const QRectF bounds = m_scene->itemsBoundingRect();
m_view->centerOn(bounds.topLeft() + QPointF(m_view->viewport()->width() / 2.0 - 24,
m_view->viewport()->height() / 2.0 - 24));
}
void JointFlowEditor::fitAll()
{
if (m_scene->items().isEmpty()) { resetView(); return; }
m_view->fitInView(m_scene->itemsBoundingRect().adjusted(-24, -24, 24, 24), Qt::KeepAspectRatio);
}
void JointFlowEditor::setEditingEnabled(bool enabled)
{
m_view->setInteractive(enabled);
if(m_inspector)m_inspector->setEnabled(enabled);
}
void JointFlowEditor::setGraphState(const QJsonObject &graph,bool reset)
{
m_graph=graph;
for(auto &node:m_nodes) {
const auto saved=WorkflowGraph::node(graph,node.id);
if(!saved.isEmpty())node.position=QPointF(saved.value("x").toDouble()-kNodeWidth/2,saved.value("y").toDouble()-kNodeHeight/2);
if(!graph.isEmpty())node.intervalSeconds=WorkflowGraph::postWait(graph,node.id)/1000.;
}
rebuildScene();if(reset)resetView();
}
void JointFlowEditor::setActiveNode(const QString &nodeId) { m_activeNodeId = nodeId; rebuildScene(); }
void JointFlowEditor::setAvailablePointNames(const QStringList &pointNames)
{
m_availablePointNames = pointNames;
m_availablePointNames.removeDuplicates();
if(m_refreshInspector)m_refreshInspector();
}
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;
if(m_useExecutionOrder) {
for(const auto &id:m_executionOrder.value(parentId))if(const auto *node=nodeById(id))result.append(node);
return 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::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;
if(!m_graph.isEmpty()) {
node->position=position;WorkflowGraph::position(m_graph,id,position+QPointF(kNodeWidth/2,kNodeHeight/2));
rebuildScene();emit changed();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("根流程");
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 QPointF center = m_view->mapToScene(m_view->viewport()->rect().center());
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\n完成后等待 %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) {
QTimer::singleShot(0,this,[this,id,pos]{if(m_view->isInteractive())moveNode(id,pos);});
},
[](const QString &) {},
[this](const QString &id) { toggleLoopCollapsed(id); });
card->setData(0, node.id);
card->setData(7010,node.id);if(node.type==LoopNode)card->setData(7011,QStringLiteral("loop"));
const auto saved=WorkflowGraph::node(m_graph,node.id);
card->setPos(saved.isEmpty()?node.position:QPointF(saved.value("x").toDouble()-kNodeWidth/2,saved.value("y").toDouble()-kNodeHeight/2));
m_scene->addItem(card);
workflowPorts(card,node.id);
if (node.id == m_selectedNodeId)
card->setSelected(true);
cards.insert(node.id, card);
}
if(m_graph.isEmpty())for (const Node &node : m_nodes) {
if (node.parentId.isEmpty() || !cards.contains(node.parentId) || !cards.contains(node.id))
continue;
const auto parent = cards.value(node.parentId)->sceneBoundingRect();
const auto child = cards.value(node.id)->sceneBoundingRect();
workflowWire(m_scene,QPointF(parent.center().x(),parent.bottom()),QPointF(child.center().x(),child.top()),true);
}
QStringList parentIds{QString()};
for (const Node &node : m_nodes)
if (!parentIds.contains(node.parentId)) parentIds.append(node.parentId);
if(m_graph.isEmpty())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 auto previousRect=cards.value(previous->id)->sceneBoundingRect();
const auto currentRect=cards.value(current->id)->sceneBoundingRect();
workflowWire(m_scene,QPointF(previousRect.right(),previousRect.center().y()),
QPointF(currentRect.left(),currentRect.center().y()));
}
}
if(!m_graph.isEmpty()) {
QHash<QString,QRectF> bounds;
for(auto it=cards.begin();it!=cards.end();++it)bounds[it.key()]=it.value()->sceneBoundingRect();
for(const auto &v:m_graph.value("nodes").toArray()) {
const auto n=v.toObject();const QString id=n.value("id").toString(),type=n.value("type").toString();
if(bounds.contains(id)||(type!="start"&&type!="end"&&type!="subStart"&&type!="subEnd"&&type!="sleep"))continue;
const Node *parent=nodeById(n.value("properties").toObject().value("parentId").toString());bool hidden=false;
while(parent){if(parent->collapsed)hidden=true;parent=nodeById(parent->parentId);}
if(hidden)continue;
auto *terminal=workflowTerminal(m_scene,id,type,QPointF(n.value("x").toDouble(),n.value("y").toDouble()));
terminal->moved=[this,id](const QPointF &center){QTimer::singleShot(0,this,[this,id,center]{if(m_view->isInteractive()){WorkflowGraph::position(m_graph,id,center);rebuildScene();emit changed();}});};
bounds[id]=terminal->sceneBoundingRect();
}
workflowContainers(m_scene,m_graph,bounds);
for(const auto &v:m_graph.value("edges").toArray()) {
const auto e=v.toObject();const QString from=e.value("sourceNodeId").toString(),to=e.value("targetNodeId").toString();
if(bounds.contains(from)&&bounds.contains(to))workflowWire(m_scene,QPointF(bounds[from].right(),bounds[from].center().y()),
QPointF(bounds[to].left(),bounds[to].center().y()),false,from,to);
}
}
// Give panning room beyond the cards, including when all cards fit in view.
m_scene->setSceneRect(m_scene->itemsBoundingRect().adjusted(-1000, -1000, 1000, 1000));
// Scene signals are blocked during rebuilding, including sceneRectChanged.
// Explicitly update the view so its scroll range follows newly added cards.
m_view->setSceneRect(m_scene->sceneRect());
m_view->centerOn(center);
notifyInsertionContext();
emit selectionDetailsChanged();
if(m_refreshInspector)m_refreshInspector();
}