feat: rebuild workflow editors with graph storage and node clipboard
This commit is contained in:
parent
10285f8cea
commit
f7ee4a842e
1
.gitignore
vendored
1
.gitignore
vendored
@ -24,3 +24,4 @@
|
||||
/.qtcreator/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
/am-freescan/
|
||||
|
||||
@ -185,6 +185,11 @@ set(CMVR_SOURCES
|
||||
src/taskprotoeditor.cpp
|
||||
src/demosimulator.cpp
|
||||
src/demosimulator.h
|
||||
src/workflowcanvas.h
|
||||
src/workflowgraph.h
|
||||
src/freescaninteropui.h
|
||||
src/freescaninterop.cpp
|
||||
src/freescaninterop.h
|
||||
src/taskdeviceoptions.cpp
|
||||
src/taskdeviceoptions.h
|
||||
src/taskrpcrunner.cpp
|
||||
|
||||
@ -406,6 +406,9 @@ HEADERS += src/taskdeviceoptions.h
|
||||
|
||||
SOURCES += src/demosimulator.cpp
|
||||
HEADERS += src/demosimulator.h
|
||||
HEADERS += src/workflowcanvas.h
|
||||
SOURCES += src/freescaninterop.cpp
|
||||
HEADERS += src/freescaninterop.h
|
||||
|
||||
# Release diagnostics retain optimization and source line information.
|
||||
QMAKE_CXXFLAGS_RELEASE += -g1
|
||||
@ -416,3 +419,5 @@ win32:CONFIG(release, debug|release) {
|
||||
QMAKE_POST_LINK += $$escape_expand(\n\t) powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $$shell_quote($$shell_path($$PWD/scripts/repair_qt3d_release.ps1)) -RuntimeDirectory $$shell_quote($$shell_path($$DESTDIR)) -IfPresent
|
||||
}
|
||||
DISTFILES += scripts/repair_qt3d_release.ps1
|
||||
|
||||
HEADERS += src/workflowgraph.h src/freescaninteropui.h
|
||||
|
||||
12
README.md
12
README.md
@ -338,3 +338,15 @@ Proto 约定和目录说明见 [protos/README.md](protos/README.md)。
|
||||
全局主题入口为 `src/applicationstyle.cpp` 和 `styles.qss`。新增消息提示/确认请使用 `AppMessageBox`,其按钮返回值兼容原 `QMessageBox`;输入框、文件选择和普通对话框统一使用应用标题栏。新弹窗不要设置 `WindowStaysOnTopHint`,有父窗口时使用窗口级模态。
|
||||
|
||||
程序图标为 `icons/cmvr-app.svg` / `icons/cmvr-app.ico`。修改图标后可运行 `scripts/generate_application_icon.py` 更新 Windows 多尺寸 ICO;qmake 和 CMake 均已嵌入可执行文件图标。
|
||||
|
||||
工作流工作区以 `am-freescan` 的组件库、端口连线、循环容器、右侧参数面板和图数据结构为依据,以原生 Qt 实现。参考仓库位于 `am-freescan/`,独立管理 Git;来源提交为 `6ace9b1`。两个编辑入口均独立全屏打开。
|
||||
|
||||
点位库支持搜索、拖入、重命名、行号排序、组复制和组内多流程。循环和等待可添加到画布;节点可自由移动,循环标题移动时带动容器内节点。任务编排左侧可搜索设备组件,右侧可直接编辑接口参数、超时和等待。端口连线决定执行顺序,Delete 删除选中的连线;不连通、环路、跨容器连线和不支持的分支在运行前报错。右键/中键或空白处平移,Ctrl+滚轮缩放,工具栏可显示全部。
|
||||
|
||||
两个画布均支持 Ctrl+C / Ctrl+V 复制粘贴选中节点。循环连同其内部节点一起复制,多节点保留内部连线;粘贴生成新的节点 ID 并偏移位置,外部连线不复制。点位流程粘贴时要求当前点位库中存在所引用的点位。执行期间禁用粘贴,文本输入框继续使用原有文本复制粘贴。
|
||||
|
||||
`joint_programs.json` 的组保留点位库和多个流程;每个流程用 `flowData` 字符串存储真实 `{nodes,edges}` 图。任务存储使用 `{flows:[{id,name,flowData}],activeFlowId}`,不再把旧的任务数组作为主存储。节点沿用中心坐标 `x/y`、`properties.parentId`、循环 `children` 和 `sourceNodeId/targetNodeId` 连线。旧文件读取后备份为 `.before-graph.<标识>.bak` 并迁移;转换失败时保留原文件。
|
||||
|
||||
两个入口均能导入/导出 am-freescan 图 JSON。导出保留 cmvr-es 的服务全名、方法名、完整请求、接口超时及 protobuf 描述集;循环和等待使用原生 loop/sleep 节点。组合点位保留多臂并行运动和逐臂关节顺序校验。网页侧通过自身 gRPC 连接调用 cmvr-es,上位机无需保持运行。资源使用参考项目的机器人角色和设备用途绑定,网页导出后在上位机导入时选择实际设备。
|
||||
|
||||
克隆仓库包含对应的网页 JSON 导入/导出、参数面板和 `CMVR_GRPC_UNARY` / `CMVR_ARM_POINT_BATCH` 后端执行适配。这些改动必须由网页项目单独构建部署后才生效,本地修改不代表线上已支持。组合调用先校验所有机械臂,再并行下发同步 MoveJ;失败或取消时取消剩余调用并请求停止。当前 Qt 执行器支持单路径及嵌套循环;条件分支、运行时参数引用、扫描仪等其他领域动作不能无损转换时明确报错。等待可位于开始之后、任务之后或循环内部。
|
||||
|
||||
@ -59,6 +59,8 @@ export function flatten(document,catalog,groupId){
|
||||
check(integer(node.count,1,100000)&&Array.isArray(node.children)&&node.children.length>0,'Invalid repeat count or empty loop');const children=visit(node.children,depth+1);
|
||||
check(steps.length+children.length*node.count<=100000,'Expanded plan exceeds 100000 steps');
|
||||
for(let iteration=0;iteration<node.count;iteration++)for(const entry of children)steps.push({node:entry.node,iterationPath:[{loopId:node.id,iteration},...entry.iterationPath]});
|
||||
check(integer(node.waitMs??0,0,2147483647),'Invalid loop post-completion delay');
|
||||
if(node.waitMs){const last=steps.at(-1);const waitMs=last.node.waitMs+node.waitMs;check(integer(waitMs,0,2147483647),'Accumulated delay exceeds limit');last.node={...last.node,waitMs};}
|
||||
}else{
|
||||
check(node.kind==='task'&&typeof node.deviceId==='string'&&node.deviceId,'Invalid task or deviceId');
|
||||
check(integer(node.waitMs,0,2147483647)&&['ms','s'].includes(node.waitUnit),'Invalid post-completion delay');
|
||||
|
||||
@ -3969,14 +3969,6 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"move",
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -3989,7 +3981,7 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"move",
|
||||
"update_period"
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
@ -4001,6 +3993,14 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"move",
|
||||
"update_period"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4041,14 +4041,6 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"home",
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4061,7 +4053,7 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"home",
|
||||
"update_period"
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
@ -4073,6 +4065,14 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"home",
|
||||
"update_period"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4105,14 +4105,6 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"mode",
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4125,7 +4117,7 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"mode",
|
||||
"update_period"
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
@ -4137,6 +4129,14 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"mode",
|
||||
"update_period"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4161,14 +4161,6 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"constraints",
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4181,7 +4173,7 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"constraints",
|
||||
"update_period"
|
||||
"positionGain"
|
||||
]
|
||||
}
|
||||
},
|
||||
@ -4193,6 +4185,14 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"constraints",
|
||||
"update_period"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4220,7 +4220,15 @@
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"positionGain",
|
||||
"position_gain",
|
||||
"updatePeriod"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"position_gain",
|
||||
"update_period"
|
||||
]
|
||||
}
|
||||
@ -4236,27 +4244,11 @@
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"position_gain",
|
||||
"positionGain",
|
||||
"update_period"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"position_gain",
|
||||
"updatePeriod"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"positionGain",
|
||||
"reconnect"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4269,15 +4261,7 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"positionGain",
|
||||
"cancel_expression"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"positionGain",
|
||||
"cancelExpression"
|
||||
"reconnect"
|
||||
]
|
||||
}
|
||||
},
|
||||
@ -4300,23 +4284,7 @@
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"update_period",
|
||||
"reconnect"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"updatePeriod",
|
||||
"reconnect"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"update_period",
|
||||
"positionGain",
|
||||
"cancel_expression"
|
||||
]
|
||||
}
|
||||
@ -4324,11 +4292,27 @@
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"update_period",
|
||||
"positionGain",
|
||||
"cancelExpression"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"updatePeriod",
|
||||
"reconnect"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"update_period",
|
||||
"reconnect"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -4345,6 +4329,22 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"update_period",
|
||||
"cancel_expression"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"update_period",
|
||||
"cancelExpression"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
@ -8259,7 +8259,7 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"map2d",
|
||||
"map_3d"
|
||||
"map3d"
|
||||
]
|
||||
}
|
||||
},
|
||||
@ -8267,14 +8267,6 @@
|
||||
"not": {
|
||||
"required": [
|
||||
"map2d",
|
||||
"map3d"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"map_2d",
|
||||
"map_3d"
|
||||
]
|
||||
}
|
||||
@ -8286,6 +8278,14 @@
|
||||
"map3d"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"not": {
|
||||
"required": [
|
||||
"map_2d",
|
||||
"map_3d"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -17032,6 +17032,11 @@
|
||||
"collapsed": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"waitMs": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"children": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
|
||||
@ -57,7 +57,7 @@ schema={"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"urn:cmvr
|
||||
"format":{"const":"cmvr.task-flow"},"executionPolicy":{"const":policy},"groups":{"type":"array","items":ref("group")}},"$defs":{
|
||||
**{"message."+name:value for name,value in messages.items()},"node":{"oneOf":[ref("task"),ref("loop")]},"task":task,
|
||||
"group":{"type":"object","required":["id","name","nodes"],"properties":{**common,"nodes":{"type":"array","items":ref("node")}}},
|
||||
"loop":{"type":"object","required":["id","name","kind","count","children"],"properties":{**common,"kind":{"const":"loop"},"count":{"type":"integer","minimum":1,"maximum":100000},"collapsed":{"type":"boolean"},"children":{"type":"array","items":ref("node")}}},
|
||||
"loop":{"type":"object","required":["id","name","kind","count","children"],"properties":{**common,"kind":{"const":"loop"},"count":{"type":"integer","minimum":1,"maximum":100000},"collapsed":{"type":"boolean"},"waitMs":{"type":"integer","minimum":0,"maximum":2147483647},"children":{"type":"array","items":ref("node")}}},
|
||||
"rpc":{"type":"object","required":["kind","service","method","request","timeoutMs","completion"],"properties":{"kind":{"const":"grpc_unary"},"service":{"type":"string"},"method":{"type":"string"},"request":{"type":"object"},"timeoutMs":{"type":"integer","minimum":100,"maximum":1800000},"completion":{"const":"rpc_response"}}},
|
||||
"adapter":{"type":"object","required":["kind","adapter","deviceId","parameters","completion"],"properties":{"kind":{"const":"client_adapter"},"adapter":{"type":"string"},"deviceId":{"type":"string"},"parameters":{"type":"object"},"completion":{"const":"adapter_callback"}}}}}
|
||||
task["properties"]["serverCalls"]={"type":"array","minItems":1,"items":{"type":"object","required":["service","method","rpcPath","requestType","responseType","clientStreaming","serverStreaming","mode","request"],"properties":{"service":{"type":"string"},"method":{"type":"string"},"rpcPath":{"type":"string"},"requestType":{"type":"string"},"responseType":{"type":"string"},"clientStreaming":{"type":"boolean"},"serverStreaming":{"type":"boolean"},"mode":{"enum":["unary","open_stream","close_stream"]},"request":{"type":"object"},"sessionKey":{"type":"string"},"runtimeRequestFields":{"type":"array","items":{"type":"string"}},"runtimeHeaderFields":{"type":"array","items":{"type":"string"}}}}}
|
||||
|
||||
474
src/freescaninterop.cpp
Normal file
474
src/freescaninterop.cpp
Normal file
@ -0,0 +1,474 @@
|
||||
#include "freescaninterop.h"
|
||||
#include "taskapi.h"
|
||||
#include "jointpointdata.h"
|
||||
#include "workflowgraph.h"
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QSet>
|
||||
#include <QCryptographicHash>
|
||||
#include <QUuid>
|
||||
#include <google/protobuf/descriptor.h>
|
||||
#include <google/protobuf/descriptor.pb.h>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
|
||||
namespace {
|
||||
QString uid() { return QUuid::createUuid().toString(QUuid::WithoutBraces); }
|
||||
void require(bool condition,const QString &message) {
|
||||
if(!condition) throw std::runtime_error(message.toUtf8().constData());
|
||||
}
|
||||
double numeric(const QJsonValue &value) {
|
||||
if(value.isDouble())return value.toDouble();
|
||||
bool ok=false;const double number=value.toString().toDouble(&ok);
|
||||
return ok?number:std::numeric_limits<double>::quiet_NaN();
|
||||
}
|
||||
QJsonObject parameter(const QString &name,const QJsonValue &value) {
|
||||
return {{"name",name},{"type","input"},{"input",value},{"quote",QJsonArray{}}};
|
||||
}
|
||||
QJsonObject literals(const QJsonObject &properties) {
|
||||
QJsonObject result;
|
||||
for(const auto &v:properties.value("nodeParams").toArray()) {
|
||||
const auto p=v.toObject();const QString name=p.value("name").toString();
|
||||
require(!name.isEmpty() && !result.contains(name),QStringLiteral("参数名为空或重复:%1").arg(name));
|
||||
require(p.value("type")=="input",QStringLiteral("参数 %1 使用运行时引用,上位机暂不能无损导入").arg(name));
|
||||
result.insert(name,p.value("input"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
QString descriptorSet(const QString &service,const QString &method) {
|
||||
const auto *request=TaskApi::requestDescriptor(service,method);
|
||||
require(request,QStringLiteral("找不到接口描述:%1.%2").arg(service,method));
|
||||
const auto *s=google::protobuf::DescriptorPool::generated_pool()->FindServiceByName(service.toStdString());
|
||||
require(s,QStringLiteral("找不到服务描述:%1").arg(service));
|
||||
google::protobuf::FileDescriptorSet files;QSet<QString> seen;
|
||||
std::function<void(const google::protobuf::FileDescriptor*)> append=[&](const auto *file) {
|
||||
const QString name=QString::fromStdString(file->name());if(seen.contains(name))return;
|
||||
seen.insert(name);for(int i=0;i<file->dependency_count();++i)append(file->dependency(i));
|
||||
file->CopyTo(files.add_file());
|
||||
};
|
||||
append(s->file());return QString::fromLatin1(QByteArray::fromStdString(files.SerializeAsString()).toBase64());
|
||||
}
|
||||
QJsonObject rpcNode(const QString &id,const QString &name,const QString &deviceType,
|
||||
const QString &device,const QString &service,const QString &method,
|
||||
const QJsonObject &request,int timeout=180000) {
|
||||
require(!device.isEmpty(),QStringLiteral("节点 %1 缺少设备 ID").arg(name));
|
||||
const auto definition=TaskApi::definition(service,method);QString error;
|
||||
require(!definition.isEmpty() && !definition.value("clientStreaming").toBool()
|
||||
&& !definition.value("serverStreaming").toBool(),QStringLiteral("不支持的单次 RPC:%1.%2").arg(service,method));
|
||||
require(TaskApi::validateRequest(service,method,request,error),error);
|
||||
return {{"id",id},{"kind","task"},{"name",name},{"deviceType",deviceType},
|
||||
{"deviceId",device},{"action",QStringLiteral("接口 · ")+method},{"waitMs",0},{"waitUnit","ms"},
|
||||
{"parameters",QJsonObject{{"service",service},{"method",method},{"request",request},{"timeoutMs",timeout}}}};
|
||||
}
|
||||
QString deviceType(const QString &service) {
|
||||
for(const auto &value:TaskApi::catalog().value("services").toArray()) {
|
||||
const auto s=value.toObject();if(s.value("service")==service)return s.value("deviceType").toString();
|
||||
}
|
||||
return QStringLiteral("通用RPC");
|
||||
}
|
||||
QJsonObject graphObject(const QJsonObject &input) {
|
||||
if(input.value("graph").isObject())return input.value("graph").toObject();
|
||||
if(input.value("flowData").isString())return QJsonDocument::fromJson(input.value("flowData").toString().toUtf8()).object();
|
||||
if(input.value("flowData").isObject())return input.value("flowData").toObject();
|
||||
return input;
|
||||
}
|
||||
void layoutFreshGraph(QJsonObject &graph) {
|
||||
QHash<QString,QJsonObject> lookup;QHash<QString,QString> next;
|
||||
for(const auto &v:graph.value("nodes").toArray()){const auto n=v.toObject();lookup[n.value("id").toString()]=n;}
|
||||
for(const auto &v:graph.value("edges").toArray()){const auto e=v.toObject();next[e.value("sourceNodeId").toString()]=e.value("targetNodeId").toString();}
|
||||
std::function<qreal(const QString &,qreal,qreal)> place=[&](const QString &parent,qreal left,qreal y) {
|
||||
QString id;for(auto it=lookup.begin();it!=lookup.end();++it)if((it.value().value("type")=="start"||it.value().value("type")=="subStart")&&it.value().value("properties").toObject().value("parentId").toString()==parent){id=it.key();break;}
|
||||
qreal cursor=left;QSet<QString> 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;
|
||||
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;
|
||||
cursor+=width+100;id=next.value(id);
|
||||
}return qMax(0.,cursor-left-100);
|
||||
};
|
||||
place(QString(),60,130);auto nodes=graph.value("nodes").toArray();for(int i=0;i<nodes.size();++i)nodes[i]=lookup.value(nodes[i].toObject().value("id").toString());graph.insert("nodes",nodes);
|
||||
}
|
||||
QJsonObject metadata(const QJsonObject &graph) {
|
||||
for(const auto &value:graph.value("nodes").toArray()) {
|
||||
const auto node=value.toObject();if(node.value("type")=="start") {
|
||||
const auto data=node.value("properties").toObject().value("cmvrInterop").toObject();
|
||||
if(!data.isEmpty())return data;
|
||||
}
|
||||
}
|
||||
return graph.value("cmvr").toObject();
|
||||
}
|
||||
void resources(QJsonObject &graph) {
|
||||
auto nodes=graph.value("nodes").toArray();QJsonArray deviceSlotArray;QHash<QString,QString> deviceSlots;
|
||||
const auto slot=[&](const QString &device,const QString &type) {
|
||||
if(deviceSlots.contains(device))return deviceSlots.value(device);
|
||||
const QString key="device_"+QString::fromLatin1(QCryptographicHash::hash(device.toUtf8(),QCryptographicHash::Sha256).toHex().left(16));
|
||||
const QMap<QString,int> kinds{{QStringLiteral("机械臂"),2},{QStringLiteral("AGV"),1},{QStringLiteral("相机"),5},
|
||||
{QStringLiteral("仿生头"),4},{QStringLiteral("麦克风"),9},{QStringLiteral("扬声器"),13},{QStringLiteral("电机"),10}};
|
||||
QJsonObject s{{"slotKey",key},{"displayName",device},{"required",true},{"allowReuse",false},{"legacyDeviceId",device}};
|
||||
s.insert("deviceKind",kinds.contains(type)?QJsonValue(kinds.value(type)):QJsonValue());deviceSlotArray.append(s);deviceSlots[device]=key;return key;
|
||||
};
|
||||
for(int i=0;i<nodes.size();++i) {
|
||||
auto n=nodes[i].toObject(),p=n.value("properties").toObject();if(p.value("nodeType")!="EDGE")continue;
|
||||
const auto values=literals(p);QJsonObject target{{"roleKey","default_executor"},{"dispatchPolicy","ONE"}};
|
||||
if(p.value("action")=="CMVR_ARM_POINT_BATCH") {
|
||||
const auto targets=QJsonDocument::fromJson(values.value("targetsJson").toString().toUtf8()).array();QJsonArray bindings;
|
||||
for(int j=0;j<targets.size();++j)bindings.append(QJsonObject{{"parameterName",QStringLiteral("deviceId_%1").arg(j)},
|
||||
{"slotKey",slot(targets[j].toObject().value("deviceId").toString(),QStringLiteral("机械臂"))}});
|
||||
target.insert("deviceBindings",bindings);
|
||||
}else target.insert("deviceSlotKey",slot(values.value("deviceId").toString(),p.value("cmvrDeviceType").toString()));
|
||||
p.insert("executionTarget",target);n.insert("properties",p);nodes[i]=n;
|
||||
}
|
||||
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("type")=="start") {
|
||||
auto n=nodes[i].toObject(),p=n.value("properties").toObject();p.insert("schemaVersion",2);
|
||||
p.insert("resourceRoles",QJsonArray{QJsonObject{{"roleKey","default_executor"},{"resourceType","ROBOT"},
|
||||
{"displayName",QStringLiteral("执行机器人")},{"required",true},{"quantity",QJsonObject{{"min",1},{"max",1}}},{"deviceSlots",deviceSlotArray}}});
|
||||
n.insert("properties",p);nodes[i]=n;
|
||||
}
|
||||
graph.insert("nodes",nodes);
|
||||
}
|
||||
}
|
||||
namespace FreeScanInterop {
|
||||
bool isGraph(const QJsonObject &document) {
|
||||
const auto graph=graphObject(document);
|
||||
return graph.value("nodes").isArray() && graph.value("edges").isArray();
|
||||
}
|
||||
bool exportGraph(QJsonObject document,int groupIndex,QJsonObject &output,QString &error) {
|
||||
try {
|
||||
require(TaskApi::serverDocument(document,error),error);
|
||||
const auto groups=document.value("groups").toArray();
|
||||
require(groupIndex>=0 && groupIndex<groups.size(),QStringLiteral("请选择需要导出的流程"));
|
||||
const auto group=groups[groupIndex].toObject();QJsonArray nodes,edges;
|
||||
const auto edge=[&](const QString &from,const QString &to) {
|
||||
edges.append(QJsonObject{{"id",from+"__"+to},{"type","bezier"},{"sourceNodeId",from},{"targetNodeId",to},
|
||||
{"sourceAnchorId",from+"_1"},{"targetAnchorId",to+"_3"},{"properties",QJsonObject{}}});
|
||||
};
|
||||
std::function<QStringList(const QJsonArray&,const QString&,int)> chain;
|
||||
chain=[&](const QJsonArray &items,const QString &parent,int depth) {
|
||||
require(depth<=16,QStringLiteral("循环嵌套超过16层"));
|
||||
QStringList ids;
|
||||
for(const auto &v:items) {
|
||||
const auto item=v.toObject();const QString id=item.value("id").toString();
|
||||
require(!id.isEmpty(),QStringLiteral("节点缺少 ID"));
|
||||
QJsonObject props{{"name",item.value("name")},{"outputType","json"},{"outputParams",QJsonArray{}}};
|
||||
if(!parent.isEmpty())props.insert("parentId",parent);
|
||||
QString type="serviceNode";QJsonObject node{{"id",id},{"x",400.0+ids.size()*430.0},{"y",160.0+depth*450.0}};
|
||||
if(item.value("kind")=="loop") {
|
||||
type="loop";props.insert("action","START_LOOP");props.insert("nodeType","NONE");
|
||||
props.insert("collapsed",item.value("collapsed"));
|
||||
props.insert("nodeParams",QJsonArray{parameter("loopNum",item.value("count"))});
|
||||
const auto children=chain(item.value("children").toArray(),id,depth+1);
|
||||
QJsonArray childIds;for(const auto &child:children)childIds.append(child);
|
||||
node.insert("children",childIds);
|
||||
} else {
|
||||
const auto execution=item.value("execution").toObject();
|
||||
require(execution.value("kind")=="grpc_unary",QStringLiteral("节点 %1 无法映射为单次 gRPC 调用").arg(item.value("name").toString()));
|
||||
const QString service=execution.value("service").toString(),method=execution.value("method").toString();
|
||||
props.insert("action","CMVR_GRPC_UNARY");props.insert("nodeType","EDGE");
|
||||
props.insert("cmvrDeviceType",item.value("deviceType"));
|
||||
props.insert("nodeParams",QJsonArray{parameter("deviceId",item.value("deviceId")),
|
||||
parameter("service",service),parameter("method",method),
|
||||
parameter("requestJson",QString::fromUtf8(QJsonDocument(execution.value("request").toObject()).toJson(QJsonDocument::Compact))),
|
||||
parameter("timeoutMs",execution.value("timeoutMs")),parameter("descriptorSet",descriptorSet(service,method))});
|
||||
}
|
||||
node.insert("type",type);node.insert("properties",props);nodes.append(node);ids.append(id);
|
||||
const int delay=item.value("waitMs").toInt();
|
||||
if(delay>0) {
|
||||
const QString sleepId=id+"_after";QJsonObject sleepProps{{"name",QStringLiteral("完成后等待")},{"action","SLEEP"},
|
||||
{"nodeType","NONE"},{"nodeParams",QJsonArray{parameter("delayMs",delay)}},{"cmvrAfterNodeId",id}};
|
||||
if(!parent.isEmpty())sleepProps.insert("parentId",parent);
|
||||
nodes.append(QJsonObject{{"id",sleepId},{"type","sleep"},{"x",600.0+ids.size()*430.0},
|
||||
{"y",160.0+depth*450.0},{"properties",sleepProps}});ids.append(sleepId);
|
||||
}
|
||||
}
|
||||
const QString scope=parent.isEmpty()?group.value("id").toString():parent;
|
||||
const QString begin=scope+"_start",end=scope+"_end";
|
||||
for(bool first:{true,false}) {
|
||||
const QString id=first?begin:end;
|
||||
QJsonObject p{{"name",first?QStringLiteral("开始"):QStringLiteral("结束")},
|
||||
{"action",parent.isEmpty()?(first?"START":"END"):(first?"SUB_START":"SUB_END")},
|
||||
{"nodeType","NONE"},{"nodeParams",QJsonArray{}},{"inputParams",QJsonArray{}}};
|
||||
if(!parent.isEmpty())p.insert("parentId",parent);
|
||||
nodes.append(QJsonObject{{"id",id},{"type",parent.isEmpty()?(first?"start":"end"):(first?"subStart":"subEnd")},
|
||||
{"x",first?0.0:800.0+ids.size()*430.0},{"y",160.0+depth*450.0},{"properties",p}});
|
||||
}
|
||||
ids.prepend(begin);ids.append(end);for(int i=1;i<ids.size();++i)edge(ids[i-1],ids[i]);return ids;
|
||||
};
|
||||
chain(group.value("nodes").toArray(),{},0);
|
||||
const QJsonObject meta{{"name",group.value("name")}};
|
||||
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("type")=="start") {
|
||||
auto node=nodes[i].toObject(),props=node.value("properties").toObject();props.insert("cmvrInterop",meta);node.insert("properties",props);nodes[i]=node;
|
||||
}
|
||||
output={{"nodes",nodes},{"edges",edges},{"cmvr",meta}};
|
||||
layoutFreshGraph(output);resources(output);
|
||||
return true;
|
||||
}catch(const std::exception &e){error=QString::fromUtf8(e.what());return false;}
|
||||
}
|
||||
|
||||
bool importGraph(const QJsonObject &input,QJsonObject &document,QString &error,bool pointMode,bool draft) {
|
||||
try {
|
||||
const auto graph=graphObject(input);require(isGraph(graph),QStringLiteral("不是 am-freescan 工作流图"));
|
||||
if(!draft){QString waitError;WorkflowGraph::waits(graph,waitError);require(waitError.isEmpty(),waitError);}
|
||||
const auto nodes=graph.value("nodes").toArray();require(nodes.size()<=10000,QStringLiteral("节点超过10000个"));
|
||||
QHash<QString,QJsonObject> lookup;QHash<QString,QString> parent;
|
||||
for(const auto &v:nodes) {
|
||||
const auto n=v.toObject();const QString id=n.value("id").toString();
|
||||
require(!id.isEmpty() && !lookup.contains(id),QStringLiteral("节点 ID 为空或重复:%1").arg(id));lookup.insert(id,n);
|
||||
parent.insert(id,n.value("properties").toObject().value("parentId").toString());
|
||||
}
|
||||
for(const auto &v:nodes) {
|
||||
const auto n=v.toObject();for(const auto &child:n.value("children").toArray()) {
|
||||
const QString id=child.toString();require(lookup.contains(id),QStringLiteral("循环子节点不存在:%1").arg(id));
|
||||
require(parent[id].isEmpty() || parent[id]==n.value("id").toString(),QStringLiteral("子节点属于多个循环:%1").arg(id));
|
||||
parent[id]=n.value("id").toString();
|
||||
}
|
||||
}
|
||||
QHash<QString,QString> next,previous;QSet<QString> edgeIds;
|
||||
for(const auto &v:graph.value("edges").toArray()) {
|
||||
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("存在分支或汇合,上位机不能将其转换为顺序流程"));
|
||||
next[from]=to;previous[to]=from;
|
||||
}
|
||||
QSet<QString> visited;
|
||||
std::function<QJsonArray(const QString&,int)> read=[&](const QString &container,int depth) {
|
||||
require(depth<=16,QStringLiteral("循环嵌套超过16层"));QStringList entries;
|
||||
for(auto it=lookup.begin();it!=lookup.end();++it)if(parent[it.key()]==container&&!previous.contains(it.key())) {
|
||||
entries.append(it.key());
|
||||
}
|
||||
if(!draft) {
|
||||
require(entries.size()==1,QStringLiteral("流程存在未连接节点、多个入口或循环连线"));
|
||||
require(lookup[entries.first()].value("type")== (container.isEmpty()?"start":"subStart"),QStringLiteral("流程必须从开始节点进入"));
|
||||
}
|
||||
if(draft)for(auto it=lookup.begin();it!=lookup.end();++it)if(parent[it.key()]==container&&!entries.contains(it.key()))entries.append(it.key());
|
||||
std::stable_sort(entries.begin(),entries.end(),[&](const QString &a,const QString &b){return lookup[a].value("x").toDouble()<lookup[b].value("x").toDouble();});
|
||||
QJsonArray result;bool ended=false;
|
||||
for(const auto &begin:entries) {
|
||||
if(visited.contains(begin))continue;QString id=begin;
|
||||
while(!id.isEmpty()) {
|
||||
if(draft&&visited.contains(id))break;
|
||||
require(!visited.contains(id),QStringLiteral("存在重复或循环连线:%1").arg(id));visited.insert(id);
|
||||
const auto n=lookup[id];const auto p=n.value("properties").toObject();
|
||||
const QString type=n.value("type").toString(),action=p.value("action").toString();
|
||||
const QString name=p.value("name").toString(id);const auto params=literals(p);
|
||||
if(type=="start" || type=="subStart") {
|
||||
require(id==begin,QStringLiteral("开始节点不在入口"));
|
||||
} else if(type=="end" || type=="subEnd") {
|
||||
require(!next.contains(id),QStringLiteral("结束节点存在后继"));
|
||||
ended=true;
|
||||
} else if(type=="loop") {
|
||||
const double count=numeric(params.value("loopNum"));
|
||||
require(count>=1&&count<=100000&&count==std::floor(count),QStringLiteral("循环次数须为1至100000的整数"));
|
||||
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") {
|
||||
const double delay=numeric(params.value("delayMs"));
|
||||
require(delay>=0&&delay<=2147483647&&delay==std::floor(delay),
|
||||
QStringLiteral("等待节点只能跟在任务或循环之后,且时长不超过2147483647毫秒"));
|
||||
if(draft && (result.isEmpty()||!previous.contains(id))) { id=next.value(id);continue; }
|
||||
if(result.isEmpty()){id=next.value(id);continue;}
|
||||
auto last=result.last().toObject();const qint64 total=qint64(last.value("waitMs").toInt())+qint64(delay);
|
||||
require(total<=2147483647,QStringLiteral("累计等待超出范围"));last.insert("waitMs",double(total));result.replace(result.size()-1,last);
|
||||
} else if(action=="CMVR_ARM_POINT_BATCH") {
|
||||
require(pointMode,QStringLiteral("组合点位请导入机械臂点位与流程窗口,以保留并行调用和关节校验"));
|
||||
require(params.value("timeoutMs").toInt(120000)==120000,QStringLiteral("点位流程固定使用120000毫秒超时,不能无损导入其他超时配置"));
|
||||
QJsonArray targets=params.value("targetsJson").isArray()?params.value("targetsJson").toArray():QJsonDocument::fromJson(params.value("targetsJson").toString().toUtf8()).array();
|
||||
require(targets.size()>=2&&targets.size()<=16,QStringLiteral("组合点位应包含2至16个机械臂"));
|
||||
RecordedJointPoint point;point.name=name;
|
||||
for(int i=0;i<targets.size();++i) {
|
||||
auto target=targets[i].toObject();const QString device=params.value(QStringLiteral("deviceId_%1").arg(i)).toString(target.value("deviceId").toString());
|
||||
target.insert("deviceId",device);point.arms.append(JointPointTarget::fromJson(target));targets[i]=target;
|
||||
}
|
||||
require(point.valid(),QStringLiteral("组合点位的设备、关节名或角度数据无效"));
|
||||
const auto first=targets.first().toObject();
|
||||
QJsonObject request{{"header",QJsonObject{{"device_id",first.value("deviceId")}}},{"target",QJsonObject{{"position",first.value("positions")}}},
|
||||
{"options",QJsonObject{{"velocity",params.value("velocity")},{"acceleration",params.value("acceleration")},{"asynchronous",false},{"jerk",0}}}};
|
||||
auto task=rpcNode(id,name,QStringLiteral("机械臂"),first.value("deviceId").toString(),"cmvr.api.ArmService","moveJ",request,120000);
|
||||
auto p=task.value("parameters").toObject();p.insert("_pointTargets",targets);task.insert("parameters",p);result.append(task);
|
||||
} else if(action=="CMVR_GRPC_UNARY") {
|
||||
require(pointMode||!params.contains("jointNamesJson"),QStringLiteral("此文件包含点位关节顺序校验,请导入机械臂点位与流程窗口"));
|
||||
QJsonParseError parse;auto requestValue=params.value("requestJson");
|
||||
const auto parsed=QJsonDocument::fromJson(requestValue.toString().toUtf8(),&parse);
|
||||
require(requestValue.isObject() || (parse.error==QJsonParseError::NoError&&parsed.isObject()),QStringLiteral("节点 %1 请求 JSON 无效").arg(name));
|
||||
const QString service=params.value("service").toString(),method=params.value("method").toString();
|
||||
const int timeout=params.value("timeoutMs").toInt(180000);
|
||||
require(timeout>=1&&timeout<=1800000,QStringLiteral("RPC 超时须为1至1800000毫秒"));
|
||||
result.append(rpcNode(id,name,deviceType(service),params.value("deviceId").toString(),service,method,
|
||||
requestValue.isObject()?requestValue.toObject():parsed.object(),timeout));
|
||||
} else if(action=="ARM_MOVE_TO_J" || action=="ARM_ENABLE" || action=="ARM_DISABLE") {
|
||||
const QSet<QString> allowed{"deviceId","target","velocity","acceleration","timeoutMs","waitTimeoutMs"};
|
||||
for(auto it=params.begin();it!=params.end();++it)
|
||||
require(allowed.contains(it.key()),QStringLiteral("机械臂参数 %1 不能无损映射为上位机请求").arg(it.key()));
|
||||
const QString device=params.value("deviceId").toString();
|
||||
const QString method=action=="ARM_MOVE_TO_J"?"moveJ":action=="ARM_ENABLE"?"torqueOn":"torqueOff";
|
||||
QJsonObject request=method=="moveJ"?QJsonObject{{"header",QJsonObject{{"device_id",device}}}}:QJsonObject{{"device_id",device}};
|
||||
if(method=="moveJ") {
|
||||
auto target=params.value("target");
|
||||
if(target.isString())target=QJsonDocument::fromJson(target.toString().toUtf8()).array();
|
||||
require(target.isArray()&&!target.toArray().isEmpty(),QStringLiteral("机械臂 target 必须是关节弧度数组"));
|
||||
request.insert("target",QJsonObject{{"position",target}});
|
||||
request.insert("options",QJsonObject{{"velocity",params.value("velocity")},{"acceleration",params.value("acceleration")},{"jerk",0}});
|
||||
}
|
||||
result.append(rpcNode(id,name,QStringLiteral("机械臂"),device,"cmvr.api.ArmService",method,request,params.value("timeoutMs").toInt(120000)));
|
||||
} else {
|
||||
require(false,QStringLiteral("节点“%1”的类型/动作尚不能无损导入:%2 / %3").arg(name,type,action));
|
||||
}
|
||||
id=next.value(id);
|
||||
}
|
||||
}
|
||||
require(draft||ended,QStringLiteral("流程必须连接到结束节点"));
|
||||
return result;
|
||||
};
|
||||
const auto tasks=read({},0);require(visited.size()==lookup.size(),QStringLiteral("图中存在未连接节点、无入口循环或孤立容器"));
|
||||
const QString name=metadata(graph).value("name").toString(QStringLiteral("导入工作流"));
|
||||
QJsonObject candidate{{"groups",QJsonArray{QJsonObject{{"id",uid()},{"name",name},{"nodes",tasks}}}}};
|
||||
require(TaskApi::normalize(candidate,error),error);document=candidate;return true;
|
||||
}catch(const std::exception &e){error=QString::fromUtf8(e.what());return false;}
|
||||
}
|
||||
|
||||
bool exportPoints(const QJsonObject &group,int flowIndex,QJsonObject &graph,QString &error) {
|
||||
try {
|
||||
QJsonArray flows=group.value("flows").toArray();
|
||||
if(flows.isEmpty())flows.append(QJsonObject{{"name",QStringLiteral("默认流程")},{"flow",group.value("flow")},
|
||||
{"moveJVelocity",group.value("moveJVelocity")},{"moveJAcceleration",group.value("moveJAcceleration")}});
|
||||
require(flowIndex>=0&&flowIndex<flows.size(),QStringLiteral("请选择需要导出的流程"));
|
||||
const auto flow=flows[flowIndex].toObject();QHash<QString,QJsonObject> points,nodes;
|
||||
for(const auto &p:group.value("points").toArray())points.insert(p.toObject().value("name").toString(),p.toObject());
|
||||
const auto source=flow.value("flow").toArray();
|
||||
for(const auto &n:source){const auto o=n.toObject();require(!nodes.contains(o.value("id").toString()),QStringLiteral("重复节点ID"));nodes.insert(o.value("id").toString(),o);}
|
||||
QSet<QString> seen;
|
||||
std::function<QJsonArray(const QString&,int)> convert=[&](const QString &parent,int depth) {
|
||||
require(depth<=16,QStringLiteral("循环嵌套过深"));QList<QJsonObject> siblings;
|
||||
for(const auto &n:source)if(n.toObject().value("parentId").toString()==parent)siblings.append(n.toObject());
|
||||
std::stable_sort(siblings.begin(),siblings.end(),[](const auto &a,const auto &b){return a.value("order").toInt()<b.value("order").toInt();});
|
||||
QJsonArray result;
|
||||
for(const auto &n:siblings) {
|
||||
const QString id=n.value("id").toString();require(!id.isEmpty()&&!seen.contains(id),QStringLiteral("无效点位节点ID或容器循环"));seen.insert(id);
|
||||
if(n.value("type")=="loop") {
|
||||
result.append(QJsonObject{{"id",id},{"kind","loop"},{"name",n.value("nodeName")},{"count",n.value("loopCount")},
|
||||
{"collapsed",n.value("collapsed")},{"waitMs",int(n.value("intervalSeconds").toDouble()*1000)},{"children",convert(id,depth+1)}});
|
||||
} else {
|
||||
const QString pointName=n.value("pointName").toString();require(points.contains(pointName),QStringLiteral("点位不存在:%1").arg(pointName));
|
||||
const auto point=RecordedJointPoint::fromJson(points[pointName]);require(point.valid(),QStringLiteral("点位数据无效:%1").arg(pointName));
|
||||
const auto target=point.targets().first();QJsonArray positions;for(double v:target.positions)positions.append(v);
|
||||
QJsonObject request{{"header",QJsonObject{{"device_id",target.deviceId}}},{"target",QJsonObject{{"position",positions}}},
|
||||
{"options",QJsonObject{{"velocity",flow.value("moveJVelocity").toDouble(.1)},{"acceleration",flow.value("moveJAcceleration").toDouble(.1)},{"jerk",0},{"asynchronous",false}}}};
|
||||
auto task=rpcNode(id,n.value("nodeName").toString(),QStringLiteral("机械臂"),target.deviceId,"cmvr.api.ArmService","moveJ",request,120000);
|
||||
task.insert("waitMs",int(n.value("intervalSeconds").toDouble()*1000));result.append(task);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const auto tasks=convert({},0);require(seen.size()==nodes.size(),QStringLiteral("存在未连接或错误父级的点位节点"));
|
||||
QJsonObject document{{"groups",QJsonArray{QJsonObject{{"id",uid()},{"name",flow.value("name")},{"nodes",tasks}}}}};
|
||||
require(exportGraph(document,0,graph,error),error);
|
||||
auto graphNodes=graph.value("nodes").toArray();
|
||||
for(int i=0;i<graphNodes.size();++i) {
|
||||
auto node=graphNodes[i].toObject();const auto originalNode=nodes.value(node.value("id").toString());
|
||||
if(originalNode.value("type")!="single")continue;
|
||||
auto props=node.value("properties").toObject();auto params=props.value("nodeParams").toArray();
|
||||
const auto point=RecordedJointPoint::fromJson(points.value(originalNode.value("pointName").toString()));
|
||||
if(point.targets().size()>1) {
|
||||
props.insert("action","CMVR_ARM_POINT_BATCH");QJsonArray targets;
|
||||
for(const auto &target:point.targets())targets.append(target.toJson());
|
||||
params=QJsonArray{parameter("targetsJson",QString::fromUtf8(QJsonDocument(targets).toJson(QJsonDocument::Compact))),
|
||||
parameter("velocity",flow.value("moveJVelocity").toDouble(.1)),parameter("acceleration",flow.value("moveJAcceleration").toDouble(.1)),
|
||||
parameter("timeoutMs",120000),parameter("descriptorSet",descriptorSet("cmvr.api.ArmService","moveJ"))};
|
||||
for(int target=0;target<targets.size();++target)params.append(parameter(QStringLiteral("deviceId_%1").arg(target),targets[target].toObject().value("deviceId")));
|
||||
}else {
|
||||
const auto names=point.targets().first().toJson().value("jointNames").toArray();
|
||||
params.append(parameter("jointNamesJson",QString::fromUtf8(QJsonDocument(names).toJson(QJsonDocument::Compact))));
|
||||
}
|
||||
props.insert("nodeParams",params);node.insert("properties",props);graphNodes.replace(i,node);
|
||||
}
|
||||
graph.insert("nodes",graphNodes);
|
||||
auto meta=graph.value("cmvr").toObject();QJsonObject pointNames;
|
||||
for(const auto &n:source)if(n.toObject().value("type")=="single")pointNames.insert(n.toObject().value("id").toString(),n.toObject().value("pointName"));
|
||||
meta.insert("pointGroupName",group.value("name"));meta.insert("pointLibrary",group.value("points"));meta.insert("pointNames",pointNames);
|
||||
meta.insert("pointMotionDefaults",QJsonObject{{"velocity",flow.value("moveJVelocity").toDouble(.1)},{"acceleration",flow.value("moveJAcceleration").toDouble(.1)}});
|
||||
graph.insert("cmvr",meta);
|
||||
graphNodes=graph.value("nodes").toArray();
|
||||
for(int i=0;i<graphNodes.size();++i)if(graphNodes[i].toObject().value("type")=="start") {
|
||||
auto node=graphNodes[i].toObject(),props=node.value("properties").toObject();props.insert("cmvrInterop",meta);node.insert("properties",props);graphNodes[i]=node;
|
||||
}
|
||||
graph.insert("nodes",graphNodes);
|
||||
resources(graph);
|
||||
return true;
|
||||
}catch(const std::exception &e){error=QString::fromUtf8(e.what());return false;}
|
||||
}
|
||||
|
||||
bool importPoints(const QJsonObject &input,QJsonObject &group,QString &error,const QJsonObject &deviceJointNames,bool draft) {
|
||||
try {
|
||||
QJsonObject document;require(importGraph(input,document,error,true,draft),error);
|
||||
const auto graph=graphObject(input),meta=metadata(graph);
|
||||
const auto original=meta.value("pointGroup").toObject();QJsonArray points=meta.contains("pointLibrary")?meta.value("pointLibrary").toArray():original.value("points").toArray(),flat;
|
||||
QHash<QString,QString> originalPointByNode;
|
||||
const auto pointNames=meta.value("pointNames").toObject();for(auto it=pointNames.begin();it!=pointNames.end();++it)originalPointByNode[it.key()]=it.value().toString();
|
||||
const int index=meta.value("pointFlowIndex").toInt();const auto flows=original.value("flows").toArray();
|
||||
require(flows.isEmpty()||(index>=0&&index<flows.size()),QStringLiteral("点位元数据的流程索引无效"));
|
||||
const auto oldFlow=flows.isEmpty()?original.value("flow").toArray():flows.at(index).toObject().value("flow").toArray();
|
||||
for(const auto &n:oldFlow)originalPointByNode[n.toObject().value("id").toString()]=n.toObject().value("pointName").toString();
|
||||
double velocity=-1,acceleration=-1;
|
||||
std::function<void(const QJsonArray&,const QString&,int)> convert=[&](const QJsonArray &items,const QString &parent,int depth) {
|
||||
int order=0;for(const auto &v:items) {
|
||||
const auto n=v.toObject();const QString id=n.value("id").toString();
|
||||
QJsonObject node{{"id",id},{"nodeName",n.value("name")},{"parentId",parent},{"order",order++},
|
||||
{"x",40+220.0*(order-1)},{"y",40+112.0*depth},{"intervalSeconds",n.value("waitMs").toDouble()/1000}};
|
||||
if(n.value("kind")=="loop") {
|
||||
require(n.value("count").toInt()<=10000,QStringLiteral("点位流程循环次数不能超过10000"));
|
||||
node.insert("type","loop");node.insert("loopCount",n.value("count"));node.insert("collapsed",n.value("collapsed"));flat.append(node);convert(n.value("children").toArray(),id,depth+1);
|
||||
} else {
|
||||
const auto p=n.value("parameters").toObject();require(p.value("service")=="cmvr.api.ArmService"&&p.value("method")=="moveJ",QStringLiteral("点位流程只能导入机械臂关节运动;其他节点请导入任务编排"));
|
||||
require(p.value("timeoutMs").toInt(120000)==120000,QStringLiteral("点位流程固定使用120000毫秒超时,其他配置请导入任务编排"));
|
||||
const auto request=p.value("request").toObject(),options=request.value("options").toObject();
|
||||
for(auto it=request.begin();it!=request.end();++it)require(it.key()=="header"||it.key()=="target"||it.key()=="options",QStringLiteral("点位流程不能无损保留请求字段:%1").arg(it.key()));
|
||||
const auto targetFields=request.value("target").toObject();for(auto it=targetFields.begin();it!=targetFields.end();++it)require(it.key()=="position",QStringLiteral("点位流程不能无损保留关节状态字段:%1").arg(it.key()));
|
||||
const QSet<QString> allowedOptions{"velocity","acceleration","jerk","asynchronous"};
|
||||
for(auto it=options.begin();it!=options.end();++it)require(allowedOptions.contains(it.key()),QStringLiteral("点位流程不能无损保留运动参数:%1").arg(it.key()));
|
||||
require(!options.value("asynchronous").toBool()&&options.value("jerk").toDouble()==0,QStringLiteral("点位流程只支持同步运动及默认 jerk,请导入任务编排以保留接口参数"));
|
||||
const double vel=options.value("velocity").toDouble(.1),acc=options.value("acceleration").toDouble(.1);
|
||||
require(velocity<0||(velocity==vel&&acceleration==acc),QStringLiteral("该流程各步骤运动参数不同,不能无损转换为统一参数的点位流程,请导入任务编排"));velocity=vel;acceleration=acc;
|
||||
const auto positions=request.value("target").toObject().value("position").toArray();
|
||||
const QString device=n.value("deviceId").toString();QString pointName=originalPointByNode.value(id);
|
||||
QJsonObject point;
|
||||
for(const auto &value:points)if(value.toObject().value("name")==pointName)point=value.toObject();
|
||||
if(p.value("_pointTargets").isArray()) {
|
||||
const auto targets=p.value("_pointTargets").toArray();
|
||||
if(point.isEmpty()||point.value("arms")!=targets) {
|
||||
pointName=(pointName.isEmpty()?n.value("name").toString():pointName)+QStringLiteral(" 导入 ")+id.left(8);
|
||||
point=QJsonObject{{"name",pointName},{"arms",targets}};points.append(point);
|
||||
}
|
||||
node.insert("type","single");node.insert("pointName",pointName);flat.append(node);continue;
|
||||
}
|
||||
if(point.isEmpty()||point.value("deviceId")!=device) {
|
||||
QJsonArray names=deviceJointNames.value(device).toArray();
|
||||
const auto graphNode=WorkflowGraph::node(graph,id);
|
||||
const auto literal=literals(graphNode.value("properties").toObject());
|
||||
if(literal.contains("jointNamesJson"))names=QJsonDocument::fromJson(literal.value("jointNamesJson").toString().toUtf8()).array();
|
||||
require(names.size()==positions.size()&&!names.isEmpty(),QStringLiteral("设备 %1 缺少关节名称,请先连接并刷新机械臂信息,或将文件导入任务编排").arg(device));
|
||||
pointName=n.value("name").toString()+" "+id.left(8);
|
||||
point={{"name",pointName},{"deviceId",device},{"jointNames",names},{"positions",positions},{"side",""}};
|
||||
points.append(point);
|
||||
}
|
||||
require(point.value("deviceId")==device&&point.value("jointNames").toArray().size()==positions.size(),QStringLiteral("设备绑定或关节数量已改变,不能沿用原点位关节名称"));
|
||||
const auto oldPositions=point.value("positions").toArray();
|
||||
if(oldPositions!=positions) {
|
||||
pointName+=QStringLiteral(" 导入 ")+id.left(8);point.insert("name",pointName);point.insert("positions",positions);points.append(point);
|
||||
}
|
||||
node.insert("type","single");node.insert("pointName",pointName);flat.append(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
const auto taskGroup=document.value("groups").toArray().first().toObject();convert(taskGroup.value("nodes").toArray(),{},0);
|
||||
const QString name=taskGroup.value("name").toString();const auto defaults=meta.value("pointMotionDefaults").toObject();
|
||||
const double vel=velocity<0?defaults.value("velocity").toDouble(.1):velocity,acc=acceleration<0?defaults.value("acceleration").toDouble(.1):acceleration;
|
||||
group={{"name",meta.value("pointGroupName").toString(original.value("name").toString(name))},{"points",points},{"flow",flat},{"moveJVelocity",vel},{"moveJAcceleration",acc},
|
||||
{"activeFlow",name},{"flows",QJsonArray{QJsonObject{{"name",name},{"flow",flat},{"moveJVelocity",vel},{"moveJAcceleration",acc}}}}};
|
||||
return true;
|
||||
}catch(const std::exception &e){error=QString::fromUtf8(e.what());return false;}
|
||||
}
|
||||
}
|
||||
10
src/freescaninterop.h
Normal file
10
src/freescaninterop.h
Normal file
@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <QJsonObject>
|
||||
namespace FreeScanInterop {
|
||||
bool isGraph(const QJsonObject &document);
|
||||
bool exportGraph(QJsonObject taskDocument, int group, QJsonObject &graph, QString &error);
|
||||
bool importGraph(const QJsonObject &graph, QJsonObject &taskDocument, QString &error, bool pointMode = false, bool draft = false);
|
||||
bool exportPoints(const QJsonObject &group, int flow, QJsonObject &graph, QString &error);
|
||||
bool importPoints(const QJsonObject &graph, QJsonObject &group, QString &error,
|
||||
const QJsonObject &deviceJointNames = {}, bool draft = false);
|
||||
}
|
||||
52
src/freescaninteropui.h
Normal file
52
src/freescaninteropui.h
Normal file
@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
#include <QtWidgets>
|
||||
namespace FreeScanInterop {
|
||||
inline bool bindGraphDevices(QJsonObject &document,QWidget *parent,const QStringList &devices) {
|
||||
QJsonObject graph=document;
|
||||
if(document.value("graph").isObject())graph=document.value("graph").toObject();
|
||||
else if(document.value("flowData").isString())graph=QJsonDocument::fromJson(document.value("flowData").toString().toUtf8()).object();
|
||||
else if(document.value("flowData").isObject())graph=document.value("flowData").toObject();
|
||||
QHash<QString,QString> bindings;auto nodes=graph.value("nodes").toArray();
|
||||
for(int i=0;i<nodes.size();++i) {
|
||||
auto n=nodes[i].toObject();auto p=n.value("properties").toObject();
|
||||
if(p.value("nodeType")!="EDGE")continue;
|
||||
auto params=p.value("nodeParams").toArray();QStringList names{QStringLiteral("deviceId")};
|
||||
if(p.value("action")=="CMVR_ARM_POINT_BATCH") {
|
||||
names.clear();QJsonArray targets;
|
||||
for(const auto &v:params)if(v.toObject().value("name")=="targetsJson")targets=QJsonDocument::fromJson(v.toObject().value("input").toString().toUtf8()).array();
|
||||
for(int index=0;index<targets.size();++index)names.append(QStringLiteral("deviceId_%1").arg(index));
|
||||
}
|
||||
const auto target=p.value("executionTarget").toObject();
|
||||
for(const auto ¶meterName:names) {
|
||||
bool hasDevice=false;
|
||||
for(const auto &v:params)if(v.toObject().value("name")==parameterName&&!v.toObject().value("input").toString().isEmpty())hasDevice=true;
|
||||
if(hasDevice)continue;
|
||||
QString slot=target.value("deviceSlotKey").toString();
|
||||
for(const auto &binding:target.value("deviceBindings").toArray())
|
||||
if(binding.toObject().value("parameterName")==parameterName)slot=binding.toObject().value("slotKey").toString();
|
||||
QString key=target.value("roleKey").toString()+"/"+slot;
|
||||
if(key=="/")key=n.value("id").toString()+"/"+parameterName;
|
||||
if(!bindings.contains(key)) {
|
||||
bool ok=false;const QString device=QInputDialog::getItem(parent,QStringLiteral("导入设备绑定"),
|
||||
QStringLiteral("为“%1”选择或填写 cmvr-es 设备 ID\n资源用途:%2\n导入不会执行设备操作。")
|
||||
.arg(p.value("name").toString(),key),devices,0,true,&ok).trimmed();
|
||||
if(!ok||device.isEmpty())return false;bindings.insert(key,device);
|
||||
}
|
||||
bool replaced=false;
|
||||
for(int j=0;j<params.size();++j)if(params[j].toObject().value("name")==parameterName) {
|
||||
params[j]=QJsonObject{{"name",parameterName},{"type","input"},{"input",bindings[key]}};replaced=true;
|
||||
}
|
||||
if(!replaced)params.append(QJsonObject{{"name",parameterName},{"type","input"},{"input",bindings[key]}});
|
||||
}
|
||||
p.insert("nodeParams",params);n.insert("properties",p);nodes.replace(i,n);
|
||||
}
|
||||
graph.insert("nodes",nodes);document=graph;return true;
|
||||
}
|
||||
inline bool writeGraph(const QString &path,const QJsonObject &graph,QString &error) {
|
||||
const auto data=QJsonDocument(graph).toJson(QJsonDocument::Indented);
|
||||
if(data.size()>16*1024*1024){error=QStringLiteral("导出文件超过16MB,请拆分流程");return false;}
|
||||
QSaveFile file(path);
|
||||
if(!file.open(QIODevice::WriteOnly)||file.write(data)!=data.size()||!file.commit()){error=file.errorString();return false;}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,7 @@
|
||||
#include "jointfloweditor.h"
|
||||
#include "uiicons.h"
|
||||
#include "workflowcanvas.h"
|
||||
#include "workflowgraph.h"
|
||||
|
||||
#include <QGraphicsItem>
|
||||
#include <QGraphicsScene>
|
||||
@ -18,6 +20,7 @@
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMouseEvent>
|
||||
#include <QWheelEvent>
|
||||
#include <QPainter>
|
||||
#include <QPen>
|
||||
#include <QPushButton>
|
||||
@ -28,143 +31,14 @@
|
||||
#include <QVBoxLayout>
|
||||
#include <QUuid>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
|
||||
namespace {
|
||||
constexpr qreal kNodeWidth = 190.0;
|
||||
constexpr qreal kNodeHeight = 76.0;
|
||||
|
||||
class NodeEditDialog final : public QDialog
|
||||
{
|
||||
public:
|
||||
NodeEditDialog(const QString &title, QWidget *parent)
|
||||
: QDialog(parent, Qt::Tool | Qt::FramelessWindowHint)
|
||||
{
|
||||
setObjectName(QStringLiteral("jointFlowChildDialog"));
|
||||
setAttribute(Qt::WA_TranslucentBackground);
|
||||
QVBoxLayout *outerLayout = new QVBoxLayout(this);
|
||||
outerLayout->setContentsMargins(12, 12, 12, 12);
|
||||
outerLayout->setSpacing(0);
|
||||
QFrame *surface = new QFrame(this);
|
||||
surface->setObjectName(QStringLiteral("jointFlowChildSurface"));
|
||||
QVBoxLayout *surfaceLayout = new QVBoxLayout(surface);
|
||||
surfaceLayout->setContentsMargins(0, 0, 0, 0);
|
||||
surfaceLayout->setSpacing(0);
|
||||
m_titleBar = new QWidget(surface);
|
||||
m_titleBar->setObjectName(QStringLiteral("jointFlowChildTitleBar"));
|
||||
m_titleBar->setFixedHeight(44);
|
||||
QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBar);
|
||||
titleLayout->setContentsMargins(12, 0, 0, 0);
|
||||
titleLayout->setSpacing(9);
|
||||
QLabel *mark = new QLabel(QStringLiteral("C"), m_titleBar);
|
||||
mark->setObjectName(QStringLiteral("jointFlowDialogMark"));
|
||||
mark->setAlignment(Qt::AlignCenter);
|
||||
mark->setFixedSize(24, 24);
|
||||
QLabel *titleLabel = new QLabel(title, m_titleBar);
|
||||
titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle"));
|
||||
QPushButton *closeButton = new QPushButton(m_titleBar);
|
||||
closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton"));
|
||||
closeButton->setFixedSize(46, 43);
|
||||
closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"),
|
||||
QColor(QStringLiteral("#4f5964")), QColor(QStringLiteral("#4f5964"))));
|
||||
titleLayout->addWidget(mark);
|
||||
titleLayout->addWidget(titleLabel);
|
||||
titleLayout->addStretch(1);
|
||||
titleLayout->addWidget(closeButton);
|
||||
surfaceLayout->addWidget(m_titleBar);
|
||||
QWidget *content = new QWidget(surface);
|
||||
content->setObjectName(QStringLiteral("jointFlowChildContent"));
|
||||
m_contentLayout = new QVBoxLayout(content);
|
||||
m_contentLayout->setContentsMargins(18, 16, 18, 16);
|
||||
m_contentLayout->setSpacing(12);
|
||||
surfaceLayout->addWidget(content, 1);
|
||||
outerLayout->addWidget(surface);
|
||||
m_titleBar->installEventFilter(this);
|
||||
titleLabel->installEventFilter(this);
|
||||
mark->installEventFilter(this);
|
||||
connect(closeButton, &QPushButton::clicked, this, &QDialog::reject);
|
||||
}
|
||||
|
||||
QVBoxLayout *contentLayout() const { return m_contentLayout; }
|
||||
|
||||
protected:
|
||||
bool eventFilter(QObject *watched, QEvent *event) override
|
||||
{
|
||||
if ((watched == m_titleBar || (watched && watched->parent() == m_titleBar)) && event) {
|
||||
if (event->type() == QEvent::MouseButtonPress) {
|
||||
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
|
||||
if (mouseEvent->button() == Qt::LeftButton) {
|
||||
m_dragging = true;
|
||||
m_dragOffset = mouseEvent->globalPos() - frameGeometry().topLeft();
|
||||
return true;
|
||||
}
|
||||
} else if (event->type() == QEvent::MouseMove && m_dragging) {
|
||||
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
|
||||
move(mouseEvent->globalPos() - m_dragOffset);
|
||||
return true;
|
||||
} else if (event->type() == QEvent::MouseButtonRelease) {
|
||||
m_dragging = false;
|
||||
}
|
||||
}
|
||||
return QDialog::eventFilter(watched, event);
|
||||
}
|
||||
|
||||
private:
|
||||
QWidget *m_titleBar = nullptr;
|
||||
QVBoxLayout *m_contentLayout = nullptr;
|
||||
QPoint m_dragOffset;
|
||||
bool m_dragging = false;
|
||||
};
|
||||
|
||||
class FlowGraphicsView final : public QGraphicsView
|
||||
{
|
||||
public:
|
||||
explicit FlowGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr)
|
||||
: QGraphicsView(scene, parent)
|
||||
{
|
||||
}
|
||||
|
||||
protected:
|
||||
void mousePressEvent(QMouseEvent *event) override
|
||||
{
|
||||
if (event->button() == Qt::RightButton) {
|
||||
m_panning = true;
|
||||
m_lastPosition = event->pos();
|
||||
viewport()->setCursor(Qt::ClosedHandCursor);
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsView::mousePressEvent(event);
|
||||
}
|
||||
|
||||
void mouseMoveEvent(QMouseEvent *event) override
|
||||
{
|
||||
if (m_panning) {
|
||||
const QPoint delta = event->pos() - m_lastPosition;
|
||||
m_lastPosition = event->pos();
|
||||
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x());
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y());
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsView::mouseMoveEvent(event);
|
||||
}
|
||||
|
||||
void mouseReleaseEvent(QMouseEvent *event) override
|
||||
{
|
||||
if (event->button() == Qt::RightButton && m_panning) {
|
||||
m_panning = false;
|
||||
viewport()->unsetCursor();
|
||||
event->accept();
|
||||
return;
|
||||
}
|
||||
QGraphicsView::mouseReleaseEvent(event);
|
||||
}
|
||||
|
||||
private:
|
||||
bool m_panning = false;
|
||||
QPoint m_lastPosition;
|
||||
};
|
||||
using FlowGraphicsView = WorkflowCanvas;
|
||||
|
||||
class FlowCardItem final : public QGraphicsItem
|
||||
{
|
||||
@ -202,7 +76,7 @@ public:
|
||||
painter->setFont(titleFont);
|
||||
painter->drawText(QRectF(14, 10, kNodeWidth - (m_loop ? 58 : 28), 25),
|
||||
Qt::AlignLeft | Qt::AlignVCenter,
|
||||
m_title);
|
||||
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");
|
||||
@ -229,7 +103,7 @@ public:
|
||||
painter->setFont(QFont());
|
||||
painter->setPen(QColor("#687684"));
|
||||
painter->drawText(QRectF(14, 38, kNodeWidth - 28, 26), Qt::AlignLeft | Qt::AlignVCenter,
|
||||
m_subtitle);
|
||||
painter->fontMetrics().elidedText(m_subtitle,Qt::ElideRight,int(kNodeWidth-28)));
|
||||
}
|
||||
|
||||
protected:
|
||||
@ -243,6 +117,7 @@ protected:
|
||||
return;
|
||||
}
|
||||
setCursor(Qt::ClosedHandCursor);
|
||||
m_dragStart = pos();
|
||||
QGraphicsItem::mousePressEvent(event);
|
||||
}
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
|
||||
@ -258,7 +133,7 @@ protected:
|
||||
}
|
||||
setCursor(Qt::OpenHandCursor);
|
||||
QGraphicsItem::mouseReleaseEvent(event);
|
||||
if (m_moved)
|
||||
if (pos()!=m_dragStart && m_moved)
|
||||
m_moved(m_id, pos());
|
||||
}
|
||||
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override
|
||||
@ -298,6 +173,7 @@ private:
|
||||
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;
|
||||
@ -316,7 +192,141 @@ JointFlowEditor::JointFlowEditor(QWidget *parent) : QWidget(parent)
|
||||
m_view->setRenderHint(QPainter::Antialiasing);
|
||||
m_view->setDragMode(QGraphicsView::RubberBandDrag);
|
||||
m_view->setMinimumHeight(230);
|
||||
layout->addWidget(m_view);
|
||||
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(true);
|
||||
toggleInspector->setObjectName(QStringLiteral("secondaryButton"));
|
||||
static_cast<QHBoxLayout *>(canvasTools->layout())->insertWidget(0,toggleInspector);
|
||||
connect(toggleInspector,&QPushButton::toggled,inspectorScroll,&QWidget::setVisible);
|
||||
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();
|
||||
@ -343,7 +353,7 @@ JointFlowEditor::~JointFlowEditor()
|
||||
void JointFlowEditor::addSingleNode(const QString &nodeName, const QString &pointName,
|
||||
double intervalSeconds)
|
||||
{
|
||||
if (nodeName.trimmed().isEmpty() || pointName.isEmpty())
|
||||
if (!m_view->isInteractive() || nodeName.trimmed().isEmpty() || pointName.isEmpty())
|
||||
return;
|
||||
Node node;
|
||||
node.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
@ -361,13 +371,14 @@ void JointFlowEditor::addSingleNode(const QString &nodeName, const QString &poin
|
||||
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 (nodeName.trimmed().isEmpty())
|
||||
if (!m_view->isInteractive() || nodeName.trimmed().isEmpty())
|
||||
return;
|
||||
Node node;
|
||||
node.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
@ -385,14 +396,17 @@ void JointFlowEditor::addLoopNode(const QString &nodeName, int loopCount,
|
||||
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)
|
||||
@ -423,12 +437,20 @@ void JointFlowEditor::removePointReferences(const QStringList &pointNames)
|
||||
emit changed();
|
||||
}
|
||||
|
||||
bool JointFlowEditor::isEmpty() const { return m_nodes.isEmpty(); }
|
||||
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 {};
|
||||
@ -444,19 +466,24 @@ bool JointFlowEditor::appendExecution(const Node &node, QList<ExecutionStep> &st
|
||||
if (error) *error = QStringLiteral("展开后的流程超过 %1 步").arg(maximumSteps);
|
||||
return false;
|
||||
}
|
||||
steps.append({node.pointName, node.intervalSeconds, node.id});
|
||||
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);
|
||||
if (children.isEmpty()) {
|
||||
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)
|
||||
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 += node.intervalSeconds;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@ -513,6 +540,8 @@ bool JointFlowEditor::fromJson(const QJsonArray &array)
|
||||
m_selectedNodeId.clear();
|
||||
m_insertionParentId.clear();
|
||||
rebuildScene();
|
||||
resetView();
|
||||
QTimer::singleShot(0, this, &JointFlowEditor::resetView);
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -522,6 +551,36 @@ void JointFlowEditor::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(); }
|
||||
|
||||
@ -529,6 +588,7 @@ void JointFlowEditor::setAvailablePointNames(const QStringList &pointNames)
|
||||
{
|
||||
m_availablePointNames = pointNames;
|
||||
m_availablePointNames.removeDuplicates();
|
||||
if(m_refreshInspector)m_refreshInspector();
|
||||
}
|
||||
|
||||
void JointFlowEditor::setInsertionAtRoot()
|
||||
@ -561,6 +621,10 @@ const JointFlowEditor::Node *JointFlowEditor::nodeById(const QString &id) const
|
||||
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;
|
||||
@ -575,65 +639,6 @@ QString JointFlowEditor::selectedNodeId() const
|
||||
return m_selectedNodeId;
|
||||
}
|
||||
|
||||
void JointFlowEditor::editNode(const QString &id)
|
||||
{
|
||||
Node *node = nodeById(id);
|
||||
if (!node) return;
|
||||
|
||||
NodeEditDialog dialog(node->type == SingleNode
|
||||
? QStringLiteral("编辑单步节点") : QStringLiteral("编辑循环节点"), this);
|
||||
dialog.setMinimumWidth(420);
|
||||
QVBoxLayout *dialogLayout = dialog.contentLayout();
|
||||
QFormLayout *form = new QFormLayout;
|
||||
QLineEdit *nameEdit = new QLineEdit(node->nodeName, &dialog);
|
||||
form->addRow(QStringLiteral("节点名称"), nameEdit);
|
||||
|
||||
QComboBox *pointCombo = nullptr;
|
||||
QSpinBox *loopCountSpin = nullptr;
|
||||
if (node->type == SingleNode) {
|
||||
QStringList pointNames = m_availablePointNames;
|
||||
if (!pointNames.contains(node->pointName))
|
||||
pointNames.prepend(node->pointName);
|
||||
pointCombo = new QComboBox(&dialog);
|
||||
pointCombo->addItems(pointNames);
|
||||
pointCombo->setCurrentText(node->pointName);
|
||||
form->addRow(QStringLiteral("执行点位"), pointCombo);
|
||||
} else {
|
||||
loopCountSpin = new QSpinBox(&dialog);
|
||||
loopCountSpin->setRange(1, 10000);
|
||||
loopCountSpin->setValue(node->loopCount);
|
||||
form->addRow(QStringLiteral("循环次数"), loopCountSpin);
|
||||
}
|
||||
QDoubleSpinBox *intervalSpin = new QDoubleSpinBox(&dialog);
|
||||
intervalSpin->setRange(0.0, 3600.0);
|
||||
intervalSpin->setDecimals(1);
|
||||
intervalSpin->setSingleStep(0.1);
|
||||
intervalSpin->setSuffix(QStringLiteral(" s"));
|
||||
intervalSpin->setValue(node->intervalSeconds);
|
||||
form->addRow(node->type == LoopNode ? QStringLiteral("循环结束后等待")
|
||||
: QStringLiteral("执行结束后等待"),
|
||||
intervalSpin);
|
||||
dialogLayout->addLayout(form);
|
||||
|
||||
QDialogButtonBox *buttons = new QDialogButtonBox(
|
||||
QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
|
||||
buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("保存"));
|
||||
buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消"));
|
||||
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
|
||||
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
|
||||
dialogLayout->addWidget(buttons);
|
||||
|
||||
if (dialog.exec() != QDialog::Accepted || nameEdit->text().trimmed().isEmpty())
|
||||
return;
|
||||
node->nodeName = nameEdit->text().trimmed();
|
||||
if (pointCombo)
|
||||
node->pointName = pointCombo->currentText();
|
||||
if (loopCountSpin)
|
||||
node->loopCount = loopCountSpin->value();
|
||||
node->intervalSeconds = intervalSpin->value();
|
||||
rebuildScene();
|
||||
emit changed();
|
||||
}
|
||||
|
||||
void JointFlowEditor::toggleLoopCollapsed(const QString &id)
|
||||
{
|
||||
@ -651,6 +656,10 @@ 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;
|
||||
@ -729,13 +738,7 @@ void JointFlowEditor::notifyInsertionContext()
|
||||
const Node *parent = nodeById(m_insertionParentId);
|
||||
const QString container = parent && parent->type == LoopNode
|
||||
? parent->nodeName : QStringLiteral("根流程");
|
||||
const Node *selected = nodeById(selectedNodeId());
|
||||
if (selected && selected->parentId == (parent ? parent->id : QString())) {
|
||||
emit insertionContextChanged(QStringLiteral("%1(插入到“%2”之后)")
|
||||
.arg(container, selected->nodeName));
|
||||
return;
|
||||
}
|
||||
emit insertionContextChanged(QStringLiteral("%1(末尾)").arg(container));
|
||||
emit insertionContextChanged(QStringLiteral("新节点所属:%1 · 端口连线决定顺序").arg(container));
|
||||
}
|
||||
|
||||
void JointFlowEditor::normalizeOrders(const QString &parentId)
|
||||
@ -747,6 +750,7 @@ void JointFlowEditor::normalizeOrders(const QString &parentId)
|
||||
|
||||
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;
|
||||
@ -769,37 +773,70 @@ void JointFlowEditor::rebuildScene()
|
||||
.arg(executionUnit).arg(node.intervalSeconds, 0, 'f', 1);
|
||||
auto *card = new FlowCardItem(node.id, title, subtitle, node.type == LoopNode,
|
||||
node.id == m_activeNodeId, node.collapsed,
|
||||
[this](const QString &id, const QPointF &pos) { moveNode(id, pos); },
|
||||
[this](const QString &id) { editNode(id); },
|
||||
[this](const QString &id, 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->setPos(node.position);
|
||||
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);
|
||||
}
|
||||
for (const Node &node : m_nodes) {
|
||||
if(m_graph.isEmpty())for (const Node &node : m_nodes) {
|
||||
if (node.parentId.isEmpty() || !cards.contains(node.parentId) || !cards.contains(node.id))
|
||||
continue;
|
||||
const QPointF from = cards.value(node.parentId)->sceneBoundingRect().center();
|
||||
const QPointF to = cards.value(node.id)->sceneBoundingRect().center();
|
||||
m_scene->addLine(QLineF(from, to), QPen(QColor("#9aabc0"), 2.0));
|
||||
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);
|
||||
for (const QString &parentId : parentIds) {
|
||||
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 QPointF from = cards.value(previous->id)->sceneBoundingRect().center();
|
||||
const QPointF to = cards.value(current->id)->sceneBoundingRect().center();
|
||||
m_scene->addLine(QLineF(from, to), QPen(QColor("#5a91cf"), 1.5, Qt::DashLine));
|
||||
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()));
|
||||
}
|
||||
}
|
||||
m_scene->setSceneRect(m_scene->itemsBoundingRect().adjusted(-60, -60, 60, 60));
|
||||
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 ¢er){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();
|
||||
}
|
||||
|
||||
@ -1,9 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QHash>
|
||||
#include <QStringList>
|
||||
#include <QList>
|
||||
#include <QPointF>
|
||||
#include <QWidget>
|
||||
#include <functional>
|
||||
|
||||
class QGraphicsScene;
|
||||
class QGraphicsView;
|
||||
@ -36,9 +40,15 @@ public:
|
||||
void setAvailablePointNames(const QStringList &pointNames);
|
||||
void setInsertionAtRoot();
|
||||
bool useSelectedLoopAsInsertionParent();
|
||||
void resetView();
|
||||
void fitAll();
|
||||
void setEditingEnabled(bool enabled);
|
||||
QJsonObject graphState() const { return m_graph; }
|
||||
void setGraphState(const QJsonObject &graph, bool reset = true);
|
||||
|
||||
signals:
|
||||
void changed();
|
||||
void selectionDetailsChanged();
|
||||
void insertionContextChanged(const QString &description);
|
||||
|
||||
private:
|
||||
@ -60,7 +70,6 @@ private:
|
||||
const Node *nodeById(const QString &id) const;
|
||||
QList<const Node *> childrenOf(const QString &parentId) const;
|
||||
QString selectedNodeId() const;
|
||||
void editNode(const QString &id);
|
||||
void toggleLoopCollapsed(const QString &id);
|
||||
void moveNode(const QString &id, const QPointF &position);
|
||||
int insertionOrder(const QString &parentId) const;
|
||||
@ -76,6 +85,12 @@ private:
|
||||
QList<Node> m_nodes;
|
||||
QGraphicsScene *m_scene = nullptr;
|
||||
QGraphicsView *m_view = nullptr;
|
||||
QWidget *m_inspector = nullptr;
|
||||
std::function<void()> m_refreshInspector;
|
||||
QJsonObject m_graph;
|
||||
mutable QHash<QString,QStringList> m_executionOrder;
|
||||
mutable QHash<QString,double> m_executionWaits;
|
||||
mutable bool m_useExecutionOrder = false;
|
||||
QString m_activeNodeId;
|
||||
QString m_selectedNodeId;
|
||||
QString m_insertionParentId;
|
||||
|
||||
@ -24,6 +24,7 @@ struct JointPointTarget {
|
||||
static JointPointTarget fromJson(const QJsonObject &o) {
|
||||
JointPointTarget t;
|
||||
t.side = o.value("side").toString();
|
||||
t.side = o.value("side").toString();
|
||||
t.deviceId = o.value("deviceId").toString();
|
||||
for (const auto &v : o.value("jointNames").toArray()) t.jointNames.append(v.toString());
|
||||
for (const auto &v : o.value("positions").toArray())
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
#include "snapshotimageview.h"
|
||||
#include "taskapi.h"
|
||||
#include "freescaninterop.h"
|
||||
#include "workflowgraph.h"
|
||||
#include "taskrpcrunner.h"
|
||||
#include "taskdeviceoptions.h"
|
||||
#include "mainwindow.h"
|
||||
@ -678,8 +680,34 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
syncTcpContext();
|
||||
setupHandEye();
|
||||
setupTouchOperation();
|
||||
m_taskOrchestration = new TaskOrchestrationWidget(m_pages);
|
||||
m_pages->addWidget(m_taskOrchestration);
|
||||
m_taskFlowDialog = new QDialog(this,Qt::Window);
|
||||
m_taskFlowDialog->setWindowTitle(QStringLiteral("任务编排工作流"));
|
||||
m_taskFlowDialog->setWindowIcon(windowIcon());
|
||||
m_taskFlowDialog->setModal(false);
|
||||
auto *taskWindowLayout = new QVBoxLayout(m_taskFlowDialog);
|
||||
taskWindowLayout->setContentsMargins(0,0,0,0);
|
||||
auto *taskWindowHeader = new QHBoxLayout;
|
||||
auto *taskWindowTitle = new QLabel(QStringLiteral("任务编排工作流"),m_taskFlowDialog);
|
||||
taskWindowTitle->setObjectName(QStringLiteral("sectionTitle"));
|
||||
auto *taskReturn = new QPushButton(QStringLiteral("返回主界面"),m_taskFlowDialog);
|
||||
taskReturn->setObjectName(QStringLiteral("secondaryButton"));
|
||||
taskWindowHeader->addWidget(taskWindowTitle);taskWindowHeader->addStretch();taskWindowHeader->addWidget(taskReturn);
|
||||
taskWindowHeader->setContentsMargins(24,12,24,0);
|
||||
taskWindowLayout->addLayout(taskWindowHeader);
|
||||
m_taskOrchestration = new TaskOrchestrationWidget(m_taskFlowDialog);
|
||||
taskWindowLayout->addWidget(m_taskOrchestration,1);
|
||||
connect(taskReturn,&QPushButton::clicked,m_taskFlowDialog,&QDialog::hide);
|
||||
auto *taskLauncher = new QWidget(m_pages);
|
||||
auto *taskLauncherLayout = new QVBoxLayout(taskLauncher);
|
||||
auto *openTaskWorkflow = new QPushButton(QStringLiteral("打开任务编排工作流"),taskLauncher);
|
||||
openTaskWorkflow->setObjectName(QStringLiteral("primaryButton"));
|
||||
taskLauncherLayout->addStretch();taskLauncherLayout->addWidget(openTaskWorkflow,0,Qt::AlignCenter);taskLauncherLayout->addStretch();
|
||||
const int taskPageIndex=m_pages->addWidget(taskLauncher);
|
||||
const auto showTaskWorkflow=[this] {
|
||||
m_taskFlowDialog->showFullScreen();m_taskFlowDialog->raise();m_taskFlowDialog->activateWindow();
|
||||
};
|
||||
connect(openTaskWorkflow,&QPushButton::clicked,this,showTaskWorkflow);
|
||||
if(taskPageIndex<m_navButtons.size())connect(m_navButtons.at(taskPageIndex),&QPushButton::clicked,this,showTaskWorkflow);
|
||||
auto *motorDebugPage=new MotorDebugWidget(m_client,m_pages);
|
||||
m_pages->addWidget(motorDebugPage);
|
||||
connect(motorDebugPage,&MotorDebugWidget::statusMessage,this,&MainWindow::appendLog);
|
||||
@ -3887,6 +3915,62 @@ void MainWindow::refreshRecordedJointPoints()
|
||||
}
|
||||
}
|
||||
|
||||
bool MainWindow::renameRecordedJointPoint(int row, const QString &requestedName, QString *error)
|
||||
{
|
||||
const auto reject = [error](const QString &message) {
|
||||
if (error) *error = message;
|
||||
return false;
|
||||
};
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending)
|
||||
return reject(QStringLiteral("请先停止执行并等待点位记录完成。"));
|
||||
if (row < 0 || row >= m_recordedJointPoints.size() || m_activeJointProgramGroup < 0)
|
||||
return reject(QStringLiteral("请先选择一个点位。"));
|
||||
const QString name = requestedName.trimmed();
|
||||
if (name.isEmpty()) return reject(QStringLiteral("点位名称不能为空。"));
|
||||
for (int i = 0; i < m_recordedJointPoints.size(); ++i)
|
||||
if (i != row && m_recordedJointPoints.at(i).name.compare(name, Qt::CaseInsensitive) == 0)
|
||||
return reject(QStringLiteral("当前组中已存在同名点位。"));
|
||||
const QString oldName = m_recordedJointPoints.at(row).name;
|
||||
if (name == oldName) return true;
|
||||
storeCurrentJointProgramGroup();
|
||||
m_recordedJointPoints[row].name = name;
|
||||
auto &group = m_jointProgramGroups[m_activeJointProgramGroup];
|
||||
for (auto &flow : group.flows) {
|
||||
for (int i = 0; i < flow.nodes.size(); ++i) {
|
||||
auto node = flow.nodes.at(i).toObject();
|
||||
if (node.value(QStringLiteral("type")).toString() != QStringLiteral("loop")
|
||||
&& node.value(QStringLiteral("pointName")).toString() == oldName) {
|
||||
node.insert(QStringLiteral("pointName"), name);
|
||||
flow.nodes.replace(i, node);
|
||||
}
|
||||
}
|
||||
}
|
||||
group.flow = group.flows.at(group.activeFlow).nodes;
|
||||
if (m_jointFlowEditor) {
|
||||
const QSignalBlocker blocker(m_jointFlowEditor);
|
||||
m_jointFlowEditor->fromJson(group.flow);
|
||||
}
|
||||
refreshRecordedJointPoints();
|
||||
m_jointPointTable->selectRow(row);
|
||||
if (m_jointPointDetailLabel) m_jointPointDetailLabel->setText(name);
|
||||
saveJointPrograms();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MainWindow::moveRecordedJointPoint(int from, int to)
|
||||
{
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending
|
||||
|| from < 0 || to < 0 || from >= m_recordedJointPoints.size()
|
||||
|| to >= m_recordedJointPoints.size())
|
||||
return false;
|
||||
if (from == to) return true;
|
||||
m_recordedJointPoints.move(from, to);
|
||||
refreshRecordedJointPoints();
|
||||
m_jointPointTable->selectRow(to);
|
||||
saveJointPrograms();
|
||||
return true;
|
||||
}
|
||||
|
||||
void MainWindow::refreshJointFlowTable()
|
||||
{
|
||||
if (m_jointFlowEditor)
|
||||
@ -4048,7 +4132,7 @@ void MainWindow::startJointPointLoop()
|
||||
}
|
||||
for (const JointFlowEditor::ExecutionStep &step : steps) {
|
||||
const int row = pointRow(step.pointName);
|
||||
if (row < 0) {
|
||||
if (row < 0 && !step.pointName.isEmpty()) {
|
||||
AppMessageBox::warning(this, QStringLiteral("执行自定义流程"),
|
||||
QStringLiteral("流程引用的点位“%1”已不存在。").arg(step.pointName));
|
||||
m_jointPointLoopRows.clear();
|
||||
@ -4076,6 +4160,7 @@ void MainWindow::startJointPointLoop()
|
||||
m_jointPointTable->setEnabled(false);
|
||||
m_jointFlowVelocitySpin->setEnabled(false);
|
||||
m_jointFlowAccelerationSpin->setEnabled(false);
|
||||
m_jointFlowEditor->setEditingEnabled(false);
|
||||
advanceJointPointLoop();
|
||||
}
|
||||
|
||||
@ -4089,6 +4174,11 @@ void MainWindow::advanceJointPointLoop()
|
||||
}
|
||||
const int executionIndex = m_jointPointLoopCursor;
|
||||
const int row = m_jointPointLoopRows.at(m_jointPointLoopCursor++);
|
||||
if(row==-1){
|
||||
const int delay=qRound(m_jointPointExecutionWaits.value(executionIndex)*1000);const auto generation=m_jointPointLoopGeneration;
|
||||
m_jointPointLoopStatus->setText(QStringLiteral("步骤 %1/%2 · 等待 %3 ms").arg(executionIndex+1).arg(m_jointPointLoopRows.size()).arg(delay));
|
||||
QTimer::singleShot(delay,this,[this,generation]{if(generation==m_jointPointLoopGeneration)advanceJointPointLoop();});return;
|
||||
}
|
||||
if (row < 0 || row >= m_recordedJointPoints.size()) {
|
||||
stopJointPointLoop(QStringLiteral("点位列表已发生变化"));
|
||||
return;
|
||||
@ -4130,6 +4220,7 @@ void MainWindow::stopJointPointLoop(const QString &reason)
|
||||
m_jointFlowVelocitySpin->setEnabled(m_connected);
|
||||
if (m_jointFlowAccelerationSpin)
|
||||
m_jointFlowAccelerationSpin->setEnabled(m_connected);
|
||||
if(m_jointFlowEditor)m_jointFlowEditor->setEditingEnabled(true);
|
||||
if (m_jointPointLoopStatus)
|
||||
m_jointPointLoopStatus->setText(reason.isEmpty() ? QStringLiteral("未运行") : reason);
|
||||
if (wasActive && !reason.isEmpty())
|
||||
@ -4373,6 +4464,64 @@ void MainWindow::storeCurrentJointProgramGroup()
|
||||
group.moveJVelocity = m_jointFlowVelocitySpin->value();
|
||||
if (m_jointFlowAccelerationSpin)
|
||||
group.moveJAcceleration = m_jointFlowAccelerationSpin->value();
|
||||
if (group.flows.isEmpty())
|
||||
group.flows.append({QStringLiteral("默认流程"), {}, 0.1, 0.1});
|
||||
JointProgramFlow &flow = group.flows[group.activeFlow];
|
||||
flow.nodes = group.flow;
|
||||
flow.velocity = group.moveJVelocity;
|
||||
flow.acceleration = group.moveJAcceleration;
|
||||
flow.graph = m_jointFlowEditor ? m_jointFlowEditor->graphState() : QJsonObject{};
|
||||
}
|
||||
|
||||
void MainWindow::refreshJointProgramFlows()
|
||||
{
|
||||
if (!m_jointProgramFlowCombo || m_activeJointProgramGroup < 0)
|
||||
return;
|
||||
JointProgramGroup &group = m_jointProgramGroups[m_activeJointProgramGroup];
|
||||
if (group.flows.isEmpty())
|
||||
group.flows.append({QStringLiteral("默认流程"), group.flow,
|
||||
group.moveJVelocity, group.moveJAcceleration});
|
||||
group.activeFlow = qBound(0, group.activeFlow, group.flows.size() - 1);
|
||||
const QSignalBlocker blocker(m_jointProgramFlowCombo);
|
||||
m_jointProgramFlowCombo->clear();
|
||||
for (const auto &flow : group.flows)
|
||||
m_jointProgramFlowCombo->addItem(flow.name);
|
||||
m_jointProgramFlowCombo->setCurrentIndex(group.activeFlow);
|
||||
}
|
||||
|
||||
void MainWindow::activateJointProgramFlow(int index)
|
||||
{
|
||||
if (m_activeJointProgramGroup < 0)
|
||||
return;
|
||||
JointProgramGroup &group = m_jointProgramGroups[m_activeJointProgramGroup];
|
||||
if (index < 0 || index >= group.flows.size() || index == group.activeFlow)
|
||||
return;
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending) {
|
||||
const QSignalBlocker blocker(m_jointProgramFlowCombo);
|
||||
m_jointProgramFlowCombo->setCurrentIndex(group.activeFlow);
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("切换流程"),
|
||||
QStringLiteral("请先停止当前点位或流程执行。"));
|
||||
return;
|
||||
}
|
||||
storeCurrentJointProgramGroup();
|
||||
group.activeFlow = index;
|
||||
const JointProgramFlow flow = group.flows.at(index);
|
||||
group.flow = flow.nodes;
|
||||
group.moveJVelocity = flow.velocity;
|
||||
group.moveJAcceleration = flow.acceleration;
|
||||
{
|
||||
const QSignalBlocker editorBlocker(m_jointFlowEditor);
|
||||
const QSignalBlocker velocityBlocker(m_jointFlowVelocitySpin);
|
||||
const QSignalBlocker accelerationBlocker(m_jointFlowAccelerationSpin);
|
||||
m_jointFlowEditor->clear();
|
||||
m_jointFlowEditor->fromJson(flow.nodes);
|
||||
m_jointFlowEditor->setGraphState(flow.graph);
|
||||
m_jointFlowVelocitySpin->setValue(flow.velocity);
|
||||
m_jointFlowAccelerationSpin->setValue(flow.acceleration);
|
||||
}
|
||||
refreshJointProgramFlows();
|
||||
refreshJointFlowTable();
|
||||
saveJointPrograms();
|
||||
}
|
||||
|
||||
void MainWindow::activateJointProgramGroup(int index)
|
||||
@ -4390,12 +4539,14 @@ void MainWindow::activateJointProgramGroup(int index)
|
||||
stopJointPointLoop(QStringLiteral("切换点位组"));
|
||||
storeCurrentJointProgramGroup();
|
||||
m_activeJointProgramGroup = index;
|
||||
refreshJointProgramFlows();
|
||||
const JointProgramGroup &group = m_jointProgramGroups.at(index);
|
||||
m_recordedJointPoints = group.points;
|
||||
if (m_jointFlowEditor) {
|
||||
const QSignalBlocker blocker(m_jointFlowEditor);
|
||||
m_jointFlowEditor->clear();
|
||||
m_jointFlowEditor->fromJson(group.flow);
|
||||
m_jointFlowEditor->setGraphState(group.flows.at(group.activeFlow).graph);
|
||||
}
|
||||
if (m_jointFlowVelocitySpin) {
|
||||
const QSignalBlocker blocker(m_jointFlowVelocitySpin);
|
||||
@ -4412,6 +4563,7 @@ void MainWindow::activateJointProgramGroup(int index)
|
||||
|
||||
void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
{
|
||||
m_jointProgramsWritable=true;
|
||||
m_jointProgramGroups.clear();
|
||||
m_activeJointProgramGroup = -1;
|
||||
const QString filePath = jointProgramsFilePath();
|
||||
@ -4437,6 +4589,34 @@ void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
QStringLiteral("moveJVelocity")).toDouble(0.1);
|
||||
group.moveJAcceleration = groupObject.value(
|
||||
QStringLiteral("moveJAcceleration")).toDouble(0.1);
|
||||
const QString activeFlowName = groupObject.value(QStringLiteral("activeFlow")).toString();
|
||||
for (const auto &value : groupObject.value(QStringLiteral("flows")).toArray()) {
|
||||
const auto object = value.toObject();
|
||||
JointProgramFlow flow;
|
||||
flow.name = object.value(QStringLiteral("name")).toString().trimmed();
|
||||
if(object.value("flowData").isString()) {
|
||||
flow.graph=QJsonDocument::fromJson(object.value("flowData").toString().toUtf8()).object();
|
||||
QJsonObject converted;QString error;
|
||||
if(!FreeScanInterop::importPoints(flow.graph,converted,error,{},true)) {
|
||||
m_jointProgramsWritable=false;appendLog("ERROR",QStringLiteral("点位图读取失败,禁止覆盖原文件:")+error);continue;
|
||||
}
|
||||
flow.nodes=converted.value("flow").toArray();flow.velocity=converted.value("moveJVelocity").toDouble(.1);
|
||||
flow.acceleration=converted.value("moveJAcceleration").toDouble(.1);
|
||||
} else {
|
||||
flow.nodes = object.value(QStringLiteral("flow")).toArray();
|
||||
flow.velocity = object.value(QStringLiteral("moveJVelocity")).toDouble(0.1);
|
||||
flow.acceleration = object.value(QStringLiteral("moveJAcceleration")).toDouble(0.1);
|
||||
}
|
||||
if (flow.name.isEmpty()) continue;
|
||||
if (flow.name == activeFlowName) group.activeFlow = group.flows.size();
|
||||
group.flows.append(flow);
|
||||
}
|
||||
if (!group.flows.isEmpty()) {
|
||||
const auto &flow = group.flows.at(group.activeFlow);
|
||||
group.flow = flow.nodes;
|
||||
group.moveJVelocity = flow.velocity;
|
||||
group.moveJAcceleration = flow.acceleration;
|
||||
}
|
||||
for (const QJsonValue &pointValue : groupObject.value(QStringLiteral("points")).toArray()) {
|
||||
const QJsonObject pointObject = pointValue.toObject();
|
||||
const RecordedJointPoint point=RecordedJointPoint::fromJson(pointObject);
|
||||
@ -4447,6 +4627,8 @@ void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
if (!group.name.isEmpty())
|
||||
m_jointProgramGroups.append(group);
|
||||
}
|
||||
if (document.isNull()||!document.isObject()||!root.value("groups").isArray())
|
||||
m_jointProgramsWritable=false;
|
||||
if (document.isNull())
|
||||
appendLog(QStringLiteral("WARN"),
|
||||
QStringLiteral("点位组 JSON 解析失败:%1").arg(parseError.errorString()));
|
||||
@ -4488,6 +4670,7 @@ void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
}
|
||||
}
|
||||
m_activeJointProgramGroup = activeIndex;
|
||||
refreshJointProgramFlows();
|
||||
m_updatingJointProgramGroup = true;
|
||||
if (m_jointProgramGroupCombo) {
|
||||
m_jointProgramGroupCombo->clear();
|
||||
@ -4501,13 +4684,19 @@ void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
const QSignalBlocker blocker(m_jointFlowEditor);
|
||||
m_jointFlowEditor->clear();
|
||||
m_jointFlowEditor->fromJson(m_jointProgramGroups.at(activeIndex).flow);
|
||||
const auto &group=m_jointProgramGroups.at(activeIndex);
|
||||
m_jointFlowEditor->setGraphState(group.flows.isEmpty()?QJsonObject{}:group.flows.at(group.activeFlow).graph);
|
||||
}
|
||||
if (m_jointFlowVelocitySpin)
|
||||
if (m_jointFlowVelocitySpin) {
|
||||
const QSignalBlocker blocker(m_jointFlowVelocitySpin);
|
||||
m_jointFlowVelocitySpin->setValue(
|
||||
m_jointProgramGroups.at(activeIndex).moveJVelocity);
|
||||
if (m_jointFlowAccelerationSpin)
|
||||
}
|
||||
if (m_jointFlowAccelerationSpin) {
|
||||
const QSignalBlocker blocker(m_jointFlowAccelerationSpin);
|
||||
m_jointFlowAccelerationSpin->setValue(
|
||||
m_jointProgramGroups.at(activeIndex).moveJAcceleration);
|
||||
}
|
||||
refreshRecordedJointPoints();
|
||||
refreshJointFlowTable();
|
||||
if (!QFileInfo::exists(filePath)) {
|
||||
@ -4521,11 +4710,12 @@ void MainWindow::loadJointPrograms(QSettings &legacySettings)
|
||||
|
||||
void MainWindow::saveJointPrograms()
|
||||
{
|
||||
if(!m_jointProgramsWritable)return;
|
||||
storeCurrentJointProgramGroup();
|
||||
if (m_jointProgramGroups.isEmpty())
|
||||
return;
|
||||
QJsonArray groups;
|
||||
for (const JointProgramGroup &group : m_jointProgramGroups) {
|
||||
for (JointProgramGroup &group : m_jointProgramGroups) {
|
||||
QJsonObject groupObject;
|
||||
groupObject.insert(QStringLiteral("name"), group.name);
|
||||
QJsonArray points;
|
||||
@ -4533,19 +4723,47 @@ void MainWindow::saveJointPrograms()
|
||||
points.append(point.toJson());
|
||||
}
|
||||
groupObject.insert(QStringLiteral("points"), points);
|
||||
groupObject.insert(QStringLiteral("flow"), group.flow);
|
||||
groupObject.insert(QStringLiteral("moveJVelocity"), group.moveJVelocity);
|
||||
groupObject.insert(QStringLiteral("moveJAcceleration"), group.moveJAcceleration);
|
||||
QJsonArray flows;
|
||||
const QList<JointProgramFlow> savedFlows = group.flows.isEmpty()
|
||||
? QList<JointProgramFlow>{{QStringLiteral("默认流程"), group.flow,
|
||||
group.moveJVelocity, group.moveJAcceleration}}
|
||||
: group.flows;
|
||||
QJsonArray nativeFlows;
|
||||
for(const auto &flow:savedFlows)nativeFlows.append(QJsonObject{{"name",flow.name},{"flow",flow.nodes},
|
||||
{"moveJVelocity",flow.velocity},{"moveJAcceleration",flow.acceleration}});
|
||||
const QJsonObject nativeGroup{{"name",group.name},{"points",points},{"flows",nativeFlows}};
|
||||
for(int i=0;i<savedFlows.size();++i) {
|
||||
QJsonObject fresh;QString error;
|
||||
if(!FreeScanInterop::exportPoints(nativeGroup,i,fresh,error)) {
|
||||
appendLog("ERROR",QStringLiteral("点位图转换失败,未覆盖原文件:")+error);return;
|
||||
}
|
||||
const auto graph=WorkflowGraph::merge(fresh,savedFlows.at(i).graph);
|
||||
if(i<group.flows.size())group.flows[i].graph=graph;
|
||||
flows.append(QJsonObject{{"name",savedFlows.at(i).name},{"flowData",QString::fromUtf8(QJsonDocument(graph).toJson(QJsonDocument::Compact))}});
|
||||
}
|
||||
groupObject.insert(QStringLiteral("flows"), flows);
|
||||
groupObject.insert(QStringLiteral("activeFlow"), savedFlows.at(
|
||||
qBound(0, group.activeFlow, savedFlows.size() - 1)).name);
|
||||
groups.append(groupObject);
|
||||
}
|
||||
QJsonObject root;
|
||||
root.insert(QStringLiteral("version"), 2);
|
||||
root.insert(QStringLiteral("activeGroup"),
|
||||
m_jointProgramGroups.at(m_activeJointProgramGroup).name);
|
||||
root.insert(QStringLiteral("groups"), groups);
|
||||
|
||||
const QString filePath = jointProgramsFilePath();
|
||||
QDir().mkpath(QFileInfo(filePath).absolutePath());
|
||||
if(QFile::exists(filePath)) {
|
||||
QFile old(filePath);if(old.open(QIODevice::ReadOnly)) {
|
||||
const auto original=QJsonDocument::fromJson(old.readAll()).object();old.close();
|
||||
const auto oldGroups=original.value("groups").toArray();
|
||||
const auto oldFlows=oldGroups.isEmpty()?QJsonArray{}:oldGroups.first().toObject().value("flows").toArray();
|
||||
const bool graphFormat=!oldFlows.isEmpty()&&oldFlows.first().toObject().contains("flowData");
|
||||
if(!graphFormat&&!QFile::copy(filePath,filePath+".before-graph."+QUuid::createUuid().toString(QUuid::WithoutBraces)+".bak")) {
|
||||
appendLog("ERROR",QStringLiteral("旧点位文件备份失败,未覆盖原文件"));return;
|
||||
}
|
||||
}
|
||||
}
|
||||
QSaveFile file(filePath);
|
||||
if (!file.open(QIODevice::WriteOnly)
|
||||
|| file.write(QJsonDocument(root).toJson(QJsonDocument::Indented)) < 0
|
||||
@ -4553,6 +4771,10 @@ void MainWindow::saveJointPrograms()
|
||||
appendLog(QStringLiteral("ERROR"),
|
||||
QStringLiteral("点位组保存失败:%1").arg(filePath));
|
||||
}
|
||||
if(m_activeJointProgramGroup>=0&&m_jointFlowEditor) {
|
||||
const auto &group=m_jointProgramGroups.at(m_activeJointProgramGroup);
|
||||
if(!group.flows.isEmpty())m_jointFlowEditor->setGraphState(group.flows.at(group.activeFlow).graph,false);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::setControlsEnabled(bool enabled)
|
||||
|
||||
@ -144,6 +144,10 @@ private:
|
||||
void loadJointPrograms(QSettings &legacySettings);
|
||||
void saveJointPrograms();
|
||||
void storeCurrentJointProgramGroup();
|
||||
bool renameRecordedJointPoint(int row, const QString &name, QString *error = nullptr);
|
||||
bool moveRecordedJointPoint(int from, int to);
|
||||
void refreshJointProgramFlows();
|
||||
void activateJointProgramFlow(int index);
|
||||
void activateJointProgramGroup(int index);
|
||||
QString jointProgramsFilePath() const;
|
||||
void setControlsEnabled(bool enabled);
|
||||
@ -326,18 +330,29 @@ private:
|
||||
QString m_pendingUrdfPath;
|
||||
bool m_armModelLoadScheduled = false;
|
||||
using RecordedJointPoint = ::RecordedJointPoint;
|
||||
struct JointProgramFlow {
|
||||
QString name;
|
||||
QJsonArray nodes;
|
||||
double velocity = 0.1;
|
||||
double acceleration = 0.1;
|
||||
QJsonObject graph;
|
||||
};
|
||||
struct JointProgramGroup {
|
||||
QString name;
|
||||
QList<RecordedJointPoint> points;
|
||||
QJsonArray flow;
|
||||
double moveJVelocity = 0.1;
|
||||
double moveJAcceleration = 0.1;
|
||||
QList<JointProgramFlow> flows;
|
||||
int activeFlow = 0;
|
||||
};
|
||||
QList<JointProgramGroup> m_jointProgramGroups;
|
||||
int m_activeJointProgramGroup = -1;
|
||||
bool m_updatingJointProgramGroup = false;
|
||||
bool m_jointProgramsWritable = true;
|
||||
QList<RecordedJointPoint> m_recordedJointPoints;
|
||||
QComboBox *m_jointProgramGroupCombo = nullptr;
|
||||
QComboBox *m_jointProgramFlowCombo = nullptr;
|
||||
QHash<QString, double> m_latestArmJointPositions;
|
||||
QLineEdit *m_jointPointNameEdit = nullptr;
|
||||
QTableWidget *m_jointPointTable = nullptr;
|
||||
@ -349,6 +364,7 @@ private:
|
||||
QSpinBox *m_jointFlowGroupCount = nullptr;
|
||||
JointFlowEditor *m_jointFlowEditor = nullptr;
|
||||
TaskOrchestrationWidget *m_taskOrchestration = nullptr;
|
||||
QDialog *m_taskFlowDialog = nullptr;
|
||||
QDialog *m_jointFlowDialog = nullptr;
|
||||
QPushButton *m_recordJointPointButton = nullptr;
|
||||
QPushButton *m_runJointPointButton = nullptr;
|
||||
|
||||
@ -1,3 +1,8 @@
|
||||
#include "workflowcanvas.h"
|
||||
#include "workflowgraph.h"
|
||||
#include "freescaninterop.h"
|
||||
#include "freescaninteropui.h"
|
||||
#include "taskorchestrationwidget.h"
|
||||
#include "snapshotimageview.h"
|
||||
#include "actionqueuetestwidget.h"
|
||||
#include "mainwindow.h"
|
||||
@ -489,14 +494,18 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointProgramGroupCombo->setMinimumWidth(220);
|
||||
m_jointProgramGroupCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
|
||||
QPushButton *newGroupButton = new QPushButton(QStringLiteral("新建组"), groupPanel);
|
||||
QPushButton *copyGroupButton = new QPushButton(QStringLiteral("复制组"), groupPanel);
|
||||
QPushButton *renameGroupButton = new QPushButton(QStringLiteral("重命名"), groupPanel);
|
||||
newGroupButton->setObjectName(QStringLiteral("primaryButton"));
|
||||
renameGroupButton->setObjectName(QStringLiteral("secondaryButton"));
|
||||
copyGroupButton->setObjectName(QStringLiteral("secondaryButton"));
|
||||
copyGroupButton->setToolTip(QStringLiteral("复制当前组的全部点位、执行流程和运动参数"));
|
||||
groupLayout->addWidget(groupLabel);
|
||||
groupLayout->addWidget(groupHint);
|
||||
groupLayout->addStretch(1);
|
||||
groupLayout->addWidget(m_jointProgramGroupCombo);
|
||||
groupLayout->addWidget(newGroupButton);
|
||||
groupLayout->addWidget(copyGroupButton);
|
||||
groupLayout->addWidget(renameGroupButton);
|
||||
moveJLayout->addWidget(groupPanel);
|
||||
|
||||
@ -527,6 +536,47 @@ QWidget *MainWindow::createArmPage()
|
||||
m_updatingJointProgramGroup = false;
|
||||
activateJointProgramGroup(newIndex);
|
||||
});
|
||||
connect(copyGroupButton, &QPushButton::clicked, this, [this]() {
|
||||
if (m_activeJointProgramGroup < 0
|
||||
|| m_activeJointProgramGroup >= m_jointProgramGroups.size())
|
||||
return;
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending) {
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("复制点位组"),
|
||||
QStringLiteral("请先停止点位执行并等待点位记录完成,再复制组。"));
|
||||
return;
|
||||
}
|
||||
const auto nameExists = [this](const QString &name) {
|
||||
for (const JointProgramGroup &group : m_jointProgramGroups)
|
||||
if (group.name.compare(name, Qt::CaseInsensitive) == 0)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
const QString baseName = m_jointProgramGroups.at(m_activeJointProgramGroup).name
|
||||
+ QStringLiteral(" 副本");
|
||||
QString suggestedName = baseName;
|
||||
for (int suffix = 2; nameExists(suggestedName); ++suffix)
|
||||
suggestedName = baseName + QStringLiteral(" %1").arg(suffix);
|
||||
bool ok = false;
|
||||
const QString name = requestFlowNodeName(
|
||||
m_jointFlowDialog, QStringLiteral("复制点位组"), suggestedName, &ok);
|
||||
if (!ok || name.isEmpty())
|
||||
return;
|
||||
if (nameExists(name)) {
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("复制点位组"),
|
||||
QStringLiteral("已存在同名点位组。"));
|
||||
return;
|
||||
}
|
||||
storeCurrentJointProgramGroup();
|
||||
JointProgramGroup copy = m_jointProgramGroups.at(m_activeJointProgramGroup);
|
||||
copy.name = name;
|
||||
m_jointProgramGroups.append(copy);
|
||||
const int newIndex = m_jointProgramGroups.size() - 1;
|
||||
m_updatingJointProgramGroup = true;
|
||||
m_jointProgramGroupCombo->addItem(name);
|
||||
m_jointProgramGroupCombo->setCurrentIndex(newIndex);
|
||||
m_updatingJointProgramGroup = false;
|
||||
activateJointProgramGroup(newIndex);
|
||||
});
|
||||
connect(renameGroupButton, &QPushButton::clicked, this, [this]() {
|
||||
if (m_activeJointProgramGroup < 0
|
||||
|| m_activeJointProgramGroup >= m_jointProgramGroups.size())
|
||||
@ -557,12 +607,13 @@ QWidget *MainWindow::createArmPage()
|
||||
QVBoxLayout *pointLayout = new QVBoxLayout(pointPanel);
|
||||
pointLayout->setContentsMargins(12, 10, 12, 10);
|
||||
pointLayout->setSpacing(8);
|
||||
QHBoxLayout *pointHeader = new QHBoxLayout;
|
||||
QVBoxLayout *pointHeader = new QVBoxLayout;
|
||||
QLabel *pointTitle = new QLabel(QStringLiteral("关节点位记录与循环"), pointPanel);
|
||||
pointTitle->setObjectName(QStringLiteral("jointFlowSectionTitle"));
|
||||
QLabel *pointSubtitle = new QLabel(
|
||||
QStringLiteral("可记录单臂或多臂点位,也可组合已有点位,原记录保留"), pointPanel);
|
||||
pointSubtitle->setObjectName(QStringLiteral("jointFlowSectionSubtitle"));
|
||||
pointSubtitle->setWordWrap(true);
|
||||
QVBoxLayout *pointHeading = new QVBoxLayout;
|
||||
pointHeading->setSpacing(2);
|
||||
pointHeading->addWidget(pointTitle);
|
||||
@ -577,9 +628,21 @@ QWidget *MainWindow::createArmPage()
|
||||
pointHeader->addWidget(m_jointPointNameEdit);
|
||||
pointHeader->addWidget(m_recordJointPointButton);
|
||||
pointLayout->addLayout(pointHeader);
|
||||
auto *pointSearch = new QLineEdit(pointPanel);
|
||||
pointSearch->setObjectName(QStringLiteral("workflowPointSearch"));
|
||||
pointSearch->setPlaceholderText(QStringLiteral("搜索点位名称或设备"));
|
||||
pointLayout->addWidget(pointSearch);
|
||||
|
||||
m_jointPointTable = new QTableWidget(0, 5, pointPanel);
|
||||
m_jointPointTable = new WorkflowPointLibrary(0, 5, pointPanel);
|
||||
m_jointPointTable->setObjectName(QStringLiteral("jointPointTable"));
|
||||
connect(pointSearch,&QLineEdit::textChanged,this,[this](const QString &text) {
|
||||
for(int row=0;row<m_jointPointTable->rowCount();++row) {
|
||||
const auto &point=m_recordedJointPoints.at(row);
|
||||
bool match=point.name.contains(text,Qt::CaseInsensitive);
|
||||
for(const auto &target:point.targets())match |= target.deviceId.contains(text,Qt::CaseInsensitive);
|
||||
m_jointPointTable->setRowHidden(row,!match);
|
||||
}
|
||||
});
|
||||
m_jointPointTable->setAlternatingRowColors(true);
|
||||
m_jointPointTable->setHorizontalHeaderLabels({
|
||||
QStringLiteral("动作名称"), QStringLiteral("机械臂"), QStringLiteral("Device ID"),
|
||||
@ -587,7 +650,19 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointPointTable->setSelectionBehavior(QAbstractItemView::SelectRows);
|
||||
m_jointPointTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
|
||||
m_jointPointTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
|
||||
m_jointPointTable->verticalHeader()->setVisible(false);
|
||||
m_jointPointTable->verticalHeader()->setVisible(true);
|
||||
m_jointPointTable->verticalHeader()->setSectionsMovable(true);
|
||||
m_jointPointTable->verticalHeader()->setToolTip(QStringLiteral("拖动左侧行号调整点位顺序"));
|
||||
m_jointPointTable->setToolTip(QStringLiteral("双击动作名称可重命名;拖动左侧行号调整顺序"));
|
||||
connect(m_jointPointTable->verticalHeader(), &QHeaderView::sectionMoved,
|
||||
this, [this](int, int from, int to) {
|
||||
// Keep the header and stored row order identical after every move.
|
||||
{
|
||||
const QSignalBlocker blocker(m_jointPointTable->verticalHeader());
|
||||
m_jointPointTable->verticalHeader()->moveSection(to, from);
|
||||
}
|
||||
moveRecordedJointPoint(from, to);
|
||||
});
|
||||
m_jointPointTable->verticalHeader()->setDefaultSectionSize(28);
|
||||
m_jointPointTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
|
||||
m_jointPointTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
|
||||
@ -595,14 +670,18 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointPointTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
|
||||
m_jointPointTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch);
|
||||
m_jointPointTable->setMinimumHeight(132);
|
||||
pointLayout->addWidget(m_jointPointTable);
|
||||
pointLayout->addWidget(m_jointPointTable, 1);
|
||||
m_jointPointTable->setColumnHidden(2,true);
|
||||
m_jointPointTable->setColumnHidden(3,true);
|
||||
m_jointPointTable->setColumnHidden(4,true);
|
||||
m_jointPointTable->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);
|
||||
m_jointPointDetailLabel = new QLabel(QStringLiteral("选择点位后查看详细关节角度"), pointPanel);
|
||||
m_jointPointDetailLabel->setObjectName(QStringLiteral("mutedLabel"));
|
||||
m_jointPointDetailLabel->setWordWrap(true);
|
||||
m_jointPointDetailLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
|
||||
pointLayout->addWidget(m_jointPointDetailLabel);
|
||||
|
||||
QHBoxLayout *pointActions = new QHBoxLayout;
|
||||
QVBoxLayout *pointActions = new QVBoxLayout;
|
||||
m_runJointPointButton = new QPushButton(QStringLiteral("执行选中点位"), pointPanel);
|
||||
m_deleteJointPointButton = new QPushButton(QStringLiteral("删除选中"), pointPanel);
|
||||
m_runJointPointButton->setObjectName(QStringLiteral("primaryButton"));
|
||||
@ -611,13 +690,42 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointPointLoopCount = new QSpinBox(pointPanel);
|
||||
m_jointPointLoopCount->setRange(1, 10000);
|
||||
m_jointPointLoopCount->setValue(1);
|
||||
m_startJointPointLoopButton = new QPushButton(QStringLiteral("执行自定义流程"), pointPanel);
|
||||
m_stopJointPointLoopButton = new QPushButton(QStringLiteral("停止循环"), pointPanel);
|
||||
m_startJointPointLoopButton = new QPushButton(QStringLiteral("运行流程"), pointPanel);
|
||||
m_stopJointPointLoopButton = new QPushButton(QStringLiteral("停止执行"), pointPanel);
|
||||
m_stopJointPointLoopButton->setEnabled(false);
|
||||
m_jointPointLoopStatus = new QLabel(QStringLiteral("未运行"), pointPanel);
|
||||
m_jointPointLoopStatus->setObjectName(QStringLiteral("mutedLabel"));
|
||||
pointActions->addWidget(m_runJointPointButton);
|
||||
pointActions->addWidget(m_deleteJointPointButton);
|
||||
auto *renamePointButton = new QPushButton(QStringLiteral("重命名点位"), pointPanel);
|
||||
renamePointButton->setObjectName(QStringLiteral("secondaryButton"));
|
||||
pointActions->addWidget(renamePointButton);
|
||||
const auto renamePoint = [this](int row) {
|
||||
if (row < 0 || row >= m_recordedJointPoints.size()) return;
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending || m_jointPointCapturePending) {
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("重命名点位"),
|
||||
QStringLiteral("请先停止执行并等待点位记录完成。"));
|
||||
return;
|
||||
}
|
||||
bool ok = false;
|
||||
const QString name = requestFlowNodeName(m_jointFlowDialog, QStringLiteral("重命名点位"),
|
||||
m_recordedJointPoints.at(row).name, &ok);
|
||||
if (!ok) return;
|
||||
QString error;
|
||||
if (!renameRecordedJointPoint(row, name, &error))
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("重命名点位"), error);
|
||||
};
|
||||
connect(renamePointButton, &QPushButton::clicked, this, [this, renamePoint] {
|
||||
const auto rows = m_jointPointTable->selectionModel()->selectedRows();
|
||||
if (rows.size() != 1) {
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("重命名点位"),
|
||||
QStringLiteral("请选择一个需要重命名的点位。"));
|
||||
return;
|
||||
}
|
||||
renamePoint(rows.first().row());
|
||||
});
|
||||
connect(m_jointPointTable, &QTableWidget::cellDoubleClicked, this,
|
||||
[renamePoint](int row, int column) { if (column == 0) renamePoint(row); });
|
||||
auto *combineButton=new QPushButton(QStringLiteral("组合选中点位"),pointPanel);
|
||||
combineButton->setToolTip(QStringLiteral("填写新名称,选择不同机械臂的已有点位,生成组合点位;保留原点位"));
|
||||
pointActions->addWidget(combineButton);
|
||||
@ -691,10 +799,12 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointFlowGroupCount->setValue(2);
|
||||
QLabel *insertionContextLabel = new QLabel(QStringLiteral("添加到:根流程(末尾)"), flowPanel);
|
||||
insertionContextLabel->setObjectName(QStringLiteral("jointFlowContextChip"));
|
||||
insertionContextLabel->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Preferred);
|
||||
insertionContextLabel->setMaximumWidth(360);
|
||||
QPushButton *insertAtRootButton = new QPushButton(
|
||||
QStringLiteral("切换到根流程末尾"), flowPanel);
|
||||
QStringLiteral("根流程"), flowPanel);
|
||||
QPushButton *enterSelectedLoopButton = new QPushButton(
|
||||
QStringLiteral("添加到选中循环"), flowPanel);
|
||||
QStringLiteral("进入所选循环"), flowPanel);
|
||||
QPushButton *addFlowStepButton = new QPushButton(QStringLiteral("+ 单步节点"), flowPanel);
|
||||
QPushButton *addFlowLoopButton = new QPushButton(QStringLiteral("+ 循环节点"), flowPanel);
|
||||
insertAtRootButton->setObjectName(QStringLiteral("secondaryButton"));
|
||||
@ -711,32 +821,91 @@ QWidget *MainWindow::createArmPage()
|
||||
flowHeader->addWidget(insertionContextLabel);
|
||||
flowLayout->addLayout(flowHeader);
|
||||
|
||||
QHBoxLayout *flowSelection = new QHBoxLayout;
|
||||
flowSelection->addWidget(new QLabel(QStringLiteral("当前流程"), flowPanel));
|
||||
m_jointProgramFlowCombo = new QComboBox(flowPanel);
|
||||
m_jointProgramFlowCombo->setObjectName(QStringLiteral("jointProgramFlowCombo"));
|
||||
m_jointProgramFlowCombo->setMinimumWidth(200);
|
||||
flowSelection->addWidget(m_jointProgramFlowCombo, 1);
|
||||
const auto editFlow = [this](bool copy, bool rename) {
|
||||
if (m_activeJointProgramGroup < 0) return;
|
||||
if (m_jointPointLoopActive || m_jointPointMovePending) {
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("管理流程"),
|
||||
QStringLiteral("请先停止当前点位或流程执行。"));
|
||||
return;
|
||||
}
|
||||
storeCurrentJointProgramGroup();
|
||||
auto &group = m_jointProgramGroups[m_activeJointProgramGroup];
|
||||
const auto nameExists = [&group](const QString &name) {
|
||||
for (const auto &flow : group.flows)
|
||||
if (flow.name.compare(name, Qt::CaseInsensitive) == 0) return true;
|
||||
return false;
|
||||
};
|
||||
const QString oldName = group.flows.at(group.activeFlow).name;
|
||||
const QString baseName = rename ? oldName : copy
|
||||
? oldName + QStringLiteral(" 副本") : QStringLiteral("新流程");
|
||||
QString suggested = baseName;
|
||||
if (!rename)
|
||||
for (int suffix = 2; nameExists(suggested); ++suffix)
|
||||
suggested = baseName + QStringLiteral(" %1").arg(suffix);
|
||||
bool ok = false;
|
||||
const QString name = requestFlowNodeName(m_jointFlowDialog,
|
||||
rename ? QStringLiteral("重命名流程") : copy ? QStringLiteral("复制流程")
|
||||
: QStringLiteral("新建流程"), suggested, &ok);
|
||||
if (!ok || name.isEmpty() || (rename && name == oldName)) return;
|
||||
if (nameExists(name)) {
|
||||
AppMessageBox::information(m_jointFlowDialog, QStringLiteral("管理流程"),
|
||||
QStringLiteral("当前组中已存在同名流程。"));
|
||||
return;
|
||||
}
|
||||
if (rename) {
|
||||
group.flows[group.activeFlow].name = name;
|
||||
refreshJointProgramFlows();
|
||||
saveJointPrograms();
|
||||
} else {
|
||||
JointProgramFlow flow = copy ? group.flows.at(group.activeFlow) : JointProgramFlow{};
|
||||
flow.name = name;
|
||||
group.flows.append(flow);
|
||||
activateJointProgramFlow(group.flows.size() - 1);
|
||||
}
|
||||
};
|
||||
for (int action = 0; action < 3; ++action) {
|
||||
auto *button = new QPushButton(action == 0 ? QStringLiteral("新建流程")
|
||||
: action == 1 ? QStringLiteral("复制流程") : QStringLiteral("重命名"), flowPanel);
|
||||
button->setObjectName(QStringLiteral("secondaryButton"));
|
||||
flowSelection->addWidget(button);
|
||||
connect(button, &QPushButton::clicked, this, [editFlow, action] {
|
||||
editFlow(action == 1, action == 2);
|
||||
});
|
||||
}
|
||||
flowLayout->addLayout(flowSelection);
|
||||
connect(m_jointProgramFlowCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
|
||||
this, &MainWindow::activateJointProgramFlow);
|
||||
|
||||
QFrame *flowToolbar = new QFrame(flowPanel);
|
||||
flowToolbar->setObjectName(QStringLiteral("jointFlowToolbar"));
|
||||
QHBoxLayout *flowBuilder = new QHBoxLayout(flowToolbar);
|
||||
flowBuilder->setContentsMargins(10, 8, 10, 8);
|
||||
flowBuilder->setSpacing(8);
|
||||
flowBuilder->addWidget(insertAtRootButton);
|
||||
flowBuilder->addWidget(enterSelectedLoopButton);
|
||||
flowBuilder->addSpacing(8);
|
||||
flowBuilder->addWidget(intervalLabel);
|
||||
flowBuilder->addWidget(m_jointPointInterval);
|
||||
flowBuilder->addWidget(addFlowStepButton);
|
||||
flowBuilder->addStretch(1);
|
||||
flowBuilder->addWidget(new QLabel(QStringLiteral("循环次数"), flowPanel));
|
||||
flowBuilder->addWidget(m_jointFlowGroupCount);
|
||||
flowBuilder->addWidget(addFlowLoopButton);
|
||||
auto *flowBuilder = new QVBoxLayout(flowToolbar);
|
||||
auto *insertionRow = new QHBoxLayout;
|
||||
insertionRow->addWidget(insertAtRootButton);insertionRow->addWidget(enterSelectedLoopButton);insertionRow->addStretch();
|
||||
auto *componentRow = new QHBoxLayout;
|
||||
componentRow->addWidget(intervalLabel);componentRow->addWidget(m_jointPointInterval);
|
||||
componentRow->addWidget(addFlowStepButton);componentRow->addStretch();
|
||||
componentRow->addWidget(new QLabel(QStringLiteral("循环次数"),flowPanel));
|
||||
componentRow->addWidget(m_jointFlowGroupCount);componentRow->addWidget(addFlowLoopButton);
|
||||
flowBuilder->addLayout(insertionRow);flowBuilder->addLayout(componentRow);
|
||||
for(int i=0;i<componentRow->count();++i)if(auto *widget=componentRow->itemAt(i)->widget())widget->hide();
|
||||
flowLayout->addWidget(flowToolbar);
|
||||
QLabel *flowHint = new QLabel(QStringLiteral(
|
||||
"未选中节点时添加到当前流程末尾;选中节点后,新节点将插入到该节点之后。"
|
||||
"选中循环并点击“添加到选中循环”可添加第一个或末尾子节点;"
|
||||
"点击“切换到根流程末尾”可退出循环并继续添加根节点。"
|
||||
"双击卡片编辑参数;左键拖动仅调整同级顺序并自动吸附,右键拖动画布。"
|
||||
"选中循环并点击“进入所选循环”可添加第一个或末尾子节点;"
|
||||
"点击“根流程”可退出循环并继续添加根节点。"
|
||||
"双击卡片编辑参数;左键自由拖动节点,连接端口确定执行顺序,右键拖动画布。"
|
||||
"循环卡片右上角可展开或收起子节点。"), flowPanel);
|
||||
flowHint->setObjectName(QStringLiteral("mutedLabel"));
|
||||
flowLayout->addWidget(flowHint);
|
||||
flowToolbar->setToolTip(flowHint->text());
|
||||
flowHint->hide();
|
||||
m_jointFlowEditor = new JointFlowEditor(flowPanel);
|
||||
flowLayout->addWidget(m_jointFlowEditor);
|
||||
flowLayout->addWidget(m_jointFlowEditor, 1);
|
||||
QHBoxLayout *flowActions = new QHBoxLayout;
|
||||
QPushButton *flowDeleteButton = new QPushButton(QStringLiteral("删除选中节点"), flowPanel);
|
||||
flowDeleteButton->setObjectName(QStringLiteral("dangerOutlineButton"));
|
||||
@ -770,14 +939,20 @@ QWidget *MainWindow::createArmPage()
|
||||
m_jointPointLoopCount->setVisible(false);
|
||||
flowActions->addWidget(m_startJointPointLoopButton);
|
||||
flowActions->addWidget(m_stopJointPointLoopButton);
|
||||
auto *motionRow = new QHBoxLayout;
|
||||
motionRow->addWidget(flowVelocityLabel);motionRow->addWidget(m_jointFlowVelocitySpin);
|
||||
motionRow->addWidget(flowAccelerationLabel);motionRow->addWidget(m_jointFlowAccelerationSpin);
|
||||
flowLayout->addLayout(motionRow);
|
||||
flowLayout->addLayout(flowActions);
|
||||
QSplitter *jointFlowSplitter = new QSplitter(Qt::Vertical, moveJPage);
|
||||
QSplitter *jointFlowSplitter = new QSplitter(Qt::Horizontal, moveJPage);
|
||||
jointFlowSplitter->setObjectName(QStringLiteral("jointFlowSplitter"));
|
||||
jointFlowSplitter->addWidget(pointPanel);
|
||||
jointFlowSplitter->addWidget(flowPanel);
|
||||
jointFlowSplitter->setStretchFactor(0, 1);
|
||||
jointFlowSplitter->setStretchFactor(1, 3);
|
||||
jointFlowSplitter->setSizes({245, 510});
|
||||
jointFlowSplitter->setSizes({320, 1120});
|
||||
jointFlowSplitter->setChildrenCollapsible(false);
|
||||
pointPanel->setMinimumWidth(280);
|
||||
moveJLayout->addWidget(jointFlowSplitter, 1);
|
||||
|
||||
connect(addFlowStepButton, &QPushButton::clicked, this, [this]() {
|
||||
@ -824,6 +999,69 @@ QWidget *MainWindow::createArmPage()
|
||||
connect(m_jointFlowEditor, &JointFlowEditor::changed, this, [this]() {
|
||||
saveJointPrograms();
|
||||
});
|
||||
auto *validatePoints = new QPushButton(QStringLiteral("校验流程"),flowPanel);
|
||||
flowActions->insertWidget(1,validatePoints);
|
||||
auto *importGraph = new QPushButton(QStringLiteral("导入工作流"),flowPanel);
|
||||
auto *exportGraph = new QPushButton(QStringLiteral("导出 am-freescan"),flowPanel);
|
||||
flowActions->insertWidget(2,importGraph);flowActions->insertWidget(3,exportGraph);
|
||||
connect(exportGraph,&QPushButton::clicked,this,[this] {
|
||||
if(m_jointPointLoopActive||m_jointPointMovePending||m_activeJointProgramGroup<0)return;
|
||||
storeCurrentJointProgramGroup();const auto &group=m_jointProgramGroups.at(m_activeJointProgramGroup);
|
||||
QJsonArray points,flows;for(const auto &point:group.points)points.append(point.toJson());
|
||||
for(const auto &flow:group.flows)flows.append(QJsonObject{{"name",flow.name},{"flow",flow.nodes},{"moveJVelocity",flow.velocity},{"moveJAcceleration",flow.acceleration}});
|
||||
QJsonObject graph;QString error;
|
||||
if(!FreeScanInterop::exportPoints(QJsonObject{{"name",group.name},{"points",points},{"flows",flows}},group.activeFlow,graph,error)) {
|
||||
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("无法导出"),error);return;
|
||||
}
|
||||
graph=WorkflowGraph::merge(graph,m_jointFlowEditor->graphState());
|
||||
const QString path=QFileDialog::getSaveFileName(m_jointFlowDialog,QStringLiteral("导出当前工作流"),"workflow.json",QStringLiteral("JSON (*.json)"));
|
||||
if(!path.isEmpty()&&!FreeScanInterop::writeGraph(path,graph,error))AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("导出失败"),error);
|
||||
});
|
||||
connect(importGraph,&QPushButton::clicked,this,[this] {
|
||||
if(m_jointPointLoopActive||m_jointPointMovePending||m_jointPointCapturePending)return;
|
||||
const QString path=QFileDialog::getOpenFileName(m_jointFlowDialog,QStringLiteral("导入 am-freescan 工作流"),{},QStringLiteral("JSON (*.json)"));if(path.isEmpty())return;
|
||||
QFile file(path);if(!file.open(QIODevice::ReadOnly)||file.size()>16*1024*1024) {
|
||||
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("无法导入"),QStringLiteral("无法读取文件,或文件超过16MB"));return;
|
||||
}
|
||||
QJsonParseError parse;const auto document=QJsonDocument::fromJson(file.readAll(),&parse);auto graph=document.object();
|
||||
if(parse.error!=QJsonParseError::NoError||!FreeScanInterop::isGraph(graph)) {
|
||||
AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("无法导入"),QStringLiteral("文件不是有效的工作流图"));return;
|
||||
}
|
||||
QStringList devices;
|
||||
for(int i=0;i<m_armSideCombo->count();++i){const auto id=m_armSideCombo->itemData(i).toString();if(!id.isEmpty()&&!devices.contains(id))devices.append(id);}
|
||||
if(!FreeScanInterop::bindGraphDevices(graph,m_jointFlowDialog,devices))return;
|
||||
QJsonObject jointNames;
|
||||
for(const auto &v:graph.value("nodes").toArray())for(const auto ¶meter:v.toObject().value("properties").toObject().value("nodeParams").toArray()) {
|
||||
if(!parameter.toObject().value("name").toString().startsWith("deviceId"))continue;
|
||||
const auto id=parameter.toObject().value("input").toString();
|
||||
auto names=m_taskOrchestration->deviceInfo(id).value("jointNames").toStringList();
|
||||
if(names.isEmpty()&&id==m_armIdEdit->text().trimmed())names=m_activeArmJointNames;
|
||||
QJsonArray values;for(const auto &name:names)values.append(name);jointNames.insert(id,values);
|
||||
}
|
||||
QString error;QJsonObject converted;
|
||||
if(!FreeScanInterop::importPoints(graph,converted,error,jointNames)) {AppMessageBox::warning(m_jointFlowDialog,QStringLiteral("无法导入"),error);return;}
|
||||
storeCurrentJointProgramGroup();JointProgramGroup group;
|
||||
const QString base=converted.value("name").toString(QStringLiteral("导入点位组"));group.name=base;
|
||||
for(int suffix=2;;++suffix) {bool used=false;for(const auto &old:m_jointProgramGroups)used |= old.name.compare(group.name,Qt::CaseInsensitive)==0;
|
||||
if(!used)break;group.name=base+QStringLiteral(" %1").arg(suffix);}
|
||||
for(const auto &v:converted.value("points").toArray())group.points.append(RecordedJointPoint::fromJson(v.toObject()));
|
||||
const auto flow=converted.value("flows").toArray().first().toObject();
|
||||
group.flow=flow.value("flow").toArray();group.moveJVelocity=flow.value("moveJVelocity").toDouble(.1);group.moveJAcceleration=flow.value("moveJAcceleration").toDouble(.1);
|
||||
group.flows.append({flow.value("name").toString(),group.flow,group.moveJVelocity,group.moveJAcceleration,graph});
|
||||
m_jointProgramGroups.append(group);const int index=m_jointProgramGroups.size()-1;
|
||||
{const QSignalBlocker blocker(m_jointProgramGroupCombo);m_jointProgramGroupCombo->addItem(group.name);m_jointProgramGroupCombo->setCurrentIndex(index);}
|
||||
activateJointProgramGroup(index);
|
||||
});
|
||||
connect(validatePoints,&QPushButton::clicked,this,[this] {
|
||||
QString error;const auto steps=m_jointFlowEditor->expandedSteps(&error);
|
||||
if(error.isEmpty() && steps.isEmpty())error=QStringLiteral("当前流程没有可执行点位。");
|
||||
for(const auto &step:steps) {
|
||||
bool found=false;for(const auto &point:m_recordedJointPoints)found |= point.name==step.pointName;
|
||||
if(!found){error=QStringLiteral("流程引用的点位“%1”不存在。").arg(step.pointName);break;}
|
||||
}
|
||||
AppMessageBox::information(m_jointFlowDialog,QStringLiteral("流程校验"),error.isEmpty()
|
||||
? QStringLiteral("校验通过,共 %1 个执行步骤;尚未调用设备。").arg(steps.size()) : error);
|
||||
});
|
||||
connect(m_jointFlowVelocitySpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
|
||||
this, [this](double) { saveJointPrograms(); });
|
||||
connect(m_jointFlowAccelerationSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
|
||||
@ -1027,7 +1265,7 @@ QWidget *MainWindow::createArmPage()
|
||||
connect(openJointFlowButton, &QPushButton::clicked, this, [this]() {
|
||||
if (!m_jointFlowDialog)
|
||||
return;
|
||||
m_jointFlowDialog->show();
|
||||
m_jointFlowDialog->showFullScreen();
|
||||
m_jointFlowDialog->raise();
|
||||
m_jointFlowDialog->activateWindow();
|
||||
});
|
||||
|
||||
@ -226,6 +226,8 @@ bool normalize(QJsonObject& root,QString& error){
|
||||
if(!ensureId(n)){error=QStringLiteral("节点/方案 id 重复");return false;}
|
||||
const QString kind=n.value("kind").toString("task");n.insert("kind",kind);
|
||||
if(kind=="loop"){
|
||||
const double wait=n.value("waitMs").toDouble(0);
|
||||
if(wait<0||wait>2147483647||std::floor(wait)!=wait){error=QStringLiteral("循环完成后等待时间无效");return false;}
|
||||
const double count=n.value("count").toDouble(-1);if(count<1||count>100000||std::floor(count)!=count||!n.value("children").isArray()){error=QStringLiteral("循环次数或子节点格式无效");return false;}
|
||||
auto children=n.value("children").toArray();qint64 size=0;if(!nodes(children,depth+1,size))return false;
|
||||
expanded+=size*qint64(count);n.insert("children",children);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -46,6 +46,7 @@ public:
|
||||
signals:
|
||||
void executionStopped();
|
||||
void cameraCapabilitiesChanged();
|
||||
void availableDevicesChanged();
|
||||
void deviceInfoChanged(const QString &deviceId);
|
||||
void deviceInfoRequested(const QString &deviceId, const QString &deviceType);
|
||||
void taskRequested(const QString &deviceType, const QString &deviceId,
|
||||
@ -69,15 +70,12 @@ private:
|
||||
void exportDocument();
|
||||
bool m_storageWritable=true;
|
||||
quint64 m_executionGeneration=0;
|
||||
void addTask(QTreeWidgetItem *parentItem = nullptr);
|
||||
void addLoop(QTreeWidgetItem *parentItem = nullptr);
|
||||
void editSelected();
|
||||
void removeSelected();
|
||||
void moveSelected(int offset);
|
||||
void startRun();
|
||||
void stopRun(const QString &reason = QString());
|
||||
void runNext();
|
||||
bool appendRunSteps(QTreeWidgetItem *item, QList<RunStep> &steps, QString *error, int depth = 0) const;
|
||||
bool appendCompiledSteps(const QJsonArray &nodes, QList<RunStep> &steps,
|
||||
QString *error, int depth = 0) const;
|
||||
void load();
|
||||
void save();
|
||||
void storeCurrentGroup();
|
||||
@ -91,6 +89,8 @@ private:
|
||||
bool useSelectedLoopAsInsertionParent();
|
||||
void insertNode(QTreeWidgetItem *item);
|
||||
void updateInsertionHint();
|
||||
bool syncGraph(QString &error);
|
||||
bool restoreGraph(const QJsonObject &graph, QString &error);
|
||||
|
||||
QComboBox *m_groupCombo = nullptr;
|
||||
QTreeWidget *m_tree = nullptr;
|
||||
@ -107,6 +107,7 @@ private:
|
||||
QList<QWidget *> m_editControls;
|
||||
QTimer *m_runTimer = nullptr;
|
||||
QList<QJsonObject> m_groups;
|
||||
QJsonObject m_graph;
|
||||
QList<RunStep> m_runSteps;
|
||||
int m_activeGroup = -1;
|
||||
int m_runIndex = 0;
|
||||
|
||||
276
src/workflowcanvas.h
Normal file
276
src/workflowcanvas.h
Normal file
@ -0,0 +1,276 @@
|
||||
#pragma once
|
||||
#include <QtWidgets>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
|
||||
inline void workflowContainers(QGraphicsScene *scene,const QJsonObject &graph,const QHash<QString,QRectF> &bounds) {
|
||||
QHash<QString,QString> parents;
|
||||
for(const auto &v:graph.value("nodes").toArray()){const auto n=v.toObject();parents[n.value("id").toString()]=n.value("properties").toObject().value("parentId").toString();}
|
||||
for(const auto &v:graph.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();const QString id=n.value("id").toString();if(n.value("type")!="loop"||!bounds.contains(id)||n.value("properties").toObject().value("collapsed").toBool())continue;
|
||||
QRectF rect=bounds[id];
|
||||
for(auto it=bounds.begin();it!=bounds.end();++it){QString parent=parents.value(it.key());QSet<QString> seen;
|
||||
while(!parent.isEmpty()&&!seen.contains(parent)){seen.insert(parent);if(parent==id){rect=rect.united(it.value());break;}parent=parents.value(parent);}}
|
||||
QPainterPath path;path.addRoundedRect(rect.adjusted(-26,-26,26,26),16,16);
|
||||
auto *frame=scene->addPath(path,QPen(QColor("#a8bddb"),1.4,Qt::DashLine),QBrush(QColor(223,234,249,65)));
|
||||
frame->setZValue(-3);frame->setData(7010,id);frame->setData(7011,QStringLiteral("loop"));
|
||||
frame->setToolTip(QStringLiteral("循环容器:将组件拖到内部添加;拖动循环标题可移动整个容器"));
|
||||
}
|
||||
}
|
||||
|
||||
inline QGraphicsPathItem *workflowWire(QGraphicsScene *scene, const QPointF &from,
|
||||
const QPointF &to, bool membership=false,
|
||||
const QString &source={},const QString &target={}) {
|
||||
QPainterPath path(from);
|
||||
if(membership) path.cubicTo(from+QPointF(0,45),to-QPointF(0,45),to);
|
||||
else {
|
||||
const qreal dx=qMax(qreal(24),qAbs(to.x()-from.x())/2);
|
||||
path.cubicTo(from+QPointF(dx,0),to-QPointF(dx,0),to);
|
||||
}
|
||||
const QColor color(membership ? "#9aabc0" : "#5a91cf");
|
||||
auto *edge=scene->addPath(path,QPen(color,1.7));edge->setZValue(-1);
|
||||
if(!source.isEmpty()) {
|
||||
edge->setFlag(QGraphicsItem::ItemIsSelectable,true);
|
||||
edge->setData(7000,QStringLiteral("wire"));edge->setData(7001,source);edge->setData(7002,target);
|
||||
edge->setToolTip(QStringLiteral("选中连线后按 Delete 删除,可重新连接"));
|
||||
}
|
||||
const QPolygonF arrow=membership
|
||||
? QPolygonF() << to << to+QPointF(-4,-7) << to+QPointF(4,-7)
|
||||
: QPolygonF() << to << to+QPointF(-7,-4) << to+QPointF(-7,4);
|
||||
scene->addPolygon(arrow,QPen(color),QBrush(color))->setZValue(-1);
|
||||
return edge;
|
||||
}
|
||||
inline void workflowPorts(QGraphicsItem *card,const QString &id,bool input=true,bool output=true) {
|
||||
const auto bounds=card->boundingRect();
|
||||
for(bool out:{false,true}) {
|
||||
if((out&&!output)||(!out&&!input))continue;
|
||||
auto *port=new QGraphicsEllipseItem(-6,-6,12,12,card);
|
||||
port->setPos(out?bounds.right():bounds.left(),bounds.center().y());
|
||||
port->setPen(QPen(QColor("#3478e5"),1.6));port->setBrush(Qt::white);port->setZValue(8);
|
||||
port->setData(7000,out?QStringLiteral("output"):QStringLiteral("input"));port->setData(7001,id);
|
||||
port->setToolTip(out?QStringLiteral("拖动到下一节点的输入端,建立执行连线"):QStringLiteral("节点输入端"));
|
||||
}
|
||||
}
|
||||
class WorkflowTerminal final : public QGraphicsEllipseItem {
|
||||
public:
|
||||
std::function<void(const QPointF &)> moved;
|
||||
WorkflowTerminal():QGraphicsEllipseItem(0,0,90,42) {
|
||||
setPen(QPen(QColor("#91a9c7"),1.5));setBrush(QColor("#edf4ff"));
|
||||
setFlags(ItemIsSelectable|ItemIsMovable);
|
||||
}
|
||||
protected:
|
||||
void mousePressEvent(QGraphicsSceneMouseEvent *event) override { m_start=pos();QGraphicsEllipseItem::mousePressEvent(event); }
|
||||
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override {
|
||||
QGraphicsEllipseItem::mouseReleaseEvent(event);if(pos()!=m_start&&moved)moved(pos()+QPointF(45,21));
|
||||
}
|
||||
private: QPointF m_start;
|
||||
};
|
||||
inline WorkflowTerminal *workflowTerminal(QGraphicsScene *scene,const QString &id,const QString &type,
|
||||
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));
|
||||
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);
|
||||
workflowPorts(item,id,!start,start||type=="sleep");return item;
|
||||
}
|
||||
|
||||
// Native Qt counterpart of the reference designer's shared canvas controls.
|
||||
class WorkflowCanvas : public QGraphicsView {
|
||||
public:
|
||||
std::function<void(const QString &)> componentDropped;
|
||||
std::function<bool(const QString &,const QString &,QString &)> connectionRequested;
|
||||
std::function<void(const QString &,const QString &)> connectionRemoved;
|
||||
std::function<QJsonObject(const QSet<QString> &)> copyNodes;
|
||||
std::function<bool(const QJsonObject &,const QPointF &)> pasteNodes;
|
||||
QPointF dropPosition;
|
||||
QString dropContainer;
|
||||
bool droppingFromPalette=false;
|
||||
explicit WorkflowCanvas(QGraphicsScene *scene, QWidget *parent = nullptr)
|
||||
: QGraphicsView(scene, parent) {
|
||||
setAcceptDrops(true);
|
||||
setRenderHint(QPainter::Antialiasing);
|
||||
// Moving cards and their child ports span several dirty regions. Repaint
|
||||
// the viewport as one frame so rapid moves cannot leave clipped fragments.
|
||||
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
|
||||
setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing, false);
|
||||
setAlignment(Qt::AlignLeft | Qt::AlignTop);
|
||||
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
|
||||
setTransformationAnchor(AnchorUnderMouse);
|
||||
setResizeAnchor(NoAnchor);
|
||||
setDragMode(RubberBandDrag);
|
||||
}
|
||||
void syncExtent() {
|
||||
const QPointF center = mapToScene(viewport()->rect().center());
|
||||
setSceneRect(scene()->itemsBoundingRect().adjusted(-1000, -1000, 1000, 1000));
|
||||
centerOn(center);
|
||||
}
|
||||
void zoomBy(qreal factor) {
|
||||
const qreal next = qBound(.02, transform().m11() * factor, 3.0);
|
||||
scale(next / transform().m11(), next / transform().m11());
|
||||
}
|
||||
void resetView() {
|
||||
resetTransform();
|
||||
centerOn(scene()->itemsBoundingRect().topLeft() + QPointF(viewport()->width()/2.-24, viewport()->height()/2.-24));
|
||||
}
|
||||
void fitAll() {
|
||||
if (scene()->items().isEmpty()) resetView();
|
||||
else fitInView(scene()->itemsBoundingRect().adjusted(-30,-30,30,30), Qt::KeepAspectRatio);
|
||||
}
|
||||
QWidget *tools(QWidget *parent) {
|
||||
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();
|
||||
for (int i=0;i<4;++i) {
|
||||
auto *button = new QPushButton(QStringList{QStringLiteral("-"),QStringLiteral("+"),QStringLiteral("回到起点"),QStringLiteral("显示全部")}[i],bar);
|
||||
button->setObjectName("secondaryButton"); layout->addWidget(button);
|
||||
QObject::connect(button,&QPushButton::clicked,this,[this,i]{
|
||||
if(i==0) zoomBy(1/1.2); else if(i==1) zoomBy(1.2); else if(i==2) resetView(); else fitAll();
|
||||
});
|
||||
}
|
||||
return bar;
|
||||
}
|
||||
protected:
|
||||
void showEvent(QShowEvent *event) override {
|
||||
QGraphicsView::showEvent(event);
|
||||
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"));
|
||||
if(transform().m11()<.3) return;
|
||||
painter->setPen(QPen(QColor("#d9dee8"),0));
|
||||
const int gap=24;
|
||||
for(qreal x=std::floor(rect.left()/gap)*gap;x<rect.right();x+=gap)
|
||||
for(qreal y=std::floor(rect.top()/gap)*gap;y<rect.bottom();y+=gap) painter->drawPoint(QPointF(x,y));
|
||||
}
|
||||
void mousePressEvent(QMouseEvent *event) override {
|
||||
auto *item=itemAt(event->pos());
|
||||
if(item&&item->parentItem()&&item->data(7000).isNull())item=item->parentItem();
|
||||
if(isInteractive()&&connectionRequested&&event->button()==Qt::LeftButton&&item&&item->data(7000)=="output") {
|
||||
m_connecting=item->data(7001).toString();m_wireStart=item->sceneBoundingRect().center();
|
||||
m_preview=scene()->addPath(QPainterPath(m_wireStart),QPen(QColor("#3478e5"),2,Qt::DashLine));
|
||||
m_preview->setZValue(20);event->accept();return;
|
||||
}
|
||||
if(event->button()==Qt::RightButton || event->button()==Qt::MiddleButton
|
||||
|| (event->button()==Qt::LeftButton && !(event->modifiers()&Qt::ControlModifier)
|
||||
&& (!item || !(item->flags()&QGraphicsItem::ItemIsSelectable)))) {
|
||||
m_panning=true;m_last=event->pos();viewport()->setCursor(Qt::ClosedHandCursor);event->accept();return;
|
||||
}
|
||||
QGraphicsView::mousePressEvent(event);
|
||||
}
|
||||
void mouseMoveEvent(QMouseEvent *event) override {
|
||||
if(m_preview) {
|
||||
QPainterPath path(m_wireStart);const auto target=mapToScene(event->pos());
|
||||
path.cubicTo(m_wireStart+QPointF(80,0),target-QPointF(80,0),target);m_preview->setPath(path);event->accept();return;
|
||||
}
|
||||
if(m_panning){const auto delta=event->pos()-m_last;m_last=event->pos();
|
||||
horizontalScrollBar()->setValue(horizontalScrollBar()->value()-delta.x());
|
||||
verticalScrollBar()->setValue(verticalScrollBar()->value()-delta.y());event->accept();return;}
|
||||
QGraphicsView::mouseMoveEvent(event);
|
||||
}
|
||||
void mouseReleaseEvent(QMouseEvent *event) override {
|
||||
if(m_preview) {
|
||||
const QString source=m_connecting;delete m_preview;m_preview=nullptr;m_connecting.clear();
|
||||
auto *item=itemAt(event->pos());const QString target=item&&item->data(7000)=="input"?item->data(7001).toString():QString();
|
||||
if(!target.isEmpty()) {
|
||||
QString error;if(!connectionRequested(source,target,error)&&!error.isEmpty())QToolTip::showText(event->globalPos(),error,viewport());
|
||||
}event->accept();return;
|
||||
}
|
||||
if(m_panning){m_panning=false;viewport()->unsetCursor();event->accept();return;}
|
||||
QGraphicsView::mouseReleaseEvent(event);
|
||||
viewport()->update();
|
||||
}
|
||||
void wheelEvent(QWheelEvent *event) override {
|
||||
if(event->modifiers()&Qt::ControlModifier){zoomBy(std::pow(1.0015,event->angleDelta().y()));event->accept();return;}
|
||||
QGraphicsView::wheelEvent(event);
|
||||
}
|
||||
void keyPressEvent(QKeyEvent *event) override {
|
||||
if(event->matches(QKeySequence::Copy)&©Nodes) {
|
||||
QSet<QString> ids;
|
||||
for(auto *item:scene()->selectedItems()) {
|
||||
const QString id=item->data(7010).toString();
|
||||
if(!id.isEmpty())ids.insert(id);
|
||||
}
|
||||
const auto data=copyNodes(ids);
|
||||
if(!data.isEmpty()) {
|
||||
auto *mime=new QMimeData;
|
||||
mime->setData("application/x-cmvr-workflow-nodes",QJsonDocument(data).toJson(QJsonDocument::Compact));
|
||||
QApplication::clipboard()->setMimeData(mime);
|
||||
m_pasteCount=0;
|
||||
}
|
||||
event->accept();return;
|
||||
}
|
||||
if(event->matches(QKeySequence::Paste)&&pasteNodes&&isInteractive()) {
|
||||
const auto *mime=QApplication::clipboard()->mimeData();
|
||||
if(mime->hasFormat("application/x-cmvr-workflow-nodes")) {
|
||||
const auto data=QJsonDocument::fromJson(mime->data("application/x-cmvr-workflow-nodes")).object();
|
||||
if(pasteNodes(data,QPointF(40,40)*(m_pasteCount+1)))++m_pasteCount;
|
||||
}
|
||||
event->accept();return;
|
||||
}
|
||||
if(isInteractive()&&connectionRemoved&&(event->key()==Qt::Key_Delete||event->key()==Qt::Key_Backspace)) {
|
||||
QString from,to;for(auto *item:scene()->selectedItems())if(item->data(7000)=="wire") {
|
||||
from=item->data(7001).toString();to=item->data(7002).toString();break;
|
||||
}
|
||||
if(!from.isEmpty()){connectionRemoved(from,to);event->accept();return;}
|
||||
}
|
||||
QGraphicsView::keyPressEvent(event);
|
||||
}
|
||||
void dragEnterEvent(QDragEnterEvent *event) override {
|
||||
if(componentDropped && event->mimeData()->hasFormat("application/x-cmvr-workflow-component")) event->acceptProposedAction();
|
||||
else QGraphicsView::dragEnterEvent(event);
|
||||
}
|
||||
void dragMoveEvent(QDragMoveEvent *event) override {
|
||||
if(componentDropped && event->mimeData()->hasFormat("application/x-cmvr-workflow-component")) event->acceptProposedAction();
|
||||
else QGraphicsView::dragMoveEvent(event);
|
||||
}
|
||||
void dropEvent(QDropEvent *event) override {
|
||||
if(componentDropped && event->mimeData()->hasFormat("application/x-cmvr-workflow-component")) {
|
||||
const auto key=QString::fromUtf8(event->mimeData()->data("application/x-cmvr-workflow-component"));
|
||||
dropPosition=mapToScene(event->pos());dropContainer.clear();
|
||||
auto *target=itemAt(event->pos());
|
||||
while(target) {
|
||||
if(target->data(7011)=="loop"){dropContainer=target->data(7010).toString();break;}
|
||||
target=target->parentItem();
|
||||
}
|
||||
event->acceptProposedAction();droppingFromPalette=true;componentDropped(key);droppingFromPalette=false;return;
|
||||
}
|
||||
QGraphicsView::dropEvent(event);
|
||||
}
|
||||
private:
|
||||
int m_pasteCount=0;
|
||||
bool m_firstShow=true,m_panning=false; QPoint m_last;
|
||||
QString m_connecting;QPointF m_wireStart;QGraphicsPathItem *m_preview=nullptr;
|
||||
};
|
||||
|
||||
class WorkflowLibrary : public QTreeWidget {
|
||||
public:
|
||||
explicit WorkflowLibrary(QWidget *parent=nullptr):QTreeWidget(parent){setHeaderHidden(true);setDragEnabled(true);setMinimumWidth(180);}
|
||||
protected:
|
||||
void startDrag(Qt::DropActions) override {
|
||||
if(!currentItem() || currentItem()->data(0,Qt::UserRole).toString().isEmpty())return;
|
||||
auto *drag=new QDrag(this);auto *mime=new QMimeData;
|
||||
mime->setData("application/x-cmvr-workflow-component",currentItem()->data(0,Qt::UserRole).toString().toUtf8());
|
||||
drag->setMimeData(mime);drag->exec(Qt::CopyAction);
|
||||
}
|
||||
};
|
||||
|
||||
class WorkflowPointLibrary : public QTableWidget {
|
||||
public:
|
||||
WorkflowPointLibrary(int rows,int columns,QWidget *parent):QTableWidget(rows,columns,parent) {
|
||||
setDragEnabled(true);setDragDropMode(QAbstractItemView::DragOnly);
|
||||
}
|
||||
protected:
|
||||
void startDrag(Qt::DropActions) override {
|
||||
if(currentRow()<0 || !item(currentRow(),0))return;
|
||||
auto *drag=new QDrag(this);auto *mime=new QMimeData;
|
||||
mime->setData("application/x-cmvr-workflow-component",("point:"+item(currentRow(),0)->text()).toUtf8());
|
||||
drag->setMimeData(mime);drag->exec(Qt::CopyAction);
|
||||
}
|
||||
};
|
||||
354
src/workflowgraph.h
Normal file
354
src/workflowgraph.h
Normal file
@ -0,0 +1,354 @@
|
||||
#pragma once
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QSet>
|
||||
#include <QHash>
|
||||
#include <QStringList>
|
||||
#include <QPointF>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <QUuid>
|
||||
namespace WorkflowGraph {
|
||||
// Copy a closed selection, including descendants of selected loop containers.
|
||||
// External edges and root terminals never become part of the clipboard.
|
||||
inline QJsonObject fragment(const QJsonObject &graph,QSet<QString> ids) {
|
||||
bool added=true;
|
||||
while(added) {
|
||||
added=false;
|
||||
for(const auto &v:graph.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();const QString id=n.value("id").toString();
|
||||
if(!ids.contains(id)&&ids.contains(n.value("properties").toObject().value("parentId").toString())) {
|
||||
ids.insert(id);added=true;
|
||||
}
|
||||
}
|
||||
}
|
||||
QJsonArray nodes,edges;QSet<QString> included;
|
||||
for(const auto &v:graph.value("nodes").toArray()) {
|
||||
auto n=v.toObject();const QString id=n.value("id").toString(),type=n.value("type").toString();
|
||||
if(!ids.contains(id)||type=="start"||type=="end")continue;
|
||||
const auto parent=n.value("properties").toObject().value("parentId").toString();
|
||||
if((type=="subStart"||type=="subEnd")&&!ids.contains(parent))continue;
|
||||
auto p=n.value("properties").toObject();
|
||||
if(!ids.contains(parent))p.remove("parentId");
|
||||
if(!ids.contains(p.value("cmvrAfterNodeId").toString()))p.remove("cmvrAfterNodeId");
|
||||
n.insert("properties",p);nodes.append(n);included.insert(id);
|
||||
}
|
||||
for(const auto &v:graph.value("edges").toArray()) {
|
||||
const auto e=v.toObject();
|
||||
if(included.contains(e.value("sourceNodeId").toString())&&included.contains(e.value("targetNodeId").toString()))edges.append(e);
|
||||
}
|
||||
return QJsonObject{{"nodes",nodes},{"edges",edges}};
|
||||
}
|
||||
inline QJsonObject node(const QJsonObject &graph,const QString &id) {
|
||||
for(const auto &v:graph.value("nodes").toArray())if(v.toObject().value("id")==id)return v.toObject();
|
||||
return {};
|
||||
}
|
||||
inline void position(QJsonObject &graph,const QString &id,const QPointF ¢er) {
|
||||
const auto original=node(graph,id);const QPointF delta=center-QPointF(original.value("x").toDouble(),original.value("y").toDouble());
|
||||
QSet<QString> moving{id};bool again=true;
|
||||
while(again){again=false;for(const auto &v:graph.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();const auto child=n.value("id").toString();
|
||||
if(!moving.contains(child)&&moving.contains(n.value("properties").toObject().value("parentId").toString())){moving.insert(child);again=true;}
|
||||
}}
|
||||
auto nodes=graph.value("nodes").toArray();
|
||||
for(int i=0;i<nodes.size();++i)if(moving.contains(nodes[i].toObject().value("id").toString())) {
|
||||
auto n=nodes[i].toObject();n.insert("x",n.value("x").toDouble()+delta.x());n.insert("y",n.value("y").toDouble()+delta.y());nodes[i]=n;
|
||||
}
|
||||
graph.insert("nodes",nodes);
|
||||
}
|
||||
inline QJsonObject remap(QJsonObject graph,QHash<QString,QString> ids) {
|
||||
auto nodes=graph.value("nodes").toArray();for(const auto &v:nodes) {
|
||||
const auto id=v.toObject().value("id").toString();if(!ids.contains(id))ids[id]=QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
}
|
||||
for(int i=0;i<nodes.size();++i) {
|
||||
auto n=nodes[i].toObject();n.insert("id",ids.value(n.value("id").toString()));
|
||||
auto p=n.value("properties").toObject();for(const auto &key:{QStringLiteral("parentId"),QStringLiteral("cmvrAfterNodeId")})
|
||||
if(ids.contains(p.value(key).toString()))p.insert(key,ids[p.value(key).toString()]);
|
||||
n.insert("properties",p);auto children=n.value("children").toArray();for(int j=0;j<children.size();++j)children[j]=ids.value(children[j].toString());
|
||||
if(n.contains("children"))n.insert("children",children);nodes[i]=n;
|
||||
}
|
||||
auto edges=graph.value("edges").toArray();for(int i=0;i<edges.size();++i) {
|
||||
auto e=edges[i].toObject();const auto from=ids.value(e.value("sourceNodeId").toString()),to=ids.value(e.value("targetNodeId").toString());
|
||||
e.insert("id",from+"__"+to);e.insert("sourceNodeId",from);e.insert("targetNodeId",to);
|
||||
e.insert("sourceAnchorId",from+"_1");e.insert("targetAnchorId",to+"_3");edges[i]=e;
|
||||
}
|
||||
graph.insert("nodes",nodes);graph.insert("edges",edges);return graph;
|
||||
}
|
||||
inline QJsonObject cloneFragment(const QJsonObject &fragment,const QPointF &offset,QHash<QString,QString> &ids) {
|
||||
for(const auto &v:fragment.value("nodes").toArray())
|
||||
ids[v.toObject().value("id").toString()]=QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
auto result=remap(fragment,ids);auto nodes=result.value("nodes").toArray();
|
||||
for(int i=0;i<nodes.size();++i) {
|
||||
auto n=nodes[i].toObject();
|
||||
n.insert("x",n.value("x").toDouble()+offset.x());n.insert("y",n.value("y").toDouble()+offset.y());nodes[i]=n;
|
||||
}
|
||||
result.insert("nodes",nodes);return result;
|
||||
}
|
||||
inline QJsonObject appendFragment(QJsonObject graph,const QJsonObject &fragment) {
|
||||
auto nodes=graph.value("nodes").toArray(),edges=graph.value("edges").toArray();
|
||||
for(const auto &n:fragment.value("nodes").toArray())nodes.append(n);
|
||||
for(const auto &e:fragment.value("edges").toArray())edges.append(e);
|
||||
graph.insert("nodes",nodes);graph.insert("edges",edges);return graph;
|
||||
}
|
||||
inline QJsonObject merge(QJsonObject fresh,const QJsonObject &previous) {
|
||||
if(previous.isEmpty())return fresh;
|
||||
QHash<QString,QString> aliases;
|
||||
for(const auto &v:fresh.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();const QString type=n.value("type").toString();
|
||||
const QString parent=n.value("properties").toObject().value("parentId").toString();
|
||||
if(type=="start"||type=="end"||type=="subStart"||type=="subEnd") {
|
||||
for(const auto &oldValue:previous.value("nodes").toArray()) {
|
||||
const auto old=oldValue.toObject();
|
||||
if(old.value("type")==type&&old.value("properties").toObject().value("parentId").toString()==parent)
|
||||
aliases[n.value("id").toString()]=old.value("id").toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!aliases.isEmpty()) {
|
||||
auto renamed=fresh.value("nodes").toArray();
|
||||
for(int i=0;i<renamed.size();++i) {
|
||||
auto n=renamed[i].toObject();const auto id=n.value("id").toString();
|
||||
if(aliases.contains(id))n.insert("id",aliases[id]);
|
||||
auto children=n.value("children").toArray();
|
||||
for(int j=0;j<children.size();++j)if(aliases.contains(children[j].toString()))children[j]=aliases[children[j].toString()];
|
||||
if(n.contains("children"))n.insert("children",children);renamed[i]=n;
|
||||
}
|
||||
auto edges=fresh.value("edges").toArray();
|
||||
for(int i=0;i<edges.size();++i) {
|
||||
auto e=edges[i].toObject();for(const auto &key:{QStringLiteral("sourceNodeId"),QStringLiteral("targetNodeId")})
|
||||
if(aliases.contains(e.value(key).toString()))e.insert(key,aliases[e.value(key).toString()]);
|
||||
e.insert("sourceAnchorId",e.value("sourceNodeId").toString()+"_1");e.insert("targetAnchorId",e.value("targetNodeId").toString()+"_3");
|
||||
e.insert("id",e.value("sourceNodeId").toString()+"__"+e.value("targetNodeId").toString());edges[i]=e;
|
||||
}
|
||||
fresh.insert("nodes",renamed);fresh.insert("edges",edges);
|
||||
}
|
||||
QSet<QString> oldIds,newIds;QJsonArray nodes;
|
||||
for(const auto &v:previous.value("nodes").toArray())oldIds.insert(v.toObject().value("id").toString());
|
||||
for(const auto &v:fresh.value("nodes").toArray()) {
|
||||
auto n=v.toObject();const QString id=n.value("id").toString();const auto old=node(previous,id);
|
||||
if(n.value("type")=="sleep") {
|
||||
if(!old.isEmpty())n=old;
|
||||
else if(oldIds.contains(n.value("properties").toObject().value("cmvrAfterNodeId").toString()))continue;
|
||||
}else if(!old.isEmpty()) {
|
||||
auto properties=old.value("properties").toObject();const auto update=n.value("properties").toObject();
|
||||
const auto type=n.value("type").toString();
|
||||
const bool terminal=type=="start"||type=="end"||type=="subStart"||type=="subEnd";
|
||||
for(auto it=update.begin();it!=update.end();++it) {
|
||||
if(terminal&&it.key()!="cmvrInterop"&&it.key()!="schemaVersion")continue;
|
||||
if(it.key()=="executionTarget"&&properties.contains("executionTarget"))continue;
|
||||
properties.insert(it.key(),it.value());
|
||||
}
|
||||
n.insert("properties",properties);
|
||||
}
|
||||
if(!old.isEmpty()&&old.value("x").isDouble()&&old.value("y").isDouble()) {
|
||||
n.insert("x",old.value("x"));n.insert("y",old.value("y"));
|
||||
}
|
||||
nodes.append(n);newIds.insert(id);
|
||||
}
|
||||
for(const auto &v:previous.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();const auto parent=n.value("properties").toObject().value("parentId").toString();
|
||||
if(n.value("type")=="sleep"&&!newIds.contains(n.value("id").toString())&&(parent.isEmpty()||newIds.contains(parent))) {
|
||||
nodes.append(n);newIds.insert(n.value("id").toString());
|
||||
}
|
||||
}
|
||||
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("type")=="loop") {
|
||||
auto n=nodes[i].toObject();QJsonArray children;
|
||||
for(const auto &child:nodes)if(child.toObject().value("properties").toObject().value("parentId")==n.value("id"))children.append(child.toObject().value("id"));
|
||||
n.insert("children",children);nodes[i]=n;
|
||||
}
|
||||
QHash<QString,QSet<QString>> usedSlots;
|
||||
for(const auto &v:nodes) {
|
||||
const auto target=v.toObject().value("properties").toObject().value("executionTarget").toObject();
|
||||
const auto role=target.value("roleKey").toString();if(role.isEmpty())continue;
|
||||
usedSlots[role].insert(target.value("deviceSlotKey").toString());
|
||||
for(const auto &b:target.value("deviceBindings").toArray())usedSlots[role].insert(b.toObject().value("slotKey").toString());
|
||||
}
|
||||
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("type")=="start") {
|
||||
auto n=nodes[i].toObject(),p=n.value("properties").toObject();auto roles=p.value("resourceRoles").toArray();
|
||||
const auto freshRoles=node(fresh,n.value("id").toString()).value("properties").toObject().value("resourceRoles").toArray();
|
||||
for(const auto &roleValue:freshRoles) {
|
||||
auto role=roleValue.toObject();const auto key=role.value("roleKey").toString();if(!usedSlots.contains(key))continue;
|
||||
int existing=-1;for(int j=0;j<roles.size();++j)if(roles[j].toObject().value("roleKey")==key)existing=j;
|
||||
auto existingRole=existing<0?role:roles[existing].toObject();auto deviceSlots=existingRole.value("deviceSlots").toArray();
|
||||
for(const auto &slot:role.value("deviceSlots").toArray()) {
|
||||
const auto slotKey=slot.toObject().value("slotKey").toString();if(!usedSlots[key].contains(slotKey))continue;
|
||||
bool found=false;for(const auto &oldSlot:deviceSlots)found|=oldSlot.toObject().value("slotKey")==slotKey;
|
||||
if(!found)deviceSlots.append(slot);
|
||||
}
|
||||
existingRole.insert("deviceSlots",deviceSlots);if(existing<0)roles.append(existingRole);else roles[existing]=existingRole;
|
||||
}
|
||||
p.insert("resourceRoles",roles);n.insert("properties",p);nodes[i]=n;
|
||||
}
|
||||
QJsonArray edges;
|
||||
for(const auto &v:previous.value("edges").toArray()) {
|
||||
const auto e=v.toObject();
|
||||
if(newIds.contains(e.value("sourceNodeId").toString())&&newIds.contains(e.value("targetNodeId").toString()))edges.append(e);
|
||||
}
|
||||
// New loop containers own their internal start/end path; new operations stay unconnected.
|
||||
for(const auto &v:fresh.value("edges").toArray()) {
|
||||
const auto e=v.toObject();const QString from=e.value("sourceNodeId").toString(),to=e.value("targetNodeId").toString();
|
||||
const auto parent=node(fresh,from).value("properties").toObject().value("parentId").toString();
|
||||
if(!oldIds.contains(from)&&!oldIds.contains(to)&&newIds.contains(from)&&newIds.contains(to)
|
||||
&& ((!parent.isEmpty()&&!oldIds.contains(parent))||node(fresh,to).value("properties").toObject().value("cmvrAfterNodeId")==from))edges.append(e);
|
||||
}
|
||||
fresh.insert("nodes",nodes);fresh.insert("edges",edges);return fresh;
|
||||
}
|
||||
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")) {
|
||||
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<QString> 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;
|
||||
}
|
||||
edges.append(QJsonObject{{"id",from+"__"+to},{"type","bezier"},{"sourceNodeId",from},{"targetNodeId",to},
|
||||
{"sourceAnchorId",from+"_1"},{"targetAnchorId",to+"_3"},{"properties",QJsonObject{}}});
|
||||
graph.insert("edges",edges);return true;
|
||||
}
|
||||
inline void disconnect(QJsonObject &graph,const QString &from,const QString &to) {
|
||||
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);
|
||||
}graph.insert("edges",edges);
|
||||
}
|
||||
inline void replaceNode(QJsonObject &graph,const QJsonObject &value) {
|
||||
auto nodes=graph.value("nodes").toArray();bool replaced=false;
|
||||
for(int i=0;i<nodes.size();++i)if(nodes[i].toObject().value("id")==value.value("id")){nodes[i]=value;replaced=true;break;}
|
||||
if(!replaced)nodes.append(value);graph.insert("nodes",nodes);
|
||||
}
|
||||
inline int delay(const QJsonObject &value) {
|
||||
for(const auto &v:value.value("properties").toObject().value("nodeParams").toArray()) {
|
||||
const auto p=v.toObject();if(p.value("name")=="delayMs") {
|
||||
const auto input=p.value("input");return input.isString()?input.toString().toInt():input.toInt();
|
||||
}
|
||||
}return 0;
|
||||
}
|
||||
inline void editDelay(QJsonObject &graph,const QString &id,const QString &name,int milliseconds) {
|
||||
auto n=node(graph,id),p=n.value("properties").toObject();p.insert("name",name);
|
||||
p.insert("nodeParams",QJsonArray{QJsonObject{{"name","delayMs"},{"type","input"},{"input",milliseconds},{"quote",QJsonArray{}}}});
|
||||
n.insert("properties",p);replaceNode(graph,n);
|
||||
}
|
||||
inline QString addSleep(QJsonObject &graph,const QString &parent,const QPointF ¢er) {
|
||||
const auto id=QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
QJsonObject p{{"name",QStringLiteral("等待")},{"action","SLEEP"}};if(!parent.isEmpty())p.insert("parentId",parent);
|
||||
replaceNode(graph,QJsonObject{{"id",id},{"type","sleep"},{"x",center.x()},{"y",center.y()},{"properties",p}});
|
||||
editDelay(graph,id,QStringLiteral("等待"),1000);return id;
|
||||
}
|
||||
inline void removeNode(QJsonObject &graph,const QString &id) {
|
||||
QSet<QString> removed{id};bool again=true;
|
||||
while(again){again=false;for(const auto &v:graph.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();if(removed.contains(n.value("properties").toObject().value("parentId").toString())&&!removed.contains(n.value("id").toString())){removed.insert(n.value("id").toString());again=true;}
|
||||
}}
|
||||
QJsonArray nodes,edges;
|
||||
for(const auto &v:graph.value("nodes").toArray())if(!removed.contains(v.toObject().value("id").toString()))nodes.append(v);
|
||||
for(const auto &v:graph.value("edges").toArray()) {
|
||||
const auto e=v.toObject();if(!removed.contains(e.value("sourceNodeId").toString())&&!removed.contains(e.value("targetNodeId").toString()))edges.append(e);
|
||||
}
|
||||
graph.insert("nodes",nodes);graph.insert("edges",edges);
|
||||
}
|
||||
inline int postWait(const QJsonObject &graph,const QString &source) {
|
||||
QString cursor=source;QSet<QString> 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) {
|
||||
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<QString> 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;
|
||||
}
|
||||
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;
|
||||
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"},
|
||||
{"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<QString,QStringList> order(const QJsonObject &graph,QString &error) {
|
||||
QHash<QString,QJsonObject> nodes;QHash<QString,QString> parent,next,previous;QSet<QString> seen;
|
||||
QHash<QString,QStringList> result;
|
||||
const auto fail=[&](const QString &message){if(error.isEmpty())error=message;};
|
||||
for(const auto &v:graph.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();const auto id=n.value("id").toString();
|
||||
if(id.isEmpty()||nodes.contains(id)){fail(QStringLiteral("节点ID为空或重复"));return {};}
|
||||
nodes[id]=n;parent[id]=n.value("properties").toObject().value("parentId").toString();
|
||||
}
|
||||
for(const auto &v:graph.value("edges").toArray()) {
|
||||
const auto e=v.toObject();const auto from=e.value("sourceNodeId").toString(),to=e.value("targetNodeId").toString();
|
||||
if(!nodes.contains(from)||!nodes.contains(to)||parent[from]!=parent[to]||next.contains(from)||previous.contains(to)) {
|
||||
fail(QStringLiteral("存在无效连线、跨容器连线或分支/汇合"));return {};
|
||||
}
|
||||
next[from]=to;previous[to]=from;
|
||||
}
|
||||
std::function<void(const QString&,int)> visit=[&](const QString &container,int depth) {
|
||||
if(depth>16){fail(QStringLiteral("循环嵌套过深"));return;}
|
||||
QString first;
|
||||
for(auto it=nodes.begin();it!=nodes.end();++it)if(parent[it.key()]==container&&!previous.contains(it.key())) {
|
||||
if(!first.isEmpty()){fail(QStringLiteral("存在未连接节点,请连接输入与输出端"));return;}first=it.key();
|
||||
}
|
||||
const QString startType=container.isEmpty()?"start":"subStart";
|
||||
if(first.isEmpty()||nodes[first].value("type")!=startType){fail(QStringLiteral("流程未从开始节点连接,或连线形成环路"));return;}
|
||||
bool ended=false;
|
||||
while(!first.isEmpty()) {
|
||||
if(seen.contains(first)){fail(QStringLiteral("连线形成环路"));return;}seen.insert(first);
|
||||
const auto n=nodes[first];const auto type=n.value("type").toString();
|
||||
if(type=="end"||type=="subEnd") {
|
||||
if(next.contains(first)){fail(QStringLiteral("结束节点不能有后继"));return;}ended=true;
|
||||
}else if(type!="start"&&type!="subStart"&&type!="sleep") {
|
||||
result[container].append(first);if(type=="loop")visit(first,depth+1);
|
||||
}
|
||||
first=next.value(first);
|
||||
}
|
||||
if(!ended)fail(QStringLiteral("流程未连接到结束节点"));
|
||||
};
|
||||
visit({},0);
|
||||
if(seen.size()!=nodes.size())fail(QStringLiteral("存在孤立节点或未连接的循环内部节点"));
|
||||
if(!error.isEmpty())return {};return result;
|
||||
}
|
||||
inline QHash<QString,double> waits(const QJsonObject &graph,QString &error) {
|
||||
QHash<QString,double> result;QHash<QString,QString> previous;
|
||||
for(const auto &v:graph.value("edges").toArray())previous[v.toObject().value("targetNodeId").toString()]=v.toObject().value("sourceNodeId").toString();
|
||||
for(const auto &v:graph.value("nodes").toArray()) {
|
||||
const auto n=v.toObject();if(n.value("type")!="sleep")continue;
|
||||
double delay=-1;for(const auto &p:n.value("properties").toObject().value("nodeParams").toArray())
|
||||
if(p.toObject().value("name")=="delayMs") {
|
||||
const auto value=p.toObject().value("input");bool ok=true;
|
||||
delay=value.isString()?value.toString().toDouble(&ok):value.toDouble(-1);
|
||||
if(!ok||p.toObject().value("type")!="input")delay=-1;
|
||||
}
|
||||
QString source=previous.value(n.value("id").toString());QSet<QString> seen;
|
||||
while(node(graph,source).value("type")=="sleep"&&!seen.contains(source)){seen.insert(source);source=previous.value(source);}
|
||||
const auto type=node(graph,source).value("type").toString();
|
||||
if(source.isEmpty()||delay<0||delay>2147483647||delay!=std::floor(delay)||!std::isfinite(delay)) {
|
||||
error=QStringLiteral("等待节点需要连接到流程,且时长须为非负整数毫秒数");return {};
|
||||
}
|
||||
result[source]+=delay/1000.;
|
||||
if(result[source]>2147483.647){error=QStringLiteral("累计等待超出计时器范围");return {};}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user