diff --git a/.gitignore b/.gitignore index c4b44db..47b3908 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ /.qtcreator/ __pycache__/ *.py[cod] +/am-freescan/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 650d8f0..716c7ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index 351bde0..212104b 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -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 diff --git a/README.md b/README.md index 39f24fa..31d83e7 100644 --- a/README.md +++ b/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 执行器支持单路径及嵌套循环;条件分支、运行时参数引用、扫描仪等其他领域动作不能无损转换时明确报错。等待可位于开始之后、任务之后或循环内部。 diff --git a/docs/task-flow/task-flow.mjs b/docs/task-flow/task-flow.mjs index dbf000b..d2da468 100644 --- a/docs/task-flow/task-flow.mjs +++ b/docs/task-flow/task-flow.mjs @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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::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 seen; + std::function append=[&](const auto *file) { + const QString name=QString::fromStdString(file->name());if(seen.contains(name))return; + seen.insert(name);for(int i=0;idependency_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 lookup;QHash 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 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 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 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 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=0 && groupIndex 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 lookup;QHash 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 next,previous;QSet 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 visited; + std::function 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()=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=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 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 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 seen; + std::function convert=[&](const QString &parent,int depth) { + require(depth<=16,QStringLiteral("循环嵌套过深"));QList 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()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 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 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 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;} +} +} diff --git a/src/freescaninterop.h b/src/freescaninterop.h new file mode 100644 index 0000000..810dc2e --- /dev/null +++ b/src/freescaninterop.h @@ -0,0 +1,10 @@ +#pragma once +#include +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); +} diff --git a/src/freescaninteropui.h b/src/freescaninteropui.h new file mode 100644 index 0000000..ac95965 --- /dev/null +++ b/src/freescaninteropui.h @@ -0,0 +1,52 @@ +#pragma once +#include +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 bindings;auto nodes=graph.value("nodes").toArray(); + for(int i=0;i16*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; +} +} diff --git a/src/jointfloweditor.cpp b/src/jointfloweditor.cpp index 057e7f9..396dbc8 100644 --- a/src/jointfloweditor.cpp +++ b/src/jointfloweditor.cpp @@ -1,5 +1,7 @@ #include "jointfloweditor.h" #include "uiicons.h" +#include "workflowcanvas.h" +#include "workflowgraph.h" #include #include @@ -18,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -28,143 +31,14 @@ #include #include #include +#include #include 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(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(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 m_moved; std::function m_edit; std::function 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(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(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(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(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(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(canvasTools->layout())->insertWidget(0,button); + connect(button,&QPushButton::clicked,this,[this,key]{if(!m_view->isInteractive())return;auto *canvas=static_cast(m_view);canvas->dropPosition=canvas->mapToScene(canvas->viewport()->rect().center());canvas->dropContainer=m_insertionParentId;canvas->componentDropped(key);}); + } + static_cast(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(m_view); + pointCanvas->copyNodes=[this](const QSet &selection) { + QSet 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 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(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::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 orderGuard(m_useExecutionOrder,!m_graph.isEmpty()); QList 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 &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 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 JointFlowEditor::childrenOf(const QString &parentId) const { QList 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 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 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 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 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(); } diff --git a/src/jointfloweditor.h b/src/jointfloweditor.h index a0a8440..af5cb32 100644 --- a/src/jointfloweditor.h +++ b/src/jointfloweditor.h @@ -1,9 +1,13 @@ #pragma once #include +#include +#include +#include #include #include #include +#include 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 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 m_nodes; QGraphicsScene *m_scene = nullptr; QGraphicsView *m_view = nullptr; + QWidget *m_inspector = nullptr; + std::function m_refreshInspector; + QJsonObject m_graph; + mutable QHash m_executionOrder; + mutable QHash m_executionWaits; + mutable bool m_useExecutionOrder = false; QString m_activeNodeId; QString m_selectedNodeId; QString m_insertionParentId; diff --git a/src/jointpointdata.h b/src/jointpointdata.h index 00f0a71..48a1f7a 100644 --- a/src/jointpointdata.h +++ b/src/jointpointdata.h @@ -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()) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 8d64e0c..e82d952 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -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(taskPageIndexaddWidget(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 savedFlows = group.flows.isEmpty() + ? QList{{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=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) diff --git a/src/mainwindow.h b/src/mainwindow.h index e4c7ca2..86fc0cb 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -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 points; QJsonArray flow; double moveJVelocity = 0.1; double moveJAcceleration = 0.1; + QList flows; + int activeFlow = 0; }; QList m_jointProgramGroups; int m_activeJointProgramGroup = -1; bool m_updatingJointProgramGroup = false; + bool m_jointProgramsWritable = true; QList m_recordedJointPoints; QComboBox *m_jointProgramGroupCombo = nullptr; + QComboBox *m_jointProgramFlowCombo = nullptr; QHash 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; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index eac1905..cb7a43c 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -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;rowrowCount();++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::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;icount();++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;icount();++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::of(&QDoubleSpinBox::valueChanged), this, [this](double) { saveJointPrograms(); }); connect(m_jointFlowAccelerationSpin, QOverload::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(); }); diff --git a/src/taskapi.cpp b/src/taskapi.cpp index 22f2286..1391cef 100644 --- a/src/taskapi.cpp +++ b/src/taskapi.cpp @@ -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); diff --git a/src/taskorchestrationwidget.cpp b/src/taskorchestrationwidget.cpp index 917cef6..e5a01be 100644 --- a/src/taskorchestrationwidget.cpp +++ b/src/taskorchestrationwidget.cpp @@ -1,12 +1,14 @@ #include "taskorchestrationwidget.h" -#include "audiostreammanager.h" #include "applicationstyle.h" #include "cameracapabilities.h" #include "bioheadoperations.h" #include "uiicons.h" +#include "workflowcanvas.h" +#include "freescaninterop.h" +#include "freescaninteropui.h" +#include "workflowgraph.h" #include "taskapi.h" #include "taskprotoeditor.h" -#include "taskjointeditor.h" #include "taskuilabels.h" #include #include @@ -75,41 +77,7 @@ void captureTaskExpansion(QTreeWidgetItem *item) constexpr qreal kTaskCardWidth = 270.0; constexpr qreal kTaskCardHeight = 94.0; -class TaskFlowView final : public QGraphicsView -{ -public: - explicit TaskFlowView(QGraphicsScene *scene, QWidget *parent = nullptr) - : QGraphicsView(scene, parent) {} -protected: - void mousePressEvent(QMouseEvent *event) override - { - if (event->button() == Qt::RightButton) { - m_panning = true; m_last = 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_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 (event->button() == Qt::RightButton && m_panning) { - m_panning = false; viewport()->unsetCursor(); event->accept(); return; - } - QGraphicsView::mouseReleaseEvent(event); - } -private: - QPoint m_last; - bool m_panning = false; -}; +using TaskFlowView = WorkflowCanvas; class TaskFlowCard final : public QGraphicsItem { @@ -123,7 +91,7 @@ public: { setFlags(ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges); setToolTip(title + QStringLiteral("\n") + subtitle - + (loop ? QStringLiteral("\n右上角折叠;选中后点击“添加到选中循环”可添加子节点") : QString())); + + (loop ? QStringLiteral("\n右上角折叠;选中后点击“进入所选循环”可添加子节点") : QString())); setAcceptHoverEvents(true); setCursor(Qt::OpenHandCursor); setZValue(2); @@ -201,7 +169,7 @@ protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value) override { if (change == ItemPositionChange && m_dragging) { - QPointF position = value.toPointF(); position.setY(m_startPos.y()); return position; + return value; } return QGraphicsItem::itemChange(change, value); } @@ -330,35 +298,6 @@ void showTaskNotice(QWidget *parent, const QString &title, const QString &messag dialog.exec(); } -QStringList legacyActionsForType(const QString &type) -{ - if (type == QStringLiteral("仿生头")) - return BioHeadOperations::actions(); - if (type == QStringLiteral("机械臂")) - return {QStringLiteral("MoveJ"), QStringLiteral("使能"), QStringLiteral("去使能"), - QStringLiteral("停止"), QStringLiteral("清除故障")}; - if (type == QStringLiteral("相机")) - return {QStringLiteral("RGB抓图"), QStringLiteral("深度抓图"), - QStringLiteral("开始预览"), QStringLiteral("停止预览"), - QStringLiteral("开始录像"), QStringLiteral("停止录像")}; - if (type == QStringLiteral("AGV")) - return {QStringLiteral("导航站点"), QStringLiteral("停止"), - QStringLiteral("暂停"), QStringLiteral("继续")}; - if (type == QStringLiteral("灵巧手")) - return {QStringLiteral("设置角度"), QStringLiteral("设置位置"), - QStringLiteral("设置速度"), QStringLiteral("设置力")}; - if (type == QStringLiteral("扬声器")) - return {QStringLiteral("播放服务端文件"), QStringLiteral("停止文件播放"), - QStringLiteral("本机麦克风流播放"), QStringLiteral("停止音频流"), - QStringLiteral("开始音频流")}; - if (type == QStringLiteral("麦克风")) - return {QStringLiteral("开始录音"), QStringLiteral("停止录音"), - QStringLiteral("开始音频流"), QStringLiteral("停止音频流")}; - return {QStringLiteral("调用RPC")}; -} - -QStringList actionsForType(const QString& type) { return (type==QStringLiteral("电机")?QStringList():legacyActionsForType(type))+TaskApi::actions(type); } - QString deviceTypeName(int type) { switch (type) { @@ -427,453 +366,9 @@ bool editNameDialog(QWidget *parent, const QString &title, const QString &label, return true; } -bool editLoopDialog(QWidget *parent, const QString &title, QString &name, int &count) -{ - TaskNodeDialog dialog(title, parent); - dialog.setWindowModality(Qt::WindowModal); - dialog.setMinimumWidth(460); - QFormLayout *form = new QFormLayout; - QLineEdit *nameEdit = new QLineEdit(name, &dialog); - QSpinBox *countSpin = new QSpinBox(&dialog); - countSpin->setRange(1, 10000); - countSpin->setValue(qMax(1, count)); - countSpin->setSuffix(QStringLiteral(" 次")); - form->addRow(QStringLiteral("节点名称"), nameEdit); - form->addRow(QStringLiteral("循环次数"), countSpin); - dialog.contentLayout()->addLayout(form); - QDialogButtonBox *buttons = new QDialogButtonBox( - QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); - buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("确定")); - buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消")); - buttons->button(QDialogButtonBox::Ok)->setObjectName(QStringLiteral("primaryButton")); - buttons->button(QDialogButtonBox::Cancel)->setObjectName(QStringLiteral("secondaryButton")); - QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); - QObject::connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); - dialog.contentLayout()->addWidget(buttons); - nameEdit->selectAll(); - nameEdit->setFocus(); - if (dialog.exec() != QDialog::Accepted) return false; - const QString result = nameEdit->text().trimmed(); - if (result.isEmpty()) { - showTaskNotice(parent, title, QStringLiteral("节点名称不能为空。")); - return false; - } - name = result; - count = countSpin->value(); - return true; + } -bool editTaskDialog(QWidget *parent, QString &name, QString &type, QString &deviceId, - QString &action, QJsonObject ¶meters, int &waitMs, - QString &waitUnit, - const QVariantList &availableDevices, - const QHash &cameraCapabilities) -{ - if (availableDevices.isEmpty()) { - showTaskNotice(parent, QStringLiteral("添加任务节点"), - QStringLiteral("尚未获取到设备列表,请先连接服务并刷新系统状态。")); - return false; - } - TaskNodeDialog dialog(QStringLiteral("任务节点参数"), parent); - dialog.setWindowModality(Qt::WindowModal); - const int availableWidth=QGuiApplication::primaryScreen()?QGuiApplication::primaryScreen()->availableGeometry().width():1200; - dialog.setMinimumWidth(qMin(980,qMax(640,availableWidth-60))); - const int availableHeight=QGuiApplication::primaryScreen()?QGuiApplication::primaryScreen()->availableGeometry().height():900; - dialog.setMaximumHeight(qMax(480,availableHeight-60)); - QVBoxLayout *layout = dialog.contentLayout(); - QFormLayout form;QFormLayout headerForm;headerForm.setHorizontalSpacing(16);headerForm.setVerticalSpacing(10);headerForm.setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - form.setHorizontalSpacing(16); - form.setVerticalSpacing(12); - form.setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter); - form.setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - QLineEdit nameEdit(name, &dialog); - QComboBox deviceCombo(&dialog);deviceCombo.setObjectName("taskDeviceCombo"); - configureComboPopup(&deviceCombo); - for (const QVariant &value : availableDevices) { - const QVariantMap device = value.toMap(); - const QString id = device.value(QStringLiteral("deviceId")).toString(); - if (id.isEmpty()) continue; - const QString typeName = deviceTypeName(device.value(QStringLiteral("type")).toInt()); - deviceCombo.addItem(QStringLiteral("%1 · %2").arg(id, typeName), device); - } - int deviceIndex = -1; - for (int i = 0; i < deviceCombo.count(); ++i) - if (deviceCombo.itemData(i).toMap().value(QStringLiteral("deviceId")).toString() == deviceId) { deviceIndex = i; break; } - if (deviceIndex >= 0) deviceCombo.setCurrentIndex(deviceIndex); - QLineEdit typeValue(&dialog); - typeValue.setReadOnly(true); - QComboBox actionCombo(&dialog);actionCombo.setObjectName("taskActionCombo"); - configureComboPopup(&actionCombo); - QWidget waitEditor(&dialog); - QHBoxLayout waitLayout(&waitEditor); - waitLayout.setContentsMargins(0, 0, 0, 0); - waitLayout.setSpacing(8); - QDoubleSpinBox waitSpin(&waitEditor); - QComboBox waitUnitCombo(&waitEditor); - configureComboPopup(&waitUnitCombo); - waitUnitCombo.addItem(QStringLiteral("毫秒 (ms)"), QStringLiteral("ms")); - waitUnitCombo.addItem(QStringLiteral("秒 (s)"), QStringLiteral("s")); - waitUnit = normalizedWaitUnit(waitUnit); - waitUnitCombo.setCurrentIndex(waitUnitCombo.findData(waitUnit)); - QString activeWaitUnit = waitUnit; - auto configureWaitSpin = [&](const QString &unit, int valueMs) { - const bool seconds = unit == QStringLiteral("s"); - waitSpin.setDecimals(seconds ? 3 : 0); - waitSpin.setRange(0.0, seconds ? 3600.0 : 3600000.0); - waitSpin.setSingleStep(seconds ? 0.1 : 100.0); - waitSpin.setValue(seconds ? valueMs / 1000.0 : valueMs); - }; - configureWaitSpin(activeWaitUnit, waitMs); - waitLayout.addWidget(&waitSpin, 1); - waitLayout.addWidget(&waitUnitCombo); - QObject::connect(&waitUnitCombo, QOverload::of(&QComboBox::currentIndexChanged), - &dialog, [&](int) { - const int currentMs = qRound(waitSpin.value() - * (activeWaitUnit == QStringLiteral("s") ? 1000.0 : 1.0)); - activeWaitUnit = normalizedWaitUnit(waitUnitCombo.currentData().toString()); - configureWaitSpin(activeWaitUnit, currentMs); - }); - QStackedWidget parameterPages(&dialog); - QWidget noParameterPage; - QHBoxLayout noParameterLayout(&noParameterPage); - QLabel noParameterLabel(QStringLiteral("此操作无需额外参数"), &noParameterPage); - noParameterLabel.setObjectName(QStringLiteral("mutedLabel")); - noParameterLayout.addWidget(&noParameterLabel); - noParameterLayout.addStretch(); - - QWidget moveJPage; QFormLayout moveJForm(&moveJPage); - TaskJointEditor jointEditor(&moveJPage); - QDoubleSpinBox velocitySpin(&moveJPage), accelerationSpin(&moveJPage); - for (QDoubleSpinBox *spin : {&velocitySpin, &accelerationSpin}) { - spin->setRange(0.001, 1000.0); spin->setDecimals(3); spin->setValue(0.1); - } - velocitySpin.setSuffix(QStringLiteral(" °/s")); - accelerationSpin.setSuffix(QStringLiteral(" °/s²")); - moveJForm.addRow(&jointEditor); - moveJForm.addRow(QStringLiteral("速度"), &velocitySpin); - moveJForm.addRow(QStringLiteral("加速度"), &accelerationSpin); - - QWidget cameraPage; QFormLayout cameraForm(&cameraPage); - QComboBox codecCombo(&cameraPage), modeCombo(&cameraPage); - configureComboPopup(&codecCombo); - configureComboPopup(&modeCombo); - codecCombo.addItems({QStringLiteral("H264"), QStringLiteral("H265")}); - modeCombo.addItem(QStringLiteral("RGB"), QStringLiteral("rgb")); - modeCombo.addItem(QStringLiteral("深度"), QStringLiteral("depth")); - cameraForm.addRow(QStringLiteral("编码格式"), &codecCombo); - cameraForm.addRow(QStringLiteral("画面类型"), &modeCombo); - - QWidget agvPage; QFormLayout agvForm(&agvPage); - QComboBox stationEdit(&agvPage);stationEdit.setObjectName("taskAgvStationSelector");configureComboPopup(&stationEdit); - QDoubleSpinBox maxSpeedSpin(&agvPage); - maxSpeedSpin.setRange(0.01, 100.0); maxSpeedSpin.setDecimals(2); - maxSpeedSpin.setValue(0.5); maxSpeedSpin.setSuffix(QStringLiteral(" m/s")); - agvForm.addRow(QStringLiteral("站点 ID"), &stationEdit); - agvForm.addRow(QStringLiteral("最大速度"), &maxSpeedSpin); - - QWidget dexPage; QFormLayout dexForm(&dexPage); - auto* dexTable=new QTableWidget(0,2,&dexPage);dexTable->setHorizontalHeaderLabels({QStringLiteral("关节 / 通道"),QStringLiteral("目标值")}); - dexTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);dexTable->verticalHeader()->hide();dexTable->setMinimumHeight(180);dexTable->setMaximumHeight(240);dexForm.addRow(dexTable); - auto* dexAdd=new QPushButton(QStringLiteral("添加设备通道"),&dexPage);dexForm.addRow(dexAdd); - auto addDex=[&](const QString& label,const QJsonValue& value){int row=dexTable->rowCount();dexTable->insertRow(row);auto* item=new QTableWidgetItem(label);item->setFlags(Qt::ItemIsEnabled);dexTable->setItem(row,0,item);auto* edit=new QLineEdit(dexTable);edit->setValidator(new QDoubleValidator(edit));edit->setPlaceholderText(QStringLiteral("输入该通道的目标值"));if(value.isDouble())edit->setText(QString::number(value.toDouble(),'g',12));dexTable->setCellWidget(row,1,edit);dexTable->setRowHeight(row,44);}; - QObject::connect(dexAdd,&QPushButton::clicked,&dialog,[&]{addDex(QStringLiteral("通道 %1").arg(dexTable->rowCount()),{});}); - auto* dexHint=new QLabel(QStringLiteral("数值单位与范围由该型号设备定义;通道按服务端顺序排列。"),&dexPage);dexHint->setWordWrap(true);dexForm.addRow(dexHint); - - QWidget rpcPage; QFormLayout rpcForm(&rpcPage); - QLineEdit serviceEdit(&rpcPage), methodEdit(&rpcPage), requestEdit(&rpcPage); - requestEdit.setPlaceholderText(QStringLiteral("例如:{}")); - rpcForm.addRow(QStringLiteral("服务名称"), &serviceEdit); - rpcForm.addRow(QStringLiteral("方法名称"), &methodEdit); - rpcForm.addRow(QStringLiteral("请求内容"), &requestEdit); - - QWidget pathPage; QFormLayout pathForm(&pathPage); - QLabel pathHint(&pathPage); - QLineEdit pathEdit(&pathPage); - pathEdit.setClearButtonEnabled(true); - pathForm.addRow(&pathHint, &pathEdit); - - QWidget localCapturePage; QFormLayout localCaptureForm(&localCapturePage); - QComboBox inputDeviceCombo(&localCapturePage); - configureComboPopup(&inputDeviceCombo); - inputDeviceCombo.addItems(AudioStreamManager::inputDeviceNames()); - QSpinBox sampleRateSpin(&localCapturePage), channelSpin(&localCapturePage); - sampleRateSpin.setRange(8000, 192000); - sampleRateSpin.setValue(parameters.value(QStringLiteral("sampleRate")).toInt(48000)); - sampleRateSpin.setSuffix(QStringLiteral(" Hz")); - channelSpin.setRange(1, 8); - channelSpin.setValue(parameters.value(QStringLiteral("channels")).toInt(1)); - localCaptureForm.addRow(QStringLiteral("本机输入设备"), &inputDeviceCombo); - localCaptureForm.addRow(QStringLiteral("采样率"), &sampleRateSpin); - localCaptureForm.addRow(QStringLiteral("声道数"), &channelSpin); - - parameterPages.addWidget(&noParameterPage); - parameterPages.addWidget(&moveJPage); - parameterPages.addWidget(&cameraPage); - parameterPages.addWidget(&agvPage); - parameterPages.addWidget(&dexPage); - parameterPages.addWidget(&rpcPage); - parameterPages.addWidget(&pathPage); - parameterPages.addWidget(&localCapturePage); - QWidget apiPage;QVBoxLayout apiLayout(&apiPage);apiLayout.setContentsMargins(0,0,0,0);apiLayout.setAlignment(Qt::AlignTop); - TaskProtoEditor apiEditor(&apiPage);apiLayout.addWidget(&apiEditor); - QSpinBox rpcTimeout(&apiPage);rpcTimeout.setRange(100,1800000);rpcTimeout.setValue(parameters.value("timeoutMs").toInt(180000));rpcTimeout.setSuffix(" ms"); - - auto* rpcHint=new QLabel(QStringLiteral("按所选设备填写目标和运动设置。操作完成条件以设备返回结果为准。"),&apiPage); - rpcHint->setWordWrap(true);apiLayout.addWidget(rpcHint);parameterPages.addWidget(&apiPage); - QString currentApi;QHash apiDrafts;QHash apiInputDrafts; - QString displayedDevice;QHash jointDrafts;QHash stationDrafts; - parameterPages.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - - const QJsonArray existingPositions = parameters.value(QStringLiteral("positions")).toArray(); - - velocitySpin.setValue(qRadiansToDegrees(parameters.value(QStringLiteral("velocity")).toDouble(0.1))); - accelerationSpin.setValue(qRadiansToDegrees(parameters.value(QStringLiteral("acceleration")).toDouble(0.1))); - codecCombo.setCurrentText(parameters.value(QStringLiteral("codec")).toString(QStringLiteral("H264"))); - const int modeIndex = modeCombo.findData(parameters.value(QStringLiteral("mode")).toString(QStringLiteral("rgb"))); - if (modeIndex >= 0) modeCombo.setCurrentIndex(modeIndex); - - maxSpeedSpin.setValue(parameters.value(QStringLiteral("maxSpeed")).toDouble(0.5)); - - serviceEdit.setText(parameters.value(QStringLiteral("service")).toString()); - methodEdit.setText(parameters.value(QStringLiteral("method")).toString()); - requestEdit.setText(QString::fromUtf8(QJsonDocument(parameters.value(QStringLiteral("request")).toObject()).toJson(QJsonDocument::Compact))); - pathEdit.setText(parameters.value(QStringLiteral("path")).toString()); - const int inputIndex = inputDeviceCombo.findText( - parameters.value(QStringLiteral("inputDevice")).toString()); - if (inputIndex >= 0) inputDeviceCombo.setCurrentIndex(inputIndex); - - QLabel parameterLabel(QStringLiteral("操作参数"), &dialog); - headerForm.addRow(QStringLiteral("节点名称"), &nameEdit); - auto* deviceRow=new QWidget(&dialog);auto* deviceRowLayout=new QHBoxLayout(deviceRow);deviceRowLayout->setContentsMargins(0,0,0,0);deviceRowLayout->addWidget(&deviceCombo,1); - QPushButton refreshInfo(QStringLiteral("刷新设备参数"),deviceRow);refreshInfo.setObjectName("secondaryButton");deviceRowLayout->addWidget(&refreshInfo); - headerForm.addRow(QStringLiteral("选择设备"), deviceRow); - typeValue.hide(); - headerForm.addRow(QStringLiteral("执行操作"), &actionCombo); - QLabel bioheadHint(&dialog); - bioheadHint.setWordWrap(true); - bioheadHint.setObjectName(QStringLiteral("mutedLabel")); - headerForm.addRow(&bioheadHint); - form.addRow(¶meterLabel, ¶meterPages); - - layout->addLayout(&headerForm); - auto* formBody=new QWidget(&dialog);formBody->setLayout(&form); - auto* formScroll=new TaskParameterScroll(&dialog);formScroll->setObjectName("taskParameterScroll");formScroll->setFrameShape(QFrame::NoFrame);formScroll->setWidgetResizable(true);formScroll->setWidget(formBody);formScroll->setMinimumHeight(160);formScroll->setMaximumHeight(qMax(160,availableHeight-540));layout->addWidget(formScroll,1); - auto* waitForm=new QFormLayout;waitForm->setHorizontalSpacing(16);waitForm->addRow(QStringLiteral("完成后等待"),&waitEditor);layout->addLayout(waitForm); - auto* timeoutSegment=new QWidget(&waitEditor);auto* timeoutLayout=new QHBoxLayout(timeoutSegment);timeoutLayout->setContentsMargins(8,0,0,0);timeoutLayout->addWidget(new QLabel(QStringLiteral("操作超时"),timeoutSegment));timeoutLayout->addWidget(&rpcTimeout);rpcTimeout.setMaximumWidth(180);waitLayout.addWidget(timeoutSegment); - - auto refreshParameterPage = [&]() { - const QString selectedType = typeValue.text(); - const QString selectedAction = actionCombo.currentData().toString(); - bioheadHint.setVisible(selectedType == QStringLiteral("仿生头")); - bioheadHint.setText(BioHeadOperations::hint(selectedAction)); - int page = 0; - if (selectedType == QStringLiteral("机械臂") && selectedAction == QStringLiteral("MoveJ")) page = 1; - else if (selectedType == QStringLiteral("AGV") && selectedAction == QStringLiteral("导航站点")) page = 3; - else if (selectedType == QStringLiteral("灵巧手")) page = 4; - else if (selectedType == QStringLiteral("通用RPC")) page = 5; - else if ((selectedType == QStringLiteral("相机") - && selectedAction == QStringLiteral("开始录像")) - || (selectedType == QStringLiteral("麦克风") - && selectedAction == QStringLiteral("开始录音")) - || (selectedType == QStringLiteral("扬声器") - && selectedAction == QStringLiteral("播放服务端文件"))) { - page = 6; - if (selectedType == QStringLiteral("相机")) { - pathHint.setText(QStringLiteral("服务端录像路径")); - pathEdit.setPlaceholderText(QStringLiteral("例如:/home/cmvr/videos/task.mp4")); - } else if (selectedType == QStringLiteral("麦克风")) { - pathHint.setText(QStringLiteral("服务端录音路径")); - pathEdit.setPlaceholderText(QStringLiteral("例如:/home/cmvr/audio/task.wav")); - } else { - pathHint.setText(QStringLiteral("服务端音频文件")); - pathEdit.setPlaceholderText(QStringLiteral("例如:/home/cmvr/audio/notice.wav")); - } - } else if (selectedType == QStringLiteral("扬声器") - && selectedAction == QStringLiteral("本机麦克风流播放")) { - page = 7; - } - if(!currentApi.isEmpty()){apiInputDrafts.insert(currentApi,apiEditor.inputState());QJsonObject request;QString error;if(apiEditor.request(request,error))apiDrafts.insert(currentApi,request);} - const auto op=TaskApi::operation(selectedType,selectedAction); - if(!op.isEmpty()){ - page=8;const QString key=deviceCombo.currentData().toMap().value("deviceId").toString()+":"+op.value("id").toString(); - QJsonObject request=apiDrafts.value(key); - if(request.isEmpty() && deviceCombo.currentData().toMap().value("deviceId").toString()==deviceId && parameters.value("service")==op.value("service") && parameters.value("method")==op.value("method"))request=parameters.value("request").toObject(); - auto* owner=qobject_cast(parent); - const QString id=deviceCombo.currentData().toMap().value("deviceId").toString(); - apiEditor.setDeviceContext(owner?owner->deviceInfo(id):QVariantMap()); - apiEditor.setOperation(op.value("service").toString(),op.value("method").toString(),request); - if(apiInputDrafts.contains(key))apiEditor.restoreInputState(apiInputDrafts.value(key));currentApi=key; - QString note=QStringLiteral("按设备填写操作参数;服务端不支持的操作会返回错误。成功只代表该接口定义的完成条件,并非所有设备都已运动到位。"); - const QString method=op.value("method").toString(); - if(method=="moveL")note+=QStringLiteral(" 直线运动:请先应用工件坐标系,再填写该坐标系内的绝对目标位姿。位置单位为米,旋转单位为弧度。"); - if(method=="moveJPose")note+=QStringLiteral(" 末端位姿MoveJ:目标为所选坐标系下的绝对TCP位姿m/rad,速度rad/s,加速度rad/s²;先应用同名同版本坐标系,SDK逆解后执行关节运动,路径不是直线。"); - if(method=="ApplyUserCoordinateSystem")note+=QStringLiteral(" 填写已保存的坐标系名称和预期记录版本。应用坐标系本身不会产生运动。"); - if(method=="getPose")note+=QStringLiteral(" 参考坐标系填写 base 或已保存的坐标系名称;末端坐标系填写 tcp 读取工具中心,tool0 读取法兰。"); - rpcHint->setToolTip(note); - rpcHint->setText(method=="moveL"?QStringLiteral("直线运动请先应用工件坐标系;填写绝对目标位姿。更多说明可将鼠标停留在此处查看。"):QStringLiteral("填写所需参数即可;悬停此处查看操作说明。")); - - }else currentApi.clear(); - timeoutSegment->setVisible(page==8); - parameterPages.setCurrentIndex(page); - const bool hasParameters = page != 0; - parameterLabel.setVisible(hasParameters); - parameterPages.setVisible(hasParameters); - if (hasParameters){ - if(parameterPages.currentWidget()->layout()){parameterPages.currentWidget()->layout()->invalidate();parameterPages.currentWidget()->layout()->activate();} - parameterPages.setFixedHeight(parameterPages.currentWidget()->sizeHint().height()); - } - else - parameterPages.setFixedHeight(0); - formScroll->setMinimumHeight(qMin(qMax(160,formBody->sizeHint().height()+12),qMax(160,availableHeight-560))); - dialog.adjustSize(); - }; - apiEditor.setLayoutChangedHandler([&]{ - if(parameterPages.currentWidget()!=&apiPage)return; - apiPage.layout()->invalidate();apiPage.layout()->activate();parameterPages.setFixedHeight(apiPage.sizeHint().height()); - formBody->layout()->activate();formBody->updateGeometry(); - formScroll->setMinimumHeight(qMin(qMax(160,formBody->sizeHint().height()+12),qMax(160,availableHeight-560)));dialog.adjustSize(); - }); - auto refreshActions = [&]() { - const QVariantMap device = deviceCombo.currentData().toMap(); - const QString selectedType = deviceTypeName(device.value(QStringLiteral("type")).toInt()); - typeValue.setText(selectedType); - const QString id=device.value("deviceId").toString();auto* owner=qobject_cast(parent); - if(!displayedDevice.isEmpty()&&!jointEditor.draft().isEmpty())jointDrafts.insert(displayedDevice,jointEditor.draft()); - const auto info=owner?owner->deviceInfo(id):QVariantMap(); - jointEditor.setDevice(info,jointDrafts.contains(id)?jointDrafts.value(id):(id==deviceId?existingPositions:QJsonArray())); - const auto deviceNames=info.value("jointNames").toStringList(); - if(displayedDevice!=id||(!deviceNames.isEmpty()&&deviceNames.size()!=dexTable->rowCount())){QJsonArray draft; - if(displayedDevice==id)for(int row=0;rowrowCount();++row){bool ok;double n=qobject_cast(dexTable->cellWidget(row,1))->text().toDouble(&ok);draft.append(ok?QJsonValue(n):QJsonValue());} - dexTable->setRowCount(0);const auto values=!draft.isEmpty()?draft:(id==deviceId?parameters.value("values").toArray():QJsonArray());const auto names=deviceNames; - for(int i=0;i=0)stationEdit.setCurrentIndex(stationIndex); - displayedDevice=id; - const QString previous = actionCombo.currentData().toString().isEmpty() ? action : actionCombo.currentData().toString(); - const QSignalBlocker actionBlocker(&actionCombo); - actionCombo.clear(); - QStringList actions = actionsForType(selectedType); - if (selectedType == QStringLiteral("相机") - && !CameraCapabilities::depthImage(cameraCapabilities.value( - device.value(QStringLiteral("deviceId")).toString()))) - {actions.removeAll(QStringLiteral("深度抓图"));actions.removeAll(QStringLiteral("接口 · GetDepthImage"));actions.removeAll(QStringLiteral("接口 · GetRGBDImages"));} - for(const auto& value:actions)actionCombo.addItem(TaskUi::operationTitle(selectedType,value),value); - if (actionCombo.findData(previous) >= 0) actionCombo.setCurrentIndex(actionCombo.findData(previous)); - refreshParameterPage(); - }; - QObject::connect(&deviceCombo, QOverload::of(&QComboBox::currentIndexChanged), &dialog, - [&](int) { refreshActions(); }); - QObject::connect(&actionCombo, &QComboBox::currentTextChanged, &dialog, - [&](const QString &) { refreshParameterPage(); }); - if (auto *orchestration = qobject_cast(parent)) - QObject::connect(orchestration, &TaskOrchestrationWidget::cameraCapabilitiesChanged, - &dialog, [&]() { refreshActions(); }); - auto requestInfo=[&]{if(auto* owner=qobject_cast(parent)){const auto device=deviceCombo.currentData().toMap();emit owner->deviceInfoRequested(device.value("deviceId").toString(),deviceTypeName(device.value("type").toInt()));}}; - QObject::connect(&refreshInfo,&QPushButton::clicked,&dialog,requestInfo); - QObject::connect(&deviceCombo,QOverload::of(&QComboBox::currentIndexChanged),&dialog,[&](int){requestInfo();}); - if(auto* owner=qobject_cast(parent))QObject::connect(owner,&TaskOrchestrationWidget::deviceInfoChanged,&dialog,[&](const QString& id){if(id==displayedDevice)refreshActions();}); - refreshActions();QTimer::singleShot(0,&dialog,requestInfo); - QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); - buttons.button(QDialogButtonBox::Ok)->setText(QStringLiteral("确定")); - buttons.button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消")); - QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); - buttons.button(QDialogButtonBox::Ok)->setObjectName(QStringLiteral("primaryButton")); - buttons.button(QDialogButtonBox::Cancel)->setObjectName(QStringLiteral("secondaryButton")); - layout->addWidget(&buttons); - auto collectParameters=[&]()->bool { - if (nameEdit.text().trimmed().isEmpty() || deviceCombo.currentIndex() < 0) { - showTaskNotice(parent, QStringLiteral("参数错误"), - QStringLiteral("节点名称和设备不能为空。")); - return false; - } - const QVariantMap selectedDevice = deviceCombo.currentData().toMap(); - name = nameEdit.text().trimmed(); type = deviceTypeName(selectedDevice.value(QStringLiteral("type")).toInt()); - deviceId = selectedDevice.value(QStringLiteral("deviceId")).toString(); action = actionCombo.currentData().toString(); - parameters = QJsonObject(); - if (parameterPages.currentIndex() == 1) { - QJsonArray values; - QString jointError; - if (!jointEditor.values(values,jointError)) { - showTaskNotice(parent, QStringLiteral("参数错误"), - jointError); - return false; - } - parameters.insert(QStringLiteral("positions"), values); - parameters.insert(QStringLiteral("velocity"), qDegreesToRadians(velocitySpin.value())); - parameters.insert(QStringLiteral("acceleration"), qDegreesToRadians(accelerationSpin.value())); - } else if (parameterPages.currentIndex() == 2) { - parameters.insert(QStringLiteral("codec"), codecCombo.currentText()); - parameters.insert(QStringLiteral("mode"), modeCombo.currentData().toString()); - } else if (parameterPages.currentIndex() == 3) { - if (stationEdit.currentData().toString().trimmed().isEmpty()) { - showTaskNotice(parent, QStringLiteral("参数错误"), - QStringLiteral("站点 ID 不能为空。")); - return false; - } - parameters.insert(QStringLiteral("stationId"), stationEdit.currentData().toString().trimmed()); - parameters.insert(QStringLiteral("maxSpeed"), maxSpeedSpin.value()); - } else if (parameterPages.currentIndex() == 4) { - QJsonArray values; - bool valid=dexTable->rowCount()>0; - for(int row=0;rowrowCount();++row){bool ok;double value=qobject_cast(dexTable->cellWidget(row,1))->text().toDouble(&ok);valid=valid&&ok&&std::isfinite(value);values.append(value);} - if (!valid) { - showTaskNotice(parent, QStringLiteral("参数错误"), - QStringLiteral("请逐项填写设备通道的有效目标值。")); - return false; - } - const auto info=qobject_cast(parent)->deviceInfo(deviceId);const auto ids=info.value("channelIds").toList(); - QJsonArray targets;for(int i=0;i methods={{QStringLiteral("设置角度"),"SetDexHandAngle"},{QStringLiteral("设置位置"),"SetDexHandPos"},{QStringLiteral("设置速度"),"SetDexHandSpeed"},{QStringLiteral("设置力"),"SetDexHandForce"}}; - const QString method=methods.value(action);action=QStringLiteral("接口 · ")+method; - parameters={{"service","cmvr.api.DexHandService"},{"method",method},{"request",QJsonObject{{"values",targets}}},{"timeoutMs",180000}}; - } else if (parameterPages.currentIndex() == 5) { - QJsonParseError error; - const QJsonDocument request = QJsonDocument::fromJson(requestEdit.text().trimmed().toUtf8(), &error); - if (serviceEdit.text().trimmed().isEmpty() || methodEdit.text().trimmed().isEmpty() - || error.error != QJsonParseError::NoError || !request.isObject()) { - showTaskNotice(parent, QStringLiteral("参数错误"), - QStringLiteral("请填写服务、方法和有效的 JSON 请求内容。")); - return false; - } - parameters.insert(QStringLiteral("service"), serviceEdit.text().trimmed()); - parameters.insert(QStringLiteral("method"), methodEdit.text().trimmed()); - parameters.insert(QStringLiteral("request"), request.object()); - } else if (parameterPages.currentIndex() == 6) { - if (pathEdit.text().trimmed().isEmpty()) { - showTaskNotice(parent, QStringLiteral("参数错误"), - QStringLiteral("文件路径不能为空。")); - return false; - } - parameters.insert(QStringLiteral("path"), pathEdit.text().trimmed()); - } else if (parameterPages.currentIndex() == 7) { - if (inputDeviceCombo.currentText().trimmed().isEmpty()) { - showTaskNotice(parent, QStringLiteral("参数错误"), - QStringLiteral("未找到可用的本机音频输入设备。")); - return false; - } - parameters.insert(QStringLiteral("inputDevice"), inputDeviceCombo.currentText()); - parameters.insert(QStringLiteral("sampleRate"), sampleRateSpin.value()); - parameters.insert(QStringLiteral("channels"), channelSpin.value()); - } - if(parameterPages.currentIndex()==8){ - QJsonObject request;QString error; - if(!apiEditor.request(request,error)){showTaskNotice(parent,QStringLiteral("接口参数错误"),error);return false;} - const auto op=TaskApi::operation(type,action); - parameters={{"service",op.value("service")},{"method",op.value("method")},{"request",request},{"timeoutMs",rpcTimeout.value()}}; - } - waitUnit = normalizedWaitUnit(waitUnitCombo.currentData().toString()); - waitMs = qRound(waitSpin.value() * (waitUnit == QStringLiteral("s") ? 1000.0 : 1.0)); - return true; - }; - QObject::connect(&buttons,&QDialogButtonBox::accepted,&dialog,[&]{if(collectParameters())dialog.accept();}); - return dialog.exec()==QDialog::Accepted; -} -} TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(parent) { @@ -893,6 +388,15 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare auto* importButton=new QPushButton(QStringLiteral("导入 JSON"),panel); auto* exportButton=new QPushButton(QStringLiteral("导出 JSON / 接口清单"),panel); groups->addWidget(importButton);groups->addWidget(exportButton); + auto *exportFreeScan=new QPushButton(QStringLiteral("导出 am-freescan"),panel); + groups->addWidget(exportFreeScan); + connect(exportFreeScan,&QPushButton::clicked,this,[this] { + if(!m_runSteps.isEmpty()||m_activeGroup<0)return; + QJsonObject graph;QString error; + if(!syncGraph(error)){showTaskNotice(this,QStringLiteral("无法导出"),error);return;}graph=m_graph; + const QString path=QFileDialog::getSaveFileName(this,QStringLiteral("导出当前方案为 am-freescan 图"),"workflow.json",QStringLiteral("JSON (*.json)")); + if(!path.isEmpty()&&!FreeScanInterop::writeGraph(path,graph,error))showTaskNotice(this,QStringLiteral("导出失败"),error); + }); connect(importButton,&QPushButton::clicked,this,&TaskOrchestrationWidget::importDocument); connect(exportButton,&QPushButton::clicked,this,&TaskOrchestrationWidget::exportDocument); m_editControls<addWidget(title); groups->addStretch(); groups->addWidget(m_groupCombo); groups->addWidget(newGroup); groups->addWidget(renameGroup); layout->addLayout(groups); - QLabel *hint = new QLabel(QStringLiteral("选中节点后可在其后插入,拖动可调整同级执行顺序。右键拖动画布,双击编辑节点。"), panel); + QLabel *hint = new QLabel(QStringLiteral("拖入组件,连接端口确定执行顺序;选中节点在右侧配置,右键平移,Ctrl+滚轮缩放。"), panel); hint->setObjectName(QStringLiteral("mutedLabel")); - layout->addWidget(hint); + hint->hide(); QHBoxLayout *toolbar = new QHBoxLayout; - QPushButton *addTaskButton = new QPushButton(QStringLiteral("+ 任务节点"), panel); - QPushButton *addLoopButton = new QPushButton(QStringLiteral("+ 循环节点"), panel); - QPushButton *editButton = new QPushButton(QStringLiteral("编辑选中"), panel); QPushButton *removeButton = new QPushButton(QStringLiteral("删除选中"), panel); - QPushButton *upButton = new QPushButton(QStringLiteral("上移"), panel); - QPushButton *downButton = new QPushButton(QStringLiteral("下移"), panel); - addTaskButton->setObjectName(QStringLiteral("primaryButton")); removeButton->setObjectName(QStringLiteral("dangerOutlineButton")); - toolbar->addWidget(addTaskButton); toolbar->addWidget(addLoopButton); toolbar->addWidget(editButton); - toolbar->addWidget(removeButton); toolbar->addSpacing(12); toolbar->addWidget(upButton); - toolbar->addWidget(downButton); toolbar->addStretch(); + toolbar->addWidget(removeButton);toolbar->addStretch(); + auto *validateButton = new QPushButton(QStringLiteral("校验流程"), panel); + toolbar->addWidget(validateButton); + connect(validateButton,&QPushButton::clicked,this,[this] { + QJsonObject document;QString error; + if(m_graph.isEmpty()||!FreeScanInterop::importGraph(m_graph,document,error)) { + showTaskNotice(this,QStringLiteral("流程校验"),error.isEmpty()?QStringLiteral("当前方案没有可执行工作流。"):error);return; + } + QList steps; + const auto groups=document.value(QStringLiteral("groups")).toArray(); + if(!groups.isEmpty())appendCompiledSteps(groups.first().toObject().value(QStringLiteral("nodes")).toArray(),steps,&error); + if(error.isEmpty() && steps.isEmpty())error=QStringLiteral("当前方案没有可执行任务。"); + showTaskNotice(this,QStringLiteral("流程校验"),error.isEmpty() + ? QStringLiteral("结构校验通过,共 %1 个执行步骤;尚未调用设备。").arg(steps.size()) : error); + }); layout->addLayout(toolbar); auto *insertionToolbar = new QHBoxLayout; - auto *rootInsertion = new QPushButton(QStringLiteral("切换到根流程末尾"), panel); - auto *loopInsertion = new QPushButton(QStringLiteral("添加到选中循环"), panel); + auto *rootInsertion = new QPushButton(QStringLiteral("根流程"), panel); + auto *loopInsertion = new QPushButton(QStringLiteral("进入所选循环"), panel); rootInsertion->setObjectName(QStringLiteral("secondaryButton")); loopInsertion->setObjectName(QStringLiteral("secondaryButton")); - insertionToolbar->addWidget(rootInsertion); - insertionToolbar->addWidget(loopInsertion); + rootInsertion->hide();loopInsertion->hide(); insertionToolbar->addStretch(); m_insertionHint = new QLabel(panel); m_insertionHint->setObjectName(QStringLiteral("jointFlowContextChip")); m_insertionHint->setWordWrap(false); m_insertionHint->setMaximumWidth(560); - m_insertionHint->setToolTip(QStringLiteral("与点位规划相同:选中节点后在同层后方插入,进入循环需点击“添加到选中循环”。")); - insertionToolbar->addWidget(m_insertionHint); - m_editControls = {newGroup, renameGroup, m_groupCombo, addTaskButton, addLoopButton, - editButton, removeButton, upButton, downButton, rootInsertion, loopInsertion, importButton, exportButton}; - layout->addLayout(insertionToolbar); + m_insertionHint->setToolTip(QStringLiteral("与点位规划相同:选中节点后在同层后方插入,进入循环需点击“进入所选循环”。")); + m_insertionHint->hide(); + m_editControls = {newGroup, renameGroup, m_groupCombo, removeButton, + rootInsertion, loopInsertion, importButton, exportButton}; connect(rootInsertion, &QPushButton::clicked, this, &TaskOrchestrationWidget::setInsertionAtRoot); connect(loopInsertion, &QPushButton::clicked, this, [this]() { if (!useSelectedLoopAsInsertionParent()) @@ -960,15 +468,272 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare m_flowView->setObjectName(QStringLiteral("jointFlowCanvas")); m_flowView->setRenderHint(QPainter::Antialiasing); m_flowView->setDragMode(QGraphicsView::RubberBandDrag); - layout->addWidget(m_flowView, 1); + layout->addWidget(static_cast(m_flowView)->tools(panel)); + auto *workspace = new QSplitter(Qt::Horizontal, panel); + workspace->setObjectName(QStringLiteral("workflowWorkspace")); + auto *libraryPanel = new QWidget(workspace); + auto *libraryLayout = new QVBoxLayout(libraryPanel); + libraryLayout->setContentsMargins(0, 0, 8, 0); + auto *libraryTitle = new QLabel(QStringLiteral("组件库"), libraryPanel); + libraryTitle->setObjectName(QStringLiteral("sectionTitle")); + auto *search = new QLineEdit(libraryPanel); + search->setPlaceholderText(QStringLiteral("搜索组件")); + auto *library = new WorkflowLibrary(libraryPanel); + library->setObjectName(QStringLiteral("workflowComponentLibrary")); + library->setStyleSheet(QStringLiteral( + "QTreeWidget#workflowComponentLibrary{border:1px solid #dbe3ee;border-radius:8px;background:#ffffff;outline:0;}" + "QTreeWidget#workflowComponentLibrary::item{min-height:30px;padding:2px 8px;border-radius:5px;}" + "QTreeWidget#workflowComponentLibrary::item:hover{background:#f1f6fd;}" + "QTreeWidget#workflowComponentLibrary::item:selected{background:#e8f1ff;color:#185abc;}" + "QScrollBar:vertical{width:8px;background:transparent;margin:4px 2px;}" + "QScrollBar::handle:vertical{min-height:28px;background:#c5d0df;border-radius:4px;}" + "QScrollBar::handle:vertical:hover{background:#91a5bd;}" + "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;background:transparent;}" + "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:transparent;}")); + auto *controlGroup = new QTreeWidgetItem(library, {QStringLiteral("流程控制")}); + auto *loopComponent = new QTreeWidgetItem(controlGroup, {QStringLiteral("循环")}); + loopComponent->setData(0, Qt::UserRole, QStringLiteral("loop")); + auto *sleepComponent=new QTreeWidgetItem(controlGroup,{QStringLiteral("等待")});sleepComponent->setData(0,Qt::UserRole,QStringLiteral("sleep")); + auto *devicesGroup = new QTreeWidgetItem(library, {QStringLiteral("服务端接口节点")}); + for (const auto &type : {QStringLiteral("机械臂"),QStringLiteral("相机"),QStringLiteral("AGV"), + QStringLiteral("灵巧手"),QStringLiteral("麦克风"),QStringLiteral("扬声器"), + QStringLiteral("仿生头"),QStringLiteral("电机")}) { + auto *serviceGroup=new QTreeWidgetItem(devicesGroup,{type}); + for(const auto &action:TaskApi::actions(type)) { + const auto op=TaskApi::operation(type,action); + const auto method=op.value("method").toString(); + if(method.isEmpty())continue; + auto *item=new QTreeWidgetItem(serviceGroup,{action.mid(QStringLiteral("接口 · ").size())}); + item->setData(0,Qt::UserRole,QStringLiteral("rpc|")+type+QStringLiteral("|")+method); + item->setToolTip(0,op.value("service").toString()+QStringLiteral(".")+method); + } + } + library->expandAll(); + libraryLayout->addWidget(libraryTitle); libraryLayout->addWidget(search); libraryLayout->addWidget(library, 1); + connect(search, &QLineEdit::textChanged, this, [library](const QString &text) { + for (int i=0;itopLevelItemCount();++i) { + auto *group=library->topLevelItem(i); bool visible=false; + for(int j=0;jchildCount();++j) { + const bool match=group->child(j)->text(0).contains(text,Qt::CaseInsensitive); + group->child(j)->setHidden(!match); visible |= match; + } + group->setHidden(!visible); + } + }); + const auto createComponent = [this](const QString &key) { + if (!m_runSteps.isEmpty()) return; + const auto *canvas=static_cast(m_flowView); + const QString previousId=m_tree->currentItem()?m_tree->currentItem()->data(0,NodeIdRole).toString():QString(); + if(canvas->droppingFromPalette) { + m_insertionParent=nullptr;m_insertionIndex=-1; + if(!canvas->dropContainer.isEmpty())for(QTreeWidgetItemIterator it(m_tree);*it;++it) + if((*it)->data(0,NodeIdRole)==canvas->dropContainer)m_insertionParent=*it; + } + if(key=="sleep") {QString error;if(!syncGraph(error)){showTaskNotice(this,QStringLiteral("流程错误"),error);return;}WorkflowGraph::addSleep(m_graph,canvas->droppingFromPalette?canvas->dropContainer:QString(),canvas->droppingFromPalette?canvas->dropPosition:QPointF(600,350));save();return;} + if(key.startsWith("rpc|")) { + const auto parts=key.split('|');if(parts.size()!=3)return; + const QString type=parts[1],method=parts[2],service=TaskApi::serviceForType(type); + const auto info=TaskApi::definition(service,method);if(info.isEmpty())return; + const QString action=QStringLiteral("接口 · ")+method; + QString deviceId; + for(const auto &device:m_availableDevices) { + const auto entry=device.toMap(); + if(deviceTypeName(entry.value("type").toInt())==type){deviceId=entry.value("deviceId").toString();break;} + } + if(deviceId.isEmpty())deviceId=QStringLiteral("未绑定设备"); + QJsonObject params{{"service",service},{"method",method},{"request",QJsonObject{}},{"timeoutMs",info.value("defaultTimeoutMs").toInt(180000)}}; + QTreeWidgetItem *item=new QTreeWidgetItem;item->setFlags(item->flags()&~Qt::ItemIsDropEnabled); + item->setData(0,NodeIdRole,QUuid::createUuid().toString(QUuid::WithoutBraces)); + item->setData(0,KindRole,"task");item->setData(0,DeviceTypeRole,type);item->setData(0,DeviceIdRole,deviceId);item->setData(0,ActionRole,action); + item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact))); + item->setData(0,WaitRole,0);item->setData(0,WaitUnitRole,"ms"); + item->setText(0,QString::fromStdString(method.toStdString()));item->setText(1,type);item->setText(2,type);item->setText(3,deviceId);item->setText(4,action);item->setText(5,"0 ms"); + insertNode(item); + QString graphError; + if(syncGraph(graphError)) { + if(canvas->droppingFromPalette)WorkflowGraph::position(m_graph,item->data(0,NodeIdRole).toString(),canvas->dropPosition); + save();m_tree->setCurrentItem(item); + } else {emit statusMessage("ERROR",QStringLiteral("接口节点未能加入流程:")+graphError);} + return; + } else if (key == QStringLiteral("loop")) { + auto *item=new QTreeWidgetItem; + item->setData(0,NodeIdRole,QUuid::createUuid().toString(QUuid::WithoutBraces)); + item->setData(0,KindRole,QStringLiteral("loop")); + item->setData(0,LoopCountRole,2); + item->setText(0,QStringLiteral("循环")); + item->setText(1,QStringLiteral("循环 × 2")); + insertNode(item); + QString error; + if(syncGraph(error)) { + if(canvas->droppingFromPalette)WorkflowGraph::position(m_graph,item->data(0,NodeIdRole).toString(),canvas->dropPosition); + save();m_tree->setCurrentItem(item); + } else emit statusMessage(QStringLiteral("ERROR"),error); + } + else return; // Only explicit components (one node per RPC) may be added. + if(canvas->droppingFromPalette&&m_tree->currentItem()&&m_tree->currentItem()->data(0,NodeIdRole).toString()!=previousId) { + WorkflowGraph::position(m_graph,m_tree->currentItem()->data(0,NodeIdRole).toString(),canvas->dropPosition);save(); + } + }; + connect(library, &QTreeWidget::itemDoubleClicked, this, [createComponent](QTreeWidgetItem *item, int) { + const auto key=item->data(0,Qt::UserRole).toString(); if(!key.isEmpty())createComponent(key); + }); + static_cast(m_flowView)->componentDropped = createComponent; + auto *taskCanvas=static_cast(m_flowView); + taskCanvas->copyNodes=[this](const QSet &ids) { + auto part=WorkflowGraph::fragment(m_graph,ids); + if(part.value("nodes").toArray().isEmpty())return QJsonObject(); + part.insert("editor",QStringLiteral("task"));return part; + }; + taskCanvas->pasteNodes=[this](const QJsonObject &data,const QPointF &offset) { + if(!m_runSteps.isEmpty()||data.value("editor")!="task")return false; + QHash ids; + const auto part=WorkflowGraph::cloneFragment(data,offset,ids); + QString error;const auto candidate=WorkflowGraph::appendFragment(m_graph,part); + if(!restoreGraph(candidate,error)) { + showTaskNotice(this,QStringLiteral("无法粘贴节点"),error);return false; + } + save(); + m_flowScene->clearSelection(); + for(auto *item:m_flowScene->items())if(ids.values().contains(item->data(7010).toString())&&(item->flags()&QGraphicsItem::ItemIsSelectable)) + item->setSelected(true); + return true; + }; + static_cast(m_flowView)->connectionRequested=[this](const QString &from,const QString &to,QString &error) { + if(!m_runSteps.isEmpty())return false; + if(!WorkflowGraph::connect(m_graph,from,to,error))return false; + save();return true; + }; + static_cast(m_flowView)->connectionRemoved=[this](const QString &from,const QString &to) { + if(!m_runSteps.isEmpty())return;WorkflowGraph::disconnect(m_graph,from,to);save(); + }; + auto *inspector = new QWidget(workspace); + auto *inspectorLayout = new QVBoxLayout(inspector); + auto *inspectorTitle = new QLabel(QStringLiteral("节点参数"), inspector); + inspectorTitle->setObjectName(QStringLiteral("sectionTitle")); + auto *nodeName = new QLineEdit(inspector); + auto *nodeSummary = new QLabel(QStringLiteral("选择画布节点查看参数"), inspector); + nodeSummary->setWordWrap(true); nodeSummary->setTextFormat(Qt::PlainText); + auto *applyName = new QPushButton(QStringLiteral("保存节点参数"), inspector); + auto *rpcEditor = new TaskProtoEditor(inspector); + auto *nodeDevice = new QComboBox(inspector); + nodeDevice->setObjectName(QStringLiteral("workflowNodeDevice")); + configureComboPopup(nodeDevice); + auto *timeout = new QSpinBox(inspector);timeout->setRange(1,1800000);timeout->setSuffix(QStringLiteral(" ms")); + auto *wait = new QSpinBox(inspector);wait->setRange(0,2147483647);wait->setSuffix(QStringLiteral(" ms")); + auto *loopCount = new QSpinBox(inspector);loopCount->setRange(1,100000); + auto *parameterForm=new QFormLayout; + parameterForm->addRow(QStringLiteral("执行设备"),nodeDevice); + parameterForm->addRow(QStringLiteral("循环次数"),loopCount); + parameterForm->addRow(QStringLiteral("接口超时"),timeout); + parameterForm->addRow(QStringLiteral("完成后等待"),wait); + inspectorLayout->addWidget(inspectorTitle); inspectorLayout->addWidget(nodeName); + inspectorLayout->addWidget(nodeSummary);inspectorLayout->addLayout(parameterForm);inspectorLayout->addWidget(rpcEditor); inspectorLayout->addWidget(applyName); + inspectorLayout->addStretch(); + const auto updateInspector = [this,nodeName,nodeSummary,applyName,rpcEditor,nodeDevice,timeout,wait,loopCount,parameterForm] { + auto *item=m_tree->currentItem();QString selected; + for(auto *graphic:m_flowScene->selectedItems())if(graphic->data(7000)=="sleep")selected=graphic->data(0).toString(); + const auto extra=WorkflowGraph::node(m_graph,selected);const bool sleep=!selected.isEmpty(); + nodeName->setProperty("sleepId",selected); + nodeName->setText(item ? item->text(0) : QString()); + nodeSummary->setText(item ? QStringLiteral("类型:%1\n设备:%2\n操作:%3\n等待:%4") + .arg(item->text(1),item->text(3),TaskUi::operationTitle(item->data(0,DeviceTypeRole).toString(),item->text(4)),item->text(5)) : QStringLiteral("选择画布节点查看参数")); + if(sleep){nodeName->setText(extra.value("properties").toObject().value("name").toString());nodeSummary->setText(QStringLiteral("等待节点 · 时长(毫秒)"));} + const bool editable=(item||sleep) && m_runSteps.isEmpty(); + nodeName->setEnabled(editable);applyName->setEnabled(editable); + const bool loop=item&&item->data(0,KindRole)=="loop"; + { + const QSignalBlocker deviceBlocker(nodeDevice); + nodeDevice->clear(); + if(item&&!loop) { + const QString requiredType=item->data(0,DeviceTypeRole).toString(); + for(const QVariant &value:m_availableDevices) { + const QVariantMap device=value.toMap(); + if(deviceTypeName(device.value(QStringLiteral("type")).toInt())!=requiredType)continue; + const QString id=device.value(QStringLiteral("deviceId")).toString(); + if(!id.isEmpty())nodeDevice->addItem(id,device); + } + if(nodeDevice->findText(item->data(0,DeviceIdRole).toString())<0) + nodeDevice->addItem(item->data(0,DeviceIdRole).toString(),QVariantMap{{QStringLiteral("deviceId"),item->data(0,DeviceIdRole).toString()}}); + nodeDevice->setCurrentText(item->data(0,DeviceIdRole).toString()); + } + } + nodeDevice->setVisible(item&&!loop); + parameterForm->labelForField(nodeDevice)->setVisible(item&&!loop); + nodeDevice->setEnabled(editable&&!nodeDevice->currentText().isEmpty()); + loopCount->setVisible(loop);parameterForm->labelForField(loopCount)->setVisible(loop);loopCount->setValue(loop?item->data(0,LoopCountRole).toInt():1); + const auto params=item?QJsonDocument::fromJson(item->data(0,ParametersRole).toString().toUtf8()).object():QJsonObject(); + const bool rpc=item&&!loop&¶ms.contains("service")&¶ms.contains("method"); + rpcEditor->setVisible(rpc);timeout->setVisible(rpc);parameterForm->labelForField(timeout)->setVisible(rpc); + rpcEditor->setProperty("service",rpc?params.value("service").toString():QString()); + rpcEditor->setProperty("method",rpc?params.value("method").toString():QString()); + if(rpc){rpcEditor->setDeviceContext(deviceInfo(item->data(0,DeviceIdRole).toString()));rpcEditor->setOperation(params.value("service").toString(),params.value("method").toString(),params.value("request").toObject());} + timeout->setValue(params.value("timeoutMs").toInt(180000)); + wait->setValue(item?WorkflowGraph::postWait(m_graph,item->data(0,NodeIdRole).toString()):0); + if(sleep)wait->setValue(WorkflowGraph::delay(extra)); + wait->setEnabled(editable);loopCount->setEnabled(editable);timeout->setEnabled(editable); + }; + connect(m_flowScene,&QGraphicsScene::selectionChanged,this,updateInspector); + connect(m_tree,&QTreeWidget::currentItemChanged,this,[updateInspector](QTreeWidgetItem*,QTreeWidgetItem*){updateInspector();}); + connect(m_tree->model(),&QAbstractItemModel::dataChanged,this,[updateInspector]{updateInspector();}); + connect(this,&TaskOrchestrationWidget::availableDevicesChanged,this,updateInspector); + connect(nodeDevice,QOverload::of(&QComboBox::currentIndexChanged),this,[this,nodeDevice,updateInspector](int index) { + auto *item=m_tree->currentItem(); + if(!item||index<0||item->data(0,KindRole)=="loop"||!m_runSteps.isEmpty())return; + const QString id=nodeDevice->currentText().trimmed();if(id.isEmpty())return; + item->setData(0,DeviceIdRole,id);item->setText(3,id); + emit deviceInfoRequested(id,item->data(0,DeviceTypeRole).toString()); + updateInspector();save(); + }); + connect(applyName,&QPushButton::clicked,this,[this,nodeName,rpcEditor,timeout,wait,loopCount] { + auto *item=m_tree->currentItem(); const auto name=nodeName->text().trimmed(); + if(!m_runSteps.isEmpty()||name.isEmpty())return; + const QString sleepId=nodeName->property("sleepId").toString(); + if(!sleepId.isEmpty()){WorkflowGraph::editDelay(m_graph,sleepId,name,wait->value());save();return;} + if(!item)return; + QJsonObject request;QString error; + const QString service=rpcEditor->property("service").toString(),method=rpcEditor->property("method").toString(); + if(!service.isEmpty()&&!rpcEditor->request(request,error)){showTaskNotice(this,QStringLiteral("参数错误"),error);return;} + { + QSignalBlocker guard(m_tree->model());item->setText(0,name); + if(item->data(0,KindRole)=="loop") {item->setData(0,LoopCountRole,loopCount->value());item->setText(1,QStringLiteral("循环 × %1").arg(loopCount->value()));} + if(!service.isEmpty()) { + const QJsonObject params{{"service",service},{"method",method},{"request",request},{"timeoutMs",timeout->value()}}; + item->setData(0,ParametersRole,QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact))); + } + item->setData(0,WaitRole,wait->value());item->setText(5,waitDisplayText(wait->value(),"ms")); + } + if(WorkflowGraph::postWait(m_graph,item->data(0,NodeIdRole).toString())!=wait->value())WorkflowGraph::setWait(m_graph,item->data(0,NodeIdRole).toString(),wait->value());save(); + }); + updateInspector(); + auto *inspectorScroll=new QScrollArea(workspace);inspectorScroll->setWidgetResizable(true);inspectorScroll->setFrameShape(QFrame::NoFrame);inspectorScroll->setWidget(inspector);inspector->setMinimumWidth(300); + inspectorScroll->setStyleSheet(QStringLiteral( + "QScrollArea{border:0;background:#f3f6fa;}" + "QScrollBar:vertical{width:8px;background:transparent;margin:4px 2px;}" + "QScrollBar::handle:vertical{min-height:28px;background:#c5d0df;border-radius:4px;}" + "QScrollBar::handle:vertical:hover{background:#91a5bd;}" + "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;background:transparent;}" + "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:transparent;}")); + workspace->addWidget(libraryPanel); workspace->addWidget(m_flowView); workspace->addWidget(inspectorScroll); + workspace->setStretchFactor(1,1); workspace->setSizes({190,850,360}); + workspace->setChildrenCollapsible(false); + layout->addWidget(workspace, 1); + m_editControls << libraryPanel << inspector; + for (const auto &entry : {qMakePair(QStringLiteral("组件库"), libraryPanel), + qMakePair(QStringLiteral("节点参数"), static_cast(inspectorScroll))}) { + auto *toggle = new QPushButton(entry.first,panel); + toggle->setObjectName(QStringLiteral("secondaryButton")); + toggle->setCheckable(true);toggle->setChecked(true); + toolbar->insertWidget(0,toggle); + connect(toggle,&QPushButton::toggled,entry.second,&QWidget::setVisible); + } QLabel *historyTitle = new QLabel(QStringLiteral("执行反馈"), panel); historyTitle->setObjectName(QStringLiteral("sectionTitle")); layout->addWidget(historyTitle); m_history = new QListWidget(panel); m_history->setObjectName(QStringLiteral("taskExecutionHistory")); m_history->setAlternatingRowColors(true); - m_history->setMaximumHeight(128); - m_history->setMinimumHeight(82); + m_history->setMaximumHeight(64); + m_history->setMinimumHeight(42); m_history->addItem(QStringLiteral("尚未执行任务")); connect(m_history->model(),&QAbstractItemModel::rowsInserted,this,[this]{while(m_history->count()>200)delete m_history->takeItem(0);}); connect(m_history,&QListWidget::itemDoubleClicked,this,[this](QListWidgetItem* item){ @@ -1006,19 +771,14 @@ TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(pare m_groups[m_activeGroup].insert(QStringLiteral("name"), name); m_groupCombo->setItemText(m_activeGroup, name); save(); }); connect(m_groupCombo, QOverload::of(&QComboBox::currentIndexChanged), this, &TaskOrchestrationWidget::activateGroup); - connect(addTaskButton, &QPushButton::clicked, this, [this]() { addTask(); }); - connect(addLoopButton, &QPushButton::clicked, this, [this]() { addLoop(); }); - connect(editButton, &QPushButton::clicked, this, &TaskOrchestrationWidget::editSelected); - connect(m_tree, &QTreeWidget::itemDoubleClicked, this, [this](QTreeWidgetItem *, int) { editSelected(); }); connect(removeButton, &QPushButton::clicked, this, &TaskOrchestrationWidget::removeSelected); - connect(upButton, &QPushButton::clicked, this, [this]() { moveSelected(-1); }); - connect(downButton, &QPushButton::clicked, this, [this]() { moveSelected(1); }); connect(m_tree->model(), &QAbstractItemModel::rowsMoved, this, [this]() { save(); }); connect(m_flowScene, &QGraphicsScene::selectionChanged, this, [this]() { const QList selected = m_flowScene->selectedItems(); if (!selected.isEmpty()) { if (TaskFlowCard *card = dynamic_cast(selected.first())) m_tree->setCurrentItem(card->source()); + else m_tree->setCurrentItem(nullptr); } else m_tree->setCurrentItem(nullptr); QTreeWidgetItem *item = m_tree->currentItem(); if (item) m_insertionParent = item->parent(); @@ -1039,37 +799,6 @@ TaskOrchestrationWidget::~TaskOrchestrationWidget() disconnect(m_flowScene, nullptr, this, nullptr); } -void TaskOrchestrationWidget::addTask(QTreeWidgetItem *) -{ - if (!m_runSteps.isEmpty()) return; - QString name = QStringLiteral("新任务"); QString type = QStringLiteral("机械臂"); - QString deviceId; QString action = QStringLiteral("MoveJ"); QJsonObject params; int waitMs = 0; - QString waitUnit = QStringLiteral("ms"); - if (!editTaskDialog(this, name, type, deviceId, action, params, waitMs, waitUnit, - m_availableDevices, m_cameraCapabilities)) return; - QTreeWidgetItem *item = new QTreeWidgetItem; - item->setFlags(item->flags() & ~Qt::ItemIsDropEnabled); - item->setData(0, KindRole, QStringLiteral("task")); item->setData(0, DeviceTypeRole, type); - item->setData(0, DeviceIdRole, deviceId); item->setData(0, ActionRole, action); - item->setData(0, ParametersRole, QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact))); - item->setData(0, WaitRole, waitMs); item->setData(0, WaitUnitRole, waitUnit); - item->setText(0, name); item->setText(1, type); item->setText(2, type); - item->setText(3, deviceId); item->setText(4, action); item->setText(5, waitDisplayText(waitMs, waitUnit)); - insertNode(item); -} - -void TaskOrchestrationWidget::addLoop(QTreeWidgetItem *) -{ - if (!m_runSteps.isEmpty()) return; - QString name = QStringLiteral("循环"); - int count = 2; - if (!editLoopDialog(this, QStringLiteral("新增循环节点"), name, count)) return; - QTreeWidgetItem *item = new QTreeWidgetItem; - item->setData(0, KindRole, QStringLiteral("loop")); item->setData(0, LoopCountRole, count); - item->setText(0, name); item->setText(1, QStringLiteral("循环 × %1").arg(count)); - item->setExpanded(true); insertNode(item); -} - void TaskOrchestrationWidget::insertNode(QTreeWidgetItem *item) { const int count = m_insertionParent ? m_insertionParent->childCount() : m_tree->topLevelItemCount(); @@ -1091,14 +820,7 @@ void TaskOrchestrationWidget::updateInsertionHint() QStringList path; for (auto *parent = m_insertionParent; parent; parent = parent->parent()) path.prepend(parent->text(0)); path.prepend(QStringLiteral("根流程")); - const int count = m_insertionParent ? m_insertionParent->childCount() : m_tree->topLevelItemCount(); - const int index = m_insertionIndex < 0 ? count : qBound(0, m_insertionIndex, count); - QTreeWidgetItem *previous = index > 0 ? (m_insertionParent ? m_insertionParent->child(index - 1) - : m_tree->topLevelItem(index - 1)) : nullptr; - const QString description = QStringLiteral("添加到:%1%2") - .arg(path.join(QStringLiteral(" / ")), - m_insertionIndex >= 0 && previous ? QStringLiteral("(插入到“%1”之后)").arg(previous->text(0)) - : QStringLiteral("(末尾)")); + const QString description=QStringLiteral("新节点所属:%1 · 端口连线决定顺序").arg(path.join(QStringLiteral(" / "))); m_insertionHint->setText(m_insertionHint->fontMetrics().elidedText(description, Qt::ElideMiddle, 520)); m_insertionHint->setToolTip(description); } @@ -1124,91 +846,107 @@ bool TaskOrchestrationWidget::useSelectedLoopAsInsertionParent() return true; } -void TaskOrchestrationWidget::editSelected() -{ - if (!m_runSteps.isEmpty()) return; - QTreeWidgetItem *item = m_tree->currentItem(); if (!item) return; - if (item->data(0, KindRole).toString() == QStringLiteral("loop")) { - QString name = item->text(0); - int count = item->data(0, LoopCountRole).toInt(); - if (!editLoopDialog(this, QStringLiteral("编辑循环节点"), name, count)) return; - item->setText(0, name); item->setText(1, QStringLiteral("循环 × %1").arg(count)); item->setData(0, LoopCountRole, count); save(); return; - } - QString name = item->text(0), type = item->data(0, DeviceTypeRole).toString(); - QString deviceId = item->data(0, DeviceIdRole).toString(), action = item->data(0, ActionRole).toString(); - QJsonObject params = QJsonDocument::fromJson(item->data(0, ParametersRole).toString().toUtf8()).object(); - int waitMs = item->data(0, WaitRole).toInt(); - QString waitUnit = normalizedWaitUnit(item->data(0, WaitUnitRole).toString()); - if (!editTaskDialog(this, name, type, deviceId, action, params, waitMs, waitUnit, - m_availableDevices, m_cameraCapabilities)) return; - item->setText(0, name); item->setText(1, type); item->setText(2, type); item->setText(3, deviceId); - item->setText(4, action); item->setText(5, waitDisplayText(waitMs, waitUnit)); - item->setData(0, DeviceTypeRole, type); item->setData(0, DeviceIdRole, deviceId); item->setData(0, ActionRole, action); - item->setData(0, ParametersRole, QString::fromUtf8(QJsonDocument(params).toJson(QJsonDocument::Compact))); - item->setData(0, WaitRole, waitMs); item->setData(0, WaitUnitRole, waitUnit); save(); -} - void TaskOrchestrationWidget::removeSelected() { if (!m_runSteps.isEmpty()) return; - QTreeWidgetItem *item = m_tree->currentItem(); if (!item) return; + QTreeWidgetItem *item = m_tree->currentItem(); + if(!item){QString id;for(auto *graphic:m_flowScene->selectedItems())if(graphic->data(7000)=="sleep")id=graphic->data(0).toString();if(!id.isEmpty()){WorkflowGraph::removeNode(m_graph,id);save();}return;} m_insertionParent = item->parent(); m_insertionIndex = -1; - delete item; save(); + WorkflowGraph::removeNode(m_graph,item->data(0,NodeIdRole).toString());delete item; save(); } -void TaskOrchestrationWidget::moveSelected(int offset) +bool TaskOrchestrationWidget::appendCompiledSteps(const QJsonArray &nodes, + QList &steps, + QString *error, int depth) const { - if (!m_runSteps.isEmpty()) return; - QTreeWidgetItem *item = m_tree->currentItem(); if (!item) return; - QTreeWidgetItem *parent = item->parent(); int index = parent ? parent->indexOfChild(item) : m_tree->indexOfTopLevelItem(item); - int count = parent ? parent->childCount() : m_tree->topLevelItemCount(); int target = qBound(0, index + offset, count - 1); - if (target == index) return; - captureTaskExpansion(item); - if (parent) { parent->takeChild(index); parent->insertChild(target, item); } - else { m_tree->takeTopLevelItem(index); m_tree->insertTopLevelItem(target, item); } - restoreTaskExpansion(item); - m_insertionParent = parent; m_insertionIndex = target + 1; - m_tree->setCurrentItem(item); save(); -} - -bool TaskOrchestrationWidget::appendRunSteps(QTreeWidgetItem *item, QList &steps, - QString *error, int depth) const -{ - if (depth > 32 || steps.size() >= 100000) { - *error = QStringLiteral("任务展开超过限制(最多 32 层、100000 步),请减少循环次数或嵌套层数"); + if (depth > 16 || steps.size() >= 100000) { + if (error) *error = QStringLiteral("工作流展开超过限制(最多 16 层、100000 步)"); return false; } - if (item->data(0, KindRole).toString() == QStringLiteral("loop")) { - if (!item->childCount()) { - *error = QStringLiteral("循环“%1”没有子节点,请先添加任务").arg(item->text(0)); + const auto appendDelay = [&](int milliseconds) { + if (milliseconds <= 0) return true; + if (steps.size() >= 100000) { + if (error) *error = QStringLiteral("工作流展开超过100000步"); return false; } - for (int repeat = 0; repeat < item->data(0, LoopCountRole).toInt(); ++repeat) - for (int i = 0; i < item->childCount(); ++i) - if (!appendRunSteps(item->child(i), steps, error, depth + 1)) return false; + RunStep delay; + delay.name = QStringLiteral("等待"); + delay.action = QStringLiteral("__workflow_wait__"); + delay.waitMs = milliseconds; + steps.append(delay); return true; + }; + for (const auto &value : nodes) { + const QJsonObject node = value.toObject(); + if (node.value(QStringLiteral("kind")) == QStringLiteral("loop")) { + const int count = node.value(QStringLiteral("count")).toInt(); + if (count < 1 || count > 100000) { + if (error) *error = QStringLiteral("循环次数无效:%1").arg(node.value("name").toString()); + return false; + } + const QJsonArray children = node.value(QStringLiteral("children")).toArray(); + if (children.isEmpty()) { + if (error) *error = QStringLiteral("循环“%1”没有子节点").arg(node.value("name").toString()); + return false; + } + const int leadingDelay=WorkflowGraph::leadingWait(m_graph,node.value(QStringLiteral("id")).toString()); + for (int i = 0; i < count; ++i) { + if(!appendDelay(leadingDelay))return false; + if (!appendCompiledSteps(children, steps, error, depth + 1)) return false; + } + if (!appendDelay(node.value(QStringLiteral("waitMs")).toInt())) return false; + continue; + } + if (node.value(QStringLiteral("kind")) != QStringLiteral("task")) { + if (error) *error = QStringLiteral("不支持的工作流节点类型:%1").arg(node.value("kind").toString()); + return false; + } + if (steps.size() >= 100000) { + if (error) *error = QStringLiteral("工作流展开超过100000步"); + return false; + } + RunStep step; + step.name = node.value(QStringLiteral("name")).toString(); + step.deviceType = node.value(QStringLiteral("deviceType")).toString(); + step.deviceId = node.value(QStringLiteral("deviceId")).toString(); + step.action = node.value(QStringLiteral("action")).toString(); + step.parameters = node.value(QStringLiteral("parameters")).toObject(); + step.waitMs = node.value(QStringLiteral("waitMs")).toInt(); + step.waitUnit = normalizedWaitUnit(node.value(QStringLiteral("waitUnit")).toString()); + const QString id = node.value(QStringLiteral("id")).toString(); + for (QTreeWidgetItemIterator it(m_tree); *it; ++it) { + if ((*it)->data(0, NodeIdRole).toString() == id) { + step.source = *it; + break; + } + } + steps.append(step); } - RunStep step; step.name = item->text(0); step.deviceType = item->data(0, DeviceTypeRole).toString(); - step.deviceId = item->data(0, DeviceIdRole).toString(); step.action = item->data(0, ActionRole).toString(); - step.parameters = QJsonDocument::fromJson(item->data(0, ParametersRole).toString().toUtf8()).object(); - step.waitMs = item->data(0, WaitRole).toInt(); - step.waitUnit = normalizedWaitUnit(item->data(0, WaitUnitRole).toString()); - step.source = item; steps.append(step); return true; } void TaskOrchestrationWidget::startRun() { if (!m_runSteps.isEmpty()) return; + QJsonObject compiledDocument; + if(!m_graph.isEmpty()) { + QString error; + if(!FreeScanInterop::importGraph(m_graph,compiledDocument,error)||!restoreGraph(m_graph,error)) { + showTaskNotice(this,QStringLiteral("无法执行工作流"),error);return; + } + } ++m_executionGeneration; m_runSteps.clear(); + const int initial=WorkflowGraph::leadingWait(m_graph,QString());if(initial){RunStep delay;delay.name=QStringLiteral("等待");delay.action="__workflow_wait__";delay.waitMs=initial;m_runSteps.append(delay);} QString error; - for (int i = 0; i < m_tree->topLevelItemCount(); ++i) - if (!appendRunSteps(m_tree->topLevelItem(i), m_runSteps, &error)) { - m_runSteps.clear(); - showTaskNotice(this, QStringLiteral("无法执行任务"), error); - return; - } + const QJsonArray compiledGroups=compiledDocument.value(QStringLiteral("groups")).toArray(); + const QJsonArray compiledNodes=compiledGroups.isEmpty()?QJsonArray(): + compiledGroups.first().toObject().value(QStringLiteral("nodes")).toArray(); + if (!appendCompiledSteps(compiledNodes, m_runSteps, &error)) { + m_runSteps.clear(); + showTaskNotice(this, QStringLiteral("无法执行工作流"), error); + return; + } if (m_runSteps.isEmpty()) { showTaskNotice(this, QStringLiteral("任务编排"), QStringLiteral("当前方案没有可执行任务。")); @@ -1234,6 +972,7 @@ void TaskOrchestrationWidget::runNext() m_history->scrollToBottom(); rebuildFlowScene(); m_status->setText(QStringLiteral("正在执行 %1(%2/%3)").arg(step.name).arg(m_runIndex).arg(m_runSteps.size())); + if(step.action=="__workflow_wait__"){m_waitingForResult=false;m_runTimer->start(step.waitMs);return;} m_waitingForResult = true; m_currentWaitMs = step.waitMs; m_currentWaitUnit = step.waitUnit; @@ -1458,6 +1197,7 @@ QJsonObject TaskOrchestrationWidget::itemToJson(QTreeWidgetItem *item) const object.insert("id",item->data(0,NodeIdRole).toString()); object.insert(QStringLiteral("kind"), kind); object.insert(QStringLiteral("name"), item->text(0)); if (kind == QStringLiteral("loop")) { + object.insert(QStringLiteral("waitMs"),item->data(0,WaitRole).toInt()); object.insert(QStringLiteral("collapsed"), !item->isExpanded()); object.insert(QStringLiteral("count"), item->data(0, LoopCountRole).toInt()); QJsonArray children; for (int i = 0; i < item->childCount(); ++i) children.append(itemToJson(item->child(i))); @@ -1480,6 +1220,7 @@ QTreeWidgetItem *TaskOrchestrationWidget::itemFromJson(const QJsonObject &object QTreeWidgetItem *item = new QTreeWidgetItem; const QString kind = object.value(QStringLiteral("kind")).toString(QStringLiteral("task")); item->setData(0,NodeIdRole,object.value("id").toString(QUuid::createUuid().toString(QUuid::WithoutBraces))); item->setData(0, KindRole, kind); item->setText(0, object.value(QStringLiteral("name")).toString()); + if(kind==QStringLiteral("loop"))item->setData(0,WaitRole,object.value("waitMs").toInt()); if (kind == QStringLiteral("loop")) { const int count = qMax(1, object.value(QStringLiteral("count")).toInt(1)); item->setData(0, LoopCountRole, count); item->setText(1, QStringLiteral("循环 × %1").arg(count)); @@ -1522,6 +1263,9 @@ void TaskOrchestrationWidget::rebuildFlowScene() std::function place = [&](QTreeWidgetItem *item, qreal x, qreal y) { positions.insert(item, QPointF(x, y)); + const auto saved=WorkflowGraph::node(m_graph,item->data(0,NodeIdRole).toString()); + if(!saved.isEmpty())positions[item]=QPointF(saved.value("x").toDouble()-kTaskCardWidth/2, + saved.value("y").toDouble()-kTaskCardHeight/2); if (!item->isExpanded()) return; qreal childX = x + 40; for (int i = 0; i < item->childCount(); ++i) { @@ -1542,20 +1286,16 @@ void TaskOrchestrationWidget::rebuildFlowScene() const QString subtitle = loop ? QStringLiteral("循环 × %1 · %2 个子节点").arg(item->data(0, LoopCountRole).toInt()).arg(item->childCount()) : QStringLiteral("%1 · %2\n等待 %3") - .arg(item->data(0, DeviceIdRole).toString(), item->data(0, ActionRole).toString()) + .arg(item->data(0, DeviceIdRole).toString(), TaskUi::operationTitle(item->data(0,DeviceTypeRole).toString(),item->data(0, ActionRole).toString())) .arg(waitDisplayText(item->data(0, WaitRole).toInt(), item->data(0, WaitUnitRole).toString())); TaskFlowCard *card = new TaskFlowCard(item, item->text(0), subtitle, loop, [this, revision](QTreeWidgetItem *source, const QPointF &position) { QTimer::singleShot(0, this, [this, source, position, revision]() { - if (revision == m_sceneRevision) moveFlowItem(source, position); - }); - }, - [this, revision](QTreeWidgetItem *source) { - QTimer::singleShot(0, this, [this, source, revision]() { - if (revision != m_sceneRevision || !m_runSteps.isEmpty()) return; - m_tree->setCurrentItem(source); editSelected(); + if(revision!=m_sceneRevision||!m_runSteps.isEmpty())return; + WorkflowGraph::position(m_graph,source->data(0,NodeIdRole).toString(),position+QPointF(kTaskCardWidth/2,kTaskCardHeight/2));save(); }); }, + [](QTreeWidgetItem *) {}, [this, revision](QTreeWidgetItem *source) { QTimer::singleShot(0, this, [this, source, revision]() { if (revision != m_sceneRevision || !m_runSteps.isEmpty()) return; @@ -1564,32 +1304,65 @@ void TaskOrchestrationWidget::rebuildFlowScene() }); card->setPos(it.value()); card->setData(0, QStringLiteral("taskNode")); card->setData(1, item->text(0)); + card->setData(7010,item->data(0,NodeIdRole));if(loop)card->setData(7011,QStringLiteral("loop")); m_flowScene->addItem(card); + workflowPorts(card,item->data(0,NodeIdRole).toString()); if (item == selected) card->setSelected(true); } auto link = [&](QTreeWidgetItem *from, QTreeWidgetItem *to, bool membership) { if (!positions.contains(from) || !positions.contains(to)) return; - const QPointF offset(kTaskCardWidth / 2, kTaskCardHeight / 2); - auto *edge = m_flowScene->addLine(QLineF(positions.value(from) + offset, positions.value(to) + offset), - QPen(QColor(membership ? "#9aabc0" : "#5a91cf"), membership ? 2.0 : 1.5, - membership ? Qt::SolidLine : Qt::DashLine)); + const auto source=positions.value(from);const auto target=positions.value(to); + auto *edge=workflowWire(m_flowScene, + source+(membership ? QPointF(kTaskCardWidth/2,kTaskCardHeight) : QPointF(kTaskCardWidth,kTaskCardHeight/2)), + target+(membership ? QPointF(kTaskCardWidth/2,0) : QPointF(0,kTaskCardHeight/2)),membership); edge->setZValue(0); edge->setData(0, membership ? QStringLiteral("membership") : QStringLiteral("sequence")); }; - for (auto it = positions.constBegin(); it != positions.constEnd(); ++it) { + if(m_graph.isEmpty())for (auto it = positions.constBegin(); it != positions.constEnd(); ++it) { QTreeWidgetItem *item = it.key(); if (item->parent()) link(item->parent(), item, true); QTreeWidgetItem *parent = item->parent(); const int index = parent ? parent->indexOfChild(item) : m_tree->indexOfTopLevelItem(item); if (index > 0) link(parent ? parent->child(index - 1) : m_tree->topLevelItem(index - 1), item, false); } - m_flowScene->setSceneRect(m_flowScene->itemsBoundingRect().adjusted(-60, -60, 60, 60)); + if(!m_graph.isEmpty()) { + QHash bounds; + for(auto it=positions.begin();it!=positions.end();++it)bounds[it.key()->data(0,NodeIdRole).toString()]=QRectF(it.value(),QSizeF(kTaskCardWidth,kTaskCardHeight)); + 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))continue; + if(type!="start"&&type!="end"&&type!="subStart"&&type!="subEnd"&&type!="sleep"&&type!="loop")continue; + QString parent=n.value("properties").toObject().value("parentId").toString();bool hidden=false; + while(!parent.isEmpty()) { + for(QTreeWidgetItemIterator it(m_tree);*it;++it) + if((*it)->data(0,NodeIdRole)==parent&&!(*it)->isExpanded())hidden=true; + parent=WorkflowGraph::node(m_graph,parent).value("properties").toObject().value("parentId").toString(); + } + if(hidden)continue; + auto *terminal=workflowTerminal(m_flowScene,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_runSteps.isEmpty()){WorkflowGraph::position(m_graph,id,center);save();}});}; + if(type=="sleep")terminal->setToolTip(QStringLiteral("选中后在右侧修改等待时长;拖动端口连接执行顺序")); + bounds[id]=terminal->sceneBoundingRect(); + } + workflowContainers(m_flowScene,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))continue; + workflowWire(m_flowScene,QPointF(bounds[from].right(),bounds[from].center().y()), + QPointF(bounds[to].left(),bounds[to].center().y()),false,from,to); + } + } + static_cast(m_flowView)->syncExtent(); updateInsertionHint(); } void TaskOrchestrationWidget::moveFlowItem(QTreeWidgetItem *item, const QPointF &position) { if (!item || !m_runSteps.isEmpty()) return; + if(!m_graph.isEmpty()) { + WorkflowGraph::position(m_graph,item->data(0,NodeIdRole).toString(),position+QPointF(kTaskCardWidth/2,kTaskCardHeight/2)); + save();return; + } QTreeWidgetItem *parent = item->parent(); QList> siblings; for (QGraphicsItem *graphicsItem : m_flowScene->items()) { @@ -1632,6 +1405,7 @@ void TaskOrchestrationWidget::setDeviceInfo(const QString& id,const QVariantMap& void TaskOrchestrationWidget::setAvailableDevices(const QVariantList &devices) { m_availableDevices = devices; + emit availableDevicesChanged(); } void TaskOrchestrationWidget::setCameraCapabilities(const QString &deviceId, @@ -1654,22 +1428,38 @@ void TaskOrchestrationWidget::activateGroup(int index) if (m_switchingGroup || index < 0 || index >= m_groups.size()) return; m_insertionParent = nullptr; m_insertionIndex = -1; storeCurrentGroup(); m_activeGroup = index; m_tree->clear(); + m_graph=QJsonDocument::fromJson(m_groups.at(index).value("flowData").toString().toUtf8()).object(); for (const QJsonValue &node : m_groups.at(index).value(QStringLiteral("nodes")).toArray()) m_tree->addTopLevelItem(itemFromJson(node.toObject())); for (int i = 0; i < m_tree->topLevelItemCount(); ++i) restoreTaskExpansion(m_tree->topLevelItem(i)); save(); + static_cast(m_flowView)->resetView(); + QTimer::singleShot(0,this,[this]{static_cast(m_flowView)->resetView();}); } void TaskOrchestrationWidget::load() { + QString activeFlowId; QFile file(storagePath()); if(file.exists()){ if(!file.open(QIODevice::ReadOnly)){m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("无法读取任务文件,禁止自动覆盖"));} else {QJsonParseError parse;const auto doc=QJsonDocument::fromJson(file.readAll(),&parse);auto data=doc.object();QString error; + activeFlowId=data.value("activeFlowId").toString(); + if(parse.error==QJsonParseError::NoError&&data.value("flows").isArray()) { + QJsonArray groups; + for(const auto &value:data.value("flows").toArray()) { + const auto record=value.toObject();const auto graph=QJsonDocument::fromJson(record.value("flowData").toString().toUtf8()).object(); + QJsonObject converted;if(!FreeScanInterop::importGraph(graph,converted,error,false,true))break; + auto group=converted.value("groups").toArray().first().toObject(); + group.insert("id",record.value("id"));group.insert("name",record.value("name"));group.insert("flowData",record.value("flowData"));groups.append(group); + } + if(!error.isEmpty()){m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("图文件读取失败,已禁止覆盖:")+error);} + data=QJsonObject{{"groups",groups}}; + } if(parse.error!=QJsonParseError::NoError||!doc.isObject()||!TaskApi::normalize(data,error)){ m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("任务文件无效,原文件保留并禁止覆盖:")+error); }else{ - if(doc.object().value("version").toInt()==1 || !doc.object().contains("format")){ - const QString backup=QFile::exists(storagePath()+".v1.bak")?storagePath()+".v1."+QUuid::createUuid().toString(QUuid::WithoutBraces)+".bak":storagePath()+".v1.bak"; + if(!doc.object().value("flows").isArray()){ + const QString backup=storagePath()+".before-graph."+QUuid::createUuid().toString(QUuid::WithoutBraces)+".bak"; if(!QFile::copy(storagePath(),backup)){m_storageWritable=false;emit statusMessage("ERROR",QStringLiteral("旧任务备份失败,禁止覆盖原文件"));} } for(const auto& g:data.value("groups").toArray())m_groups.append(g.toObject()); @@ -1678,10 +1468,33 @@ void TaskOrchestrationWidget::load() } if (m_groups.isEmpty()) { QJsonObject group; group.insert("id",QUuid::createUuid().toString(QUuid::WithoutBraces)); group.insert(QStringLiteral("name"), QStringLiteral("默认任务")); group.insert(QStringLiteral("nodes"), QJsonArray()); m_groups.append(group); } m_switchingGroup = true; for (const QJsonObject &group : m_groups) m_groupCombo->addItem(group.value(QStringLiteral("name")).toString()); - m_groupCombo->setCurrentIndex(0); m_switchingGroup = false; m_activeGroup = 0; - for (const QJsonValue &node : m_groups.first().value(QStringLiteral("nodes")).toArray()) m_tree->addTopLevelItem(itemFromJson(node.toObject())); + int active=0;for(int i=0;isetCurrentIndex(active); m_switchingGroup = false; m_activeGroup = active; + for (const QJsonValue &node : m_groups.at(active).value(QStringLiteral("nodes")).toArray()) m_tree->addTopLevelItem(itemFromJson(node.toObject())); for (int i = 0; i < m_tree->topLevelItemCount(); ++i) restoreTaskExpansion(m_tree->topLevelItem(i)); + m_graph=QJsonDocument::fromJson(m_groups.at(active).value("flowData").toString().toUtf8()).object(); + if(m_storageWritable){QString error;if(!syncGraph(error))emit statusMessage("ERROR",error);} rebuildFlowScene(); + if(m_storageWritable)save(); +} + +bool TaskOrchestrationWidget::syncGraph(QString &error) +{ + if(m_activeGroup<0)return false; + storeCurrentGroup();QJsonObject graph; + if(!FreeScanInterop::exportGraph(QJsonObject{{"groups",QJsonArray{m_groups.at(m_activeGroup)}}},0,graph,error))return false; + m_graph=WorkflowGraph::merge(graph,m_graph); + m_groups[m_activeGroup].insert("flowData",QString::fromUtf8(QJsonDocument(m_graph).toJson(QJsonDocument::Compact))); + return true; +} +bool TaskOrchestrationWidget::restoreGraph(const QJsonObject &graph,QString &error) +{ + QJsonObject document;if(!FreeScanInterop::importGraph(graph,document,error,false,true))return false; + m_insertionParent=nullptr;m_insertionIndex=-1; + m_tree->clear();for(const auto &n:document.value("groups").toArray().first().toObject().value("nodes").toArray()) + m_tree->addTopLevelItem(itemFromJson(n.toObject())); + for(int i=0;itopLevelItemCount();++i)restoreTaskExpansion(m_tree->topLevelItem(i)); + m_graph=graph;storeCurrentGroup();return true; } void TaskOrchestrationWidget::save() @@ -1691,13 +1504,28 @@ void TaskOrchestrationWidget::save() QJsonObject root; root.insert(QStringLiteral("groups"), groups); QString error;if(!TaskApi::normalize(root,error)){emit statusMessage("ERROR",QStringLiteral("任务校验失败,未覆盖文件:")+error);return;} m_groups.clear();for(const auto& group:root.value("groups").toArray())m_groups.append(group.toObject()); + if(!syncGraph(error)){emit statusMessage("ERROR",QStringLiteral("图转换失败,原文件未覆盖:")+error);return;} + QJsonArray records; + for(auto &group:m_groups) { + if(group.value("flowData").toString().isEmpty()) { + QJsonObject graph;if(!FreeScanInterop::exportGraph(QJsonObject{{"groups",QJsonArray{group}}},0,graph,error)){ + emit statusMessage("ERROR",error);return;} + group.insert("flowData",QString::fromUtf8(QJsonDocument(graph).toJson(QJsonDocument::Compact))); + } + records.append(QJsonObject{{"id",group.value("id")},{"name",group.value("name")},{"flowData",group.value("flowData")}}); + } + const QJsonObject stored{{"flows",records},{"activeFlowId",m_groups.at(m_activeGroup).value("id")}}; QDir().mkpath(QFileInfo(storagePath()).absolutePath()); QSaveFile file(storagePath()); - if (!file.open(QIODevice::WriteOnly) || file.write(QJsonDocument(root).toJson(QJsonDocument::Indented)) < 0 || !file.commit()) + if (!file.open(QIODevice::WriteOnly) || file.write(QJsonDocument(stored).toJson(QJsonDocument::Indented)) < 0 || !file.commit()) emit statusMessage(QStringLiteral("ERROR"), QStringLiteral("任务编排 JSON 保存失败:%1").arg(storagePath())); rebuildFlowScene(); } void TaskOrchestrationWidget::exportDocument(){ + if(!m_graph.isEmpty()) { + QJsonObject compiled;QString error; + if(!FreeScanInterop::importGraph(m_graph,compiled,error)||!restoreGraph(m_graph,error)){showTaskNotice(this,QStringLiteral("无法导出未连通流程"),error);return;} + } storeCurrentGroup();QJsonArray groups;for(const auto& g:m_groups)groups.append(g); QJsonObject document{{"groups",groups}};QString error; if(!TaskApi::serverDocument(document,error)){showTaskNotice(this,QStringLiteral("无法导出"),error);return;} @@ -1713,11 +1541,17 @@ void TaskOrchestrationWidget::importDocument(){ const QString path=QFileDialog::getOpenFileName(this,QStringLiteral("导入任务"),{},QStringLiteral("JSON (*.json)"));if(path.isEmpty())return; QFile file(path);if(!file.open(QIODevice::ReadOnly)){showTaskNotice(this,QStringLiteral("导入失败"),file.errorString());return;} if(file.size()>16*1024*1024){showTaskNotice(this,QStringLiteral("导入失败"),QStringLiteral("文件超过16MB"));return;} - QJsonParseError parse;const auto parsed=QJsonDocument::fromJson(file.readAll(),&parse);auto doc=parsed.object();QString error; + QJsonParseError parse;const auto parsed=QJsonDocument::fromJson(file.readAll(),&parse);auto doc=parsed.object();QString error;QJsonObject sourceGraph; + if(parse.error==QJsonParseError::NoError&&parsed.isObject()&&FreeScanInterop::isGraph(doc)) { + QStringList devices;for(const auto &v:m_availableDevices)devices.append(v.toMap().value("deviceId").toString()); + if(!FreeScanInterop::bindGraphDevices(doc,this,devices))return; + sourceGraph=doc;QJsonObject converted;if(!FreeScanInterop::importGraph(doc,converted,error,false,true)){showTaskNotice(this,QStringLiteral("导入失败"),error);return;}doc=converted; + } if(parse.error!=QJsonParseError::NoError||!parsed.isObject()||!TaskApi::normalize(doc,error)){showTaskNotice(this,QStringLiteral("导入失败"),error.isEmpty()?parse.errorString():error);return;} // Imported plans are appended; existing plans and source files are preserved. - const auto regenerate=[](QJsonObject g){ - std::function renew=[&](QJsonObject& n){n.insert("id",QUuid::createUuid().toString(QUuid::WithoutBraces));auto children=n.value("children").toArray();for(int i=0;i idMap; + const auto regenerate=[&idMap](QJsonObject g){ + std::function renew=[&](QJsonObject& n){const auto id=QUuid::createUuid().toString(QUuid::WithoutBraces);idMap[n.value("id").toString()]=id;n.insert("id",id);auto children=n.value("children").toArray();for(int i=0;iaddItem(group.value("name").toString());} + for(const auto& value:doc.value("groups").toArray()){auto group=regenerate(value.toObject()); + if(!sourceGraph.isEmpty())group.insert("flowData",QString::fromUtf8(QJsonDocument(WorkflowGraph::remap(sourceGraph,idMap)).toJson(QJsonDocument::Compact))); + m_groups.append(group);m_groupCombo->addItem(group.value("name").toString());} m_switchingGroup=false;m_storageWritable=true; if(m_groups.size()>first){m_groupCombo->setCurrentIndex(first);if(m_activeGroup!=first)activateGroup(first);}else save(); } diff --git a/src/taskorchestrationwidget.h b/src/taskorchestrationwidget.h index daf55bf..5e8a676 100644 --- a/src/taskorchestrationwidget.h +++ b/src/taskorchestrationwidget.h @@ -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 &steps, QString *error, int depth = 0) const; + bool appendCompiledSteps(const QJsonArray &nodes, QList &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 m_editControls; QTimer *m_runTimer = nullptr; QList m_groups; + QJsonObject m_graph; QList m_runSteps; int m_activeGroup = -1; int m_runIndex = 0; diff --git a/src/workflowcanvas.h b/src/workflowcanvas.h new file mode 100644 index 0000000..76f7f1c --- /dev/null +++ b/src/workflowcanvas.h @@ -0,0 +1,276 @@ +#pragma once +#include +#include +#include +#include +#include + +inline void workflowContainers(QGraphicsScene *scene,const QJsonObject &graph,const QHash &bounds) { + QHash 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 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 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 componentDropped; + std::function connectionRequested; + std::function connectionRemoved; + std::function &)> copyNodes; + std::function 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;xdrawPoint(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 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); + } +}; diff --git a/src/workflowgraph.h b/src/workflowgraph.h new file mode 100644 index 0000000..d9eca8d --- /dev/null +++ b/src/workflowgraph.h @@ -0,0 +1,354 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +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 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 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 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 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 &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 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 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> 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 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 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 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 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 order(const QJsonObject &graph,QString &error) { + QHash nodes;QHash parent,next,previous;QSet seen; + QHash result; + const auto fail=[&](const QString &message){if(error.isEmpty())error=message;}; + 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 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 waits(const QJsonObject &graph,QString &error) { + QHash result;QHash 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 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; +} +}