diff --git a/CMakeLists.txt b/CMakeLists.txt index 716c7ad..85867fe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,7 +30,7 @@ set(PROTO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/protos") set(GENERATED_ROOT "${CMAKE_CURRENT_BINARY_DIR}/generated_cpp") find_package(Qt5 5.12 REQUIRED COMPONENTS - Core Gui Widgets Network Multimedia 3DCore 3DRender 3DExtras 3DInput 3DAnimation) + Core Gui Widgets Svg Network Multimedia 3DCore 3DRender 3DExtras 3DInput 3DAnimation) get_target_property(CMVR_QMAKE_EXECUTABLE Qt5::qmake IMPORTED_LOCATION) if(CMVR_QMAKE_EXECUTABLE) @@ -187,6 +187,7 @@ set(CMVR_SOURCES src/demosimulator.h src/workflowcanvas.h src/workflowgraph.h + src/workflowruntime.h src/freescaninteropui.h src/freescaninterop.cpp src/freescaninterop.h @@ -289,7 +290,7 @@ if(CMVR_WITH_MSQUIC) endif() target_link_libraries(CmvrControlStation PRIVATE - Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Network Qt5::Multimedia + Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Svg Qt5::Network Qt5::Multimedia Qt5::3DCore Qt5::3DRender Qt5::3DExtras Qt5::3DInput Qt5::3DAnimation) # Generate every project-local CMVR message. This avoids source-tree generated diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index 212104b..a1bcc44 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -1,4 +1,4 @@ -QT += core gui widgets network multimedia 3dcore 3drender 3dextras 3dinput 3danimation +QT += core gui widgets svg network multimedia 3dcore 3drender 3dextras 3dinput 3danimation CONFIG += c++17 warn_on debug_and_release win32-g++: QMAKE_CXXFLAGS += -Wa,-mbig-obj @@ -421,3 +421,4 @@ win32:CONFIG(release, debug|release) { DISTFILES += scripts/repair_qt3d_release.ps1 HEADERS += src/workflowgraph.h src/freescaninteropui.h +HEADERS += src/workflowruntime.h diff --git a/README.md b/README.md index 31d83e7..18383c6 100644 --- a/README.md +++ b/README.md @@ -341,7 +341,7 @@ Proto 约定和目录说明见 [protos/README.md](protos/README.md)。 工作流工作区以 `am-freescan` 的组件库、端口连线、循环容器、右侧参数面板和图数据结构为依据,以原生 Qt 实现。参考仓库位于 `am-freescan/`,独立管理 Git;来源提交为 `6ace9b1`。两个编辑入口均独立全屏打开。 -点位库支持搜索、拖入、重命名、行号排序、组复制和组内多流程。循环和等待可添加到画布;节点可自由移动,循环标题移动时带动容器内节点。任务编排左侧可搜索设备组件,右侧可直接编辑接口参数、超时和等待。端口连线决定执行顺序,Delete 删除选中的连线;不连通、环路、跨容器连线和不支持的分支在运行前报错。右键/中键或空白处平移,Ctrl+滚轮缩放,工具栏可显示全部。 +点位库支持搜索、拖入、重命名、行号排序、组复制和组内多流程。循环和等待可添加到画布;节点可自由移动,循环标题移动时带动容器内节点。任务编排左侧可搜索设备组件,右侧可直接编辑接口参数、超时和等待。端口连线决定执行顺序,Delete 删除选中的连线;不连通、环路和跨容器连线在运行前报错。右键/中键或空白处平移,Ctrl+滚轮缩放,工具栏可显示全部。 两个画布均支持 Ctrl+C / Ctrl+V 复制粘贴选中节点。循环连同其内部节点一起复制,多节点保留内部连线;粘贴生成新的节点 ID 并偏移位置,外部连线不复制。点位流程粘贴时要求当前点位库中存在所引用的点位。执行期间禁用粘贴,文本输入框继续使用原有文本复制粘贴。 @@ -349,4 +349,4 @@ Proto 约定和目录说明见 [protos/README.md](protos/README.md)。 两个入口均能导入/导出 am-freescan 图 JSON。导出保留 cmvr-es 的服务全名、方法名、完整请求、接口超时及 protobuf 描述集;循环和等待使用原生 loop/sleep 节点。组合点位保留多臂并行运动和逐臂关节顺序校验。网页侧通过自身 gRPC 连接调用 cmvr-es,上位机无需保持运行。资源使用参考项目的机器人角色和设备用途绑定,网页导出后在上位机导入时选择实际设备。 -克隆仓库包含对应的网页 JSON 导入/导出、参数面板和 `CMVR_GRPC_UNARY` / `CMVR_ARM_POINT_BATCH` 后端执行适配。这些改动必须由网页项目单独构建部署后才生效,本地修改不代表线上已支持。组合调用先校验所有机械臂,再并行下发同步 MoveJ;失败或取消时取消剩余调用并请求停止。当前 Qt 执行器支持单路径及嵌套循环;条件分支、运行时参数引用、扫描仪等其他领域动作不能无损转换时明确报错。等待可位于开始之后、任务之后或循环内部。 +克隆仓库包含对应的网页 JSON 导入/导出、参数面板和 `CMVR_GRPC_UNARY` / `CMVR_ARM_POINT_BATCH` 后端执行适配。这些改动必须由网页项目单独构建部署后才生效,本地修改不代表线上已支持。组合调用先校验所有机械臂,再并行下发同步 MoveJ;失败或取消时取消剩余调用并请求停止。任务编排使用图执行器,支持并行分支、汇合屏障及嵌套循环;每次循环独立记录前驱完成状态,各 RPC 以独立调用标识收取结果。失败和停止会取消全部在途 RPC;已执行的调用不会自动重试。点位执行器保留单路径与组合点位调用。条件分支、运行时参数引用、扫描仪等其他领域动作不能无损转换时明确报错。等待可位于开始之后、任务之后或循环内部。 diff --git a/resources.qrc b/resources.qrc index 011d1fd..70278f7 100644 --- a/resources.qrc +++ b/resources.qrc @@ -42,4 +42,21 @@ icons/trash-2.svg icons/plus.svg + + resources/workflow-icons/arm.svg + resources/workflow-icons/agv.svg + resources/workflow-icons/hand.svg + resources/workflow-icons/camera.svg + resources/workflow-icons/video.svg + resources/workflow-icons/microphone.svg + resources/workflow-icons/audio.svg + resources/workflow-icons/expression.svg + resources/workflow-icons/motor.svg + resources/workflow-icons/start.svg + resources/workflow-icons/end.svg + resources/workflow-icons/sleep.svg + resources/workflow-icons/loop.svg + resources/workflow-icons/plan.svg + resources/workflow-icons/touch.svg + diff --git a/resources/workflow-icons/README.md b/resources/workflow-icons/README.md new file mode 100644 index 0000000..f377502 --- /dev/null +++ b/resources/workflow-icons/README.md @@ -0,0 +1,8 @@ +The original web SVGs are copied without rasterization from the local am-freescan +reference project: am-web/src/cmvr/common/views/flow/icon/. The additional arm.svg, +agv.svg and hand.svg use device-specific shapes in the same palette; the arm is +not represented by the web project's legacy video-camera icon. + +The Qt workflow canvas renders the source paths with QSvgRenderer, preserving +their original colors and geometry at the current canvas zoom and screen DPI. +The workflow node style follows NodeTitle.vue (36px badge, 22px icon, 15px title). diff --git a/resources/workflow-icons/agv.svg b/resources/workflow-icons/agv.svg new file mode 100644 index 0000000..7528dd7 --- /dev/null +++ b/resources/workflow-icons/agv.svg @@ -0,0 +1 @@ + diff --git a/resources/workflow-icons/arm.svg b/resources/workflow-icons/arm.svg new file mode 100644 index 0000000..1b64cdb --- /dev/null +++ b/resources/workflow-icons/arm.svg @@ -0,0 +1 @@ + diff --git a/resources/workflow-icons/audio.svg b/resources/workflow-icons/audio.svg new file mode 100644 index 0000000..e71eb39 --- /dev/null +++ b/resources/workflow-icons/audio.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/camera.svg b/resources/workflow-icons/camera.svg new file mode 100644 index 0000000..5d21dd9 --- /dev/null +++ b/resources/workflow-icons/camera.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/end.svg b/resources/workflow-icons/end.svg new file mode 100644 index 0000000..81dc559 --- /dev/null +++ b/resources/workflow-icons/end.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/expression.svg b/resources/workflow-icons/expression.svg new file mode 100644 index 0000000..ae84256 --- /dev/null +++ b/resources/workflow-icons/expression.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/hand.svg b/resources/workflow-icons/hand.svg new file mode 100644 index 0000000..7c2840b --- /dev/null +++ b/resources/workflow-icons/hand.svg @@ -0,0 +1 @@ + diff --git a/resources/workflow-icons/loop.svg b/resources/workflow-icons/loop.svg new file mode 100644 index 0000000..00e5311 --- /dev/null +++ b/resources/workflow-icons/loop.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/microphone.svg b/resources/workflow-icons/microphone.svg new file mode 100644 index 0000000..d576328 --- /dev/null +++ b/resources/workflow-icons/microphone.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/resources/workflow-icons/motor.svg b/resources/workflow-icons/motor.svg new file mode 100644 index 0000000..95170ea --- /dev/null +++ b/resources/workflow-icons/motor.svg @@ -0,0 +1 @@ + diff --git a/resources/workflow-icons/plan.svg b/resources/workflow-icons/plan.svg new file mode 100644 index 0000000..d166240 --- /dev/null +++ b/resources/workflow-icons/plan.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/sleep.svg b/resources/workflow-icons/sleep.svg new file mode 100644 index 0000000..75639ab --- /dev/null +++ b/resources/workflow-icons/sleep.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/start.svg b/resources/workflow-icons/start.svg new file mode 100644 index 0000000..6e6db22 --- /dev/null +++ b/resources/workflow-icons/start.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/resources/workflow-icons/touch.svg b/resources/workflow-icons/touch.svg new file mode 100644 index 0000000..44a14a5 --- /dev/null +++ b/resources/workflow-icons/touch.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/workflow-icons/video.svg b/resources/workflow-icons/video.svg new file mode 100644 index 0000000..400695e --- /dev/null +++ b/resources/workflow-icons/video.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/freescaninterop.cpp b/src/freescaninterop.cpp index 687ba7b..1ce2935 100644 --- a/src/freescaninterop.cpp +++ b/src/freescaninterop.cpp @@ -84,9 +84,9 @@ void layoutFreshGraph(QJsonObject &graph) { qreal cursor=left;QSet seen; while(!id.isEmpty()&&!seen.contains(id)) { seen.insert(id);auto n=lookup.value(id);const QString type=n.value("type").toString(); - qreal width=type=="serviceNode"||type=="loop"?270:90; + qreal width=type=="serviceNode"||type=="loop"?300:260; if(type=="loop")width=qMax(width,place(id,cursor+60,y+240)+120); - n.insert("x",cursor+(type=="loop"?135:width/2));n.insert("y",y);lookup[id]=n; + n.insert("x",cursor+(type=="loop"?150:width/2));n.insert("y",y);lookup[id]=n; cursor+=width+100;id=next.value(id); }return qMax(0.,cursor-left-100); }; @@ -231,7 +231,7 @@ bool importGraph(const QJsonObject &input,QJsonObject &document,QString &error,b const auto e=v.toObject();const QString from=e.value("sourceNodeId").toString(),to=e.value("targetNodeId").toString(); require(lookup.contains(from)&&lookup.contains(to),QStringLiteral("连线引用不存在的节点")); require(parent[from]==parent[to],QStringLiteral("不支持跨循环容器连线")); - require(!next.contains(from)&&!previous.contains(to),QStringLiteral("存在分支或汇合,上位机不能将其转换为顺序流程")); + require(draft||(!next.contains(from)&&!previous.contains(to)),QStringLiteral("并行图不能转换为旧版顺序流程,请使用图执行器")); next[from]=to;previous[to]=from; } QSet visited; @@ -266,6 +266,7 @@ bool importGraph(const QJsonObject &input,QJsonObject &document,QString &error,b result.append(QJsonObject{{"id",id},{"kind","loop"},{"name",name},{"count",int(count)}, {"collapsed",p.value("collapsed")},{"children",read(id,depth+1)}}); } else if(type=="sleep") { + if(draft&&!pointMode){id=next.value(id);continue;} const double delay=numeric(params.value("delayMs")); require(delay>=0&&delay<=2147483647&&delay==std::floor(delay), QStringLiteral("等待节点只能跟在任务或循环之后,且时长不超过2147483647毫秒")); diff --git a/src/jointfloweditor.cpp b/src/jointfloweditor.cpp index 396dbc8..f1b0e75 100644 --- a/src/jointfloweditor.cpp +++ b/src/jointfloweditor.cpp @@ -35,8 +35,8 @@ #include namespace { -constexpr qreal kNodeWidth = 190.0; -constexpr qreal kNodeHeight = 76.0; +constexpr qreal kNodeWidth = 300.0; +constexpr qreal kNodeHeight = 110.0; using FlowGraphicsView = WorkflowCanvas; @@ -63,49 +63,14 @@ public: 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, - painter->fontMetrics().elidedText(m_title,Qt::ElideRight,int(kNodeWidth-(m_loop?58:28)))); - 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); + 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("−")); } - painter->setFont(QFont()); - painter->setPen(QColor("#687684")); - painter->drawText(QRectF(14, 38, kNodeWidth - 28, 26), Qt::AlignLeft | Qt::AlignVCenter, - painter->fontMetrics().elidedText(m_subtitle,Qt::ElideRight,int(kNodeWidth-28))); } - protected: void mousePressEvent(QGraphicsSceneMouseEvent *event) override { @@ -248,10 +213,14 @@ JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent) inspectorScroll->setFrameShape(QFrame::NoFrame); inspectorScroll->setWidget(inspector); auto *toggleInspector = new QPushButton(QStringLiteral("节点参数"),canvasTools); - toggleInspector->setCheckable(true);toggleInspector->setChecked(true); + toggleInspector->setCheckable(true);toggleInspector->setChecked(false); toggleInspector->setObjectName(QStringLiteral("secondaryButton")); static_cast(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); @@ -769,7 +738,7 @@ void JointFlowEditor::rebuildScene() 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") + 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, diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e82d952..f8b56bb 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -715,6 +715,18 @@ MainWindow::MainWindow(QWidget *parent) this, &MainWindow::appendLog); auto* taskRpcRunner=new TaskRpcRunner(m_client,this); connect(m_taskOrchestration,&TaskOrchestrationWidget::executionStopped,taskRpcRunner,&TaskRpcRunner::cancel); + connect(m_taskOrchestration,&TaskOrchestrationWidget::workflowCallRequested,this, + [this,taskRpcRunner](const QString &token,const QJsonObject &execution) { + const auto generation=m_taskOrchestration->executionGeneration(); + taskRpcRunner->runConcurrent(execution,[this,token,generation,execution](bool ok,const QString &response) { + if(generation!=m_taskOrchestration->executionGeneration())return; + QString detail;const bool success=TaskApi::responseSucceeded(ok,response,detail); + const auto method=execution.value("method").toString(); + if(execution.value("service")=="cmvr.api.ArmService"&&(method=="torqueOn"||method=="torqueOff")) + emit m_client->torqueFinished(execution.value("request").toObject().value("device_id").toString(),method=="torqueOn",success,detail); + m_taskOrchestration->completeWorkflowCall(token,success,detail); + }); + }); connect(m_taskOrchestration, &TaskOrchestrationWidget::taskRequested, this, [this,taskRpcRunner](const QString &deviceType, const QString &deviceId, const QString &action, const QJsonObject ¶meters) { diff --git a/src/taskjointeditor.h b/src/taskjointeditor.h index 3f3ed33..3a72a8e 100644 --- a/src/taskjointeditor.h +++ b/src/taskjointeditor.h @@ -20,6 +20,9 @@ public: m_table=new QTableWidget(0,3,this);m_table->setObjectName("taskJointTable"); m_table->setHorizontalHeaderLabels({QStringLiteral("关节名称"),QStringLiteral("目标角度(°)"),QStringLiteral("允许范围(°)")}); m_table->verticalHeader()->hide();m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + m_table->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents); + m_table->horizontalHeader()->setSectionResizeMode(2,QHeaderView::ResizeToContents); + m_table->setTextElideMode(Qt::ElideNone); m_table->setMinimumHeight(150);m_table->setMaximumHeight(400);layout->addWidget(m_table); } void setDevice(const QVariantMap& info,const QJsonArray& values={},bool checkLimits=true) { @@ -34,7 +37,7 @@ public: QStringLiteral("逐关节填写角速度;保存时换算为弧度/秒。"))); if(mismatched)m_hint->setText(QStringLiteral("原目标数量与设备关节数不一致,请按当前关节列表重新填写。")); for(int i=0;isetFlags(Qt::ItemIsEnabled);m_table->setItem(i,0,name); + auto* name=new QTableWidgetItem(m_names[i]);name->setFlags(Qt::ItemIsEnabled);name->setToolTip(m_names[i]);m_table->setItem(i,0,name); auto* edit=new QLineEdit(m_table);edit->setObjectName(QString("jointTarget_%1").arg(i)); edit->setProperty("taskJointName",m_names[i]); edit->setValidator(new QDoubleValidator(-1e12,1e12,9,edit));edit->setPlaceholderText(QStringLiteral("输入角度")); diff --git a/src/taskorchestrationwidget.cpp b/src/taskorchestrationwidget.cpp index e5a01be..e7c285b 100644 --- a/src/taskorchestrationwidget.cpp +++ b/src/taskorchestrationwidget.cpp @@ -7,6 +7,7 @@ #include "freescaninterop.h" #include "freescaninteropui.h" #include "workflowgraph.h" +#include "workflowruntime.h" #include "taskapi.h" #include "taskprotoeditor.h" #include "taskuilabels.h" @@ -74,8 +75,8 @@ void captureTaskExpansion(QTreeWidgetItem *item) for (int i = 0; i < item->childCount(); ++i) captureTaskExpansion(item->child(i)); } -constexpr qreal kTaskCardWidth = 270.0; -constexpr qreal kTaskCardHeight = 94.0; +constexpr qreal kTaskCardWidth = 300.0; +constexpr qreal kTaskCardHeight = 110.0; using TaskFlowView = WorkflowCanvas; @@ -102,39 +103,16 @@ public: void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override { - painter->setRenderHint(QPainter::Antialiasing); - const QString state = m_source->data(0, RunStateRole).toString(); - QColor stateColor = state == QStringLiteral("running") ? QColor("#1b6ef3") - : state == QStringLiteral("success") ? QColor("#20a36a") - : state == QStringLiteral("failed") ? QColor("#d44343") : QColor("#cbd6e2"); - painter->setPen(QPen(isSelected() ? QColor("#1b6ef3") : stateColor, - isSelected() || !state.isEmpty() ? 2.0 : 1.4)); - painter->setBrush(state == QStringLiteral("running") ? QColor("#eef5ff") - : state == QStringLiteral("success") ? QColor("#effaf5") - : state == QStringLiteral("failed") ? QColor("#fff2f2") - : m_loop ? QColor("#f4efff") : QColor("#ffffff")); - painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), 10, 10); - QFont titleFont = painter->font(); titleFont.setBold(true); - painter->setFont(titleFont); painter->setPen(QColor("#25313d")); - painter->drawText(QRectF(14, 9, kTaskCardWidth - (m_loop ? 52 : 28), 27), - Qt::AlignLeft | Qt::AlignVCenter, - painter->fontMetrics().elidedText(m_title, Qt::ElideRight, - int(kTaskCardWidth - (m_loop ? 52 : 28)))); - painter->setFont(QFont()); painter->setPen(QColor("#687684")); - painter->drawText(QRectF(14, 38, kTaskCardWidth - (m_loop ? 52 : 28), 45), - Qt::AlignLeft | Qt::AlignVCenter | Qt::TextWordWrap, m_subtitle); - if (m_loop) { - painter->setPen(QPen(QColor("#b8c7d8"), 1.2)); painter->setBrush(Qt::white); - painter->drawRoundedRect(toggleRect(), 5, 5); - painter->setPen(QPen(QColor("#286fc2"), 1.8)); - const QPointF c = toggleRect().center(); - if (m_source->isExpanded()) - painter->drawPolyline(QPolygonF() << QPointF(c.x()-5,c.y()-3) << QPointF(c.x(),c.y()+3) << QPointF(c.x()+5,c.y()-3)); - else - painter->drawPolyline(QPolygonF() << QPointF(c.x()-3,c.y()-5) << QPointF(c.x()+3,c.y()) << QPointF(c.x()-3,c.y()+5)); + const QString state=m_source->data(0,RunStateRole).toString(); + const QColor accent=state=="failed"?QColor("#e05b64"):state=="success"?QColor("#20a36a"): + state=="running"?QColor("#357dff"):m_loop?QColor("#a086d7"):QColor("#557799"); + workflowCardPaint(painter,boundingRect(),m_title,m_subtitle,accent,isSelected(),m_loop?25:0, + m_loop?QStringLiteral("loop"):workflowDeviceIcon(m_source->data(0,DeviceTypeRole).toString())); + if(m_loop) { + painter->setPen(QColor("#73849a")); + painter->drawText(toggleRect(),Qt::AlignCenter,m_source->isExpanded()?QStringLiteral("−"):QStringLiteral("+")); } } - protected: void mousePressEvent(QGraphicsSceneMouseEvent *event) override { @@ -373,13 +351,13 @@ bool editNameDialog(QWidget *parent, const QString &title, const QString &label, TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(parent) { QVBoxLayout *root = new QVBoxLayout(this); - root->setContentsMargins(24, 20, 24, 20); + root->setContentsMargins(8, 6, 8, 6); root->setSpacing(12); QFrame *panel = new QFrame(this); panel->setObjectName(QStringLiteral("panel")); QVBoxLayout *layout = new QVBoxLayout(panel); - layout->setContentsMargins(18, 16, 18, 16); - layout->setSpacing(10); + layout->setContentsMargins(10, 8, 10, 8); + layout->setSpacing(6); QHBoxLayout *groups = new QHBoxLayout; QLabel *title = new QLabel(QStringLiteral("任务方案"), panel); title->setObjectName(QStringLiteral("sectionTitle")); @@ -418,16 +396,10 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare auto *validateButton = new QPushButton(QStringLiteral("校验流程"), panel); toolbar->addWidget(validateButton); connect(validateButton,&QPushButton::clicked,this,[this] { - QJsonObject document;QString error; - if(m_graph.isEmpty()||!FreeScanInterop::importGraph(m_graph,document,error)) { - showTaskNotice(this,QStringLiteral("流程校验"),error.isEmpty()?QStringLiteral("当前方案没有可执行工作流。"):error);return; - } - QList steps; - const auto groups=document.value(QStringLiteral("groups")).toArray(); - if(!groups.isEmpty())appendCompiledSteps(groups.first().toObject().value(QStringLiteral("nodes")).toArray(),steps,&error); - if(error.isEmpty() && steps.isEmpty())error=QStringLiteral("当前方案没有可执行任务。"); - showTaskNotice(this,QStringLiteral("流程校验"),error.isEmpty() - ? QStringLiteral("结构校验通过,共 %1 个执行步骤;尚未调用设备。").arg(steps.size()) : error); + QHash executions;QString error; + const bool ok=prepareWorkflow(executions,error); + showTaskNotice(this,QStringLiteral("流程校验"),ok + ?QStringLiteral("图结构与接口参数校验通过,共 %1 个接口节点;分支并行执行,汇合节点等待所有前驱完成。").arg(executions.size()):error); }); layout->addLayout(toolbar); auto *insertionToolbar = new QHBoxLayout; @@ -468,7 +440,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare m_flowView->setObjectName(QStringLiteral("jointFlowCanvas")); m_flowView->setRenderHint(QPainter::Antialiasing); m_flowView->setDragMode(QGraphicsView::RubberBandDrag); - layout->addWidget(static_cast(m_flowView)->tools(panel)); + toolbar->addWidget(static_cast(m_flowView)->tools(panel)); auto *workspace = new QSplitter(Qt::Horizontal, panel); workspace->setObjectName(QStringLiteral("workflowWorkspace")); auto *libraryPanel = new QWidget(workspace); @@ -493,31 +465,39 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare auto *controlGroup = new QTreeWidgetItem(library, {QStringLiteral("流程控制")}); auto *loopComponent = new QTreeWidgetItem(controlGroup, {QStringLiteral("循环")}); loopComponent->setData(0, Qt::UserRole, QStringLiteral("loop")); + loopComponent->setData(0,Qt::UserRole+1,QStringLiteral("重复执行循环体内的流程")); auto *sleepComponent=new QTreeWidgetItem(controlGroup,{QStringLiteral("等待")});sleepComponent->setData(0,Qt::UserRole,QStringLiteral("sleep")); - auto *devicesGroup = new QTreeWidgetItem(library, {QStringLiteral("服务端接口节点")}); + sleepComponent->setData(0,Qt::UserRole+1,QStringLiteral("延迟指定时长后继续执行")); for (const auto &type : {QStringLiteral("机械臂"),QStringLiteral("相机"),QStringLiteral("AGV"), QStringLiteral("灵巧手"),QStringLiteral("麦克风"),QStringLiteral("扬声器"), QStringLiteral("仿生头"),QStringLiteral("电机")}) { - auto *serviceGroup=new QTreeWidgetItem(devicesGroup,{type}); + auto *serviceGroup=new QTreeWidgetItem(library,{type+QStringLiteral(" · %1").arg(TaskApi::actions(type).size())}); for(const auto &action:TaskApi::actions(type)) { const auto op=TaskApi::operation(type,action); const auto method=op.value("method").toString(); if(method.isEmpty())continue; - auto *item=new QTreeWidgetItem(serviceGroup,{action.mid(QStringLiteral("接口 · ").size())}); + auto *item=new QTreeWidgetItem(serviceGroup,{TaskUi::text("operations",method)}); item->setData(0,Qt::UserRole,QStringLiteral("rpc|")+type+QStringLiteral("|")+method); + item->setData(0,Qt::UserRole+1,TaskUi::operationDescription(type,method)); + item->setData(0,Qt::UserRole+2,method); + item->setData(0,Qt::UserRole+3,workflowDeviceIcon(type)); item->setToolTip(0,op.value("service").toString()+QStringLiteral(".")+method); } } - library->expandAll(); + controlGroup->setExpanded(true); libraryLayout->addWidget(libraryTitle); libraryLayout->addWidget(search); libraryLayout->addWidget(library, 1); connect(search, &QLineEdit::textChanged, this, [library](const QString &text) { for (int i=0;itopLevelItemCount();++i) { auto *group=library->topLevelItem(i); bool visible=false; for(int j=0;jchildCount();++j) { - const bool match=group->child(j)->text(0).contains(text,Qt::CaseInsensitive); - group->child(j)->setHidden(!match); visible |= match; + const bool match=group->text(0).contains(text,Qt::CaseInsensitive) + ||group->child(j)->text(0).contains(text,Qt::CaseInsensitive) + ||group->child(j)->data(0,Qt::UserRole+1).toString().contains(text,Qt::CaseInsensitive); + const bool methodMatch=group->child(j)->data(0,Qt::UserRole+2).toString().contains(text,Qt::CaseInsensitive); + group->child(j)->setHidden(!match&&!methodMatch); visible |= match||methodMatch; } group->setHidden(!visible); + if(!text.isEmpty())group->setExpanded(visible); } }); const auto createComponent = [this](const QString &key) { @@ -547,7 +527,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare item->setData(0,KindRole,"task");item->setData(0,DeviceTypeRole,type);item->setData(0,DeviceIdRole,deviceId);item->setData(0,ActionRole,action); item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact))); item->setData(0,WaitRole,0);item->setData(0,WaitUnitRole,"ms"); - item->setText(0,QString::fromStdString(method.toStdString()));item->setText(1,type);item->setText(2,type);item->setText(3,deviceId);item->setText(4,action);item->setText(5,"0 ms"); + item->setText(0,TaskUi::text("operations",method));item->setText(1,type);item->setText(2,type);item->setText(3,deviceId);item->setText(4,action);item->setText(5,"0 ms"); insertNode(item); QString graphError; if(syncGraph(graphError)) { @@ -705,7 +685,9 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare if(WorkflowGraph::postWait(m_graph,item->data(0,NodeIdRole).toString())!=wait->value())WorkflowGraph::setWait(m_graph,item->data(0,NodeIdRole).toString(),wait->value());save(); }); updateInspector(); - auto *inspectorScroll=new QScrollArea(workspace);inspectorScroll->setWidgetResizable(true);inspectorScroll->setFrameShape(QFrame::NoFrame);inspectorScroll->setWidget(inspector);inspector->setMinimumWidth(300); + auto *inspectorScroll=new QScrollArea(workspace);inspectorScroll->setWidgetResizable(true);inspectorScroll->setFrameShape(QFrame::NoFrame);inspectorScroll->setWidget(inspector);inspector->setMinimumWidth(460); + inspectorScroll->setMinimumWidth(540); + inspectorScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); inspectorScroll->setStyleSheet(QStringLiteral( "QScrollArea{border:0;background:#f3f6fa;}" "QScrollBar:vertical{width:8px;background:transparent;margin:4px 2px;}" @@ -714,7 +696,7 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;background:transparent;}" "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:transparent;}")); workspace->addWidget(libraryPanel); workspace->addWidget(m_flowView); workspace->addWidget(inspectorScroll); - workspace->setStretchFactor(1,1); workspace->setSizes({190,850,360}); + workspace->setStretchFactor(1,1); workspace->setSizes({270,1000,340}); workspace->setChildrenCollapsible(false); layout->addWidget(workspace, 1); m_editControls << libraryPanel << inspector; @@ -725,6 +707,12 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare toggle->setCheckable(true);toggle->setChecked(true); toolbar->insertWidget(0,toggle); connect(toggle,&QPushButton::toggled,entry.second,&QWidget::setVisible); + if(entry.second==inspectorScroll) { + toggle->setChecked(false);inspectorScroll->hide(); + connect(m_flowScene,&QGraphicsScene::selectionChanged,this,[this,toggle] { + if(!m_flowScene->selectedItems().isEmpty())toggle->setChecked(true); + }); + } } QLabel *historyTitle = new QLabel(QStringLiteral("执行反馈"), panel); historyTitle->setObjectName(QStringLiteral("sectionTitle")); @@ -735,6 +723,13 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare m_history->setMaximumHeight(64); m_history->setMinimumHeight(42); m_history->addItem(QStringLiteral("尚未执行任务")); + auto *historyToggle=new QPushButton(QStringLiteral("执行反馈"),panel); + historyToggle->setObjectName(QStringLiteral("secondaryButton"));historyToggle->setCheckable(true); + toolbar->insertWidget(2,historyToggle); + connect(historyToggle,&QPushButton::toggled,historyTitle,&QWidget::setVisible); + connect(historyToggle,&QPushButton::toggled,m_history,&QWidget::setVisible); + historyTitle->hide();m_history->hide(); + connect(m_history->model(),&QAbstractItemModel::rowsInserted,this,[historyToggle]{historyToggle->setChecked(true);}); connect(m_history->model(),&QAbstractItemModel::rowsInserted,this,[this]{while(m_history->count()>200)delete m_history->takeItem(0);}); connect(m_history,&QListWidget::itemDoubleClicked,this,[this](QListWidgetItem* item){ const QString detail=item->data(Qt::UserRole).toString();if(detail.isEmpty())return; @@ -925,44 +920,74 @@ bool TaskOrchestrationWidget::appendCompiledSteps(const QJsonArray &nodes, return true; } -void TaskOrchestrationWidget::startRun() +bool TaskOrchestrationWidget::prepareWorkflow(QHash &executions,QString &error) const { - if (!m_runSteps.isEmpty()) return; - QJsonObject compiledDocument; - if(!m_graph.isEmpty()) { - QString error; - if(!FreeScanInterop::importGraph(m_graph,compiledDocument,error)||!restoreGraph(m_graph,error)) { - showTaskNotice(this,QStringLiteral("无法执行工作流"),error);return; + if(!WorkflowRuntime::validate(m_graph,error))return false; + for(QTreeWidgetItemIterator it(m_tree);*it;++it) { + auto *item=*it;if(item->data(0,KindRole)!=QStringLiteral("task"))continue; + const auto parameters=QJsonDocument::fromJson(item->data(0,ParametersRole).toString().toUtf8()).object(); + const auto execution=TaskApi::execution(item->data(0,DeviceTypeRole).toString(),item->data(0,ActionRole).toString(),item->data(0,DeviceIdRole).toString(),parameters); + if(execution.value("timeoutMs").toInt()<100||execution.value("timeoutMs").toInt()>1800000) { + error=QStringLiteral("接口超时应为100至1800000毫秒:")+item->text(0);return false; + } + if(execution.value("kind")!="grpc_unary"||!TaskApi::validateRequest(execution.value("service").toString(),execution.value("method").toString(),execution.value("request").toObject(),error)) { + if(error.isEmpty())error=QStringLiteral("节点未转换为独立服务端接口:")+item->text(0); + return false; + } + if(item->data(0,DeviceIdRole).toString().isEmpty()||item->data(0,DeviceIdRole)==QStringLiteral("未绑定设备")) { + error=QStringLiteral("节点尚未绑定设备:")+item->text(0);return false; + } + executions[item->data(0,NodeIdRole).toString()]=execution; + } + for(const auto &v:m_graph.value("nodes").toArray()) { + const auto n=v.toObject();if(n.value("type")=="serviceNode"&&!executions.contains(n.value("id").toString())) { + error=QStringLiteral("接口节点未能解析:")+n.value("id").toString();return false; } } - ++m_executionGeneration; - m_runSteps.clear(); - const int initial=WorkflowGraph::leadingWait(m_graph,QString());if(initial){RunStep delay;delay.name=QStringLiteral("等待");delay.action="__workflow_wait__";delay.waitMs=initial;m_runSteps.append(delay);} - QString error; - const QJsonArray compiledGroups=compiledDocument.value(QStringLiteral("groups")).toArray(); - const QJsonArray compiledNodes=compiledGroups.isEmpty()?QJsonArray(): - compiledGroups.first().toObject().value(QStringLiteral("nodes")).toArray(); - if (!appendCompiledSteps(compiledNodes, m_runSteps, &error)) { - m_runSteps.clear(); - showTaskNotice(this, QStringLiteral("无法执行工作流"), error); - return; - } - if (m_runSteps.isEmpty()) { - showTaskNotice(this, QStringLiteral("任务编排"), - QStringLiteral("当前方案没有可执行任务。")); - return; - } - std::function clearState = [&](QTreeWidgetItem *item) { - item->setData(0, RunStateRole, QString()); - for (int i = 0; i < item->childCount(); ++i) clearState(item->child(i)); - }; - for (int i = 0; i < m_tree->topLevelItemCount(); ++i) clearState(m_tree->topLevelItem(i)); - m_history->clear(); - for (auto *control : m_editControls) control->setEnabled(false); - m_flowView->setInteractive(false); - m_runIndex = 0; m_runButton->setEnabled(false); m_stopButton->setEnabled(true); runNext(); + return true; } +void TaskOrchestrationWidget::startRun() +{ + if(!m_runSteps.isEmpty())return; + QHash executions;QString error; + if(!prepareWorkflow(executions,error)){showTaskNotice(this,QStringLiteral("无法执行工作流"),error);return;} + if(!m_runtime)m_runtime=new WorkflowRuntime(this); + ++m_executionGeneration; + m_workflowCalls.clear();m_runSteps.append(RunStep{}); + for(QTreeWidgetItemIterator it(m_tree);*it;++it)(*it)->setData(0,RunStateRole,QString()); + m_history->clear(); + for(auto *control:m_editControls)control->setEnabled(false); + m_flowView->setInteractive(false);m_runButton->setEnabled(false);m_stopButton->setEnabled(true); + m_status->setText(QStringLiteral("工作流运行中 · 分支并行,汇合等待全部前驱")); + m_runtime->nodeState=[this](const QString &id,const QString &state) { + for(QTreeWidgetItemIterator it(m_tree);*it;++it)if((*it)->data(0,NodeIdRole)==id)(*it)->setData(0,RunStateRole,state); + rebuildFlowScene(); + }; + m_runtime->dispatch=[this,executions](const QString &token,const QString &id) { + if(!executions.contains(id)){m_runtime->complete(token,false,QStringLiteral("缺少接口请求"));return;} + m_workflowCalls[token]=id; + const auto n=WorkflowGraph::node(m_graph,id); + m_history->addItem(QStringLiteral("▶ %1").arg(n.value("properties").toObject().value("name").toString(id))); + m_history->scrollToBottom(); + emit workflowCallRequested(token,executions.value(id)); + }; + m_runtime->finished=[this](bool ok,const QString &message) { + stopRun(ok?QStringLiteral("执行完成"):QStringLiteral("执行失败:")+message); + if(!ok)emit statusMessage(QStringLiteral("ERROR"),message); + }; + if(!m_runtime->start(m_graph,error))stopRun(error); +} + +void TaskOrchestrationWidget::completeWorkflowCall(const QString &token,bool success,const QString &detail) +{ + if(!m_runtime||!m_workflowCalls.contains(token)||m_runSteps.isEmpty())return; + const auto id=m_workflowCalls.take(token); + const auto name=WorkflowGraph::node(m_graph,id).value("properties").toObject().value("name").toString(id); + m_history->addItem(QStringLiteral("%1 %2 · %3").arg(success?QStringLiteral("✓"):QStringLiteral("✕"),name,detail.left(2048))); + m_history->item(m_history->count()-1)->setData(Qt::UserRole,detail.left(1048576)); + m_history->scrollToBottom();m_runtime->complete(token,success,detail); +} void TaskOrchestrationWidget::runNext() { if (m_runIndex >= m_runSteps.size()) { stopRun(QStringLiteral("执行完成")); return; } @@ -1179,6 +1204,8 @@ void TaskOrchestrationWidget::completeActionTask(const QString &deviceType, void TaskOrchestrationWidget::stopRun(const QString &reason) { + if(m_runtime)m_runtime->cancel(); + m_workflowCalls.clear(); ++m_executionGeneration;emit executionStopped(); m_runTimer->stop(); m_runSteps.clear(); m_runIndex = 0; m_waitingForResult = false; for (auto *control : m_editControls) control->setEnabled(true); @@ -1288,7 +1315,9 @@ void TaskOrchestrationWidget::rebuildFlowScene() : QStringLiteral("%1 · %2\n等待 %3") .arg(item->data(0, DeviceIdRole).toString(), TaskUi::operationTitle(item->data(0,DeviceTypeRole).toString(),item->data(0, ActionRole).toString())) .arg(waitDisplayText(item->data(0, WaitRole).toInt(), item->data(0, WaitUnitRole).toString())); - TaskFlowCard *card = new TaskFlowCard(item, item->text(0), subtitle, loop, + const QString method=item->data(0,ActionRole).toString().mid(QStringLiteral("接口 · ").size()); + const QString cardTitle=!loop&&item->text(0)==method?TaskUi::text("operations",method):item->text(0); + TaskFlowCard *card = new TaskFlowCard(item, cardTitle, subtitle, loop, [this, revision](QTreeWidgetItem *source, const QPointF &position) { QTimer::singleShot(0, this, [this, source, position, revision]() { if(revision!=m_sceneRevision||!m_runSteps.isEmpty())return; @@ -1522,20 +1551,16 @@ void TaskOrchestrationWidget::save() } void TaskOrchestrationWidget::exportDocument(){ - if(!m_graph.isEmpty()) { - QJsonObject compiled;QString error; - if(!FreeScanInterop::importGraph(m_graph,compiled,error)||!restoreGraph(m_graph,error)){showTaskNotice(this,QStringLiteral("无法导出未连通流程"),error);return;} - } - storeCurrentGroup();QJsonArray groups;for(const auto& g:m_groups)groups.append(g); - QJsonObject document{{"groups",groups}};QString error; - if(!TaskApi::serverDocument(document,error)){showTaskNotice(this,QStringLiteral("无法导出"),error);return;} - const QString path=QFileDialog::getSaveFileName(this,QStringLiteral("导出任务"),"task_flow.json",QStringLiteral("JSON (*.json)"));if(path.isEmpty())return; - QSaveFile output(path);const auto bytes=QJsonDocument(document).toJson(QJsonDocument::Indented); - if(!output.open(QIODevice::WriteOnly)||output.write(bytes)!=bytes.size()||!output.commit()){showTaskNotice(this,QStringLiteral("导出失败"),output.errorString());return;} + if(!m_runSteps.isEmpty())return; + QString error; + if(!syncGraph(error)){showTaskNotice(this,QStringLiteral("无法导出"),error);return;} + const QString path=QFileDialog::getSaveFileName(this,QStringLiteral("导出工作流图"),"workflow.json",QStringLiteral("JSON (*.json)"));if(path.isEmpty())return; + if(!FreeScanInterop::writeGraph(path,m_graph,error)){showTaskNotice(this,QStringLiteral("导出失败"),error);return;} QSaveFile catalog(QFileInfo(path).absolutePath()+"/task_operations.json");const auto definitions=QJsonDocument(TaskApi::catalog()).toJson(QJsonDocument::Indented); if(!catalog.open(QIODevice::WriteOnly)||catalog.write(definitions)!=definitions.size()||!catalog.commit())showTaskNotice(this,QStringLiteral("接口清单导出失败"),catalog.errorString()); - else emit statusMessage("OK",QStringLiteral("已导出任务和 task_operations.json;未发送任何设备操作")); + emit statusMessage(QStringLiteral("INFO"),QStringLiteral("已导出完整工作流图(保留并行分支、循环、接口与参数)及接口清单")); } + void TaskOrchestrationWidget::importDocument(){ if(!m_runSteps.isEmpty())return; const QString path=QFileDialog::getOpenFileName(this,QStringLiteral("导入任务"),{},QStringLiteral("JSON (*.json)"));if(path.isEmpty())return; diff --git a/src/taskorchestrationwidget.h b/src/taskorchestrationwidget.h index 5e8a676..3e16309 100644 --- a/src/taskorchestrationwidget.h +++ b/src/taskorchestrationwidget.h @@ -15,6 +15,7 @@ class QGraphicsScene; class QGraphicsView; class QPointF; class QListWidget; +class WorkflowRuntime; class TaskOrchestrationWidget final : public QWidget { @@ -42,9 +43,11 @@ public: const QString &detail); quint64 executionGeneration() const { return m_executionGeneration; } + void completeWorkflowCall(const QString &token,bool success,const QString &detail); signals: void executionStopped(); + void workflowCallRequested(const QString &token,const QJsonObject &execution); void cameraCapabilitiesChanged(); void availableDevicesChanged(); void deviceInfoChanged(const QString &deviceId); @@ -91,6 +94,9 @@ private: void updateInsertionHint(); bool syncGraph(QString &error); bool restoreGraph(const QJsonObject &graph, QString &error); + bool prepareWorkflow(QHash &executions,QString &error) const; + WorkflowRuntime *m_runtime=nullptr; + QHash m_workflowCalls; QComboBox *m_groupCombo = nullptr; QTreeWidget *m_tree = nullptr; diff --git a/src/taskrpcrunner.cpp b/src/taskrpcrunner.cpp index 619e395..9ef7d43 100644 --- a/src/taskrpcrunner.cpp +++ b/src/taskrpcrunner.cpp @@ -20,8 +20,15 @@ TaskRpcRunner::TaskRpcRunner(RobotClient* client,QObject* parent):QObject(parent connect(client,&RobotClient::connectRequested,this,[this](const QString& host,int port,bool demo){m_connected=false;cancel();m_demo=demo;m_endpoint=host.trimmed()+":"+QString::number(port);}); connect(client,&RobotClient::connectionChanged,this,[this](bool ok,int,const QString&){m_connected=ok;if(!ok)cancel();}); } -TaskRpcRunner::~TaskRpcRunner(){if(m_demoCompletion){DemoSimulator::instance().stop(m_demoDevice);m_demoCompletion={};++m_demoGeneration;}cancel();if(m_thread){m_thread->wait();delete m_thread;}} -void TaskRpcRunner::cancel(){if(m_context)m_context->TryCancel();if(m_demoCompletion){++m_demoGeneration;DemoSimulator::instance().stop(m_demoDevice);m_busy=false;auto done=std::move(m_demoCompletion);done(false,QStringLiteral("演示调用已取消"));}} +TaskRpcRunner::~TaskRpcRunner(){const auto parallel=m_parallel;m_parallel.clear();for(auto *runner:parallel){QObject::disconnect(runner,nullptr,this,nullptr);delete runner;}if(m_demoCompletion){DemoSimulator::instance().stop(m_demoDevice);m_demoCompletion={};++m_demoGeneration;}cancel();if(m_thread){m_thread->wait();delete m_thread;}} +void TaskRpcRunner::cancel(){const auto parallel=m_parallel;for(auto *runner:parallel)runner->cancel();if(m_context)m_context->TryCancel();if(m_demoCompletion){++m_demoGeneration;DemoSimulator::instance().stop(m_demoDevice);m_busy=false;auto done=std::move(m_demoCompletion);done(false,QStringLiteral("演示调用已取消"));}} +void TaskRpcRunner::runConcurrent(const QJsonObject &execution,std::function done) { + auto *runner=new TaskRpcRunner(m_client,this); + runner->m_endpoint=m_endpoint;runner->m_connected=m_connected;runner->m_demo=m_demo; + m_parallel.append(runner); + connect(runner,&QObject::destroyed,this,[this,runner]{m_parallel.removeAll(runner);}); + runner->run(execution,[runner,done](bool ok,const QString &detail){done(ok,detail);runner->deleteLater();}); +} void TaskRpcRunner::run(const QJsonObject& ex,std::function done){ if(!m_connected||m_busy){done(false,QStringLiteral("接口未连接或上次调用仍未结束,未发送请求"));return;} QString error;const QString service=ex.value("service").toString(),method=ex.value("method").toString(); diff --git a/src/taskrpcrunner.h b/src/taskrpcrunner.h index 95a80de..05fe859 100644 --- a/src/taskrpcrunner.h +++ b/src/taskrpcrunner.h @@ -3,6 +3,7 @@ #include #include #include +#include class RobotClient;class QThread; namespace grpc {class ClientContext;} class TaskRpcRunner final:public QObject { @@ -10,9 +11,11 @@ public: explicit TaskRpcRunner(RobotClient*,QObject* parent=nullptr); ~TaskRpcRunner()override; void run(const QJsonObject& execution,std::function done); + void runConcurrent(const QJsonObject& execution,std::function done); void cancel(); private: friend struct TaskRpcTestAccess; + QList m_parallel; quint64 m_demoGeneration=0; QString m_demoDevice; std::function m_demoCompletion; diff --git a/src/taskuilabels.h b/src/taskuilabels.h index f1d19ff..436c9c1 100644 --- a/src/taskuilabels.h +++ b/src/taskuilabels.h @@ -2,8 +2,27 @@ #include #include #include +#include namespace TaskUi { inline QJsonObject metadata(){static const QJsonObject data=[] {QFile file(":/resources/task_ui.json");file.open(QIODevice::ReadOnly);return QJsonDocument::fromJson(file.readAll()).object();}();return data;} inline QString text(const QString& section,const QString& key){return metadata().value(section).toObject().value(key).toString(key);} +inline QString operationDescription(const QString &type,const QString &method) { + static const QHash descriptions{ + {"StartCamera",QStringLiteral("采集图像前启动相机")}, + {"StopCamera",QStringLiteral("采集完成后关闭相机")}, + {"GetRGBImage",QStringLiteral("获取相机拍摄的彩色图像")}, + {"GetDepthImage",QStringLiteral("获取相机拍摄的深度图像")}, + {"GetRGBDImages",QStringLiteral("同时采集彩色图像与深度图像")}, + {"moveJ",QStringLiteral("按关节角度移动至目标位置")}, + {"moveL",QStringLiteral("沿直线路径移动至目标位姿")}, + {"moveJPose",QStringLiteral("通过关节运动到达目标末端位姿")}, + {"torqueOn",QStringLiteral("使能设备,为后续运动做准备")}, + {"torqueOff",QStringLiteral("关闭设备使能")}, + {"clearFault",QStringLiteral("清除设备当前故障")}, + {"stopMotion",QStringLiteral("停止当前运动")}, + {"GetStatus",QStringLiteral("读取设备当前运行状态")} + }; + return descriptions.value(method,QStringLiteral("%1 · %2").arg(type,text("operations",method))); +} inline QString operationTitle(const QString&,const QString& action){const QString prefix=QStringLiteral("接口 · ");if(!action.startsWith(prefix))return action=="MoveJ"?QStringLiteral("关节角度运动"):action;return text("operations",action.mid(prefix.size()))+QStringLiteral("(接口)");} } diff --git a/src/workflowcanvas.h b/src/workflowcanvas.h index 76f7f1c..ecb802b 100644 --- a/src/workflowcanvas.h +++ b/src/workflowcanvas.h @@ -4,6 +4,55 @@ #include #include #include +#include + +inline QString workflowDeviceIcon(const QString &type) { + if(type==QStringLiteral("相机"))return QStringLiteral("camera"); + if(type==QStringLiteral("机械臂"))return QStringLiteral("arm"); + if(type==QStringLiteral("AGV"))return QStringLiteral("agv"); + if(type==QStringLiteral("灵巧手"))return QStringLiteral("hand"); + if(type==QStringLiteral("仿生头"))return QStringLiteral("expression"); + if(type==QStringLiteral("麦克风"))return QStringLiteral("microphone"); + if(type==QStringLiteral("扬声器"))return QStringLiteral("audio"); + if(type==QStringLiteral("电机"))return QStringLiteral("motor"); + return QStringLiteral("plan"); +} +inline void workflowVectorIcon(QPainter *p,const QRectF &rect,const QString &name) { + static QHash> renderers; + if(!renderers.contains(name)) + renderers.insert(name,QSharedPointer::create(QStringLiteral(":/workflow-icons/")+name+QStringLiteral(".svg"))); + renderers.value(name)->render(p,rect); +} + +inline void workflowCardPaint(QPainter *p,const QRectF &bounds,const QString &title, + const QString &detail,const QColor &accent,bool selected, + qreal reserved=0,const QString &iconName={}) { + p->save();p->setRenderHint(QPainter::Antialiasing); + const QRectF body=bounds.adjusted(1.5,1.5,-1.5,-1.5); + p->setPen(Qt::NoPen);p->setBrush(QColor(25,45,75,9)); + p->drawRoundedRect(body.translated(0,2),6,6); + p->setPen(QPen(selected?QColor("#357dff"):QColor("#e1e7ef"),selected?2:1)); + p->setBrush(Qt::white);p->drawRoundedRect(body,6,6); + p->setPen(QPen(accent,3,Qt::SolidLine,Qt::RoundCap)); + p->drawLine(QPointF(3,9),QPointF(3,bounds.height()-9)); + QRectF badge(15,14,36,36); + p->setPen(Qt::NoPen);p->setBrush(QColor("#edf6fc"));p->drawRoundedRect(badge,6,6); + const QString icon=!iconName.isEmpty()?iconName: + title.contains(QStringLiteral("相机"))||title.contains(QStringLiteral("图像"))?QStringLiteral("camera"): + title.contains(QStringLiteral("开始"))?QStringLiteral("start"):title.contains(QStringLiteral("结束"))?QStringLiteral("end"): + title.contains(QStringLiteral("循环"))?QStringLiteral("loop"):title.contains(QStringLiteral("等待"))?QStringLiteral("sleep"):QStringLiteral("video"); + workflowVectorIcon(p,badge.adjusted(7,7,-7,-7),icon); + QFont font=QApplication::font();font.setPixelSize(15);font.setBold(true); + p->setFont(font);p->setPen(QColor("#19334d")); + p->drawText(QRectF(61,14,bounds.width()-76-reserved,32),Qt::AlignVCenter, + p->fontMetrics().elidedText(title,Qt::ElideRight,int(bounds.width()-76-reserved))); + font.setPixelSize(12);font.setBold(false);p->setFont(font);p->setPen(QColor("#738297")); + const QStringList lines=detail.split('\n'); + for(int i=0;idrawText(QRectF(16,58+i*19,bounds.width()-32,19),Qt::AlignVCenter, + p->fontMetrics().elidedText(lines[i],Qt::ElideRight,int(bounds.width()-32))); + p->restore(); +} inline void workflowContainers(QGraphicsScene *scene,const QJsonObject &graph,const QHash &bounds) { QHash parents; @@ -53,17 +102,22 @@ inline void workflowPorts(QGraphicsItem *card,const QString &id,bool input=true, port->setToolTip(out?QStringLiteral("拖动到下一节点的输入端,建立执行连线"):QStringLiteral("节点输入端")); } } -class WorkflowTerminal final : public QGraphicsEllipseItem { +class WorkflowTerminal final : public QGraphicsRectItem { public: + QString title,detail; + QColor accent; std::function moved; - WorkflowTerminal():QGraphicsEllipseItem(0,0,90,42) { - setPen(QPen(QColor("#91a9c7"),1.5));setBrush(QColor("#edf4ff")); + WorkflowTerminal():QGraphicsRectItem(0,0,260,88) { + setPen(Qt::NoPen); setFlags(ItemIsSelectable|ItemIsMovable); } + void paint(QPainter *p,const QStyleOptionGraphicsItem *,QWidget *) override { + workflowCardPaint(p,rect(),title,detail,accent,isSelected()); + } protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event) override { m_start=pos();QGraphicsEllipseItem::mousePressEvent(event); } + void mousePressEvent(QGraphicsSceneMouseEvent *event) override { m_start=pos();QGraphicsRectItem::mousePressEvent(event); } void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override { - QGraphicsEllipseItem::mouseReleaseEvent(event);if(pos()!=m_start&&moved)moved(pos()+QPointF(45,21)); + QGraphicsRectItem::mouseReleaseEvent(event);if(pos()!=m_start&&moved)moved(pos()+rect().center()); } private: QPointF m_start; }; @@ -71,11 +125,11 @@ inline WorkflowTerminal *workflowTerminal(QGraphicsScene *scene,const QString &i const QPointF ¢er) { auto *item=new WorkflowTerminal;scene->addItem(item); item->setData(0,id);item->setData(7010,id);item->setData(7000,type); - item->setPos(center-QPointF(45,21)); + item->setPos(center-item->rect().center()); const bool start=type=="start"||type=="subStart"; - auto *label=new QGraphicsSimpleTextItem(type=="sleep"?QStringLiteral("等待"):start?QStringLiteral("开始"):QStringLiteral("结束"),item); - label->setAcceptedMouseButtons(Qt::NoButton); - label->setPos(45-label->boundingRect().width()/2,21-label->boundingRect().height()/2); + item->title=type=="sleep"?QStringLiteral("睡眠等待"):start?QStringLiteral("流程开始"):QStringLiteral("流程结束"); + item->detail=type=="sleep"?QStringLiteral("等待指定时长后继续执行"):start?QStringLiteral("从此节点进入工作流"):QStringLiteral("当前工作流执行完成"); + item->accent=type=="sleep"?QColor("#55b9db"):start?QColor("#20a36a"):QColor("#e05b64"); workflowPorts(item,id,!start,start||type=="sleep");return item; } @@ -126,7 +180,8 @@ public: auto *bar = new QWidget(parent); auto *layout = new QHBoxLayout(bar); layout->setContentsMargins(0,0,0,0); auto *hint = new QLabel(QStringLiteral("右键平移 · Ctrl+滚轮缩放"), bar); - hint->setObjectName("mutedLabel"); layout->addWidget(hint); layout->addStretch(); + hint->setObjectName("mutedLabel");hint->hide();bar->setToolTip(hint->text()+QStringLiteral(" · Ctrl+C / Ctrl+V 复制粘贴")); + layout->addStretch(); for (int i=0;i<4;++i) { auto *button = new QPushButton(QStringList{QStringLiteral("-"),QStringLiteral("+"),QStringLiteral("回到起点"),QStringLiteral("显示全部")}[i],bar); button->setObjectName("secondaryButton"); layout->addWidget(button); @@ -142,9 +197,9 @@ protected: if(m_firstShow){m_firstShow=false;QTimer::singleShot(0,this,[this]{fitAll();});} } void drawBackground(QPainter *painter, const QRectF &rect) override { - painter->fillRect(rect,QColor("#f6f8fc")); + painter->fillRect(rect,QColor("#ffffff")); if(transform().m11()<.3) return; - painter->setPen(QPen(QColor("#d9dee8"),0)); + painter->setPen(QPen(QColor("#e5ebf3"),0)); const int gap=24; for(qreal x=std::floor(rect.left()/gap)*gap;xdrawPoint(QPointF(x,y)); @@ -249,9 +304,32 @@ private: QString m_connecting;QPointF m_wireStart;QGraphicsPathItem *m_preview=nullptr; }; +class WorkflowComponentDelegate : public QStyledItemDelegate { +public: + using QStyledItemDelegate::QStyledItemDelegate; + QSize sizeHint(const QStyleOptionViewItem &,const QModelIndex &index) const override { + return QSize(240,index.data(Qt::UserRole).toString().isEmpty()?44:86); + } + void paint(QPainter *p,const QStyleOptionViewItem &option,const QModelIndex &index) const override { + if(index.data(Qt::UserRole).toString().isEmpty()) { + QStyledItemDelegate::paint(p,option,index);return; + } + p->save();p->setClipRect(option.rect); + const QRectF body=QRectF(option.rect).adjusted(4,4,-6,-4); + p->translate(body.topLeft()); + workflowCardPaint(p,QRectF(QPointF(),body.size()),index.data().toString(), + index.data(Qt::UserRole+1).toString(),QColor("#58b9dc"),option.state&QStyle::State_Selected, + 0,index.data(Qt::UserRole+3).toString()); + p->restore(); + } +}; class WorkflowLibrary : public QTreeWidget { public: - explicit WorkflowLibrary(QWidget *parent=nullptr):QTreeWidget(parent){setHeaderHidden(true);setDragEnabled(true);setMinimumWidth(180);} + explicit WorkflowLibrary(QWidget *parent=nullptr):QTreeWidget(parent){ + setHeaderHidden(true);setDragEnabled(true);setMinimumWidth(250); + setItemDelegate(new WorkflowComponentDelegate(this));setIndentation(10); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + } protected: void startDrag(Qt::DropActions) override { if(!currentItem() || currentItem()->data(0,Qt::UserRole).toString().isEmpty())return; diff --git a/src/workflowgraph.h b/src/workflowgraph.h index d9eca8d..d3b32c7 100644 --- a/src/workflowgraph.h +++ b/src/workflowgraph.h @@ -196,17 +196,17 @@ inline QJsonObject merge(QJsonObject fresh,const QJsonObject &previous) { inline bool connect(QJsonObject &graph,const QString &from,const QString &to,QString &error) { const auto a=node(graph,from),b=node(graph,to); if(a.isEmpty()||b.isEmpty()||from==to){error=QStringLiteral("请选择不同节点的输出端和输入端");return false;} - if(a.value("properties").toObject().value("parentId")!=b.value("properties").toObject().value("parentId")) { + if(a.value("properties").toObject().value("parentId").toString()!=b.value("properties").toObject().value("parentId").toString()) { error=QStringLiteral("循环内外不能直接连线,请连接同一容器内的节点");return false; } - QJsonArray edges; - for(const auto &v:graph.value("edges").toArray()) { - const auto e=v.toObject();if(e.value("sourceNodeId")!=from&&e.value("targetNodeId")!=to)edges.append(e); - } - QString cursor=to;QSet seen; - while(!cursor.isEmpty()&&!seen.contains(cursor)) { - if(cursor==from){error=QStringLiteral("该连线会形成环路,请使用循环组件");return false;}seen.insert(cursor); - QString next;for(const auto &v:edges)if(v.toObject().value("sourceNodeId")==cursor)next=v.toObject().value("targetNodeId").toString();cursor=next; + QJsonArray edges=graph.value("edges").toArray(); + for(const auto &v:edges)if(v.toObject().value("sourceNodeId")==from&&v.toObject().value("targetNodeId")==to)return true; + QStringList pending{to};QSet seen; + while(!pending.isEmpty()) { + const QString cursor=pending.takeLast(); + if(cursor==from){error=QStringLiteral("该连线会形成环路,请使用循环组件");return false;} + if(seen.contains(cursor))continue;seen.insert(cursor); + for(const auto &v:edges)if(v.toObject().value("sourceNodeId")==cursor)pending.append(v.toObject().value("targetNodeId").toString()); } edges.append(QJsonObject{{"id",from+"__"+to},{"type","bezier"},{"sourceNodeId",from},{"targetNodeId",to}, {"sourceAnchorId",from+"_1"},{"targetAnchorId",to+"_3"},{"properties",QJsonObject{}}}); @@ -253,42 +253,40 @@ inline void removeNode(QJsonObject &graph,const QString &id) { graph.insert("nodes",nodes);graph.insert("edges",edges); } inline int postWait(const QJsonObject &graph,const QString &source) { - QString cursor=source;QSet seen;double result=0; - while(!cursor.isEmpty()&&!seen.contains(cursor)) { - seen.insert(cursor);QString next; - for(const auto &v:graph.value("edges").toArray())if(v.toObject().value("sourceNodeId")==cursor)next=v.toObject().value("targetNodeId").toString(); - const auto n=node(graph,next);if(n.value("type")!="sleep")break; - for(const auto &v:n.value("properties").toObject().value("nodeParams").toArray())if(v.toObject().value("name")=="delayMs") { - const auto value=v.toObject().value("input");result+=value.isString()?value.toString().toDouble():value.toDouble(); - }cursor=next; - } - return int(qBound(0.,result,2147483647.)); -} -inline int leadingWait(const QJsonObject &graph,const QString &container) { + QStringList targets; + for(const auto &v:graph.value("edges").toArray())if(v.toObject().value("sourceNodeId")==source)targets.append(v.toObject().value("targetNodeId").toString()); + if(targets.size()!=1)return 0; + const auto wait=node(graph,targets.first()); + return wait.value("type")=="sleep"&&wait.value("properties").toObject().value("cmvrAfterNodeId")==source?delay(wait):0; +}inline int leadingWait(const QJsonObject &graph,const QString &container) { for(const auto &v:graph.value("nodes").toArray()) { const auto n=v.toObject();if((n.value("type")=="start"||n.value("type")=="subStart")&&n.value("properties").toObject().value("parentId").toString()==container)return postWait(graph,n.value("id").toString()); }return 0; } inline void setWait(QJsonObject &graph,const QString &source,int milliseconds) { - QString cursor=source,next;QSet removed; - while(true) { - next.clear();for(const auto &v:graph.value("edges").toArray())if(v.toObject().value("sourceNodeId")==cursor)next=v.toObject().value("targetNodeId").toString(); - if(node(graph,next).value("type")!="sleep"||removed.contains(next))break; - removed.insert(next);cursor=next; + QStringList targets; + for(const auto &v:graph.value("edges").toArray())if(v.toObject().value("sourceNodeId")==source)targets.append(v.toObject().value("targetNodeId").toString()); + if(targets.size()==1) { + const auto wait=node(graph,targets.first()); + if(wait.value("type")=="sleep"&&wait.value("properties").toObject().value("cmvrAfterNodeId")==source) { + const QString id=targets.first();targets.clear(); + for(const auto &v:graph.value("edges").toArray())if(v.toObject().value("sourceNodeId")==id)targets.append(v.toObject().value("targetNodeId").toString()); + removeNode(graph,id); + } } - for(const auto &id:removed)removeNode(graph,id); QJsonArray edges;for(const auto &v:graph.value("edges").toArray())if(v.toObject().value("sourceNodeId")!=source)edges.append(v); - graph.insert("edges",edges);QString error; + graph.insert("edges",edges);QString error;QString tail=source; if(milliseconds>0) { - QString id=source+"_after";if(!node(graph,id).isEmpty())id=QUuid::createUuid().toString(QUuid::WithoutBraces); - const auto previous=node(graph,source);QJsonObject properties{{"name",QStringLiteral("完成后等待")},{"action","SLEEP"},{"nodeType","NONE"}, + const QString id=QUuid::createUuid().toString(QUuid::WithoutBraces); + const auto previous=node(graph,source); + QJsonObject properties{{"name",QStringLiteral("完成后等待")},{"action","SLEEP"},{"nodeType","NONE"}, {"nodeParams",QJsonArray{QJsonObject{{"name","delayMs"},{"type","input"},{"input",milliseconds}}}},{"cmvrAfterNodeId",source}}; const auto parent=previous.value("properties").toObject().value("parentId");if(parent.isString())properties.insert("parentId",parent); replaceNode(graph,QJsonObject{{"id",id},{"type","sleep"},{"x",previous.value("x").toDouble()+230},{"y",previous.value("y")},{"properties",properties}}); - connect(graph,source,id,error);if(!next.isEmpty())connect(graph,id,next,error); - }else if(!next.isEmpty())connect(graph,source,next,error); -} -inline QHash order(const QJsonObject &graph,QString &error) { + connect(graph,source,id,error);tail=id; + } + for(const auto &target:targets)connect(graph,tail,target,error); +}inline QHash order(const QJsonObject &graph,QString &error) { QHash nodes;QHash parent,next,previous;QSet seen; QHash result; const auto fail=[&](const QString &message){if(error.isEmpty())error=message;}; diff --git a/src/workflowruntime.h b/src/workflowruntime.h new file mode 100644 index 0000000..0b16367 --- /dev/null +++ b/src/workflowruntime.h @@ -0,0 +1,176 @@ +#pragma once +#include +#include +#include +#include + +// Each scope/loop iteration owns independent predecessor counters. RPC replies +// are correlated by invocation token, never by method name or completion order. +class WorkflowRuntime final : public QObject { +public: + using QObject::QObject; + std::function dispatch; + std::function nodeState; + std::function finished; + static QJsonObject inputs(const QJsonObject &node) { + QJsonObject result; + for(const auto &v:node.value("properties").toObject().value("nodeParams").toArray()) { + const auto p=v.toObject();result.insert(p.value("name").toString(),p.value("input")); + } + return result; + } + static bool validate(const QJsonObject &graph,QString &error) { + QHash nodes;QHash scopes,out,in; + const auto fail=[&](const QString &message){error=message;return false;}; + for(const auto &v:graph.value("nodes").toArray()) { + const auto n=v.toObject();const QString id=n.value("id").toString(); + if(id.isEmpty()||nodes.contains(id))return fail(QStringLiteral("节点 ID 为空或重复")); + nodes[id]=n;scopes[n.value("properties").toObject().value("parentId").toString()].append(id); + } + if(nodes.isEmpty()||nodes.size()>10000)return fail(QStringLiteral("流程节点数量无效")); + for(auto it=nodes.begin();it!=nodes.end();++it) { + QString parent=it.value().value("properties").toObject().value("parentId").toString(); + QSet ancestors{it.key()}; + while(!parent.isEmpty()) { + if(!nodes.contains(parent)||nodes[parent].value("type")!="loop"||ancestors.contains(parent)||ancestors.size()>16) + return fail(QStringLiteral("循环容器引用无效或嵌套过深")); + ancestors.insert(parent);parent=nodes[parent].value("properties").toObject().value("parentId").toString(); + } + const QString type=it.value().value("type").toString(); + if(!QStringList{"start","end","subStart","subEnd","sleep","loop","serviceNode"}.contains(type)) + return fail(QStringLiteral("不支持的节点类型:")+type); + const auto params=inputs(it.value()); + if(type=="sleep"||type=="loop") { + const auto value=params.value(type=="sleep"?"delayMs":"loopNum"); + bool ok=false;const double number=value.isString()?value.toString().toDouble(&ok):value.toDouble(-1); + if(!value.isString())ok=value.isDouble(); + if(!ok||!std::isfinite(number)||number!=std::floor(number)||number<(type=="sleep"?0:1)||number>(type=="sleep"?2147483647:100000)) + return fail(QStringLiteral("等待时长或循环次数无效:")+it.key()); + } + } + QSet edges; + for(const auto &v:graph.value("edges").toArray()) { + const auto e=v.toObject();const QString a=e.value("sourceNodeId").toString(),b=e.value("targetNodeId").toString(); + if(!nodes.contains(a)||!nodes.contains(b)||a==b||edges.contains(a+"\n"+b)) + return fail(QStringLiteral("连线引用无效或重复")); + if(nodes[a].value("properties").toObject().value("parentId").toString()!=nodes[b].value("properties").toObject().value("parentId").toString()) + return fail(QStringLiteral("循环内外不能直接连线")); + edges.insert(a+"\n"+b);out[a].append(b);in[b].append(a); + } + for(auto it=scopes.begin();it!=scopes.end();++it) { + QString start,end; + for(const auto &id:it.value()) { + const QString type=nodes[id].value("type").toString(); + if(type==(it.key().isEmpty()?"start":"subStart")) { + if(!start.isEmpty())return fail(QStringLiteral("一个流程容器只能有一个开始节点"));start=id; + } + if(type==(it.key().isEmpty()?"end":"subEnd")) { + if(!end.isEmpty())return fail(QStringLiteral("一个流程容器只能有一个结束节点"));end=id; + } + } + if(start.isEmpty()||end.isEmpty()||!in[start].isEmpty()||!out[end].isEmpty()) + return fail(QStringLiteral("流程容器缺少有效的开始或结束节点")); + const auto reachable=[&](const QString &first,const QHash &links) { + QSet seen;QStringList todo{first}; + while(!todo.isEmpty()){const auto id=todo.takeLast();if(seen.contains(id))continue;seen.insert(id);todo.append(links.value(id));} + return seen; + }; + if(reachable(start,out).size()!=it.value().size()||reachable(end,in).size()!=it.value().size()) + return fail(QStringLiteral("存在未连接节点或未汇入结束节点的分支")); + QHash degree;QStringList ready;int visited=0; + for(const auto &id:it.value()){degree[id]=in[id].size();if(!degree[id])ready.append(id);} + while(!ready.isEmpty()){const auto id=ready.takeLast();++visited;for(const auto &next:out[id])if(--degree[next]==0)ready.append(next);} + if(visited!=it.value().size())return fail(QStringLiteral("连线形成环路,请使用循环组件")); + } + for(auto it=nodes.begin();it!=nodes.end();++it)if(it.value().value("type")=="loop"&&!scopes.contains(it.key())) + return fail(QStringLiteral("循环没有内部流程")); + return true; + } + bool start(const QJsonObject &graph,QString &error) { + cancel();if(!validate(graph,error))return false; + m_graph=graph;m_running=true;m_count=0; + const auto generation=m_generation; + QTimer::singleShot(0,this,[this,generation] { + if(!active(generation))return; + scope({},[this,generation] {if(active(generation)){m_running=false;if(finished)finished(true,QStringLiteral("执行完成"));}}); + }); + return true; + } + void cancel(){++m_generation;m_running=false;m_pending.clear();} + void complete(const QString &token,bool success,const QString &detail) { + if(!m_running||!m_pending.contains(token))return; + const auto pending=m_pending.take(token); + if(!success){if(nodeState)nodeState(pending.id,"failed");fail(detail);return;} + finishNode(pending.scope,pending.id); + } +private: + struct Scope { + QHash degree; + QHash out; + QSet done,scheduled; + int size=0; + std::function finished; + }; + struct Pending {std::shared_ptr scope;QString id;}; + QHash m_pending; + QJsonObject m_graph; + quint64 m_generation=0; + int m_count=0; + bool m_running=false; + bool active(quint64 generation)const{return m_running&&generation==m_generation;} + QJsonObject node(const QString &id)const { + for(const auto &v:m_graph.value("nodes").toArray())if(v.toObject().value("id")==id)return v.toObject(); + return {}; + } + void fail(const QString &message) { + if(!m_running)return;cancel();if(finished)finished(false,message); + } + void scope(const QString &parent,const std::function &done) { + auto state=std::make_shared();state->finished=done; + for(const auto &v:m_graph.value("nodes").toArray()) { + const auto n=v.toObject();if(n.value("properties").toObject().value("parentId").toString()==parent) + state->degree[n.value("id").toString()]=0; + } + state->size=state->degree.size(); + 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(state->degree.contains(from)){++state->degree[to];state->out[from].append(to);} + } + for(auto it=state->degree.begin();it!=state->degree.end();++it)if(it.value()==0)schedule(state,it.key()); + } + void schedule(const std::shared_ptr &state,const QString &id) { + if(!m_running||state->scheduled.contains(id))return; + state->scheduled.insert(id);const auto generation=m_generation; + QTimer::singleShot(0,this,[this,state,id,generation] { + if(!active(generation))return; + if(++m_count>100000){fail(QStringLiteral("流程展开超过100000步"));return;} + const auto n=node(id);const QString type=n.value("type").toString(); + if(nodeState)nodeState(id,"running"); + if(type=="sleep") { + const auto delay=inputs(n).value("delayMs"); + const int ms=delay.isString()?delay.toString().toInt():delay.toInt(); + QTimer::singleShot(ms,this,[this,state,id,generation]{if(active(generation))finishNode(state,id);}); + }else if(type=="loop") { + const auto value=inputs(n).value("loopNum"); + iteration(state,id,value.isString()?value.toString().toInt():value.toInt(),generation); + }else if(type=="serviceNode") { + const QString token=QUuid::createUuid().toString(QUuid::WithoutBraces); + m_pending.insert(token,Pending{state,id}); + if(dispatch)dispatch(token,id);else fail(QStringLiteral("未连接接口执行器")); + }else finishNode(state,id); + }); + } + void iteration(const std::shared_ptr &state,const QString &id,int left,quint64 generation) { + if(!active(generation))return; + if(!left){finishNode(state,id);return;} + scope(id,[this,state,id,left,generation] { + QTimer::singleShot(0,this,[this,state,id,left,generation]{iteration(state,id,left-1,generation);}); + }); + } + void finishNode(const std::shared_ptr &state,const QString &id) { + if(!m_running||state->done.contains(id))return; + state->done.insert(id);if(nodeState)nodeState(id,"success"); + for(const auto &next:state->out.value(id))if(--state->degree[next]==0)schedule(state,next); + if(state->done.size()==state->size&&state->finished)state->finished(); + } +};