From 270afd0fb382f3a983a42e2bd9b143560b85cb7f Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Fri, 16 Oct 2026 09:39:44 +0800 Subject: [PATCH] Unify application theme and settings with task orchestration updates --- .gitignore | 1 + CMakeLists.txt | 21 +- CmvrControlStation.pro | 21 +- README.md | 14 + cmake/SeedApplicationSettings.cmake | 9 + icons/cmvr-app.ico | Bin 0 -> 7077 bytes icons/cmvr-app.svg | 5 + icons/settings.svg | 1 + protos/cmvr/api/camera_command.proto | 2 + resources.qrc | 3 + resources/application.rc | 1 + resources/application_settings.json | 20 + scripts/generate_application_icon.py | 61 ++ src/applicationsettings.cpp | 244 +++++ src/applicationsettings.h | 41 + src/applicationstyle.cpp | 312 ++++++ src/applicationstyle.h | 12 + src/appmessagebox.h | 120 +++ src/cameracapabilities.h | 6 + src/configeditorwidget.cpp | 31 +- src/handeyebridge.cpp | 36 +- src/handeyemotionwidget.cpp | 4 +- src/handeyeprocessworker.h | 31 + src/main.cpp | 25 +- src/mainwindow.cpp | 610 ++++++++++-- src/mainwindow.h | 24 + src/mainwindow_ui.cpp | 73 +- src/robotclient.cpp | 66 +- src/taskorchestrationwidget.cpp | 1374 ++++++++++++++++++++++++++ src/taskorchestrationwidget.h | 96 ++ src/tcpcalibrationwidget.cpp | 14 +- src/touchoperationwidget.cpp | 4 +- src/uiicons.h | 4 +- src/urdfviewerwidget.cpp | 36 + src/urdfviewerwidget.h | 2 + styles.qss | 182 +++- tests/application_shell_test.cpp | 110 +++ tests/applicationtheme_test.cpp | 217 ++++ tests/applicationtheme_test.pro | 9 + tests/run_theme_shell_test.py | 41 + tests/test_camera_modes_protocol.py | 13 + ui/handeyecalibrationwidget.cpp | 10 +- 42 files changed, 3740 insertions(+), 166 deletions(-) create mode 100644 cmake/SeedApplicationSettings.cmake create mode 100644 icons/cmvr-app.ico create mode 100644 icons/cmvr-app.svg create mode 100644 icons/settings.svg create mode 100644 resources/application.rc create mode 100644 resources/application_settings.json create mode 100644 scripts/generate_application_icon.py create mode 100644 src/applicationsettings.cpp create mode 100644 src/applicationsettings.h create mode 100644 src/applicationstyle.cpp create mode 100644 src/applicationstyle.h create mode 100644 src/appmessagebox.h create mode 100644 src/handeyeprocessworker.h create mode 100644 src/taskorchestrationwidget.cpp create mode 100644 src/taskorchestrationwidget.h create mode 100644 tests/application_shell_test.cpp create mode 100644 tests/applicationtheme_test.cpp create mode 100644 tests/applicationtheme_test.pro create mode 100644 tests/run_theme_shell_test.py diff --git a/.gitignore b/.gitignore index e0aa5e9..c4b44db 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ /Makefile /Makefile.* /object_script.* +/*_resource.rc /bin/ /build/ /build_*/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 65a43f5..f41c8c5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.16) project(CmvrControlStation VERSION 1.0.0 LANGUAGES CXX) -set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_AUTOMOC ON) @@ -164,6 +164,8 @@ set(CMVR_SOURCES src/mainwindow.cpp src/mainwindow_ui.cpp src/mainwindow.h + src/taskorchestrationwidget.cpp + src/taskorchestrationwidget.h src/quictestserver.cpp src/quictestserver.h src/rpcservicewidget.cpp @@ -198,7 +200,10 @@ set(CMVR_SOURCES resources.qrc) list(APPEND CMVR_SOURCES - src/handeyebridge.cpp src/handeyebridge.h + src/applicationsettings.cpp src/applicationsettings.h + src/applicationstyle.cpp src/applicationstyle.h + src/appmessagebox.h + src/handeyebridge.cpp src/handeyebridge.h src/handeyeprocessworker.h src/handeyestore.cpp src/handeyestore.h src/handeyeurdf.cpp src/handeyeurdf.h src/touchplanner.cpp src/touchplanner.h @@ -213,6 +218,7 @@ list(APPEND CMVR_SOURCES src/tcpcalibrationwidget.cpp src/tcpcalibrationwidget.h) add_executable(CmvrControlStation ${CMVR_SOURCES}) if(WIN32) + target_sources(CmvrControlStation PRIVATE resources/application.rc) set_target_properties(CmvrControlStation PROPERTIES WIN32_EXECUTABLE TRUE) endif() @@ -374,6 +380,17 @@ add_custom_command(TARGET CmvrControlStation POST_BUILD "$/models") install(TARGETS CmvrControlStation RUNTIME DESTINATION bin) +add_custom_command(TARGET CmvrControlStation POST_BUILD + COMMAND ${CMAKE_COMMAND} + "-DSOURCE=${CMAKE_CURRENT_SOURCE_DIR}/resources/application_settings.json" + "-DDESTINATION=$/data/application_settings.json" + -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/SeedApplicationSettings.cmake" + VERBATIM) +install(CODE " + set(SOURCE \"${CMAKE_CURRENT_SOURCE_DIR}/resources/application_settings.json\") + set(DESTINATION \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/bin/data/application_settings.json\") + include(\"${CMAKE_CURRENT_SOURCE_DIR}/cmake/SeedApplicationSettings.cmake\") +") add_custom_command(TARGET CmvrControlStation POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "$/scripts" COMMAND ${CMAKE_COMMAND} -E copy_if_different diff --git a/CmvrControlStation.pro b/CmvrControlStation.pro index 3d214d5..4ad7383 100644 --- a/CmvrControlStation.pro +++ b/CmvrControlStation.pro @@ -1,6 +1,6 @@ QT += core gui widgets multimedia 3dcore 3drender 3dextras 3dinput 3danimation -CONFIG += c++14 warn_on debug_and_release +CONFIG += c++17 warn_on debug_and_release TEMPLATE = app DEFINES += QT_DEPRECATED_WARNINGS _WIN32_WINNT=0x0600 @@ -237,6 +237,9 @@ CONFIG(debug, debug|release) { !exists($$ASSIMP_SCENE_PARSER): error("Qt3D Assimp scene parser not found in the selected Qt Kit.") SOURCES += \ + src/applicationsettings.cpp \ + src/applicationstyle.cpp \ + src/taskorchestrationwidget.cpp \ src/handeyebridge.cpp \ src/handeyestore.cpp \ src/handeyeurdf.cpp \ @@ -267,7 +270,12 @@ SOURCES += \ ui/handeyecalibrationwidget.cpp HEADERS += \ + src/applicationsettings.h \ + src/applicationstyle.h \ + src/appmessagebox.h \ + src/taskorchestrationwidget.h \ src/handeyebridge.h \ + src/handeyeprocessworker.h \ src/handeyestore.h \ src/handeyeurdf.h \ src/touchplanner.h \ @@ -332,9 +340,18 @@ win32 { } DISTFILES += scripts/handeye_worker.py scripts/handeye_math.py scripts/handeye_refinement.py DISTFILES += scripts/package_handeye_runtime.py +DISTFILES += resources/application_settings.json cmake/SeedApplicationSettings.cmake QMAKE_POST_LINK += $$QMAKE_COPY_DIR $$shell_quote($$shell_path($$MODEL_DIR)) $$shell_quote($$shell_path($$DESTDIR/models)) +win32 { + QMAKE_POST_LINK += $$escape_expand(\n\t) if not exist $$shell_quote($$shell_path($$DESTDIR/data)) $$QMAKE_MKDIR $$shell_quote($$shell_path($$DESTDIR/data)) + QMAKE_POST_LINK += $$escape_expand(\n\t) if not exist $$shell_quote($$shell_path($$DESTDIR/data/application_settings.json)) $$QMAKE_COPY_FILE $$shell_quote($$shell_path($$PWD/resources/application_settings.json)) $$shell_quote($$shell_path($$DESTDIR/data/application_settings.json)) +} else { + QMAKE_POST_LINK += $$escape_expand(\n\t) $$QMAKE_MKDIR $$shell_quote($$DESTDIR/data) + QMAKE_POST_LINK += $$escape_expand(\n\t) test -e $$shell_quote($$DESTDIR/data/application_settings.json) || $$QMAKE_COPY_FILE $$shell_quote($$PWD/resources/application_settings.json) $$shell_quote($$DESTDIR/data/application_settings.json) +} + win32 { isEmpty(HAND_EYE_RUNTIME_DIR): HAND_EYE_RUNTIME_DIR = $$PWD/third_party/handeye-runtime !exists($$HAND_EYE_RUNTIME_DIR/manifest.json): error(Build the bundled runtime with scripts/package_handeye_runtime.py first) @@ -344,7 +361,7 @@ win32 { QMAKE_POST_LINK += $$escape_expand(\n\t) $$QMAKE_COPY_FILE $$shell_quote($$shell_path($$MSQUIC_TEST_CA)) $$shell_quote($$shell_path($$DESTDIR/quic-test-ca.crt)) } -win32:RC_ICONS = +win32:RC_ICONS = icons/cmvr-app.ico HEADERS += src/calibrationfile.h diff --git a/README.md b/README.md index 8f1db04..a4e0954 100644 --- a/README.md +++ b/README.md @@ -294,3 +294,17 @@ powershell -ExecutionPolicy Bypass ` - QUIC 无法启动:检查 MsQuic 动态库搜索路径、PFX 文件、密码、监听地址和防火墙。 Proto 约定和目录说明见 [protos/README.md](protos/README.md)。 + +## 软件设置与界面主题 + +侧栏底部的「软件设置」用于调整界面字体、基础字号、启动页面、窗口大小与位置记忆、启动最大化、日志保留行数和自动滚动。字体与日志设置保存后立即生效,启动选项下次启动生效。 + +「启动与机械臂」中的模型预览开关默认关闭,保存后重启程序生效。关闭时不初始化 Qt3D 场景,机械臂连接、遥测和位置控制照常使用。该开关允许用户选择是否加载模型,并不修复特定 Qt3D/显卡组合的渲染兼容性问题。 + +软件设置保存在可执行文件旁的 `data/application_settings.json`,采用原子写入。现有连接信息、标定、机械臂点位和任务编排继续使用各自的存储,不因修改软件设置而被清除。目录没有写入权限时,设置弹窗会显示保存失败原因。 + +仓库中的 `resources/application_settings.json` 保存随程序分发的初始配置。qmake 构建、CMake 构建和安装时仅在目标目录缺少配置文件时复制,已有的软件设置不会被覆盖;程序的读取路径保持不变。 + +全局主题入口为 `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 均已嵌入可执行文件图标。 diff --git a/cmake/SeedApplicationSettings.cmake b/cmake/SeedApplicationSettings.cmake new file mode 100644 index 0000000..86a8388 --- /dev/null +++ b/cmake/SeedApplicationSettings.cmake @@ -0,0 +1,9 @@ +# Seed a new installation without replacing settings saved by the user. +if(NOT DEFINED SOURCE OR NOT DEFINED DESTINATION) + message(FATAL_ERROR "SOURCE and DESTINATION must be specified") +endif() +if(NOT EXISTS "${DESTINATION}") + get_filename_component(settings_directory "${DESTINATION}" DIRECTORY) + file(MAKE_DIRECTORY "${settings_directory}") + configure_file("${SOURCE}" "${DESTINATION}" COPYONLY) +endif() diff --git a/icons/cmvr-app.ico b/icons/cmvr-app.ico new file mode 100644 index 0000000000000000000000000000000000000000..730a16461fea277f208729e82a2e3718f9fcf740 GIT binary patch literal 7077 zcmai3c|27A*Z<5l7+c1Y?1m&;_MI3Rsq8`$5elhnAxn%klU<^+j6^Bf`i2S_`@SV) z$-b6-ABK6R@Avoo{&=3}_59}bx}WnopL6e>Ip@6J=ibj50APR?Ad!F~QD74Q;7d6; zIsehm!2ocj94OR3I*u|gfB=w@`A4Uv%oX4Opwa*6P84081^_JfAH9Vd06c+FYDZc<95tM6zz$W}ZdL7OT4H z(Keug2`+OX4x*9+^ul005OriMO!L+dUH+WCvn5JY2AvrpG*r1fPu6oMA3lO1d4!`H z6Cs-Xnu)Liqa(;|e{Xr5>{vm@%0@FmC{+b2ZWBf@1VJdn7qfN~^x8{&X~E&MYuvy~ zyhX{Wv*kz5BttNjeYs=bogbv_5b{qlS-t4+WH*Q@a<`{KKf5Cx(Lsdy(k(+tqb|8B zf~Kh{VqFF)x12%ayNBmpU%?V6UVw|bMwp^=_F?~r%akAk&c9ur@H@Lli4fg?yG(#` zH#K=cDHZMqHWUfOZ-c2_Gzo9O_-zE+zD8u{jE$dn^d^RgPt!OttkLLyTUsRtRveN- zmUaYWXiBvmBElF{&y|YPKi^s=zp5Y~O;a3B#ltEtxQBJkV0%RODs!T=FgK!(x zV$ovX-)cwxsa8`rt9>VtQ?A5i?_3piOKn)QkB40_X=kOfZTo}&xK;H@3^17XeubW?&>Fz>! zLNQ`^4sbZ@tV{tQ#W!*u9mpwxAcK9<@C$A-kltQ|BwhuJpeL)C*lf3 zd_+k^*FT9^wmz#*rH$+~{xsIr^{s0|JS6l8R?5K=md9Yp;brf3p|zwv8BLD`2+vLfsm4?)w}s<8*~R!!ZoTsE*bt%g+0oVvwVluoMIG%P}R)d1mQxC$}}2 z9Ssyw3K}-AX`Q}8V@IRvAVN^|XJFZfdipJ9SO(u@zDz-6P1;&~CF~C0m@`IObcEYv zwwco0w0NELBLJGP>c7o7@ACvX-V$)RJ}nDa45lYune98AZZSTVZ!PfBUR_YIIKGJX zqxaFIJ9~0x$pTAU#AfI|6jXL(14kL%oV)E=KHRl1aSzkVcBq}JS}3qPia;l~by(=H zj0G7bO2^m>+JD(@x1vX!!>$UCedWH?s>7LngIx&yfKgcK{F_+}M~7M1p@UTPtil14 zA@bU#o%DTFyv2)vlEx#Kq}@rWgXwLQl*$h~S!&PL=A##i(J?EiU`527GxM<>Drp{r z$FDpVJpTg>&=foRZy3CD^&A5LlK2-4uBjWv1k1x+nK?>3GRtQAxIWCg$X}Q#^t08w+W4Ce}@Y`MKKc5ecJJr?Y2&*@*Uc|j` z$boOeW8N9zB=X*z`o`*?kaEQAZ!!4RFos!sT}g=b^6Wg7c@@sTqwRN+jNEMhh5UVu zICflYMYo;-S}OLK#a?#O$>S^&qx-a1^wnNG?43Q_6`0^&A-YgsKRCL+ukGw75fDTa zyjuI$1KQPqO==5qSBv%ZH(>_UH&swVZYK$s?$rd|)}wrvNqJ$Z4iC(7e|N;oun2y0 zWP@#hPUZ9UBnp&<`W}fr%AaaL{;q6m zkQX;HS3bwd1`;G4WvzV4QJLo?8y!^S?nFL8yoZGjKw;;X4q7K`t7wQYjm zzd9Z@d-H+}F=v=S8sHxV@nnr@A zU3u#RtiJsI4;aHz?AX6CRKyAaFKLfi<^$$1e1Zs^Y3QeSPOT zm%fOKveQSNdual-JxR--KkQ@MY+^Ot%I^8-=p+mn zD*MXEMHQ=I`VxcL9k05|l3vg-ymm`MFW8)Q4zfv*dE!7)4gc&^JFQW+o~D5DvVDDN zk#nfMjq?&W9wq7;6qe0M2e|EE2+lRrG(oeo$KFe29titCoBusScS{qXql{%87s5y8 z(Z2@TsDb2?lL>li>5Zk$0T)ATJgHx6ufMVAv;S71|JqXE=FGP1=El$Nx#i}+=7eg= z9!y1z&TChL^h8k4;$Y~)b;07%A;sRGXmw|Y$Ig@mU%G>JPL?U3f?-K&SCR;P(KP6;rZfmD1ts=DbSNYp&~Gwk zf;<7*gZ(6{-lZsQz2L72rS;=$S~lTsj!q~sNXHbQ1K7ofR~eL~{2$oaGFrIQ{nb22 z*8l)Bze8%|)QnC)3eA@e$GS&JTgo;mBhftRRA9h*xvH{zKSB%;why>fIvP@J)PqMJ zDa%lU_x_qQW0zI=R6m_aL-#O(lHmR5{Zr+RhO=@L+8u!Ks4`_VMwuF3DiPTVutWGK zBfGG$A7b`q;8W3IsqIY{B#KE%m%8%(VGH-i?dkfm)oU9B@z-}w=tE%8A))8!i)lMP zC4N#Ecuam%{2a{0%?CVwN+tJ>X`}-WPjbc~7a*M4onPt(;Ie;61CzotFYqZ*i{5XX z6=;rBv#-{Zjf z(*X!ed67r_5%x$I4v^Z1h6pMw7{K`^>>`{?nkI?qzO$;`t|2)r1F|)w#@0O7s}E)vPBPZWazPdUGmWBpg;5~;`?uSf!zZ`oulLS9{lF=-9LZyN=7%7I(j$7qww=>=9>4r{ z-NtPc+k0hoBK{#w9EEOg+@hNOtr0J>w6f*4Zq7%-7h8nn zqFA^z-GvjJQRb4U$TLeS-Ulq9=!6Nsrgmi#wZ2Yg>jFRNSmti;w% z<7KV<96u~Ht`POU7> zo`-a8nRjmM(My|ud}%tNh31Wq^O$O|kNisD5Z-mTAJtLet+R zo0oqU?slnLwr<{wv@Gb4ovSWd*=Hx^^mkP)?*2M>S5Q!}yTj=iE8Fxx2DJ~XhchvU z`h3@a&6vGOQ>*#jSC(aWTlds9Y1rH2Yp{~hKzEyF_u}B>Y3GFWfJyB)XM9S7ql&T# ze|gnRCJZXK^JLD&a&`@Nzd#5k^#!WDjU;4;P7B!l>PXK@)}>iD;9u(@@{(OL->(x) zZ#BvXG&uUr?=`dfe|Lq}pV4YbK3R=3K8b-_B9%NydaQv8E_G`x%rzrKW8qzwHK$2B zCrcr`k-DynJ~UW(;}88UPAroC}8<}J^HDSWl^HbGO2qsC`aO~1XZZdDSRS+ zVOgxUcA+bzfrwj)AoS*Ug)Gsq{nT&Hz$4%)S}cgIv-5r@api-i#a+@P#^#cEQ~MsUdUh6(v^ow66QwbN&^}NtZ8ph57j~f#>vxPb(JE4)N&O_V` zG&er)PQYy}+S7p_%X;RX71`$nh}*BmgM9Mr4kxv)>`&W$y?RJo9lySaCkIyt;2Xyc zLIlWu`x%Sgah{V+f~iLv3*mhy3YhUh4`(xWeO7FT;JCe&Pf?#Zc5?~I*&oKskA-Zk zxA&jMS6hD{QVu<5bIs-?iqVR{>KK`6t!|R^#MoPn^bm_2yf@r~IjAGYXKIe+;zRoJ zeKqY<6%FoCc>Eh!9ofJB;F`LrnMRcu<}C@ zOW`*0s%2#yy@P=U&&3KlH)7*@XtqbY%w|YDGdyw=lpo#GYM$R?rV8cNo<37IK(1*2 zrI*J$64z*Dt>|LTjDmf7?tqKwbd)X6Dve|dWyRJ#>I5!#tm6%+j=E?pn`z~Q(u z6j*Fj2s-kc1s;Ch|6Oy`&ckyx_Tea1_f)I|Y&fJk(A7OR;4o{K%StYz)Q}TY75?~9 z=XG_It$R)bl+fB2u9BA`6SasbsFfsVpGScZ<5W8FYhq1;SZEc22Szx?ez#a9#10u9 zI5$L%%@jVc!i%UPK!yON(*snr{`7M^g8%euCP*mCNFZwenRl8A6x?{4ihyOiBpI7G z8af{wPWegKsE@1`UHZINvA8-#HgIN$w>-3ZYlQ$Sreo@1o5o$5^Vf-sJ-sZ}&zsK{ zn7@3-Bk=$ujCq`0k;^=h69*kfbK_cJV+ z1>I~MjhizXeIT?f*h=2|U9A-?JuetL>WBnt8M_Gsvm$}Jxk(2M5ZakZBam*pB9q(6 zR*o7AfoKzH@AF^kCQn>tHiS|178QZG9+k)U-u34i9v^+`RaJXm7hXxip{6rrWPn4(NBcN4vJ?6*!fwn3=+5j@3$4%%60ymIr8O?ono zXXd!2gR8R&lgYs4aL3Qw=N`iRi`FdY3HUkA(*OB4JV)5(+FB^A=fjP> z+;O>^KSxrI=_$H2241EIg>FZk2Wi!Vy(5!FotVqh-`h;2sIjT)N8C(W4dcGeN2f&UNlj8c={8!ouydDni`m z@!xgWWh6oB3RxQVOs7-{PYpcJ0FzuAbT^szF_b9@qTOIvAy5J(>YRBJQgMn3mVJQ* z31&<<=J9Z#`xvW0dAd<>3%Y12&txL;{*!Sr`kKc#Rz_fUg6bmtHvKy>mq`Z{4t=+_j9S`;0mYnnn%+YO z0aW;_N_d%Qz?H5~AI}oEj?+pq!XAZ-e4~9M%|VNv;Zw1bLQu{T1=hllA(hu0e9nNe z$$3|9UYZtbtQlCQ0{+Cz2-z?k#J->*EFMkf!L#7|3#QXxgw|&1D`yPCk(A{716^%6 zXxs$Jp>S}KUElkRF5Y?a(R3+8-fr3N}_L(KD(ym%+$g8WrZ3`6El@qk~S%Ek} zecbYgDYJz=6)4Z+4M~r1$G99{HB<#34QPy(>m%`-%Lfk@yxhwo?o!r_Xok-`3+cO( zcW{{%6#63CXt%tz3eefYKn??Y2j8r(f^yp-lny&eY>(h;m*%MKjPs+gZ<~k0zEkud zG^5Mzrnm_=;K~8Wmfxh~?^N`uQ2Oiu^3M#}vO)WUk3|fh=wP^7|3M-jkp{TGZDess zMJQj6y{IokMIZo|YP|{D*3-ws?QG(-3$7ms_pA+=VA)6@_mpn@1iadS z>9t7>Z8N@U;5s%8AZ}WPjJ*z?s6TD@hNu10YyM{WX)6dDM5rFKk@dSv1kHZUid!4y zHFsxqwXjnlI%XMf3XhA+!tAqiCtmAcV`I-*nA1Gm zm>z#!6GN6)4Jf#2ja_d!OY(jH#1>5Spm!cZy`mhBzqv*(JgNkQ zuc5rtYcbag+g^&vyM(x(@Fi-Wpy~UF{xtqnYRC7cC3JhMxqD_Wb%*smxB!P>&C(el z1p$ZR?Nnec#srdT7>o5CcenMC&h;lNutZub-~Q}3(;xZw%M-@M3&vYXWNr}8v?OP$ zedi9BD_)zFx@S1H6SMf>7|5q}0pZsZ#$LorO>glPlhbKtUWj0FB*${OLXm^)gB*jR zRRWSEWu_Lo2$#U)n~V7=*I4P-ZPzo`e|j?U2CuD=n-mDQ(HpMy_oL_Um)oiQekdrb z>gS?%%|q?Jxe8wEK zOqYopV_sb$`d&RLSn()QbKp{CVZ%P1$@4>!YsHqxf}}8acGCF%X^q3fUhMf-3NN~< zx0R`CU%JAWSXTr#79O3Vlh(NK{kfDd(brB_R4AK&Y)?)=^`RvG1Eqys+rXGTg-DpsGd(m1b sYS?{iQB}oGi|6!j=SH5a|Fs9FN)}N;s5{u literal 0 HcmV?d00001 diff --git a/icons/cmvr-app.svg b/icons/cmvr-app.svg new file mode 100644 index 0000000..d6036bc --- /dev/null +++ b/icons/cmvr-app.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/icons/settings.svg b/icons/settings.svg new file mode 100644 index 0000000..8ae8ed8 --- /dev/null +++ b/icons/settings.svg @@ -0,0 +1 @@ + diff --git a/protos/cmvr/api/camera_command.proto b/protos/cmvr/api/camera_command.proto index c2a044a..adb8468 100644 --- a/protos/cmvr/api/camera_command.proto +++ b/protos/cmvr/api/camera_command.proto @@ -56,6 +56,8 @@ message CameraCapabilities { uint64 session_generation = 11; string unavailable_reason = 12; string intrinsics_signature = 13; + bool depth_image = 14; + bool depth_stream = 15; } message CameraState { diff --git a/resources.qrc b/resources.qrc index f1e8717..0e24e20 100644 --- a/resources.qrc +++ b/resources.qrc @@ -1,6 +1,9 @@ styles.qss + icons/cmvr-app.ico + icons/cmvr-app.svg + icons/settings.svg icons/activity.svg icons/bot.svg icons/camera.svg diff --git a/resources/application.rc b/resources/application.rc new file mode 100644 index 0000000..357e90e --- /dev/null +++ b/resources/application.rc @@ -0,0 +1 @@ +IDI_ICON1 ICON "../icons/cmvr-app.ico" diff --git a/resources/application_settings.json b/resources/application_settings.json new file mode 100644 index 0000000..4b4748e --- /dev/null +++ b/resources/application_settings.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "appearance": { + "fontFamily": "Microsoft YaHei UI", + "fontPixels": 13 + }, + "arm": { + "modelPreview": false + }, + "window": { + "rememberGeometry": true, + "startMaximized": true, + "startupPage": 0, + "geometry": "AdnQywADAAAAAAAAAAAAAAAAB38AAASHAAAAAAAAABQAAAd/AAAESwAAAAACAAAAB4AAAAAAAAAAAAAAB38AAASH" + }, + "log": { + "maximumLines": 3000, + "autoScroll": true + } +} diff --git a/scripts/generate_application_icon.py b/scripts/generate_application_icon.py new file mode 100644 index 0000000..0fb6ce3 --- /dev/null +++ b/scripts/generate_application_icon.py @@ -0,0 +1,61 @@ +"""Generate the multi-resolution Windows icon without third-party packages. + +The geometry mirrors icons/cmvr-app.svg. Run after changing the logo. +""" +import math +import pathlib +import struct +import zlib + + +def chunk(kind, data): + return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) + + +def color_at(x, y): + # Rounded blue app tile, a white C, and a cyan status dot. + dx, dy = max(abs(x - 32) - 15, 0), max(abs(y - 32) - 15, 0) + if dx * dx + dy * dy > 15 * 15: + return (0, 0, 0, 0) + color = (27, 110, 243, 255) + radius = math.hypot(x - 32, y - 32) + angle = abs(math.atan2(y - 32, x - 32)) + if 13.5 <= radius <= 20.5 and angle >= math.radians(40): + color = (255, 255, 255, 255) + for angle in (-40, 40): + cx, cy = 32 + 17 * math.cos(math.radians(angle)), 32 + 17 * math.sin(math.radians(angle)) + if math.hypot(x - cx, y - cy) <= 3.5: + color = (255, 255, 255, 255) + dx, dy = max(abs(x - 47.5) - 1.5, 0), max(abs(y - 32.5) - 1.5, 0) + if dx * dx + dy * dy <= 9: + color = (143, 221, 255, 255) + return color + + +def png(size): + rows = bytearray() + samples = 4 + for row in range(size): + rows.append(0) + for col in range(size): + colors = [color_at((col + (sx + .5) / samples) * 64 / size, + (row + (sy + .5) / samples) * 64 / size) + for sy in range(samples) for sx in range(samples)] + alpha = sum(c[3] for c in colors) + rgb = [round(sum(c[k] * c[3] for c in colors) / alpha) if alpha else 0 for k in range(3)] + rows.extend(rgb + [round(alpha / (samples * samples))]) + return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(rows, 9)) + chunk(b'IEND', b'')) + + +if __name__ == '__main__': + sizes = (16, 24, 32, 48, 64, 128, 256) + images = [png(size) for size in sizes] + offset = 6 + 16 * len(images) + directory = bytearray(struct.pack(' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +ApplicationSettings::ApplicationSettings(const QString &path) + : m_path(path.isEmpty() ? QDir(QCoreApplication::applicationDirPath()).filePath( + QStringLiteral("data/application_settings.json")) : path) +{ + QFile file(m_path); + if (!file.exists()) return; + if (!file.open(QIODevice::ReadOnly)) { + m_loadError = file.errorString(); + return; + } + QJsonParseError error; + const QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &error); + if (error.error != QJsonParseError::NoError || !document.isObject()) { + m_loadError = QStringLiteral("设置文件格式错误,已使用默认设置;原文件已保留。"); + return; + } + m_document = document.object(); + const QJsonObject appearance = m_document.value("appearance").toObject(); + const QString family = appearance.value("fontFamily").toString().trimmed(); + if (!family.isEmpty()) m_options.fontFamily = family; + m_options.fontPixels = qBound(11, appearance.value("fontPixels").toInt(13), 18); + const QJsonObject arm = m_document.value("arm").toObject(); + m_options.armModelPreview = arm.value("modelPreview").toBool(false); + const QJsonObject window = m_document.value("window").toObject(); + m_options.rememberWindow = window.value("rememberGeometry").toBool(true); + m_options.startMaximized = window.value("startMaximized").toBool(true); + const int page = window.value("startupPage").toInt(0); + m_options.startupPage = (page == 0 || page == 1 || page == 2 || page == 11 || page == 16) + ? page : 0; + const QJsonObject log = m_document.value("log").toObject(); + m_options.logMaximumLines = qBound(500, log.value("maximumLines").toInt(3000), 20000); + m_options.logAutoScroll = log.value("autoScroll").toBool(true); +} + +ApplicationSettings &ApplicationSettings::instance() +{ + static ApplicationSettings settings; + return settings; +} + +QByteArray ApplicationSettings::windowGeometry() const +{ + return QByteArray::fromBase64(m_document.value("window").toObject() + .value("geometry").toString().toLatin1()); +} + +bool ApplicationSettings::write(const QJsonObject &document, QString *error) +{ + if (!QDir().mkpath(QFileInfo(m_path).absolutePath())) { + if (error) *error = QStringLiteral("无法创建设置目录:%1").arg(QFileInfo(m_path).absolutePath()); + return false; + } + QSaveFile file(m_path); + const QByteArray data = QJsonDocument(document).toJson(QJsonDocument::Indented); + if (!file.open(QIODevice::WriteOnly) || file.write(data) != data.size() || !file.commit()) { + if (error) *error = QStringLiteral("设置保存失败:%1").arg(file.errorString()); + return false; + } + m_document = document; + m_loadError.clear(); + return true; +} + +bool ApplicationSettings::save(const ApplicationOptions &options, QString *error) +{ + QJsonObject document = m_document; + QJsonObject appearance = document.value("appearance").toObject(); + appearance.insert("fontFamily", options.fontFamily); + appearance.insert("fontPixels", qBound(11, options.fontPixels, 18)); + document.insert("appearance", appearance); + QJsonObject arm = document.value("arm").toObject(); + arm.insert("modelPreview", options.armModelPreview); + document.insert("arm", arm); + QJsonObject window = document.value("window").toObject(); + window.insert("rememberGeometry", options.rememberWindow); + window.insert("startMaximized", options.startMaximized); + window.insert("startupPage", options.startupPage); + document.insert("window", window); + QJsonObject log = document.value("log").toObject(); + log.insert("maximumLines", qBound(500, options.logMaximumLines, 20000)); + log.insert("autoScroll", options.logAutoScroll); + document.insert("log", log); + document.insert("version", 1); + if (!write(document, error)) return false; + m_options = options; + m_options.fontPixels = appearance.value("fontPixels").toInt(); + m_options.logMaximumLines = log.value("maximumLines").toInt(); + return true; +} + +bool ApplicationSettings::saveWindowGeometry(const QByteArray &geometry, QString *error) +{ + // Automatic geometry persistence must not replace a damaged settings file. + if (!m_options.rememberWindow || !m_loadError.isEmpty()) return true; + QJsonObject document = m_document; + QJsonObject window = document.value("window").toObject(); + window.insert("geometry", QString::fromLatin1(geometry.toBase64())); + document.insert("window", window); + return write(document, error); +} + +void showApplicationSettings(QWidget *parent, const std::function &applied) +{ + auto &settings = ApplicationSettings::instance(); + const ApplicationOptions original = settings.options(); + QDialog dialog(parent); + dialog.setWindowTitle(QStringLiteral("软件设置")); + dialog.setObjectName(QStringLiteral("applicationSettingsDialog")); + dialog.setWindowModality(Qt::WindowModal); + dialog.resize(660, 540); + dialog.setMinimumSize(580, 480); + auto *layout = new QVBoxLayout(&dialog); + layout->setContentsMargins(22, 20, 22, 20); + layout->setSpacing(16); + auto *intro = new QLabel(QStringLiteral("定制显示与启动行为"), &dialog); + intro->setObjectName(QStringLiteral("sectionTitle")); + layout->addWidget(intro); + auto *tabs = new QTabWidget(&dialog); + tabs->setObjectName(QStringLiteral("settingsTabs")); + auto addPage = [&](const QString &title) { + auto *page = new QWidget(tabs); + auto *form = new QFormLayout(page); + form->setContentsMargins(18, 22, 18, 18); + form->setSpacing(18); + form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + tabs->addTab(page, title); + return form; + }; + auto *appearance = addPage(QStringLiteral("外观")); + auto *family = new QFontComboBox(&dialog); + family->setObjectName(QStringLiteral("settingsFontFamily")); + auto *pixels = new QSpinBox(&dialog); + pixels->setRange(11, 18); + pixels->setSuffix(QStringLiteral(" px")); + appearance->addRow(QStringLiteral("界面字体"), family); + appearance->addRow(QStringLiteral("基础字号"), pixels); + auto *sample = new QLabel(QStringLiteral("CMVR 控制台 · 关节位置 123.456°"), &dialog); + sample->setObjectName(QStringLiteral("settingsFontSample")); + sample->setWordWrap(true); + appearance->addRow(QStringLiteral("字体预览"), sample); + auto previewFont = [=]() { + QString name = family->currentFont().family(); + name.remove(QLatin1Char('"')); name.remove(QLatin1Char('\\')); + sample->setStyleSheet(QStringLiteral("QLabel#settingsFontSample { font-family: \"%1\"; font-size: %2px; }") + .arg(name).arg(pixels->value())); + }; + QObject::connect(family, &QFontComboBox::currentFontChanged, &dialog, [=](const QFont &) { previewFont(); }); + QObject::connect(pixels, QOverload::of(&QSpinBox::valueChanged), &dialog, [=](int) { previewFont(); }); + + auto *startup = addPage(QStringLiteral("启动与机械臂")); + auto *model = new QCheckBox(QStringLiteral("加载机械臂三维模型预览"), &dialog); + model->setObjectName(QStringLiteral("settingsArmModelPreview")); + startup->addRow(QStringLiteral("模型预览"), model); + auto *modelHint = new QLabel(QStringLiteral("重启程序后生效。默认关闭;开启后使用 Qt3D 加载模型。\n当前工具链曾出现模型加载闪退,建议确认运行环境兼容后开启。"), &dialog); + modelHint->setWordWrap(true); + modelHint->setObjectName(QStringLiteral("mutedLabel")); + startup->addRow(QString(), modelHint); + auto *maximized = new QCheckBox(QStringLiteral("启动时最大化"), &dialog); + auto *remember = new QCheckBox(QStringLiteral("记住窗口大小和位置"), &dialog); + auto *page = new QComboBox(&dialog); + page->addItem(QStringLiteral("系统概览"), 0); + page->addItem(QStringLiteral("设备管理"), 11); + page->addItem(QStringLiteral("机械臂"), 1); + page->addItem(QStringLiteral("相机"), 2); + page->addItem(QStringLiteral("任务编排"), 16); + startup->addRow(QStringLiteral("启动页面"), page); + startup->addRow(QStringLiteral("窗口"), maximized); + startup->addRow(QString(), remember); + + auto *logs = addPage(QStringLiteral("日志与数据")); + auto *maximum = new QSpinBox(&dialog); + maximum->setRange(500, 20000); + maximum->setSingleStep(500); + maximum->setSuffix(QStringLiteral(" 行")); + auto *scroll = new QCheckBox(QStringLiteral("新日志到达时滚动到底部"), &dialog); + logs->addRow(QStringLiteral("日志保留上限"), maximum); + logs->addRow(QStringLiteral("自动滚动"), scroll); + auto *dataHint = new QLabel(QStringLiteral("软件设置与任务编排、机械臂点位分别保存。\n修改设置不会清除已有点位、任务或连接信息。"), &dialog); + dataHint->setWordWrap(true); + dataHint->setObjectName(QStringLiteral("mutedLabel")); + logs->addRow(dataHint); + layout->addWidget(tabs, 1); + + auto fill = [&](const ApplicationOptions &options) { + family->setCurrentFont(QFont(options.fontFamily)); pixels->setValue(options.fontPixels); + model->setChecked(options.armModelPreview); maximized->setChecked(options.startMaximized); + remember->setChecked(options.rememberWindow); + page->setCurrentIndex(qMax(0, page->findData(options.startupPage))); + maximum->setValue(options.logMaximumLines); scroll->setChecked(options.logAutoScroll); + previewFont(); + }; + fill(original); + auto *path = new QLabel(QStringLiteral("设置文件:%1").arg(QDir::toNativeSeparators(settings.filePath())), &dialog); + path->setObjectName(QStringLiteral("mutedLabel")); path->setWordWrap(true); + path->setTextInteractionFlags(Qt::TextSelectableByMouse); + layout->addWidget(path); + auto *feedback = new QLabel(settings.loadError(), &dialog); + feedback->setWordWrap(true); + feedback->setObjectName(QStringLiteral("settingsFeedback")); + layout->addWidget(feedback); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Save | QDialogButtonBox::Cancel, &dialog); + buttons->button(QDialogButtonBox::RestoreDefaults)->setText(QStringLiteral("恢复默认")); + buttons->button(QDialogButtonBox::Save)->setText(QStringLiteral("保存设置")); + buttons->button(QDialogButtonBox::Save)->setObjectName(QStringLiteral("primaryButton")); + buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消")); + QObject::connect(buttons->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, &dialog, + [&]() { fill(ApplicationOptions()); }); + QObject::connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, [&]() { + ApplicationOptions options; + options.fontFamily = family->currentFont().family(); options.fontPixels = pixels->value(); + options.armModelPreview = model->isChecked(); options.startMaximized = maximized->isChecked(); + options.rememberWindow = remember->isChecked(); options.startupPage = page->currentData().toInt(); + options.logMaximumLines = maximum->value(); options.logAutoScroll = scroll->isChecked(); + QString error; + if (!settings.save(options, &error)) { feedback->setText(error); return; } + ApplicationStyle::apply(); + if (applied) applied(); + dialog.accept(); + }); + layout->addWidget(buttons); + dialog.exec(); +} diff --git a/src/applicationsettings.h b/src/applicationsettings.h new file mode 100644 index 0000000..1af11f6 --- /dev/null +++ b/src/applicationsettings.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include + +class QWidget; + +struct ApplicationOptions { + QString fontFamily = QStringLiteral("Microsoft YaHei UI"); + int fontPixels = 13; + bool armModelPreview = false; + bool rememberWindow = true; + bool startMaximized = true; + int startupPage = 0; + int logMaximumLines = 3000; + bool logAutoScroll = true; +}; + +class ApplicationSettings +{ +public: + explicit ApplicationSettings(const QString &path = QString()); + static ApplicationSettings &instance(); + const ApplicationOptions &options() const { return m_options; } + QString filePath() const { return m_path; } + QString loadError() const { return m_loadError; } + QByteArray windowGeometry() const; + bool save(const ApplicationOptions &options, QString *error = nullptr); + bool saveWindowGeometry(const QByteArray &geometry, QString *error = nullptr); + +private: + bool write(const QJsonObject &document, QString *error); + QString m_path; + QString m_loadError; + ApplicationOptions m_options; + QJsonObject m_document; +}; + +void showApplicationSettings(QWidget *parent, const std::function &applied); diff --git a/src/applicationstyle.cpp b/src/applicationstyle.cpp new file mode 100644 index 0000000..f32d302 --- /dev/null +++ b/src/applicationstyle.cpp @@ -0,0 +1,312 @@ +#include "applicationstyle.h" +#include "applicationsettings.h" +#include "uiicons.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +class FontPopupDelegate final : public QStyledItemDelegate +{ +public: + FontPopupDelegate(QAbstractItemDelegate *original, QObject *parent) + : QStyledItemDelegate(parent), m_original(original) {} + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const override + { + QStyleOptionViewItem themed = option; + const bool selected = option.state & QStyle::State_Selected; + const bool hovered = option.state & QStyle::State_MouseOver; + painter->save(); + painter->setPen(Qt::NoPen); + painter->setBrush(selected ? QColor("#e8f1ff") + : hovered ? QColor("#f1f5fb") : QColor("#ffffff")); + painter->drawRoundedRect(option.rect.adjusted(1, 1, -1, -1), 4, 4); + // The native font delegate chooses its own palette when Selected is + // present. Paint that state ourselves, then retain its font samples. + themed.state &= ~(QStyle::State_Selected | QStyle::State_MouseOver | QStyle::State_HasFocus); + themed.backgroundBrush = Qt::NoBrush; + themed.palette.setColor(QPalette::Text, selected ? QColor("#165dcc") : QColor("#334155")); + if (m_original) m_original->paint(painter, themed, index); + else QStyledItemDelegate::paint(painter, themed, index); + painter->restore(); + } + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override + { + QSize size = m_original ? m_original->sizeHint(option, index) + : QStyledItemDelegate::sizeHint(option, index); + size.setHeight(qMax(32, size.height())); + return size; + } +private: + QPointer m_original; +}; + +class ApplicationStyleFilter final : public QObject +{ +public: + explicit ApplicationStyleFilter(QObject *parent) : QObject(parent) {} + +protected: + bool eventFilter(QObject *object, QEvent *event) override + { + if (event->type() == QEvent::Polish) { + if (auto *label = qobject_cast(object)) { + const QString name = label->objectName(); + if (name == QStringLiteral("titleBarMark") || name == QStringLiteral("brandMark") + || name == QStringLiteral("jointFlowDialogMark")) { + const int size = name == QStringLiteral("brandMark") ? 34 + : name == QStringLiteral("titleBarMark") ? 26 : 24; + label->setPixmap(QApplication::windowIcon().pixmap(size, size)); + } + } + if (auto *combo = qobject_cast(object)) { + ApplicationStyle::styleComboBox(combo); + } + if (auto *box = qobject_cast(object)) { + for (QAbstractButton *button : box->buttons()) { + const auto role = box->buttonRole(button); + if (button->objectName().isEmpty() && + (role == QDialogButtonBox::AcceptRole || role == QDialogButtonBox::YesRole)) + button->setObjectName(QStringLiteral("primaryButton")); + } + const QPair translations[] = { + {QDialogButtonBox::Ok, "确定"}, {QDialogButtonBox::Cancel, "取消"}, + {QDialogButtonBox::Yes, "是"}, {QDialogButtonBox::No, "否"}, + {QDialogButtonBox::Close, "关闭"}, {QDialogButtonBox::Apply, "应用"}, + {QDialogButtonBox::Save, "保存"}, {QDialogButtonBox::Discard, "放弃修改"}, + {QDialogButtonBox::RestoreDefaults, "恢复默认"}}; + for (const auto &item : translations) + if (QPushButton *button = box->button(item.first)) { + // Keep deliberately named domain-specific actions. + const QString current = button->text(); + if (!current.contains(QRegularExpression(QStringLiteral("[\\x{4e00}-\\x{9fff}]")))) + button->setText(QString::fromUtf8(item.second)); + } + } + if (auto *dialog = qobject_cast(object)) + if (!qobject_cast(dialog)) decorateDialog(dialog); + } + if (event->type() == QEvent::Resize) { + if (auto *dialog = qobject_cast(object)) { + if (dialog->property("applicationChrome").toBool()) { + if (auto *bar = dialog->findChild(QStringLiteral("applicationDialogTitleBar"), Qt::FindDirectChildrenOnly)) { + bar->setGeometry(1, 1, qMax(0, dialog->width() - 2), 44); + bar->raise(); + } + } + } + } + auto *widget = qobject_cast(object); + if (event->type() == QEvent::Show) { + if (auto *combo = qobject_cast(object)) + ApplicationStyle::styleComboBox(combo); + if (auto *view = qobject_cast(object)) { + // A view can be replaced after the combo's Polish event. Apply + // the shared style again when the actual popup is displayed. + for (QObject *owner = view->parent(); owner; owner = owner->parent()) { + if (auto *combo = qobject_cast(owner)) { + if (combo->view() == view) ApplicationStyle::styleComboBox(combo); + break; + } + } + } + if (auto *button = qobject_cast(object)) { + if (!button->property("applicationButtonStyled").toBool()) { + button->setProperty("applicationButtonStyled", true); + button->style()->unpolish(button); + button->style()->polish(button); + } + } + } + if (widget && widget->property("applicationTitleDrag").toBool()) { + if (event->type() == QEvent::MouseButtonPress) { + auto *mouse = static_cast(event); + if (mouse->button() == Qt::LeftButton) { + m_dragDialog = qobject_cast(widget->window()); + if (m_dragDialog) m_dragOffset = mouse->globalPos() - m_dragDialog->frameGeometry().topLeft(); + return bool(m_dragDialog); + } + } else if (event->type() == QEvent::MouseMove && m_dragDialog) { + auto *mouse = static_cast(event); + if (mouse->buttons() & Qt::LeftButton) { + m_dragDialog->move(mouse->globalPos() - m_dragOffset); + return true; + } + m_dragDialog.clear(); + } else if (event->type() == QEvent::MouseButtonRelease) { + m_dragDialog.clear(); + } + } + return QObject::eventFilter(object, event); + } + +public: + static void decorateDialog(QDialog *dialog) + { + dialog->setWindowIcon(QApplication::windowIcon()); + if (dialog->property("applicationChrome").toBool() || !dialog->layout() + || (dialog->windowFlags() & Qt::FramelessWindowHint)) return; + // Preserve the caller's modality and result handling, including nested + // message boxes. Never add an always-on-top or application-modal flag. + dialog->setProperty("applicationChrome", true); + const auto modality = dialog->windowModality(); + dialog->setWindowFlags((dialog->windowFlags() & ~Qt::WindowContextHelpButtonHint + & ~Qt::WindowStaysOnTopHint) | Qt::FramelessWindowHint); + dialog->setWindowModality(modality); + // QMessageBox and QFileDialog keep private pointers to their original + // layouts. Reserve title space without wrapping or moving those layouts. + QLayout *layout = dialog->layout(); + const QMargins margins = layout->contentsMargins(); + layout->setContentsMargins(qMax(16, margins.left()), margins.top() + 44, + qMax(16, margins.right()), qMax(16, margins.bottom())); + auto *bar = new QWidget(dialog); + bar->setObjectName(QStringLiteral("applicationDialogTitleBar")); + bar->setProperty("applicationTitleDrag", true); + bar->setMinimumHeight(44); + auto *row = new QHBoxLayout(bar); + row->setContentsMargins(14, 0, 0, 0); + row->setSpacing(10); + auto *icon = new QLabel(bar); + icon->setPixmap(QApplication::windowIcon().pixmap(24, 24)); + icon->setProperty("applicationTitleDrag", true); + auto *title = new QLabel(dialog->windowTitle(), bar); + title->setObjectName(QStringLiteral("applicationDialogTitle")); + title->setProperty("applicationTitleDrag", true); + QObject::connect(dialog, &QWidget::windowTitleChanged, title, &QLabel::setText); + auto *close = new QPushButton(bar); + close->setObjectName(QStringLiteral("applicationDialogClose")); + close->setToolTip(QStringLiteral("关闭")); + close->setAccessibleName(QStringLiteral("关闭")); + close->setFixedSize(44, 43); + close->setAutoDefault(false); + close->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), QColor("#64748b"), QColor("#64748b"))); + QObject::connect(close, &QPushButton::clicked, dialog, &QDialog::reject); + row->addWidget(icon); row->addWidget(title, 1); row->addWidget(close); + bar->setGeometry(1, 1, qMax(0, dialog->width() - 2), 44); + bar->raise(); + if (qobject_cast(dialog)) { + dialog->setMinimumWidth(400); + } else { + dialog->setSizeGripEnabled(true); + } + } +private: + QPointer m_dragDialog; + QPoint m_dragOffset; +}; +} + +void ApplicationStyle::decorateDialog(QDialog *dialog) +{ + ApplicationStyleFilter::decorateDialog(dialog); +} + +void ApplicationStyle::styleComboBox(QComboBox *combo) +{ + if (!combo || combo->property("applicationComboStyling").toBool()) return; + combo->setProperty("applicationComboStyling", true); + auto *view = combo->view(); + view->setObjectName(QStringLiteral("comboPopupView")); + view->setFrameShape(QFrame::NoFrame); + view->setFont(combo->font()); + view->setMouseTracking(true); + view->viewport()->setAttribute(Qt::WA_Hover); + // Qt's default combo menu delegate may paint a native selection despite + // QSS. Font previews retain Qt's rendering through a palette adapter. + if (!qobject_cast(combo) + && !view->property("applicationComboDelegate").toBool()) { + view->setItemDelegate(new QStyledItemDelegate(view)); + view->setProperty("applicationComboDelegate", true); + } + if (qobject_cast(combo) + && !view->property("applicationFontPreviewPreserved").toBool()) { + view->setItemDelegate(new FontPopupDelegate(view->itemDelegate(), view)); + view->setProperty("applicationFontPreviewPreserved", true); + } + const QString sheet = QStringLiteral( + "QAbstractItemView { background:#ffffff; color:#334155; border:1px solid #cbd5e1;" + " border-radius:6px; padding:5px; outline:0; selection-background-color:#e8f1ff;" + " selection-color:#165dcc; }" + "QAbstractItemView::item { min-height:30px; padding:2px 10px; border:0; border-radius:4px; }" + "QAbstractItemView::item:hover { background:#f1f5fb; color:#165dcc; }" + "QAbstractItemView::item:selected { background:#e8f1ff; color:#165dcc; }" + "QAbstractItemView::item:disabled { background:transparent; color:#94a3b8; }"); + if (view->styleSheet() != sheet) view->setStyleSheet(sheet); + combo->setProperty("applicationComboStyling", false); +} + +void ApplicationStyle::install(QApplication &application) +{ + application.setStyle(QStringLiteral("Fusion")); + application.setWindowIcon(QIcon(QStringLiteral(":/icons/cmvr-app.ico"))); + auto *filter = new ApplicationStyleFilter(&application); + application.installEventFilter(filter); + apply(); +} + +void ApplicationStyle::apply() +{ + const auto &options = ApplicationSettings::instance().options(); + QFont font(options.fontFamily); + font.setPixelSize(options.fontPixels); + font.setStyleStrategy(QFont::PreferAntialias); + qApp->setFont(font); + QPalette palette; + palette.setColor(QPalette::Window, QColor("#f4f6fa")); + palette.setColor(QPalette::WindowText, QColor("#253246")); + palette.setColor(QPalette::Base, Qt::white); + palette.setColor(QPalette::AlternateBase, QColor("#f7f9fc")); + palette.setColor(QPalette::Text, QColor("#253246")); + palette.setColor(QPalette::Button, Qt::white); + palette.setColor(QPalette::ButtonText, QColor("#334155")); + palette.setColor(QPalette::Highlight, QColor("#e2edff")); + palette.setColor(QPalette::HighlightedText, QColor("#165dcc")); + palette.setColor(QPalette::ToolTipBase, QColor("#253246")); + palette.setColor(QPalette::ToolTipText, Qt::white); + palette.setColor(QPalette::Link, QColor("#1b6ef3")); + palette.setColor(QPalette::Disabled, QPalette::Text, QColor("#94a3b8")); + palette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor("#94a3b8")); + palette.setColor(QPalette::Disabled, QPalette::WindowText, QColor("#94a3b8")); + qApp->setPalette(palette); + QFile file(QStringLiteral(":/styles.qss")); + if (!file.open(QIODevice::ReadOnly)) return; + QString sheet = QString::fromUtf8(file.readAll()); + QString family = options.fontFamily; + family.replace(QLatin1Char('"'), QString()); + family.replace(QLatin1Char('\\'), QString()); + sheet.replace(QStringLiteral("\"Microsoft YaHei UI\""), QStringLiteral("\"%1\"").arg(family)); + sheet.replace(QStringLiteral("font-family: Consolas;"), QStringLiteral("font-family: \"%1\";").arg(family)); + // Scale the existing heading/caption hierarchy from the same base size. + QRegularExpression sizes(QStringLiteral("font-size:\\s*(\\d+)px")); + auto matches = sizes.globalMatch(sheet); + QList replacements; + while (matches.hasNext()) replacements.append(matches.next()); + for (auto it = replacements.crbegin(); it != replacements.crend(); ++it) { + const int size = qMax(10, qRound(it->captured(1).toInt() * options.fontPixels / 13.0)); + sheet.replace(it->capturedStart(), it->capturedLength(), QStringLiteral("font-size: %1px").arg(size)); + } + // Keep source/config text aligned in a monospace font while all interface + // labels and numerical controls follow the selected application family. + sheet += QStringLiteral("\nQTextEdit#rpcEditor, QPlainTextEdit[codeEditor=\"true\"] { font-family: Consolas; }\n"); + qApp->setStyleSheet(sheet); +} diff --git a/src/applicationstyle.h b/src/applicationstyle.h new file mode 100644 index 0000000..5fd4e20 --- /dev/null +++ b/src/applicationstyle.h @@ -0,0 +1,12 @@ +#pragma once + +class QApplication; +class QDialog; +class QComboBox; + +namespace ApplicationStyle { +void install(QApplication &application); +void apply(); +void decorateDialog(QDialog *dialog); +void styleComboBox(QComboBox *combo); +} diff --git a/src/appmessagebox.h b/src/appmessagebox.h new file mode 100644 index 0000000..2a36b68 --- /dev/null +++ b/src/appmessagebox.h @@ -0,0 +1,120 @@ +#pragma once + +#include "applicationstyle.h" +#include +#include +#include +#include +#include +#include +#include +#include + +// Application-owned dialog with QMessageBox-compatible button values. Keeping +// our title bar outside QMessageBox's private layout avoids Qt 5.12 assumptions +// about its native window and default/escape buttons. +class AppMessageBox : public QDialog +{ +public: + using Icon = QMessageBox::Icon; + using StandardButton = QMessageBox::StandardButton; + using StandardButtons = QMessageBox::StandardButtons; + static constexpr Icon Information = QMessageBox::Information; + static constexpr Icon Warning = QMessageBox::Warning; + static constexpr Icon Critical = QMessageBox::Critical; + static constexpr Icon Question = QMessageBox::Question; + static constexpr StandardButton NoButton = QMessageBox::NoButton; + static constexpr StandardButton Ok = QMessageBox::Ok; + static constexpr StandardButton Yes = QMessageBox::Yes; + static constexpr StandardButton No = QMessageBox::No; + static constexpr StandardButton Cancel = QMessageBox::Cancel; + static constexpr StandardButton Discard = QMessageBox::Discard; + static constexpr StandardButton Close = QMessageBox::Close; + + AppMessageBox(Icon icon, const QString &title, const QString &text, + StandardButtons buttons = NoButton, QWidget *parent = nullptr) + : QDialog(parent), m_standardButtons(buttons == NoButton ? StandardButtons(Ok) : buttons) + { + setWindowTitle(title); + setObjectName(QStringLiteral("applicationMessageBox")); + setMinimumWidth(420); + auto *layout = new QVBoxLayout(this); + layout->setContentsMargins(22, 22, 22, 18); + layout->setSpacing(20); + auto *row = new QHBoxLayout; + row->setSpacing(16); + auto *mark = new QLabel(this); + const auto standardIcon = icon == Warning ? QStyle::SP_MessageBoxWarning + : icon == Critical ? QStyle::SP_MessageBoxCritical + : icon == Question ? QStyle::SP_MessageBoxQuestion : QStyle::SP_MessageBoxInformation; + mark->setPixmap(style()->standardIcon(standardIcon).pixmap(32, 32)); + row->addWidget(mark, 0, Qt::AlignTop); + auto *message = new QLabel(text, this); + message->setTextFormat(Qt::PlainText); + message->setWordWrap(true); + message->setMinimumWidth(280); + message->setMaximumWidth(640); + message->setTextInteractionFlags(Qt::TextSelectableByMouse); + row->addWidget(message, 1); + layout->addLayout(row); + m_buttons = new QDialogButtonBox(QDialogButtonBox::StandardButtons(int(m_standardButtons)), this); + layout->addWidget(m_buttons); + connect(m_buttons, &QDialogButtonBox::clicked, this, [this](QAbstractButton *clicked) { + done(int(m_buttons->standardButton(clicked))); + }); + setDefaultButton(m_standardButtons.testFlag(Ok) ? Ok + : m_standardButtons.testFlag(Yes) ? Yes + : m_standardButtons.testFlag(No) ? No : Cancel); + ApplicationStyle::decorateDialog(this); + } + + QAbstractButton *button(StandardButton which) const + { return m_buttons->button(static_cast(which)); } + void setDefaultButton(StandardButton which) + { + for (QAbstractButton *item : m_buttons->buttons()) + if (auto *push = qobject_cast(item)) { + const bool selected = m_buttons->standardButton(push) == int(which); + push->setDefault(selected); + if (selected) push->setFocus(); + } + } + void reject() override + { + done(m_standardButtons.testFlag(Cancel) ? int(Cancel) + : m_standardButtons.testFlag(No) ? int(No) + : m_standardButtons.testFlag(Close) ? int(Close) + : m_buttons->buttons().size() == 1 + ? int(m_buttons->standardButton(m_buttons->buttons().first())) : int(NoButton)); + } + + static StandardButton information(QWidget *parent, const QString &title, + const QString &text, StandardButtons buttons = Ok, + StandardButton defaultButton = NoButton) + { return showMessage(Information, parent, title, text, buttons, defaultButton); } + static StandardButton warning(QWidget *parent, const QString &title, + const QString &text, StandardButtons buttons = Ok, + StandardButton defaultButton = NoButton) + { return showMessage(Warning, parent, title, text, buttons, defaultButton); } + static StandardButton critical(QWidget *parent, const QString &title, + const QString &text, StandardButtons buttons = Ok, + StandardButton defaultButton = NoButton) + { return showMessage(Critical, parent, title, text, buttons, defaultButton); } + static StandardButton question(QWidget *parent, const QString &title, + const QString &text, StandardButtons buttons = StandardButtons(Yes | No), + StandardButton defaultButton = NoButton) + { return showMessage(Question, parent, title, text, buttons, defaultButton); } + +private: + QDialogButtonBox *m_buttons = nullptr; + StandardButtons m_standardButtons; + static StandardButton showMessage(Icon icon, QWidget *parent, const QString &title, + const QString &text, StandardButtons buttons, + StandardButton defaultButton) + { + AppMessageBox dialog(icon, title, text, buttons, parent); + dialog.setWindowModality(Qt::WindowModal); + if (defaultButton != NoButton) dialog.setDefaultButton(defaultButton); + return static_cast(dialog.exec()); + } +}; diff --git a/src/cameracapabilities.h b/src/cameracapabilities.h index cee96b6..56f3c5b 100644 --- a/src/cameracapabilities.h +++ b/src/cameracapabilities.h @@ -3,6 +3,12 @@ namespace CameraCapabilities { enum class Mode { Preview, Depth, Plane }; +inline bool depthImage(const QVariantMap &c) { + return c.value("depthImage").toBool() || c.value("metricAlignedDepth").toBool(); +} +inline bool depthStream(const QVariantMap &c) { + return c.value("depthStream").toBool() || c.value("metricAlignedDepth").toBool(); +} inline bool known(const QVariantMap& c) { return c.value("version").toUInt()==1 && !c.value("serial").toString().isEmpty() && c.value("sessionGeneration").toULongLong()>0; diff --git a/src/configeditorwidget.cpp b/src/configeditorwidget.cpp index 9035e71..876fdeb 100644 --- a/src/configeditorwidget.cpp +++ b/src/configeditorwidget.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include "appmessagebox.h" #include #include #include @@ -802,6 +802,7 @@ ConfigEditorWidget::ConfigEditorWidget(RobotClient *client, QWidget *parent) m_editorTabs = new QTabWidget(editorPanel); m_textEditor = new QPlainTextEdit(m_editorTabs); + m_textEditor->setProperty("codeEditor", true); m_textEditor->setLineWrapMode(QPlainTextEdit::NoWrap); m_textEditor->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); m_textEditor->setPlaceholderText(QStringLiteral("选择左侧配置文件后在此编辑")); @@ -1113,11 +1114,11 @@ void ConfigEditorWidget::rebuildDeviceCards() deleteButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/trash-2.svg"))); deleteButton->setToolTip(QStringLiteral("删除设备")); connect(deleteButton, &QToolButton::clicked, this, [this, uid, deviceId]() { - const auto answer = QMessageBox::question( + const auto answer = AppMessageBox::question( this, QStringLiteral("删除设备"), QStringLiteral("确定从 DeviceManager 配置中删除设备“%1”吗?").arg(deviceId), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (answer != QMessageBox::Yes) + AppMessageBox::Yes | AppMessageBox::No, AppMessageBox::No); + if (answer != AppMessageBox::Yes) return; const int editIndex = editableDeviceIndex(uid); if (editIndex >= 0) @@ -1586,7 +1587,7 @@ void ConfigEditorWidget::buildEditableDevices() const bool managerReady = m_managerContent.trimmed().isEmpty() || google::protobuf::TextFormat::ParseFromString(m_managerContent.toStdString(), &manager); if (!managerReady) { - QMessageBox::critical(this, QStringLiteral("读取设备配置"), + AppMessageBox::critical(this, QStringLiteral("读取设备配置"), QStringLiteral("DeviceManager 配置格式与当前上位机协议不兼容。")); cancelDeviceEditing(); return; @@ -1705,7 +1706,7 @@ void ConfigEditorWidget::toggleDeviceEditing() return; } if (!m_edgeConnected) { - QMessageBox::information(this, QStringLiteral("设备配置"), + AppMessageBox::information(this, QStringLiteral("设备配置"), QStringLiteral("请先连接 cmvr-es,再修改设备配置。")); return; } @@ -1908,13 +1909,13 @@ void ConfigEditorWidget::finishDeviceEditing() } m_devices = demoDevices; cancelDeviceEditing(); - QMessageBox::information(this, QStringLiteral("演示模式"), + AppMessageBox::information(this, QStringLiteral("演示模式"), QStringLiteral("演示配置已应用到当前界面;未写入远端文件。")); return; } QString error; if (!prepareOverviewSave(&error)) { - QMessageBox::warning(this, QStringLiteral("无法保存设备配置"), error); + AppMessageBox::warning(this, QStringLiteral("无法保存设备配置"), error); return; } m_overviewSaving = true; @@ -1930,7 +1931,7 @@ void ConfigEditorWidget::saveNextOverviewConfiguration() m_overviewCurrentSave.clear(); cancelDeviceEditing(); m_client->requestSystemRefresh(); - QMessageBox::information( + AppMessageBox::information( this, QStringLiteral("设备配置已保存"), QStringLiteral("配置文件已上传到 cmvr-es。配置重载/重启功能将在后续接入。")); return; @@ -2085,7 +2086,7 @@ void ConfigEditorWidget::handleFilesReceived(const QString &configRoot, m_overviewLoading = false; m_deviceEditButton->setEnabled(true); m_deviceEditButton->setText(QStringLiteral("修改")); - QMessageBox::warning(this, QStringLiteral("读取设备配置"), + AppMessageBox::warning(this, QStringLiteral("读取设备配置"), QStringLiteral("远端配置列表中未找到 device_manager.pb.txt。")); return; } @@ -2124,7 +2125,7 @@ void ConfigEditorWidget::handleFileReceived(const QString &relativePath, m_overviewLoading = false; m_deviceEditButton->setEnabled(true); m_deviceEditButton->setText(QStringLiteral("修改")); - QMessageBox::warning(this, QStringLiteral("读取设备配置"), + AppMessageBox::warning(this, QStringLiteral("读取设备配置"), detail.isEmpty() ? QStringLiteral("读取 %1 失败").arg(relativePath) : detail); return; @@ -2183,7 +2184,7 @@ void ConfigEditorWidget::handleSaveFinished(const QString &relativePath, m_overviewSaving = false; m_deviceEditButton->setEnabled(true); m_deviceEditButton->setText(QStringLiteral("完成")); - QMessageBox::critical( + AppMessageBox::critical( this, QStringLiteral("保存设备配置失败"), QStringLiteral("%1\n%2\n\n已成功保存的文件不会自动回滚,请刷新后再试。") .arg(relativePath, detail.isEmpty() ? QStringLiteral("远端拒绝保存") : detail)); @@ -2514,11 +2515,11 @@ bool ConfigEditorWidget::confirmDiscardChanges() { if (!m_dirty) return true; - const auto answer = QMessageBox::question( + const auto answer = AppMessageBox::question( this, QStringLiteral("未保存的修改"), QStringLiteral("当前配置尚未保存,确定放弃修改吗?"), - QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel); - return answer == QMessageBox::Discard; + AppMessageBox::Discard | AppMessageBox::Cancel, AppMessageBox::Cancel); + return answer == AppMessageBox::Discard; } void ConfigEditorWidget::setBusy(bool busy) diff --git a/src/handeyebridge.cpp b/src/handeyebridge.cpp index 5f1eefc..2ed38e5 100644 --- a/src/handeyebridge.cpp +++ b/src/handeyebridge.cpp @@ -1,4 +1,5 @@ #include "handeyebridge.h" +#include "handeyeprocessworker.h" #include #include #include @@ -6,16 +7,8 @@ #include #include -class HandEyeProcessWorker : public QObject +void HandEyeProcessWorker::dispose() { - Q_OBJECT -public: - QProcess *process = nullptr; - QTimer *timer = nullptr; - QByteArray buffer, diagnostics; - quint64 epoch = 0; - bool pending = false; - void dispose() { pending = false; if (timer) timer->stop(); if (process) { @@ -26,13 +19,17 @@ public: process = nullptr; } buffer.clear(); diagnostics.clear(); - } - void fail(const QString &message) { +} + +void HandEyeProcessWorker::fail(const QString &message) +{ const auto current = epoch; dispose(); emit error(current, message); - } - void launch(quint64 generation, const QString &python, const QString &script) { +} + +void HandEyeProcessWorker::launch(quint64 generation, const QString &python, const QString &script) +{ dispose(); epoch = generation; if (!timer) { timer = new QTimer(this); timer->setSingleShot(true); @@ -78,8 +75,10 @@ public: process->setProcessEnvironment(environment); process->setWorkingDirectory(QFileInfo(python).absolutePath()); process->start(python, {QStringLiteral("-I"),QStringLiteral("-B"),QStringLiteral("-u"),script}); - } - void send(quint64 generation, QVariantMap request, const VideoFrame &frame) { +} + +void HandEyeProcessWorker::send(quint64 generation, QVariantMap request, const VideoFrame &frame) +{ if (generation != epoch) return; if (!process) { emit error(epoch,QStringLiteral("请先启动手眼算法。")); return; } if (pending) { fail(QStringLiteral("手眼算法请求重叠。")); return; } @@ -102,11 +101,7 @@ public: pending=true; timer->start(request.value("op").toString()==QStringLiteral("solve") ? 90000 : 12000); process->write(QJsonDocument::fromVariant(request).toJson(QJsonDocument::Compact)+'\n'); - } -signals: - void reply(quint64 generation,const QVariantMap &value); - void error(quint64 generation,const QString &message); -}; +} HandEyeBridge::HandEyeBridge(QObject *parent) : QObject(parent), m_thread(new QThread(this)), m_worker(new HandEyeProcessWorker) { @@ -146,4 +141,3 @@ bool HandEyeBridge::submit(const QVariantMap &request,const VideoFrame &frame) return true; } -#include "handeyebridge.moc" diff --git a/src/handeyemotionwidget.cpp b/src/handeyemotionwidget.cpp index abb756e..629ae2d 100644 --- a/src/handeyemotionwidget.cpp +++ b/src/handeyemotionwidget.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include "appmessagebox.h" #include #include #include @@ -387,5 +387,5 @@ void HandEyeMotionWidget::prepare(const TcpCalibration::Pose &baseFlange) void HandEyeMotionWidget::reportError(const QString &message) { emit logMessage(QStringLiteral("WARN"),message); - QMessageBox::warning(this,QStringLiteral("手眼坐标转换"),message); + AppMessageBox::warning(this,QStringLiteral("手眼坐标转换"),message); } diff --git a/src/handeyeprocessworker.h b/src/handeyeprocessworker.h new file mode 100644 index 0000000..6ee6b09 --- /dev/null +++ b/src/handeyeprocessworker.h @@ -0,0 +1,31 @@ +#pragma once + +#include "videoframe.h" + +#include +#include +#include + +class QProcess; +class QTimer; + +class HandEyeProcessWorker : public QObject +{ + Q_OBJECT +public: + QProcess *process = nullptr; + QTimer *timer = nullptr; + QByteArray buffer; + QByteArray diagnostics; + quint64 epoch = 0; + bool pending = false; + + void dispose(); + void fail(const QString &message); + void launch(quint64 generation, const QString &python, const QString &script); + void send(quint64 generation, QVariantMap request, const VideoFrame &frame); + +signals: + void reply(quint64 generation, const QVariantMap &value); + void error(quint64 generation, const QString &message); +}; diff --git a/src/main.cpp b/src/main.cpp index 24fc210..a6ec539 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,8 @@ #include "mainwindow.h" #include "quictestserver.h" #include "videorenderwidget.h" +#include "applicationsettings.h" +#include "applicationstyle.h" #include #include @@ -100,19 +102,14 @@ int main(int argc, char *argv[]) #ifdef Q_OS_WIN SetUnhandledExceptionFilter(writeCrashDump); #endif + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication::setAttribute(Qt::AA_DontUseNativeDialogs); QApplication app(argc, argv); app.setApplicationName(QStringLiteral("CMVR Control Station")); app.setOrganizationName(QStringLiteral("CMVR")); app.setApplicationVersion(QStringLiteral("1.0.0")); - app.setStyle(QStringLiteral("Fusion")); - - QFile styleFile(QStringLiteral(":/styles.qss")); - if (!styleFile.open(QIODevice::ReadOnly)) { - styleFile.setFileName(QCoreApplication::applicationDirPath() + QStringLiteral("/../styles.qss")); - styleFile.open(QIODevice::ReadOnly); - } - if (styleFile.isOpen()) - app.setStyleSheet(QString::fromUtf8(styleFile.readAll())); + ApplicationStyle::install(app); const QStringList args = app.arguments(); if (args.contains(QStringLiteral("--quic-smoke-test"))) { @@ -169,13 +166,13 @@ int main(int argc, char *argv[]) MainWindow window; if (cameraSmokeIndex >= 0) appendCameraSmokeLog(QStringLiteral("STEP 主窗口构造完成")); - window.showMaximized(); + const auto &preferences = ApplicationSettings::instance(); + if (preferences.options().rememberWindow && !preferences.windowGeometry().isEmpty()) + window.restoreGeometry(preferences.windowGeometry()); + if (preferences.options().startMaximized) window.showMaximized(); + else { window.setWindowState(window.windowState() & ~Qt::WindowMaximized); window.show(); } if (cameraSmokeIndex >= 0) appendCameraSmokeLog(QStringLiteral("STEP 主窗口显示请求完成")); - QTimer::singleShot(0, &window, [&window]() { - if (!window.isMaximized()) - window.showMaximized(); - }); const int pageIndex = args.indexOf(QStringLiteral("--page")); if (pageIndex >= 0 && pageIndex + 1 < args.size()) { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 927709a..9fc1418 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,6 +1,9 @@ #include "mainwindow.h" +#include "applicationsettings.h" +#include "applicationstyle.h" #include "tactileheatmapwidget.h" #include "jointfloweditor.h" +#include "taskorchestrationwidget.h" #include "videorenderwidget.h" #include "agvmapviewwidget.h" @@ -29,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -43,7 +47,8 @@ #include #include #include -#include +#include "appmessagebox.h" +#include #include #include #include @@ -53,6 +58,8 @@ #include #include #include +#include +#include #include #include #include @@ -71,6 +78,87 @@ #endif namespace { +class TaskMediaDialog final : public QDialog +{ +public: + TaskMediaDialog(const QString &title, QWidget *parent) + : QDialog(parent, Qt::Window | Qt::FramelessWindowHint) + { + setAttribute(Qt::WA_TranslucentBackground); + setObjectName(QStringLiteral("jointFlowChildDialog")); + resize(900, 650); + setMinimumSize(560, 420); + auto *outer = new QVBoxLayout(this); + outer->setContentsMargins(12, 12, 12, 12); + outer->setSpacing(0); + auto *surface = new QFrame(this); + surface->setObjectName(QStringLiteral("jointFlowChildSurface")); + auto *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); + auto *titleLayout = new QHBoxLayout(m_titleBar); + titleLayout->setContentsMargins(12, 0, 0, 0); + titleLayout->setSpacing(9); + auto *mark = new QLabel(QStringLiteral("C"), m_titleBar); + mark->setObjectName(QStringLiteral("jointFlowDialogMark")); + mark->setAlignment(Qt::AlignCenter); + mark->setFixedSize(24, 24); + auto *titleLabel = new QLabel(title, m_titleBar); + titleLabel->setObjectName(QStringLiteral("jointFlowDialogTitle")); + auto *closeButton = new QPushButton(m_titleBar); + closeButton->setObjectName(QStringLiteral("jointFlowDialogCloseButton")); + closeButton->setFixedSize(46, 43); + closeButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/x.svg"), + QColor("#4f5964"), QColor("#4f5964"))); + titleLayout->addWidget(mark); + titleLayout->addWidget(titleLabel); + titleLayout->addStretch(); + titleLayout->addWidget(closeButton); + surfaceLayout->addWidget(m_titleBar); + m_content = new QWidget(surface); + m_content->setObjectName(QStringLiteral("jointFlowChildContent")); + m_layout = new QVBoxLayout(m_content); + m_layout->setContentsMargins(16, 16, 16, 16); + m_layout->setSpacing(10); + surfaceLayout->addWidget(m_content, 1); + outer->addWidget(surface); + m_titleBar->installEventFilter(this); + titleLabel->installEventFilter(this); + mark->installEventFilter(this); + connect(closeButton, &QPushButton::clicked, this, &QWidget::hide); + } + QVBoxLayout *contentLayout() const { return m_layout; } +protected: + bool eventFilter(QObject *watched, QEvent *event) override + { + if ((watched == m_titleBar || (watched && watched->parent() == m_titleBar)) && event) { + if (event->type() == QEvent::MouseButtonPress) { + auto *mouse = static_cast(event); + if (mouse->button() == Qt::LeftButton) { + m_dragging = true; + m_offset = mouse->globalPos() - frameGeometry().topLeft(); + return true; + } + } else if (event->type() == QEvent::MouseMove && m_dragging) { + move(static_cast(event)->globalPos() - m_offset); + return true; + } else if (event->type() == QEvent::MouseButtonRelease) { + m_dragging = false; + } + } + return QDialog::eventFilter(watched, event); + } +private: + QWidget *m_titleBar = nullptr; + QWidget *m_content = nullptr; + QVBoxLayout *m_layout = nullptr; + QPoint m_offset; + bool m_dragging = false; +}; + bool pageUsesArmTelemetry(int index) { return index == 1 || index == 13 || index == 14 || index == 15; @@ -83,7 +171,8 @@ const QStringList kPageTitles = { QStringLiteral("HLC 控制"), QStringLiteral("接口调试"), QStringLiteral("QUIC Server"), QStringLiteral("设备管理"), QStringLiteral("运行日志"), QStringLiteral("工具坐标标定"), - QStringLiteral("手眼标定"), QStringLiteral("末端操作") + QStringLiteral("手眼标定"), QStringLiteral("末端操作"), + QStringLiteral("任务编排") }; const QStringList kPageSubtitles = { QStringLiteral("系统信息、运行资源与全局停止"), @@ -101,7 +190,8 @@ const QStringList kPageSubtitles = { QStringLiteral("检查连接信息与 RPC 执行记录"), QStringLiteral("机械臂工具中心点与工具坐标系标定入口"), QStringLiteral("相机与机械臂坐标系的手眼标定入口"), - QStringLiteral("视觉取点与触控笔单击、双击、滑动") + QStringLiteral("视觉取点与触控笔单击、双击、滑动"), + QStringLiteral("跨设备任务、循环与执行等待编排") }; } @@ -293,6 +383,8 @@ MainWindow::MainWindow(QWidget *parent) QStringLiteral("手眼标定"), complexContent, 2); QPushButton *touchNavButton = createPageButton( QStringLiteral("末端操作"), complexContent, 2); + QPushButton *taskOrchestrationNavButton = createPageButton( + QStringLiteral("任务编排"), grpcContent, 1); ui.hlcNavButton->setParent(complexContent); ui.hlcNavButton->setProperty("navLevel", 2); complexLayout->addWidget(toolCalibrationNavButton); @@ -303,6 +395,7 @@ MainWindow::MainWindow(QWidget *parent) ui.configurationNavButton->setParent(grpcContent); grpcLayout->addWidget(ui.configurationNavButton); grpcLayout->addWidget(deviceContent); + grpcLayout->addWidget(taskOrchestrationNavButton); grpcLayout->addWidget(complexGroupButton); grpcLayout->addWidget(complexContent); @@ -321,6 +414,22 @@ MainWindow::MainWindow(QWidget *parent) navTreeLayout->addWidget(ui.quicNavButton); navTreeLayout->addWidget(ui.diagnosticsNavButton); navTreeLayout->addStretch(1); + auto *settingsButton = new QPushButton(QStringLiteral("软件设置"), navTree); + settingsButton->setObjectName(QStringLiteral("navButton")); + settingsButton->setProperty("navLevel", 0); + settingsButton->setIcon(UiIcons::icon(QStringLiteral(":/icons/settings.svg"), + QColor("#aab7c6"), QColor("#ffffff"))); + settingsButton->setIconSize(QSize(18, 18)); + settingsButton->setToolTip(QStringLiteral("外观、模型预览、启动与日志设置")); + navTreeLayout->addWidget(settingsButton); + connect(settingsButton, &QPushButton::clicked, this, [this]() { + showApplicationSettings(this, [this]() { + const auto &options = ApplicationSettings::instance().options(); + if (m_logView) m_logView->document()->setMaximumBlockCount(options.logMaximumLines); + if (m_quicLogView) m_quicLogView->document()->setMaximumBlockCount(options.logMaximumLines); + appendLog(QStringLiteral("OK"), QStringLiteral("软件设置已保存;模型预览和启动设置在下次启动时生效")); + }); + }); m_navGroup = new QButtonGroup(this); m_navGroup->setExclusive(true); @@ -329,7 +438,8 @@ MainWindow::MainWindow(QWidget *parent) ui.agvNavButton, ui.speakerNavButton, ui.microphoneNavButton, ui.dexhandNavButton, ui.bioheadNavButton, ui.hlcNavButton, ui.testNavButton, ui.quicNavButton, ui.configurationNavButton, - ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton, touchNavButton + ui.diagnosticsNavButton, toolCalibrationNavButton, handEyeNavButton, touchNavButton, + taskOrchestrationNavButton }; const QStringList icons = { QStringLiteral(":/icons/activity.svg"), @@ -346,7 +456,8 @@ MainWindow::MainWindow(QWidget *parent) QStringLiteral(":/icons/folder-open.svg"), QStringLiteral(":/icons/scroll-text.svg"), QStringLiteral(":/icons/crosshair.svg"), - QStringLiteral(":/icons/camera.svg"), QStringLiteral(":/icons/crosshair.svg") + QStringLiteral(":/icons/camera.svg"), QStringLiteral(":/icons/crosshair.svg"), + QStringLiteral(":/icons/braces.svg") }; for (int i = 0; i < m_navButtons.size(); ++i) { m_navButtons.at(i)->setIcon(UiIcons::icon( @@ -485,7 +596,7 @@ MainWindow::MainWindow(QWidget *parent) connect(m_tcpJog, &TcpJogController::stopRequested, m_client, &RobotClient::requestArmStop); connect(m_tcpJog, &TcpJogController::errorOccurred, this, [this](const QString &error) { appendLog(QStringLiteral("ERROR"), error); - QMessageBox::warning(this, QStringLiteral("TCP 点动"), error); + AppMessageBox::warning(this, QStringLiteral("TCP 点动"), error); }); // A global/other stop must invalidate any pending local continuation too. connect(m_client, &RobotClient::armStopRequested, m_tcpJog, &TcpJogController::stop); @@ -533,7 +644,10 @@ MainWindow::MainWindow(QWidget *parent) [this, tcpCalibration](bool connected, int, const QString &) { tcpCalibration->setContext(endpoint(), m_armIdEdit->text().trimmed(), connected, m_demoCheck->isChecked()); - if (!connected) m_controllerTcpFrames.clear(); + if (!connected) { + m_controllerBaseFrames.clear(); + m_controllerTcpFrames.clear(); + } refreshTcpChoices(); }); // Invalidate in-flight captures immediately, before the worker processes disconnect. @@ -545,6 +659,176 @@ MainWindow::MainWindow(QWidget *parent) syncTcpContext(); setupHandEye(); setupTouchOperation(); + m_taskOrchestration = new TaskOrchestrationWidget(m_pages); + m_pages->addWidget(m_taskOrchestration); + connect(m_taskOrchestration, &TaskOrchestrationWidget::statusMessage, + this, &MainWindow::appendLog); + connect(m_taskOrchestration, &TaskOrchestrationWidget::taskRequested, this, + [this](const QString &deviceType, const QString &deviceId, + const QString &action, const QJsonObject ¶meters) { + bool dispatched = false; + if (deviceType == QStringLiteral("机械臂")) { + if (action == QStringLiteral("MoveJ")) { + dispatched = true; + QVariantList positions; + for (const QJsonValue &value : parameters.value(QStringLiteral("positions")).toArray()) + positions.append(value.toDouble()); + m_client->requestMoveJ(deviceId, positions, + parameters.value(QStringLiteral("velocity")).toDouble(0.1), + parameters.value(QStringLiteral("acceleration")).toDouble(0.1)); + } else if (action == QStringLiteral("使能")) { + dispatched = true; + m_client->requestTorque(deviceId, true); + } else if (action == QStringLiteral("去使能")) { + dispatched = true; + m_client->requestTorque(deviceId, false); + } else if (action == QStringLiteral("停止")) { + dispatched = true; + m_client->requestArmStop(deviceId); + } else if (action == QStringLiteral("清除故障")) { + dispatched = true; + m_client->requestArmClearFault(deviceId); + } + } else if (deviceType == QStringLiteral("相机")) { + if (action == QStringLiteral("RGB抓图")) { + dispatched = true; + m_taskSnapshotCameraId = deviceId; + showTaskCameraResult(deviceId, QStringLiteral("RGB 抓图")); + m_client->requestSnapshot(deviceId); + } else if (action == QStringLiteral("深度抓图")) { + dispatched = true; + m_taskSnapshotCameraId = deviceId; + showTaskCameraResult(deviceId, QStringLiteral("深度抓图")); + m_client->requestDepthSnapshot(deviceId); + } else if (action == QStringLiteral("开始预览")) { + dispatched = true; + showTaskCameraResult(deviceId, QStringLiteral("视频预览")); + const QString codec = m_cameraCodecById.value(deviceId); + if (codec.isEmpty()) { + m_pendingTaskCameraPreviews.insert(deviceId); + m_taskOrchestration->reportTaskFeedback( + deviceId, QStringLiteral("正在读取设备编码器配置")); + m_client->requestCameraStatus(deviceId); + } else { + m_client->startCameraStream(deviceId, codec, QStringLiteral("rgb")); + } + } else if (action == QStringLiteral("停止预览")) { + dispatched = true; + m_client->stopCameraStream(deviceId); + if (m_taskCameraResults.contains(deviceId)) + m_taskCameraResults[deviceId].status->setText(QStringLiteral("正在停止预览…")); + } else if (action == QStringLiteral("开始录像")) { + dispatched = true; + m_taskCameraRecordingId = deviceId; + m_taskCameraRecordingAction = action; + m_client->startCameraRecording( + deviceId, parameters.value(QStringLiteral("path")).toString()); + } else if (action == QStringLiteral("停止录像")) { + dispatched = true; + m_taskCameraRecordingId = deviceId; + m_taskCameraRecordingAction = action; + m_client->stopCameraRecording(deviceId); + } + } else if (deviceType == QStringLiteral("AGV")) { + if (action == QStringLiteral("导航站点")) { + dispatched = true; + m_client->requestAgvNavigateStation(deviceId, + parameters.value(QStringLiteral("stationId")).toString(), + parameters.value(QStringLiteral("maxSpeed")).toDouble(0.5)); + } else if (action == QStringLiteral("停止") + || action == QStringLiteral("暂停") + || action == QStringLiteral("继续")) { + dispatched = true; + const QHash commands = { + {QStringLiteral("停止"), QStringLiteral("stop")}, + {QStringLiteral("暂停"), QStringLiteral("pause")}, + {QStringLiteral("继续"), QStringLiteral("resume")}}; + m_client->requestAgvAction(deviceId, commands.value(action)); + } + } else if (deviceType == QStringLiteral("灵巧手")) { + const QHash commands = { + {QStringLiteral("设置角度"), QStringLiteral("angle")}, + {QStringLiteral("设置位置"), QStringLiteral("position")}, + {QStringLiteral("设置速度"), QStringLiteral("speed")}, + {QStringLiteral("设置力"), QStringLiteral("force")}}; + if (commands.contains(action)) { + dispatched = true; + QVariantList values; + for (const QJsonValue &value : parameters.value(QStringLiteral("values")).toArray()) + values.append(value.toDouble()); + m_client->requestDexHandCommand(deviceId, commands.value(action), values); + } + } else if (deviceType == QStringLiteral("扬声器")) { + if (action == QStringLiteral("播放服务端文件") + || action == QStringLiteral("停止文件播放")) { + dispatched = true; + QJsonObject header; + header.insert(QStringLiteral("deviceId"), deviceId); + QJsonObject request; + request.insert(QStringLiteral("header"), header); + const QString method = action == QStringLiteral("播放服务端文件") + ? QStringLiteral("PlayAudio") : QStringLiteral("StopPlayback"); + if (method == QStringLiteral("PlayAudio")) + request.insert(QStringLiteral("audioPath"), + parameters.value(QStringLiteral("path")).toString()); + m_client->requestRpc(QStringLiteral("cmvr.api.SpeakerService"), method, + QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)), + deviceId); + } else if (action == QStringLiteral("本机麦克风流播放")) { + dispatched = true; + m_pendingTaskSpeakerCaptureId = deviceId; + m_pendingTaskSpeakerCaptureParameters = parameters; + m_taskOrchestration->reportTaskFeedback( + deviceId, QStringLiteral("正在建立扬声器音频流")); + m_client->startSpeakerAudioStream(deviceId); + } else if (action == QStringLiteral("开始音频流")) { + dispatched = true; + m_client->startSpeakerAudioStream(deviceId); + } else if (action == QStringLiteral("停止音频流")) { + dispatched = true; + m_audioManager->stopSource(); + m_client->stopSpeakerAudioStream(); + } + } else if (deviceType == QStringLiteral("麦克风")) { + if (action == QStringLiteral("开始录音") + || action == QStringLiteral("停止录音")) { + dispatched = true; + QJsonObject header; + header.insert(QStringLiteral("deviceId"), deviceId); + QJsonObject request; + request.insert(QStringLiteral("header"), header); + const QString method = action == QStringLiteral("开始录音") + ? QStringLiteral("StartRecord") : QStringLiteral("StopRecord"); + if (method == QStringLiteral("StartRecord")) + request.insert(QStringLiteral("filePath"), + parameters.value(QStringLiteral("path")).toString()); + m_client->requestRpc(QStringLiteral("cmvr.api.MicPhoneService"), method, + QString::fromUtf8(QJsonDocument(request).toJson(QJsonDocument::Compact)), + deviceId); + } else if (action == QStringLiteral("开始音频流")) { + dispatched = true; + m_client->startMicrophoneAudioStream(deviceId); + } else if (action == QStringLiteral("停止音频流")) { + dispatched = true; + m_client->stopMicrophoneAudioStream(); + } + } else if (deviceType == QStringLiteral("通用RPC")) { + dispatched = true; + m_client->requestRpc(parameters.value(QStringLiteral("service")).toString(), + parameters.value(QStringLiteral("method")).toString(), + QString::fromUtf8(QJsonDocument(parameters.value(QStringLiteral("request")).toObject()) + .toJson(QJsonDocument::Compact)), deviceId); + } + if (!dispatched) + m_taskOrchestration->completeCurrentTask( + false, QStringLiteral("不支持的任务操作:%1 / %2").arg(deviceType, action)); + }); + connect(m_client, &RobotClient::rpcFinished, this, + [this](const QString &service, const QString &method, + bool success, const QString &detail) { + if (m_taskOrchestration) + m_taskOrchestration->completeRpcTask(service, method, success, detail); + }); connect(m_client,&RobotClient::cameraStreamStartRequested,this, [this](const QString &camera,const QString &,const QString &mode) { m_cameraStreamModes.insert(camera,mode); @@ -573,32 +857,9 @@ MainWindow::MainWindow(QWidget *parent) connect(m_client,&RobotClient::disconnectRequested,this, [this] { stopJointPointLoop(QStringLiteral("连接已断开")); }); - const QString comboPopupStyle = QStringLiteral( - "QListView {" - " background: #ffffff; color: #33404c;" - " border: 1px solid #cfd4da; border-radius: 4px;" - " padding: 4px; outline: 0;" - "}" - "QListView::item {" - " min-height: 32px; padding: 0 10px;" - " border: none; border-radius: 3px;" - "}" - "QListView::item:hover {" - " color: #27313b; background: #f3f7fb;" - "}" - "QListView::item:selected {" - " color: #145da8; background: #e8f2ff; font-weight: 600;" - "}" - ); const QList comboBoxes = findChildren(); - for (QComboBox *comboBox : comboBoxes) { - QListView *popupView = new QListView(comboBox); - popupView->setObjectName(QStringLiteral("comboPopupView")); - popupView->setSpacing(1); - popupView->setUniformItemSizes(true); - popupView->setStyleSheet(comboPopupStyle); - comboBox->setView(popupView); - } + for (QComboBox *comboBox : comboBoxes) + ApplicationStyle::styleComboBox(comboBox); connect(m_client, &RobotClient::connectionChanged, this, &MainWindow::updateConnection); connect(m_client, &RobotClient::armInfoReceived, this, &MainWindow::updateArmInfo); @@ -607,6 +868,12 @@ MainWindow::MainWindow(QWidget *parent) this, &MainWindow::updateArmTelemetryHealth); connect(m_client, &RobotClient::systemStatusReceived, this, &MainWindow::updateSystemStatus); connect(m_client,&RobotClient::cameraCapabilitiesReceived,this,[this](quint64 token,const QString& camera,const QVariantMap& caps,bool success,const QString& detail) { + if (m_connected) { + m_cameraCapabilitiesById.insert(camera, success ? caps : QVariantMap()); + if (m_taskOrchestration) + m_taskOrchestration->setCameraCapabilities(camera, success ? caps : QVariantMap()); + refreshCameraDepthControls(); + } if(token!=m_cameraCapabilitiesToken || camera!=m_activeCameraId || !m_connected) return; m_cameraCapabilityInFlight=false; const auto next=success?caps:QVariantMap{}; @@ -615,23 +882,15 @@ MainWindow::MainWindow(QWidget *parent) m_client->stopCameraStream(camera); m_runningCameraIds.remove(camera); } m_activeCameraCapabilities=next; - if(CameraCapabilities::known(next) && m_cameraStreamModeCombo) { - if(auto *model=qobject_cast(m_cameraStreamModeCombo->model())) { - for(int i=0;icount();++i) { - const auto mode=m_cameraStreamModeCombo->itemData(i).toString(); - if(auto *item=model->item(i)) item->setEnabled(mode=="rgb" || next.value("metricAlignedDepth").toBool()); - } - } - if(!next.value("metricAlignedDepth").toBool() && m_cameraStreamModeCombo->currentData().toString()!="rgb") { - const QSignalBlocker block(m_cameraStreamModeCombo); m_cameraStreamModeCombo->setCurrentIndex(0); - } - } if(m_handEyeMotion) m_handEyeMotion->setCameraCapabilities(camera,next); if(m_handEye) m_handEye->setCameraCapabilities(camera,next); if(m_touchOperation) m_touchOperation->setCameraCapabilities(camera,next); if(!success && m_cameraStreamStateLabel) m_cameraStreamStateLabel->setText(detail); }); connect(m_client,&RobotClient::connectionChanged,this,[this](bool,int,const QString&) { + m_cameraCapabilitiesById.clear(); + if (m_taskOrchestration) m_taskOrchestration->setCameraCapabilities(QString(), {}); + refreshCameraDepthControls(); ++m_cameraCapabilitiesToken; m_cameraCapabilityInFlight=false; m_activeCameraId.clear(); m_activeCameraCapabilities.clear(); if(m_handEyeMotion) m_handEyeMotion->setCameraCapabilities({},{}); @@ -648,11 +907,19 @@ MainWindow::MainWindow(QWidget *parent) connect(m_client, &RobotClient::imageReceived, this, &MainWindow::updateImage); connect(m_client, &RobotClient::cameraStatusReceived, this, [this](const QString &cameraId, const QVariantMap &state) { + const QString codec = state.value(QStringLiteral("codec")).toString().toLower(); + if (!codec.isEmpty()) + m_cameraCodecById.insert(cameraId, codec); + if (!codec.isEmpty() && m_pendingTaskCameraPreviews.remove(cameraId) > 0) { + if (m_taskOrchestration) + m_taskOrchestration->reportTaskFeedback( + cameraId, QStringLiteral("使用设备编码器 %1").arg(codec.toUpper())); + m_client->startCameraStream(cameraId, codec, QStringLiteral("rgb")); + } if (!m_cameraDeviceCombo || !m_cameraCodecCombo || m_cameraDeviceCombo->currentData().toString() != cameraId) { return; } - const QString codec = state.value(QStringLiteral("codec")).toString().toLower(); if (codec.isEmpty()) return; const bool isH265 = codec.contains(QStringLiteral("265")) @@ -679,8 +946,35 @@ MainWindow::MainWindow(QWidget *parent) connect(m_client, &RobotClient::videoFrameReceived, this, &MainWindow::updateVideoFrame); connect(m_client, &RobotClient::cameraStreamStateChanged, this, &MainWindow::updateCameraStreamState); + connect(m_client, &RobotClient::cameraStreamStateChanged, this, + [this](const QString &cameraId, bool running, const QString &detail) { + if (m_taskCameraResults.contains(cameraId)) { + TaskCameraResult &result = m_taskCameraResults[cameraId]; + result.status->setText(running ? QStringLiteral("预览中 · %1").arg(detail) + : QStringLiteral("已停止 · %1").arg(detail)); + } + if (m_taskOrchestration && !detail.isEmpty()) + m_taskOrchestration->reportTaskFeedback( + cameraId, detail, running || !detail.contains(QStringLiteral("失败"))); + if (m_taskOrchestration) + m_taskOrchestration->completeCameraStreamTask(cameraId, running, detail); + }); connect(m_client, &RobotClient::cameraRecordingStateChanged, - this, &MainWindow::updateCameraRecordingState); + this, [this](bool recording, const QString &detail) { + updateCameraRecordingState(recording, detail); + if (!m_taskCameraRecordingId.isEmpty() && m_taskOrchestration) { + const QString action = m_taskCameraRecordingAction; + const QString deviceId = m_taskCameraRecordingId; + m_taskCameraRecordingId.clear(); + m_taskCameraRecordingAction.clear(); + const bool expectedState = action == QStringLiteral("开始录像"); + const bool success = recording == expectedState + && !detail.contains(QStringLiteral("失败"), Qt::CaseInsensitive) + && !detail.contains(QStringLiteral("error"), Qt::CaseInsensitive); + m_taskOrchestration->completeActionTask( + QStringLiteral("相机"), deviceId, action, success, detail); + } + }); connect(m_client, &RobotClient::agvStateReceived, this, &MainWindow::updateAgvState); connect(m_client, &RobotClient::agvInventoryReceived, this, &MainWindow::updateAgvInventory); connect(m_client, &RobotClient::agvMapFrameReceived, this, @@ -732,6 +1026,75 @@ MainWindow::MainWindow(QWidget *parent) m_audioManager, &AudioStreamManager::playPcmFrame); connect(m_audioManager, &AudioStreamManager::logMessage, this, &MainWindow::appendLog); + connect(m_client, &RobotClient::audioStreamStateChanged, this, + [this](const QString &service, bool running, const QString &detail) { + if (!m_taskOrchestration) return; + const bool success = !detail.contains(QStringLiteral("失败"), Qt::CaseInsensitive) + && !detail.contains(QStringLiteral("error"), Qt::CaseInsensitive); + if (service == QStringLiteral("SpeakerService")) { + if (!m_pendingTaskSpeakerCaptureId.isEmpty()) { + const QString deviceId = m_pendingTaskSpeakerCaptureId; + const QJsonObject parameters = m_pendingTaskSpeakerCaptureParameters; + if (!running) { + m_pendingTaskSpeakerCaptureId.clear(); + m_pendingTaskSpeakerCaptureParameters = QJsonObject(); + m_taskOrchestration->completeActionTask( + QStringLiteral("扬声器"), deviceId, + QStringLiteral("本机麦克风流播放"), false, detail); + return; + } + if (!m_audioManager->startCapture( + parameters.value(QStringLiteral("inputDevice")).toString(), + parameters.value(QStringLiteral("sampleRate")).toInt(48000), + parameters.value(QStringLiteral("channels")).toInt(1))) { + m_pendingTaskSpeakerCaptureId.clear(); + m_pendingTaskSpeakerCaptureParameters = QJsonObject(); + m_client->stopSpeakerAudioStream(); + m_taskOrchestration->completeActionTask( + QStringLiteral("扬声器"), deviceId, + QStringLiteral("本机麦克风流播放"), false, + QStringLiteral("本机麦克风采集启动失败")); + } + return; + } + if (running) { + m_taskOrchestration->completeActionTask( + QStringLiteral("扬声器"), QString(), + QStringLiteral("开始音频流"), success, detail); + } else { + m_taskOrchestration->completeActionTask( + QStringLiteral("扬声器"), QString(), + QStringLiteral("开始音频流"), false, detail); + m_taskOrchestration->completeActionTask( + QStringLiteral("扬声器"), QString(), + QStringLiteral("停止音频流"), success, detail); + } + } else if (service == QStringLiteral("MicPhoneService")) { + if (running) { + m_taskOrchestration->completeActionTask( + QStringLiteral("麦克风"), QString(), + QStringLiteral("开始音频流"), success, detail); + } else { + m_taskOrchestration->completeActionTask( + QStringLiteral("麦克风"), QString(), + QStringLiteral("开始音频流"), false, detail); + m_taskOrchestration->completeActionTask( + QStringLiteral("麦克风"), QString(), + QStringLiteral("停止音频流"), success, detail); + } + } + }); + connect(m_audioManager, &AudioStreamManager::sourceStateChanged, this, + [this](bool running, const QString &detail) { + if (!running || m_pendingTaskSpeakerCaptureId.isEmpty() || !m_taskOrchestration) + return; + const QString deviceId = m_pendingTaskSpeakerCaptureId; + m_pendingTaskSpeakerCaptureId.clear(); + m_pendingTaskSpeakerCaptureParameters = QJsonObject(); + m_taskOrchestration->completeActionTask( + QStringLiteral("扬声器"), deviceId, + QStringLiteral("本机麦克风流播放"), true, detail); + }); connect(m_quicServer, &QuicTestServer::runningChanged, this, &MainWindow::updateQuicRunning); connect(m_quicServer, &QuicTestServer::clientCountChanged, this, [this](int count) { @@ -757,6 +1120,8 @@ MainWindow::MainWindow(QWidget *parent) this, &MainWindow::appendQuicLog); loadSettings(); + if (m_logView) m_logView->document()->setMaximumBlockCount(ApplicationSettings::instance().options().logMaximumLines); + if (m_quicLogView) m_quicLogView->document()->setMaximumBlockCount(ApplicationSettings::instance().options().logMaximumLines); const QStringList startupArguments = QCoreApplication::arguments(); const int cameraCodecArgument = startupArguments.indexOf( QStringLiteral("--camera-codec")); @@ -774,6 +1139,7 @@ MainWindow::MainWindow(QWidget *parent) if (validPage && requestedPage >= 0 && requestedPage < m_pages->count()) initialPage = requestedPage; } + if (pageArgument < 0) initialPage = ApplicationSettings::instance().options().startupPage; selectPage(initialPage); setControlsEnabled(false); qApp->installEventFilter(this); @@ -803,6 +1169,7 @@ MainWindow::~MainWindow() m_client->stopMicrophoneAudioStream(); m_quicServer->stopServer(); saveSettings(); + ApplicationSettings::instance().saveWindowGeometry(saveGeometry()); } bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) @@ -1053,17 +1420,22 @@ void MainWindow::appendQuicLog(const QString &level, const QString &message) { if (!m_quicLogView) return; - QString color = QStringLiteral("#aeb6c0"); + const int scrollPosition = m_quicLogView->verticalScrollBar()->value(); + QString color = QStringLiteral("#64748b"); if (level == QStringLiteral("ERROR")) - color = QStringLiteral("#ff7b72"); + color = QStringLiteral("#bd343b"); else if (level == QStringLiteral("WARN")) - color = QStringLiteral("#e3b341"); + color = QStringLiteral("#a16207"); else if (level == QStringLiteral("OK")) - color = QStringLiteral("#56d39b"); + color = QStringLiteral("#177553"); const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz"); m_quicLogView->append(QStringLiteral("%1 " "[%3] %4") .arg(timestamp, color, level, message.toHtmlEscaped())); + if (!ApplicationSettings::instance().options().logAutoScroll) + m_quicLogView->verticalScrollBar()->setValue(scrollPosition); + else + m_quicLogView->verticalScrollBar()->setValue(m_quicLogView->verticalScrollBar()->maximum()); } void MainWindow::setArmTelemetryEnabled(bool enabled) @@ -1197,7 +1569,7 @@ void MainWindow::presentPendingAgvMapFrame() void MainWindow::ensureArmModelLoaded() { - if (!m_urdfViewer || m_pendingUrdfPath.isEmpty() + if (!m_urdfViewer || !m_urdfViewer->modelPreviewEnabled() || m_pendingUrdfPath.isEmpty() || !m_urdfViewer->currentFile().isEmpty() || m_armModelLoadScheduled) { return; } @@ -1227,7 +1599,7 @@ void MainWindow::toggleConnection() } if (m_hostEdit->text().trimmed().isEmpty()) { - QMessageBox::warning(this, QStringLiteral("连接参数"), QStringLiteral("请填写主机地址。")); + AppMessageBox::warning(this, QStringLiteral("连接参数"), QStringLiteral("请填写主机地址。")); return; } saveSettings(); @@ -1248,6 +1620,9 @@ void MainWindow::toggleConnection() void MainWindow::updateConnection(bool connected, int latencyMs, const QString &detail) { m_connected = connected; + if (!connected && m_taskOrchestration) + m_taskOrchestration->failActiveTask( + detail.isEmpty() ? QStringLiteral("gRPC 连接已断开") : detail); m_connectButton->setEnabled(true); m_connectButton->setText(connected ? QStringLiteral("断开连接") : QStringLiteral("连接")); m_connectionText->setText(connected ? QStringLiteral("gRPC 已连接") @@ -1625,7 +2000,7 @@ void MainWindow::setupHandEye() appendLog(QStringLiteral("OK"),QStringLiteral("标定 URDF 已加载:%1").arg(path)); } else { if (!previous.isEmpty()) m_urdfViewer->loadUrdf(previous); - QMessageBox::warning(this,QStringLiteral("URDF 更新"),QStringLiteral("文件已导出,但模型加载失败。请检查网格资源路径。")); + AppMessageBox::warning(this,QStringLiteral("URDF 更新"),QStringLiteral("文件已导出,但模型加载失败。请检查网格资源路径。")); } }); connect(m_handEye,&HandEyeCalibrationWidget::previewRequested,this,[this](const QString &camera,bool start) { @@ -1724,10 +2099,19 @@ void MainWindow::updateArmPoseFrames() m_tcpFrameCombo->setToolTip(local ? QStringLiteral("使用当前机器人的标定偏移进行点动;单步最多 2 mm / 0.29°,松开即停止") : QStringLiteral("控制器坐标名称;原速度命令仍使用基座方向")); - // Local names must never be sent to the server's named-frame RPC. + // Display fallbacks such as "base" and "tool0" are UI labels only. A + // named getPose request is safe only for a pair returned by the server's + // frame-list RPCs; motor-backed arms otherwise reject those invented names + // against their URDF. Empty names deliberately keep telemetry on + // getRobotState.actual_tcp_pose. + const QString baseFrame = m_baseFrameCombo->currentText().trimmed(); + const QString tcpFrame = m_tcpFrameCombo->currentText().trimmed(); + const bool serverFramePair = !local + && m_controllerBaseFrames.contains(baseFrame) + && m_controllerTcpFrames.contains(tcpFrame); m_client->setArmTelemetryFrames(m_armIdEdit->text().trimmed(), - local ? QStringLiteral("base") : m_baseFrameCombo->currentText(), - local ? QString() : m_tcpFrameCombo->currentText()); + serverFramePair ? baseFrame : QString(), + serverFramePair ? tcpFrame : QString()); for (auto *label : m_cartesianJogPoseLabels) label->setText(QStringLiteral("--")); for (auto *label : m_poseMetricValues) label->setText(QStringLiteral("--")); } @@ -2075,9 +2459,9 @@ void MainWindow::updateArmAlert(const QString &deviceId, const QString &alertKey return; m_armLastAlertPopupMs.insert(popupKey, nowMs); - QMessageBox *popup = new QMessageBox( - level == QStringLiteral("ERROR") ? QMessageBox::Critical : QMessageBox::Warning, - QStringLiteral("机械臂状态提醒"), message, QMessageBox::Ok, this); + AppMessageBox *popup = new AppMessageBox( + level == QStringLiteral("ERROR") ? AppMessageBox::Critical : AppMessageBox::Warning, + QStringLiteral("机械臂状态提醒"), message, AppMessageBox::Ok, this); popup->setAttribute(Qt::WA_DeleteOnClose); popup->setWindowModality(Qt::NonModal); popup->open(); @@ -2086,6 +2470,16 @@ void MainWindow::updateArmAlert(const QString &deviceId, const QString &alertKey void MainWindow::updateSystemStatus(double cpu, double memory, double disk, const QVariantList &devices) { + if (m_taskOrchestration) + m_taskOrchestration->setAvailableDevices(devices); + if (m_connected) { + for (const QVariant &value : devices) { + const QVariantMap device = value.toMap(); + const QString id = device.value(QStringLiteral("deviceId")).toString(); + if (device.value(QStringLiteral("type")).toInt() == 2 && !id.isEmpty()) + m_client->requestCameraCapabilities(id, 0); + } + } if(m_connected && !m_demoCheck->isChecked()) { QStringList cameras,automatic; for(const auto& value:devices) { @@ -2190,6 +2584,7 @@ void MainWindow::updateSystemStatus(double cpu, double memory, double disk, && previousCameraId != m_cameraDeviceCombo->currentData().toString()) rebuildCameraPreviewGrid(configuredCameraIds()); const QString cameraId = m_cameraDeviceCombo->currentData().toString(); + refreshCameraDepthControls(); if (!cameraId.isEmpty() && (previousCameraId != cameraId || m_cameraCodecCombo->toolTip().isEmpty())) m_client->requestCameraStatus(cameraId); @@ -2470,6 +2865,47 @@ void MainWindow::updateAgvInventory(const QStringList &maps, const QVariantList m_agvMapOverview->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } +void MainWindow::showTaskCameraResult(const QString &cameraId, const QString &title) +{ + if (cameraId.isEmpty()) return; + TaskCameraResult &result = m_taskCameraResults[cameraId]; + if (!result.window) { + auto *dialog = new TaskMediaDialog( + QStringLiteral("%1 · %2").arg(cameraId, title), this); + dialog->setAttribute(Qt::WA_DeleteOnClose, false); + result.window = dialog; + result.render = new VideoRenderWidget(dialog); + result.render->setMinimumSize(520, 320); + result.status = new QLabel(QStringLiteral("等待媒体数据…"), dialog); + result.status->setObjectName(QStringLiteral("mutedLabel")); + dialog->contentLayout()->addWidget(result.render, 1); + dialog->contentLayout()->addWidget(result.status); + } + result.window->show(); + result.window->raise(); + result.window->activateWindow(); +} + +void MainWindow::updateTaskCameraImage(const QString &cameraId, const QImage &image, + const QString &detail) +{ + if (cameraId.isEmpty() || !m_taskCameraResults.contains(cameraId)) return; + TaskCameraResult &result = m_taskCameraResults[cameraId]; + result.render->setImage(image); + result.status->setText(detail); + if (m_taskOrchestration) + m_taskOrchestration->reportTaskFeedback(cameraId, detail, !image.isNull()); +} + +void MainWindow::updateTaskCameraFrame(const QString &cameraId, const VideoFrame &frame, + const QString &detail) +{ + if (cameraId.isEmpty() || !m_taskCameraResults.contains(cameraId)) return; + TaskCameraResult &result = m_taskCameraResults[cameraId]; + result.render->setFrame(frame); + result.status->setText(detail); +} + void MainWindow::updateImage(const QImage &image, const QString &detail) { m_lastImage = image; @@ -2478,6 +2914,10 @@ void MainWindow::updateImage(const QImage &image, const QString &detail) m_videoRender->setImage(image); m_imageMetaLabel->setText(detail); m_saveImageButton->setEnabled(true); + if (!m_taskSnapshotCameraId.isEmpty()) { + updateTaskCameraImage(m_taskSnapshotCameraId, image, detail); + m_taskSnapshotCameraId.clear(); + } } void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &frame, @@ -2489,6 +2929,7 @@ void MainWindow::updateVideoFrame(const QString &cameraId, const VideoFrame &fra // stopped. Do not let those stale frames overwrite a later snapshot. if (!m_runningCameraIds.contains(resolvedId)) return; + updateTaskCameraFrame(resolvedId, frame, detail); const auto it = m_cameraPreviewTiles.find(resolvedId); if (it == m_cameraPreviewTiles.end()) return; @@ -2551,6 +2992,24 @@ void MainWindow::updateCameraRecordingState(bool recording, const QString &detai void MainWindow::handleCommand(const QString &command, bool success, const QString &detail) { + if (!success) { + if (command == QStringLiteral("Snapshot") + || command == QStringLiteral("Depth Snapshot")) + m_taskSnapshotCameraId.clear(); + else if (command == QStringLiteral("Camera Stream")) + m_pendingTaskCameraPreviews.clear(); + else if (command == QStringLiteral("Camera Start Recording") + || command == QStringLiteral("Camera Stop Recording")) { + m_taskCameraRecordingId.clear(); + m_taskCameraRecordingAction.clear(); + } else if (command == QStringLiteral("Speaker Stream")) { + m_pendingTaskSpeakerCaptureId.clear(); + m_pendingTaskSpeakerCaptureParameters = QJsonObject(); + m_audioManager->stopSource(); + } + } + if (m_taskOrchestration) + m_taskOrchestration->completeCommandTask(command, success, detail); QLabel *stateLabel = nullptr; QString stateText; if (command == QStringLiteral("Torque On")) { @@ -2651,23 +3110,28 @@ void MainWindow::appendLog(const QString &level, const QString &message) } if (!m_logView) return; - QString color = QStringLiteral("#aeb6c0"); + const int scrollPosition = m_logView->verticalScrollBar()->value(); + QString color = QStringLiteral("#64748b"); if (level == QStringLiteral("ERROR")) - color = QStringLiteral("#ff7b72"); + color = QStringLiteral("#bd343b"); else if (level == QStringLiteral("WARN")) - color = QStringLiteral("#e3b341"); + color = QStringLiteral("#a16207"); else if (level == QStringLiteral("OK")) - color = QStringLiteral("#56d39b"); + color = QStringLiteral("#177553"); const QString timestamp = QDateTime::currentDateTime().toString("HH:mm:ss.zzz"); m_logView->append(QStringLiteral("%1 " "[%3] %4") .arg(timestamp, color, level, message.toHtmlEscaped())); + if (!ApplicationSettings::instance().options().logAutoScroll) + m_logView->verticalScrollBar()->setValue(scrollPosition); + else + m_logView->verticalScrollBar()->setValue(m_logView->verticalScrollBar()->maximum()); } void MainWindow::sendMoveJ() { if (m_armIdEdit->text().trimmed().isEmpty() || m_targetSpins.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("MoveJ 关节位置控制"), + AppMessageBox::warning(this, QStringLiteral("MoveJ 关节位置控制"), QStringLiteral("请先选择机械臂并等待关节信息加载完成。")); return; } @@ -2722,13 +3186,13 @@ void MainWindow::recordCurrentJointPoint() const QString name = m_jointPointNameEdit ? m_jointPointNameEdit->text().trimmed() : QString(); if (name.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("记录关节点位"), + AppMessageBox::warning(this, QStringLiteral("记录关节点位"), QStringLiteral("请输入动作名称。")); return; } for (const RecordedJointPoint &point : m_recordedJointPoints) { if (point.name.compare(name, Qt::CaseInsensitive) == 0) { - QMessageBox::warning(this, QStringLiteral("记录关节点位"), + AppMessageBox::warning(this, QStringLiteral("记录关节点位"), QStringLiteral("动作名称“%1”已存在,请使用其他名称。") .arg(name)); return; @@ -2737,7 +3201,7 @@ void MainWindow::recordCurrentJointPoint() const QStringList jointNames = m_activeArmJointNames; if (jointNames.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("记录关节点位"), + AppMessageBox::warning(this, QStringLiteral("记录关节点位"), QStringLiteral("当前 URDF 中没有该机械臂的可运动关节。")); return; } @@ -2757,13 +3221,13 @@ void MainWindow::recordCurrentJointPoint() point.positions.append(m_latestArmJointPositions.value(jointName)); } if (!missing.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("记录关节点位"), + AppMessageBox::warning(this, QStringLiteral("记录关节点位"), QStringLiteral("尚未收到以下关节的实时角度:\n%1\n\n请先启动遥测。") .arg(missing.join(QStringLiteral(", ")))); return; } if (point.deviceId.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("记录关节点位"), + AppMessageBox::warning(this, QStringLiteral("记录关节点位"), QStringLiteral("当前 Device ID 为空。")); return; } @@ -2785,7 +3249,7 @@ void MainWindow::executeSelectedJointPoint() const QModelIndexList selected = m_jointPointTable ? m_jointPointTable->selectionModel()->selectedRows() : QModelIndexList(); if (selected.isEmpty()) { - QMessageBox::information(this, QStringLiteral("执行关节点位"), + AppMessageBox::information(this, QStringLiteral("执行关节点位"), QStringLiteral("请先选择一个已记录动作。")); return; } @@ -2810,7 +3274,7 @@ void MainWindow::startJointPointLoop() return; ++m_jointPointLoopGeneration; if (!m_jointFlowEditor || m_jointFlowEditor->isEmpty()) { - QMessageBox::information(this, QStringLiteral("执行自定义流程"), + AppMessageBox::information(this, QStringLiteral("执行自定义流程"), QStringLiteral("请先向自定义流程中添加步骤。")); return; } @@ -2828,13 +3292,13 @@ void MainWindow::startJointPointLoop() const QList steps = m_jointFlowEditor->expandedSteps(&flowError); if (!flowError.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("执行自定义流程"), flowError); + AppMessageBox::warning(this, QStringLiteral("执行自定义流程"), flowError); return; } for (const JointFlowEditor::ExecutionStep &step : steps) { const int row = pointRow(step.pointName); if (row < 0) { - QMessageBox::warning(this, QStringLiteral("执行自定义流程"), + AppMessageBox::warning(this, QStringLiteral("执行自定义流程"), QStringLiteral("流程引用的点位“%1”已不存在。").arg(step.pointName)); m_jointPointLoopRows.clear(); m_jointPointExecutionWaits.clear(); @@ -2846,7 +3310,7 @@ void MainWindow::startJointPointLoop() m_jointPointExecutionNodeIds.append(step.nodeId); } if (m_jointPointLoopRows.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("执行自定义流程"), + AppMessageBox::warning(this, QStringLiteral("执行自定义流程"), QStringLiteral("流程引用的点位已不存在。")); return; } diff --git a/src/mainwindow.h b/src/mainwindow.h index a160ad3..41d2d6b 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -50,6 +51,7 @@ class HandEyeMotionWidget; class AgvMapViewWidget; class TactileHeatmapWidget; class JointFlowEditor; +class TaskOrchestrationWidget; class MainWindow : public QMainWindow { @@ -108,6 +110,11 @@ private slots: void saveSnapshot(); private: + void showTaskCameraResult(const QString &cameraId, const QString &title); + void updateTaskCameraImage(const QString &cameraId, const QImage &image, + const QString &detail); + void updateTaskCameraFrame(const QString &cameraId, const VideoFrame &frame, + const QString &detail); QWidget *createSystemPage(); QWidget *createArmPage(); QWidget *createCameraPage(); @@ -115,6 +122,7 @@ private: QStringList configuredCameraIds() const; void rebuildCameraPreviewGrid(const QStringList &cameraIds); void refreshCameraStreamControls(); + void refreshCameraDepthControls(); QWidget *createAgvPage(); QWidget *createAudioPage(bool speaker); QWidget *createRpcPage(const QString &serviceName); @@ -161,6 +169,7 @@ private: TouchOperationWidget *m_touchOperation = nullptr; QString m_touchOwnedCamera; QString m_tcpChoiceEndpoint, m_tcpChoiceDevice; + QStringList m_controllerBaseFrames; QStringList m_controllerTcpFrames; QLabel *m_armPoseSubtitle = nullptr; AudioStreamManager *m_audioManager = nullptr; @@ -301,6 +310,7 @@ private: QDoubleSpinBox *m_jointFlowAccelerationSpin = nullptr; QSpinBox *m_jointFlowGroupCount = nullptr; JointFlowEditor *m_jointFlowEditor = nullptr; + TaskOrchestrationWidget *m_taskOrchestration = nullptr; QDialog *m_jointFlowDialog = nullptr; QPushButton *m_recordJointPointButton = nullptr; QPushButton *m_runJointPointButton = nullptr; @@ -342,9 +352,21 @@ private: }; QHash m_cameraPreviewTiles; QHash m_cameraStreamModes; + QHash m_cameraCodecById; + QSet m_pendingTaskCameraPreviews; + struct TaskCameraResult { + QDialog *window = nullptr; + VideoRenderWidget *render = nullptr; + QLabel *status = nullptr; + }; + QHash m_taskCameraResults; + QString m_taskSnapshotCameraId; + QString m_taskCameraRecordingId; + QString m_taskCameraRecordingAction; QSet m_runningCameraIds; QString m_activeCameraId; QVariantMap m_activeCameraCapabilities; + QHash m_cameraCapabilitiesById; quint64 m_cameraCapabilitiesToken=0; bool m_cameraCapabilityInFlight=false; QImage m_lastImage; @@ -424,6 +446,8 @@ private: QPushButton *m_microphoneStreamStopButton = nullptr; QLineEdit *m_speakerIdEdit = nullptr; QLineEdit *m_microphoneIdEdit = nullptr; + QString m_pendingTaskSpeakerCaptureId; + QJsonObject m_pendingTaskSpeakerCaptureParameters; QLineEdit *m_quicBindEdit = nullptr; QSpinBox *m_quicPortSpin = nullptr; diff --git a/src/mainwindow_ui.cpp b/src/mainwindow_ui.cpp index 40f7402..3a4dfb3 100644 --- a/src/mainwindow_ui.cpp +++ b/src/mainwindow_ui.cpp @@ -2,6 +2,7 @@ #include "agvmapviewwidget.h" #include "audiostreammanager.h" +#include "cameracapabilities.h" #include "robotclient.h" #include "tcptoolstore.h" #include "handeyemotionwidget.h" @@ -44,7 +45,7 @@ #include #include #include -#include +#include "appmessagebox.h" #include #include #include @@ -487,7 +488,7 @@ QWidget *MainWindow::createArmPage() return; for (const JointProgramGroup &group : m_jointProgramGroups) { if (group.name.compare(name, Qt::CaseInsensitive) == 0) { - QMessageBox::information(m_jointFlowDialog, QStringLiteral("新建点位组"), + AppMessageBox::information(m_jointFlowDialog, QStringLiteral("新建点位组"), QStringLiteral("已存在同名点位组。")); return; } @@ -516,7 +517,7 @@ QWidget *MainWindow::createArmPage() for (int i = 0; i < m_jointProgramGroups.size(); ++i) { if (i != m_activeJointProgramGroup && m_jointProgramGroups.at(i).name.compare(name, Qt::CaseInsensitive) == 0) { - QMessageBox::information(m_jointFlowDialog, QStringLiteral("重命名点位组"), + AppMessageBox::information(m_jointFlowDialog, QStringLiteral("重命名点位组"), QStringLiteral("已存在同名点位组。")); return; } @@ -759,7 +760,7 @@ QWidget *MainWindow::createArmPage() connect(addFlowStepButton, &QPushButton::clicked, this, [this]() { const QModelIndexList rows = m_jointPointTable->selectionModel()->selectedRows(); if (rows.isEmpty()) { - QMessageBox::information(m_jointFlowDialog, QStringLiteral("添加单步节点"), + AppMessageBox::information(m_jointFlowDialog, QStringLiteral("添加单步节点"), QStringLiteral("请先选择一个已记录点位。")); return; } @@ -786,7 +787,7 @@ QWidget *MainWindow::createArmPage() m_jointFlowEditor, &JointFlowEditor::setInsertionAtRoot); connect(enterSelectedLoopButton, &QPushButton::clicked, this, [this]() { if (!m_jointFlowEditor->useSelectedLoopAsInsertionParent()) { - QMessageBox::information(m_jointFlowDialog, QStringLiteral("添加到循环"), + AppMessageBox::information(m_jointFlowDialog, QStringLiteral("添加到循环"), QStringLiteral("请先在画布中选择一个循环节点。")); } }); @@ -1208,7 +1209,7 @@ QWidget *MainWindow::createArmPage() }); connect(m_armTelemetryButton, &QPushButton::clicked, this, [this](bool enabled) { if (enabled && m_armIdEdit->text().trimmed().isEmpty()) { - QMessageBox::warning(this, QStringLiteral("ArmService"), + AppMessageBox::warning(this, QStringLiteral("ArmService"), QStringLiteral("请先选择机械臂设备。")); setArmTelemetryEnabled(false); return; @@ -1228,12 +1229,12 @@ QWidget *MainWindow::createArmPage() const QString deviceId = m_armIdEdit->text().trimmed(); const QString jointName = m_zeroJointCombo->currentText().trimmed(); if (deviceId.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("零位标定"), + AppMessageBox::warning(this, QStringLiteral("零位标定"), QStringLiteral("请先填写机械臂设备 ID。")); return; } if (jointName.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("零位标定"), + AppMessageBox::warning(this, QStringLiteral("零位标定"), QStringLiteral("请选择需要设置零位的关节。")); return; } @@ -1241,9 +1242,9 @@ QWidget *MainWindow::createArmPage() "即将把设备 %1 的关节 %2 当前位置设置为零位。\n\n" "该操作会改变关节坐标基准,是否继续?") .arg(deviceId, jointName); - if (QMessageBox::warning(this, QStringLiteral("确认零位标定"), prompt, - QMessageBox::Yes | QMessageBox::Cancel, - QMessageBox::Cancel) != QMessageBox::Yes) { + if (AppMessageBox::warning(this, QStringLiteral("确认零位标定"), prompt, + AppMessageBox::Yes | AppMessageBox::Cancel, + AppMessageBox::Cancel) != AppMessageBox::Yes) { return; } m_client->requestArmCalibrateZero(deviceId, jointName); @@ -1268,7 +1269,7 @@ QWidget *MainWindow::createArmPage() m_latestArmJointPositions.value(jointName)); } if (!missing.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("同步当前位置"), + AppMessageBox::warning(this, QStringLiteral("同步当前位置"), QStringLiteral("以下关节尚无遥测位置:\n%1\n\n请先启动遥测。") .arg(missing.join(QStringLiteral(", ")))); return; @@ -1309,6 +1310,7 @@ QWidget *MainWindow::createArmPage() }; fillFrames(m_baseFrameCombo, baseFrames, m_armDefaultBaseFrame, QStringLiteral("base")); + m_controllerBaseFrames = baseFrames; m_controllerTcpFrames = tcpFrames; refreshTcpChoices(); }); @@ -1379,8 +1381,11 @@ QWidget *MainWindow::createArmPage() m_syncCurrentToTargetButton->setEnabled(false); rebuildArmJogControls(); m_zeroJointCombo->clear(); + m_controllerBaseFrames.clear(); + m_controllerTcpFrames.clear(); m_armDefaultBaseFrame.clear(); m_armDefaultTcpFrame.clear(); + refreshTcpChoices(); m_latestArmPose.clear(); for (QLabel *valueLabel : m_poseMetricValues) valueLabel->setText(QStringLiteral("--")); @@ -1479,6 +1484,30 @@ void MainWindow::rebuildCameraPreviewGrid(const QStringList &cameraIds) ? nullptr : m_cameraPreviewTiles.value(cameraIds.first()).render; } +void MainWindow::refreshCameraDepthControls() +{ + if (!m_cameraStreamModeCombo || !m_cameraDeviceCombo) return; + const QString cameraId = m_cameraDeviceCombo->currentData().toString(); + const QVariantMap capabilities = m_cameraCapabilitiesById.value(cameraId); + const bool depth = CameraCapabilities::depthStream(capabilities); + if (m_depthSnapshotButton) + m_depthSnapshotButton->setVisible(CameraCapabilities::depthImage(capabilities)); + const QString previousMode = m_cameraStreamModeCombo->currentData().toString(); + const QSignalBlocker blocker(m_cameraStreamModeCombo); + if (!depth) { + for (int i = m_cameraStreamModeCombo->count() - 1; i >= 0; --i) + if (m_cameraStreamModeCombo->itemData(i).toString() != QStringLiteral("rgb")) + m_cameraStreamModeCombo->removeItem(i); + } else { + if (m_cameraStreamModeCombo->findData(QStringLiteral("depth")) < 0) + m_cameraStreamModeCombo->addItem(QStringLiteral("深度"), QStringLiteral("depth")); + if (m_cameraStreamModeCombo->findData(QStringLiteral("rgbd")) < 0) + m_cameraStreamModeCombo->addItem(QStringLiteral("RGB + 深度"), QStringLiteral("rgbd")); + } + const int index = m_cameraStreamModeCombo->findData(previousMode); + m_cameraStreamModeCombo->setCurrentIndex(index >= 0 ? index : 0); +} + void MainWindow::refreshCameraStreamControls() { m_cameraStreaming = !m_runningCameraIds.isEmpty(); @@ -1501,6 +1530,7 @@ void MainWindow::refreshCameraStreamControls() m_cameraStreamStateLabel->setText(m_cameraStreaming ? QStringLiteral("%1 路播放中").arg(m_runningCameraIds.size()) : QStringLiteral("已停止")); + refreshCameraDepthControls(); } QWidget *MainWindow::createCameraPage() @@ -1525,6 +1555,7 @@ QWidget *MainWindow::createCameraPage() m_snapshotButton = ui.snapshotButton; m_depthSnapshotButton = new QPushButton(QStringLiteral("获取深度图像"), ui.controlsPanel); m_depthSnapshotButton->setObjectName(QStringLiteral("secondaryButton")); + m_depthSnapshotButton->hide(); const int snapshotIndex = ui.controlsLayout->indexOf(m_snapshotButton); ui.controlsLayout->insertWidget(snapshotIndex + 1, m_depthSnapshotButton); m_cameraStreamButton = ui.cameraStreamButton; @@ -1553,7 +1584,8 @@ QWidget *MainWindow::createCameraPage() }); connect(m_depthSnapshotButton, &QPushButton::clicked, this, [this]() { const QStringList cameraIds = configuredCameraIds(); - if (!cameraIds.isEmpty()) + if (!cameraIds.isEmpty() && CameraCapabilities::depthImage( + m_cameraCapabilitiesById.value(cameraIds.first()))) m_client->requestDepthSnapshot(cameraIds.first()); }); connect(m_cameraCodecCombo, QOverload::of(&QComboBox::currentIndexChanged), @@ -1568,6 +1600,7 @@ QWidget *MainWindow::createCameraPage() }); connect(m_cameraDeviceCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int) { + refreshCameraDepthControls(); if (!m_cameraStreaming) { rebuildCameraPreviewGrid(configuredCameraIds()); saveSettings(); @@ -2053,7 +2086,7 @@ QWidget *MainWindow::createAgvPage() return; QFile file(path); if (!file.open(QIODevice::ReadOnly)) { - QMessageBox::warning(this, QStringLiteral("上传地图"), + AppMessageBox::warning(this, QStringLiteral("上传地图"), QStringLiteral("无法读取地图文件:%1").arg(path)); return; } @@ -2071,7 +2104,7 @@ QWidget *MainWindow::createAgvPage() connect(ui.downloadMapButton, &QPushButton::clicked, this, [this]() { const QString mapName = m_agvMapCombo->currentText().trimmed(); if (mapName.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("下载地图"), + AppMessageBox::warning(this, QStringLiteral("下载地图"), QStringLiteral("请先选择或输入地图名称")); return; } @@ -2123,7 +2156,7 @@ QWidget *MainWindow::createAgvPage() const QStringList pair = lines.at(row).split(QLatin1Char(','), QString::KeepEmptyParts); if (pair.size() != 2 || pair.at(0).trimmed().isEmpty() || pair.at(1).trimmed().isEmpty()) { - QMessageBox::warning( + AppMessageBox::warning( this, QStringLiteral("路径格式错误"), QStringLiteral("第 %1 行格式无效,请使用“起点站点,终点站点”。").arg(row + 1)); return; @@ -2134,7 +2167,7 @@ QWidget *MainWindow::createAgvPage() path.append(segment); } if (path.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("路径为空"), + AppMessageBox::warning(this, QStringLiteral("路径为空"), QStringLiteral("请至少输入一个路径段。")); return; } @@ -2257,7 +2290,7 @@ QWidget *MainWindow::createAudioPage(bool speaker) channelsCombo = ui.channelsCombo, stateLabel = ui.streamStateLabel]() { const QString deviceId = deviceEdit->text().trimmed(); if (deviceId.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("流式发送"), + AppMessageBox::warning(this, QStringLiteral("流式发送"), QStringLiteral("请填写扬声器设备 ID。")); return; } @@ -2305,7 +2338,7 @@ QWidget *MainWindow::createAudioPage(bool speaker) stateLabel = ui.streamStateLabel]() { const QString deviceId = deviceEdit->text().trimmed(); if (deviceId.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("拉流播放"), + AppMessageBox::warning(this, QStringLiteral("拉流播放"), QStringLiteral("请填写麦克风设备 ID。")); return; } @@ -2547,7 +2580,7 @@ QWidget *MainWindow::createDexHandPage() connect(sendButton, &QPushButton::clicked, this, [this, command, commandSpins]() { const QString deviceId = m_dexHandDeviceCombo->currentData().toString(); if (deviceId.isEmpty()) { - QMessageBox::warning(this, QStringLiteral("灵巧手控制"), + AppMessageBox::warning(this, QStringLiteral("灵巧手控制"), QStringLiteral("服务端未返回可用灵巧手设备")); return; } diff --git a/src/robotclient.cpp b/src/robotclient.cpp index a4c47fc..ea66a1c 100644 --- a/src/robotclient.cpp +++ b/src/robotclient.cpp @@ -290,6 +290,16 @@ public: public: void connectToServer(const QString &host, int port, bool demoMode) { + // A failed gRPC channel can leave stubs and stream threads alive even + // though the server has disappeared. Always rebuild from a clean + // transport before accepting a new connection request. + if (m_connected +#ifdef CMVR_WITH_GRPC + || m_channel +#endif + ) { + disconnectFromServer(); + } m_host = host.trimmed(); m_port = port; m_demoMode = demoMode; @@ -329,6 +339,7 @@ public: m_microphone = cmvr::api::MicPhoneService::NewStub(m_channel); m_generic = std::make_unique(m_channel); m_connected = true; + m_channelFailureTicks = 0; m_pollTimer->start(); emit connectionChanged(true, static_cast(elapsed.elapsed()), QString::fromStdString(endpoint)); emit logMessage(QStringLiteral("INFO"), QStringLiteral("gRPC 通道已连接:%1").arg(QString::fromStdString(endpoint))); @@ -354,10 +365,12 @@ public: emit cameraRecordingStateChanged(false, QStringLiteral("连接已断开,录像状态未知")); } m_connected = false; + m_channelFailureTicks = 0; m_armPollingEnabled = false; #ifdef CMVR_WITH_GRPC m_arm.reset(); m_camera.reset(); + m_dexHand.reset(); m_system.reset(); m_agv.reset(); m_microphone.reset(); @@ -1461,7 +1474,9 @@ public: result={{"version",c.version()},{"driver",QString::fromStdString(c.driver())},{"model",QString::fromStdString(c.model())}, {"serial",QString::fromStdString(c.serial())},{"transport",QString::fromStdString(c.transport())}, {"rawImage",c.raw_image()},{"validIntrinsics",c.valid_intrinsics()},{"captureTimestamp",c.capture_timestamp()}, - {"metricAlignedDepth",c.metric_aligned_depth()},{"distortionModel",QString::fromStdString(c.distortion_model())}, + {"metricAlignedDepth",c.metric_aligned_depth()}, + {"depthImage",c.depth_image()},{"depthStream",c.depth_stream()}, + {"distortionModel",QString::fromStdString(c.distortion_model())}, {"sessionGeneration",qulonglong(c.session_generation())},{"unavailableReason",QString::fromStdString(c.unavailable_reason())}, {"width",response.state().width()},{"height",response.state().height()}, {"intrinsicsSignature",QString::fromStdString(c.intrinsics_signature())}}; @@ -3180,6 +3195,23 @@ private: return; } #ifdef CMVR_WITH_GRPC + if (m_channel) { + const grpc_connectivity_state state = m_channel->GetState(true); + if (state == GRPC_CHANNEL_READY || state == GRPC_CHANNEL_IDLE) { + m_channelFailureTicks = 0; + } else if (state == GRPC_CHANNEL_TRANSIENT_FAILURE + || state == GRPC_CHANNEL_SHUTDOWN) { + ++m_channelFailureTicks; + // Avoid treating a single Wi-Fi jitter as a disconnect. At + // 100 ms polling this reports a persistent failure in about + // one second and releases every old stream/context. + if (m_channelFailureTicks >= 10) { + handleUnexpectedDisconnect(QStringLiteral( + "gRPC 服务连接已中断,请重新连接")); + return; + } + } + } pollGrpc(); #endif } @@ -3242,6 +3274,37 @@ private: } #ifdef CMVR_WITH_GRPC + void handleUnexpectedDisconnect(const QString &detail) + { + if (!m_connected) + return; + m_pollTimer->stop(); + stopArmMotionInternal(); + stopCameraStreamInternal(); + stopSpeakerStreamInternal(true); + stopMicrophoneStreamInternal(); + stopDexHandTactileStreamInternal(); + stopAgvMapStreamInternal(); + if (m_cameraRecording) { + m_cameraRecording = false; + emit cameraRecordingStateChanged(false, + QStringLiteral("连接中断,录像状态未知")); + } + m_connected = false; + m_armPollingEnabled = false; + m_channelFailureTicks = 0; + m_arm.reset(); + m_camera.reset(); + m_dexHand.reset(); + m_system.reset(); + m_agv.reset(); + m_microphone.reset(); + m_generic.reset(); + m_channel.reset(); + emit connectionChanged(false, 0, detail); + emit logMessage(QStringLiteral("ERROR"), detail); + } + static void fillHeader(cmvr::api::CommandHeader::Request *header, const QString &deviceId, int validForMs = 5000) { @@ -4062,6 +4125,7 @@ private: int m_port = 50052; int m_tick = 0; int m_consecutivePollErrors = 0; + int m_channelFailureTicks = 0; bool m_connected = false; bool m_configConnected = false; bool m_demoMode = true; diff --git a/src/taskorchestrationwidget.cpp b/src/taskorchestrationwidget.cpp new file mode 100644 index 0000000..67276c4 --- /dev/null +++ b/src/taskorchestrationwidget.cpp @@ -0,0 +1,1374 @@ +#include "taskorchestrationwidget.h" +#include "audiostreammanager.h" +#include "applicationstyle.h" +#include "cameracapabilities.h" +#include "uiicons.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +enum Roles { KindRole = Qt::UserRole, DeviceTypeRole, DeviceIdRole, ActionRole, + ParametersRole, WaitRole, WaitUnitRole, LoopCountRole, RunStateRole }; + +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; +}; + +class TaskFlowCard final : public QGraphicsItem +{ +public: + TaskFlowCard(QTreeWidgetItem *source, const QString &title, const QString &subtitle, + bool loop, std::function moved, + std::function edited, + std::function toggled) + : m_source(source), m_title(title), m_subtitle(subtitle), m_loop(loop), + m_moved(std::move(moved)), m_edited(std::move(edited)), m_toggled(std::move(toggled)) + { + setFlags(ItemIsMovable | ItemIsSelectable); + setAcceptHoverEvents(true); + setCursor(Qt::OpenHandCursor); + setZValue(2); + } + + QRectF boundingRect() const override { return QRectF(0, 0, kTaskCardWidth, kTaskCardHeight); } + QTreeWidgetItem *source() const { return m_source; } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override + { + painter->setRenderHint(QPainter::Antialiasing); + const QString state = m_source->data(0, RunStateRole).toString(); + QColor stateColor = state == QStringLiteral("running") ? QColor("#1b6ef3") + : state == QStringLiteral("success") ? QColor("#20a36a") + : state == QStringLiteral("failed") ? QColor("#d44343") : QColor("#cbd6e2"); + painter->setPen(QPen(isSelected() ? QColor("#1b6ef3") : stateColor, + isSelected() || !state.isEmpty() ? 2.0 : 1.4)); + painter->setBrush(state == QStringLiteral("running") ? QColor("#eef5ff") + : state == QStringLiteral("success") ? QColor("#effaf5") + : state == QStringLiteral("failed") ? QColor("#fff2f2") + : m_loop ? QColor("#f4efff") : QColor("#ffffff")); + painter->drawRoundedRect(boundingRect().adjusted(1, 1, -1, -1), 10, 10); + QFont titleFont = painter->font(); titleFont.setBold(true); + painter->setFont(titleFont); painter->setPen(QColor("#25313d")); + painter->drawText(QRectF(14, 9, kTaskCardWidth - (m_loop ? 52 : 28), 27), + Qt::AlignLeft | Qt::AlignVCenter, m_title); + painter->setFont(QFont()); painter->setPen(QColor("#687684")); + painter->drawText(QRectF(14, 38, kTaskCardWidth - 28, 45), + Qt::AlignLeft | Qt::AlignVCenter | Qt::TextWordWrap, m_subtitle); + if (m_loop) { + painter->setPen(QPen(QColor("#b8c7d8"), 1.2)); painter->setBrush(Qt::white); + painter->drawRoundedRect(toggleRect(), 5, 5); + painter->setPen(QPen(QColor("#286fc2"), 1.8)); + const QPointF c = toggleRect().center(); + if (m_source->isExpanded()) + painter->drawPolyline(QPolygonF() << QPointF(c.x()-5,c.y()-3) << QPointF(c.x(),c.y()+3) << QPointF(c.x()+5,c.y()-3)); + else + painter->drawPolyline(QPolygonF() << QPointF(c.x()-3,c.y()-5) << QPointF(c.x()+3,c.y()) << QPointF(c.x()-3,c.y()+5)); + } + } + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event) override + { + if (m_loop && toggleRect().contains(event->pos())) { + if (m_toggled) m_toggled(m_source); + event->accept(); return; + } + setCursor(Qt::ClosedHandCursor); + QGraphicsItem::mousePressEvent(event); + } + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override + { + setCursor(Qt::OpenHandCursor); + QGraphicsItem::mouseReleaseEvent(event); + if (m_moved) m_moved(m_source, pos()); + } + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override + { if (m_edited) m_edited(m_source); event->accept(); } + +private: + QRectF toggleRect() const { return QRectF(kTaskCardWidth - 35, 10, 22, 22); } + QTreeWidgetItem *m_source = nullptr; + QString m_title, m_subtitle; + bool m_loop = false; + std::function m_moved; + std::function m_edited; + std::function m_toggled; +}; + +class TaskNodeDialog final : public QDialog +{ +public: + TaskNodeDialog(const QString &title, QWidget *parent) + : QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint) + { + setObjectName(QStringLiteral("jointFlowChildDialog")); + setAttribute(Qt::WA_TranslucentBackground); + QVBoxLayout *outer = new QVBoxLayout(this); + outer->setContentsMargins(12, 12, 12, 12); + outer->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(); + 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); + outer->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 *mouse = static_cast(event); + if (mouse->button() == Qt::LeftButton) { + m_dragging = true; + m_dragOffset = mouse->globalPos() - frameGeometry().topLeft(); + return true; + } + } else if (event->type() == QEvent::MouseMove && m_dragging) { + move(static_cast(event)->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; +}; + +void showTaskNotice(QWidget *parent, const QString &title, const QString &message) +{ + TaskNodeDialog dialog(title, parent); + dialog.setWindowModality(Qt::WindowModal); + dialog.setMinimumWidth(480); + + QLabel *messageLabel = new QLabel(message, &dialog); + messageLabel->setObjectName(QStringLiteral("jointFlowDialogMessage")); + messageLabel->setWordWrap(true); + messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + dialog.contentLayout()->addWidget(messageLabel); + + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok, &dialog); + buttons->button(QDialogButtonBox::Ok)->setText(QStringLiteral("知道了")); + buttons->button(QDialogButtonBox::Ok)->setObjectName(QStringLiteral("primaryButton")); + QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + dialog.contentLayout()->addWidget(buttons); + buttons->button(QDialogButtonBox::Ok)->setFocus(); + dialog.exec(); +} + +QStringList actionsForType(const QString &type) +{ + 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")}; +} + +QString deviceTypeName(int type) +{ + switch (type) { + case 6: return QStringLiteral("机械臂"); + case 2: return QStringLiteral("相机"); + case 0: return QStringLiteral("AGV"); + case 3: return QStringLiteral("灵巧手"); + case 7: return QStringLiteral("扬声器"); + case 5: return QStringLiteral("麦克风"); + default: return QStringLiteral("通用RPC"); + } +} + +bool parseNumberList(const QString &text, QJsonArray &values) +{ + values = QJsonArray(); + const QStringList parts = text.split(',', QString::SkipEmptyParts); + if (parts.isEmpty()) return false; + for (const QString &part : parts) { + bool ok = false; + const double value = part.trimmed().toDouble(&ok); + if (!ok) return false; + values.append(value); + } + return true; +} + +void configureComboPopup(QComboBox *combo) +{ + ApplicationStyle::styleComboBox(combo); +} + +QString normalizedWaitUnit(const QString &unit) +{ + return unit == QStringLiteral("s") ? QStringLiteral("s") : QStringLiteral("ms"); +} + +QString waitDisplayText(int waitMs, const QString &unit) +{ + if (normalizedWaitUnit(unit) == QStringLiteral("s")) { + QString value = QString::number(waitMs / 1000.0, 'f', 3); + while (value.contains(QLatin1Char('.')) && value.endsWith(QLatin1Char('0'))) + value.chop(1); + if (value.endsWith(QLatin1Char('.'))) value.chop(1); + return QStringLiteral("%1 s").arg(value); + } + return QStringLiteral("%1 ms").arg(waitMs); +} + +bool editNameDialog(QWidget *parent, const QString &title, const QString &label, + QString &value) +{ + TaskNodeDialog dialog(title, parent); + dialog.setWindowModality(Qt::WindowModal); + dialog.setMinimumWidth(440); + QFormLayout *form = new QFormLayout; + QLineEdit *nameEdit = new QLineEdit(value, &dialog); + nameEdit->selectAll(); + form->addRow(label, nameEdit); + 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->setFocus(); + if (dialog.exec() != QDialog::Accepted) return false; + const QString result = nameEdit->text().trimmed(); + if (result.isEmpty()) { + showTaskNotice(parent, title, QStringLiteral("名称不能为空。")); + return false; + } + value = result; + 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); + dialog.setMinimumWidth(560); + QVBoxLayout *layout = dialog.contentLayout(); + QFormLayout form; + form.setHorizontalSpacing(16); + form.setVerticalSpacing(12); + form.setLabelAlignment(Qt::AlignLeft | Qt::AlignVCenter); + form.setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); + QLineEdit nameEdit(name, &dialog); + QComboBox deviceCombo(&dialog); + 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); + 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); + QLineEdit positionsEdit(&moveJPage); + positionsEdit.setPlaceholderText(QStringLiteral("例如:0, 0, 0, 0, 0, 0, 0")); + 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(" rad/s")); + accelerationSpin.setSuffix(QStringLiteral(" rad/s²")); + moveJForm.addRow(QStringLiteral("目标关节位置"), &positionsEdit); + 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); + QLineEdit stationEdit(&agvPage); + 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); + QLineEdit dexValuesEdit(&dexPage); + dexValuesEdit.setPlaceholderText(QStringLiteral("例如:0, 0, 0, 0, 0, 0")); + dexForm.addRow(QStringLiteral("六指令值"), &dexValuesEdit); + + 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); + parameterPages.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + + const QJsonArray existingPositions = parameters.value(QStringLiteral("positions")).toArray(); + QStringList positionTexts; + for (const QJsonValue &value : existingPositions) positionTexts << QString::number(value.toDouble(), 'f', 6); + positionsEdit.setText(positionTexts.join(QStringLiteral(", "))); + velocitySpin.setValue(parameters.value(QStringLiteral("velocity")).toDouble(0.1)); + accelerationSpin.setValue(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); + stationEdit.setText(parameters.value(QStringLiteral("stationId")).toString()); + maxSpeedSpin.setValue(parameters.value(QStringLiteral("maxSpeed")).toDouble(0.5)); + QStringList dexTexts; + for (const QJsonValue &value : parameters.value(QStringLiteral("values")).toArray()) + dexTexts << QString::number(value.toDouble(), 'f', 3); + dexValuesEdit.setText(dexTexts.join(QStringLiteral(", "))); + 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); + form.addRow(QStringLiteral("节点名称"), &nameEdit); + form.addRow(QStringLiteral("选择设备"), &deviceCombo); + form.addRow(QStringLiteral("设备类型"), &typeValue); + form.addRow(QStringLiteral("执行操作"), &actionCombo); + form.addRow(¶meterLabel, ¶meterPages); + form.addRow(QStringLiteral("完成后等待"), &waitEditor); + layout->addLayout(&form); + + auto refreshParameterPage = [&]() { + const QString selectedType = typeValue.text(); + const QString selectedAction = actionCombo.currentText(); + 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; + } + parameterPages.setCurrentIndex(page); + const bool hasParameters = page != 0; + parameterLabel.setVisible(hasParameters); + parameterPages.setVisible(hasParameters); + if (hasParameters) + parameterPages.setFixedHeight(parameterPages.currentWidget()->sizeHint().height()); + else + parameterPages.setFixedHeight(0); + dialog.adjustSize(); + }; + auto refreshActions = [&]() { + const QVariantMap device = deviceCombo.currentData().toMap(); + const QString selectedType = deviceTypeName(device.value(QStringLiteral("type")).toInt()); + typeValue.setText(selectedType); + const QString previous = actionCombo.currentText().isEmpty() ? action : actionCombo.currentText(); + actionCombo.clear(); + QStringList actions = actionsForType(selectedType); + if (selectedType == QStringLiteral("相机") + && !CameraCapabilities::depthImage(cameraCapabilities.value( + device.value(QStringLiteral("deviceId")).toString()))) + actions.removeAll(QStringLiteral("深度抓图")); + actionCombo.addItems(actions); + if (actionCombo.findText(previous) >= 0) actionCombo.setCurrentText(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(); }); + refreshActions(); + QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog); + buttons.button(QDialogButtonBox::Ok)->setText(QStringLiteral("确定")); + buttons.button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消")); + QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + 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); + if (dialog.exec() != QDialog::Accepted) return false; + 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.currentText(); + parameters = QJsonObject(); + if (parameterPages.currentIndex() == 1) { + QJsonArray values; + if (!parseNumberList(positionsEdit.text(), values)) { + showTaskNotice(parent, QStringLiteral("参数错误"), + QStringLiteral("请填写有效的关节位置,数值之间使用逗号分隔。")); + return false; + } + parameters.insert(QStringLiteral("positions"), values); + parameters.insert(QStringLiteral("velocity"), velocitySpin.value()); + parameters.insert(QStringLiteral("acceleration"), 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.text().trimmed().isEmpty()) { + showTaskNotice(parent, QStringLiteral("参数错误"), + QStringLiteral("站点 ID 不能为空。")); + return false; + } + parameters.insert(QStringLiteral("stationId"), stationEdit.text().trimmed()); + parameters.insert(QStringLiteral("maxSpeed"), maxSpeedSpin.value()); + } else if (parameterPages.currentIndex() == 4) { + QJsonArray values; + if (!parseNumberList(dexValuesEdit.text(), values)) { + showTaskNotice(parent, QStringLiteral("参数错误"), + QStringLiteral("请填写有效的指令值,数值之间使用逗号分隔。")); + return false; + } + parameters.insert(QStringLiteral("values"), values); + } 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()); + } + waitUnit = normalizedWaitUnit(waitUnitCombo.currentData().toString()); + waitMs = qRound(waitSpin.value() * (waitUnit == QStringLiteral("s") ? 1000.0 : 1.0)); + return true; +} +} + +TaskOrchestrationWidget::TaskOrchestrationWidget(QWidget *parent) : QWidget(parent) +{ + QVBoxLayout *root = new QVBoxLayout(this); + root->setContentsMargins(24, 20, 24, 20); + root->setSpacing(12); + QFrame *panel = new QFrame(this); + panel->setObjectName(QStringLiteral("panel")); + QVBoxLayout *layout = new QVBoxLayout(panel); + layout->setContentsMargins(18, 16, 18, 16); + layout->setSpacing(10); + QHBoxLayout *groups = new QHBoxLayout; + QLabel *title = new QLabel(QStringLiteral("任务方案"), panel); + title->setObjectName(QStringLiteral("sectionTitle")); + m_groupCombo = new QComboBox(panel); + m_groupCombo->setMinimumWidth(240); + QPushButton *newGroup = new QPushButton(QStringLiteral("新建方案"), panel); + QPushButton *renameGroup = new QPushButton(QStringLiteral("重命名"), panel); + newGroup->setObjectName(QStringLiteral("primaryButton")); + renameGroup->setObjectName(QStringLiteral("secondaryButton")); + groups->addWidget(title); groups->addStretch(); groups->addWidget(m_groupCombo); + groups->addWidget(newGroup); groups->addWidget(renameGroup); + layout->addLayout(groups); + QLabel *hint = new QLabel(QStringLiteral("任务节点可来自不同设备;循环节点可嵌套任务。拖动节点可调整顺序或放入循环。"), panel); + hint->setObjectName(QStringLiteral("mutedLabel")); + layout->addWidget(hint); + 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(); + layout->addLayout(toolbar); + m_tree = new QTreeWidget(panel); + m_tree->setColumnCount(6); + m_tree->setHeaderLabels({QStringLiteral("节点名称"), QStringLiteral("类型"), + QStringLiteral("设备"), QStringLiteral("Device ID"), QStringLiteral("操作"), + QStringLiteral("等待")}); + m_tree->setSelectionMode(QAbstractItemView::SingleSelection); + m_tree->setDragDropMode(QAbstractItemView::InternalMove); + m_tree->setDefaultDropAction(Qt::MoveAction); + m_tree->setAlternatingRowColors(true); + m_tree->header()->setSectionResizeMode(0, QHeaderView::Stretch); + for (int i = 1; i < 6; ++i) m_tree->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); + m_tree->hide(); + m_flowScene = new QGraphicsScene(this); + m_flowScene->setBackgroundBrush(QColor(QStringLiteral("#f4f7fa"))); + m_flowView = new TaskFlowView(m_flowScene, panel); + m_flowView->setObjectName(QStringLiteral("jointFlowCanvas")); + m_flowView->setRenderHint(QPainter::Antialiasing); + m_flowView->setDragMode(QGraphicsView::RubberBandDrag); + layout->addWidget(m_flowView, 1); + 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->addItem(QStringLiteral("尚未执行任务")); + layout->addWidget(m_history); + QHBoxLayout *actions = new QHBoxLayout; + m_status = new QLabel(QStringLiteral("未运行"), panel); + m_status->setObjectName(QStringLiteral("mutedLabel")); + m_runButton = new QPushButton(QStringLiteral("执行任务编排"), panel); + m_stopButton = new QPushButton(QStringLiteral("停止执行"), panel); + m_runButton->setObjectName(QStringLiteral("primaryButton")); + m_stopButton->setObjectName(QStringLiteral("dangerButton")); + m_stopButton->setEnabled(false); + actions->addWidget(m_status); actions->addStretch(); actions->addWidget(m_runButton); actions->addWidget(m_stopButton); + layout->addLayout(actions); + root->addWidget(panel, 1); + m_runTimer = new QTimer(this); m_runTimer->setSingleShot(true); + + connect(newGroup, &QPushButton::clicked, this, [this]() { + QString name = QStringLiteral("新任务方案"); + if (!editNameDialog(this, QStringLiteral("新建任务方案"), QStringLiteral("方案名称"), name)) return; + storeCurrentGroup(); + QJsonObject group; group.insert(QStringLiteral("name"), name); group.insert(QStringLiteral("nodes"), QJsonArray()); + m_groups.append(group); m_groupCombo->addItem(name); m_groupCombo->setCurrentIndex(m_groups.size() - 1); + }); + connect(renameGroup, &QPushButton::clicked, this, [this]() { + if (m_activeGroup < 0) return; + QString name = m_groupCombo->currentText(); + if (!editNameDialog(this, QStringLiteral("重命名任务方案"), QStringLiteral("方案名称"), name)) return; + 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()); + } + }); + connect(m_runButton, &QPushButton::clicked, this, &TaskOrchestrationWidget::startRun); + connect(m_stopButton, &QPushButton::clicked, this, [this]() { stopRun(QStringLiteral("已手动停止")); }); + connect(m_runTimer, &QTimer::timeout, this, &TaskOrchestrationWidget::runNext); + load(); +} + +void TaskOrchestrationWidget::addTask(QTreeWidgetItem *) +{ + 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)); + QTreeWidgetItem *selected = m_tree->currentItem(); + QTreeWidgetItem *parent = selected && selected->data(0, KindRole).toString() == QStringLiteral("loop") ? selected : (selected ? selected->parent() : nullptr); + if (selected && selected->data(0, KindRole).toString() != QStringLiteral("loop")) { + const int index = parent ? parent->indexOfChild(selected) : m_tree->indexOfTopLevelItem(selected); + if (parent) parent->insertChild(index + 1, item); else m_tree->insertTopLevelItem(index + 1, item); + } else if (parent) parent->addChild(item); else m_tree->addTopLevelItem(item); + m_tree->setCurrentItem(item); save(); +} + +void TaskOrchestrationWidget::addLoop(QTreeWidgetItem *) +{ + 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)); + QTreeWidgetItem *selected = m_tree->currentItem(); + QTreeWidgetItem *parent = selected && selected->data(0, KindRole).toString() == QStringLiteral("loop") ? selected : (selected ? selected->parent() : nullptr); + if (selected && selected->data(0, KindRole).toString() != QStringLiteral("loop")) { + const int index = parent ? parent->indexOfChild(selected) : m_tree->indexOfTopLevelItem(selected); + if (parent) parent->insertChild(index + 1, item); else m_tree->insertTopLevelItem(index + 1, item); + } else if (parent) parent->addChild(item); else m_tree->addTopLevelItem(item); + item->setExpanded(true); m_tree->setCurrentItem(item); save(); +} + +void TaskOrchestrationWidget::editSelected() +{ + 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() +{ QTreeWidgetItem *item = m_tree->currentItem(); if (!item) return; delete item; save(); } + +void TaskOrchestrationWidget::moveSelected(int offset) +{ + 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; + if (parent) { parent->takeChild(index); parent->insertChild(target, item); } + else { m_tree->takeTopLevelItem(index); m_tree->insertTopLevelItem(target, item); } + m_tree->setCurrentItem(item); save(); +} + +void TaskOrchestrationWidget::appendRunSteps(QTreeWidgetItem *item, QList &steps) const +{ + if (item->data(0, KindRole).toString() == QStringLiteral("loop")) { + for (int repeat = 0; repeat < item->data(0, LoopCountRole).toInt(); ++repeat) + for (int i = 0; i < item->childCount(); ++i) appendRunSteps(item->child(i), steps); + return; + } + 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); +} + +void TaskOrchestrationWidget::startRun() +{ + m_runSteps.clear(); for (int i = 0; i < m_tree->topLevelItemCount(); ++i) appendRunSteps(m_tree->topLevelItem(i), m_runSteps); + if (m_runSteps.isEmpty()) { + showTaskNotice(this, QStringLiteral("任务编排"), + QStringLiteral("当前方案没有可执行任务。")); + return; + } + std::function clearState = [&](QTreeWidgetItem *item) { + item->setData(0, RunStateRole, QString()); + for (int i = 0; i < item->childCount(); ++i) clearState(item->child(i)); + }; + for (int i = 0; i < m_tree->topLevelItemCount(); ++i) clearState(m_tree->topLevelItem(i)); + m_history->clear(); + m_runIndex = 0; m_runButton->setEnabled(false); m_stopButton->setEnabled(true); runNext(); +} + +void TaskOrchestrationWidget::runNext() +{ + if (m_runIndex >= m_runSteps.size()) { stopRun(QStringLiteral("执行完成")); return; } + const RunStep step = m_runSteps.at(m_runIndex++); + if (step.source) step.source->setData(0, RunStateRole, QStringLiteral("running")); + m_history->addItem(QStringLiteral("▶ %1 · %2 · %3").arg(step.name, step.deviceId, step.action)); + m_history->scrollToBottom(); + rebuildFlowScene(); + m_status->setText(QStringLiteral("正在执行 %1(%2/%3)").arg(step.name).arg(m_runIndex).arg(m_runSteps.size())); + m_waitingForResult = true; + m_currentWaitMs = step.waitMs; + m_currentWaitUnit = step.waitUnit; + if (step.deviceType == QStringLiteral("相机") && step.action == QStringLiteral("深度抓图") + && !CameraCapabilities::depthImage(m_cameraCapabilities.value(step.deviceId))) { + completeCurrentTask(false, QStringLiteral("相机 %1 不支持深度图像或尚未获取深度能力") + .arg(step.deviceId)); + return; + } + emit taskRequested(step.deviceType, step.deviceId, step.action, step.parameters); +} + +void TaskOrchestrationWidget::completeCurrentTask(bool success, const QString &detail) +{ + if (!m_waitingForResult) + return; + m_waitingForResult = false; + RunStep *step = m_runIndex > 0 && m_runIndex <= m_runSteps.size() + ? &m_runSteps[m_runIndex - 1] : nullptr; + if (step && step->source) + step->source->setData(0, RunStateRole, success ? QStringLiteral("success") : QStringLiteral("failed")); + if (step) { + m_history->addItem(QStringLiteral("%1 %2 · %3") + .arg(success ? QStringLiteral("✓") : QStringLiteral("✕"), step->name, + detail.isEmpty() ? QStringLiteral("已完成") : detail)); + m_history->scrollToBottom(); + } + rebuildFlowScene(); + if (!success) { + stopRun(QStringLiteral("执行失败:%1").arg(detail)); + emit statusMessage(QStringLiteral("ERROR"), m_status->text()); + return; + } + m_status->setText(m_currentWaitMs > 0 + ? QStringLiteral("任务完成,等待 %1").arg(waitDisplayText(m_currentWaitMs, m_currentWaitUnit)) + : QStringLiteral("任务完成,继续执行")); + m_runTimer->start(m_currentWaitMs); +} + +void TaskOrchestrationWidget::completeCommandTask(const QString &command, bool success, + const QString &detail) +{ + if (!m_waitingForResult || m_runIndex <= 0 || m_runIndex > m_runSteps.size()) + return; + const RunStep &step = m_runSteps.at(m_runIndex - 1); + QString expected; + bool stateDriven = false; + if (step.deviceType == QStringLiteral("机械臂")) { + if (step.action == QStringLiteral("MoveJ")) expected = QStringLiteral("MoveJ"); + else if (step.action == QStringLiteral("使能")) expected = QStringLiteral("Torque On"); + else if (step.action == QStringLiteral("去使能")) expected = QStringLiteral("Torque Off"); + else if (step.action == QStringLiteral("停止")) expected = QStringLiteral("Stop Motion"); + else if (step.action == QStringLiteral("清除故障")) expected = QStringLiteral("Clear Fault"); + } else if (step.deviceType == QStringLiteral("相机")) { + if (step.action == QStringLiteral("RGB抓图")) expected = QStringLiteral("Snapshot"); + else if (step.action == QStringLiteral("深度抓图")) expected = QStringLiteral("Depth Snapshot"); + else if (step.action == QStringLiteral("开始预览") + || step.action == QStringLiteral("停止预览")) { + expected = QStringLiteral("Camera Stream"); + stateDriven = true; + } else if (step.action == QStringLiteral("开始录像")) { + expected = QStringLiteral("Camera Start Recording"); + stateDriven = true; + } else if (step.action == QStringLiteral("停止录像")) { + expected = QStringLiteral("Camera Stop Recording"); + stateDriven = true; + } + } else if (step.deviceType == QStringLiteral("AGV")) { + if (step.action == QStringLiteral("导航站点")) expected = QStringLiteral("AGV NavigateToStation"); + else if (step.action == QStringLiteral("停止")) expected = QStringLiteral("AGV stop"); + else if (step.action == QStringLiteral("暂停")) expected = QStringLiteral("AGV pause"); + else if (step.action == QStringLiteral("继续")) expected = QStringLiteral("AGV resume"); + } else if (step.deviceType == QStringLiteral("灵巧手")) { + const QHash commands = { + {QStringLiteral("设置角度"), QStringLiteral("DexHand angle")}, + {QStringLiteral("设置位置"), QStringLiteral("DexHand position")}, + {QStringLiteral("设置速度"), QStringLiteral("DexHand speed")}, + {QStringLiteral("设置力"), QStringLiteral("DexHand force")}}; + expected = commands.value(step.action); + } else if (step.deviceType == QStringLiteral("扬声器") + && (step.action == QStringLiteral("本机麦克风流播放") + || step.action == QStringLiteral("开始音频流") + || step.action == QStringLiteral("停止音频流"))) { + expected = QStringLiteral("Speaker Stream"); + stateDriven = true; + } else if (step.deviceType == QStringLiteral("麦克风") + && (step.action == QStringLiteral("开始音频流") + || step.action == QStringLiteral("停止音频流"))) { + expected = QStringLiteral("MicPhone Stream"); + stateDriven = true; + } + if (expected.isEmpty() || command != expected) + return; + // Streams and recording finish through their state callbacks. Their + // command callback is used only to surface an immediate interface error. + if (stateDriven && success) + return; + completeCurrentTask(success, detail); +} + +void TaskOrchestrationWidget::completeRpcTask(const QString &service, + const QString &method, + bool success, + const QString &detail) +{ + if (!m_waitingForResult || m_runIndex <= 0 || m_runIndex > m_runSteps.size()) + return; + const RunStep &step = m_runSteps.at(m_runIndex - 1); + QString expectedService; + QString expectedMethod; + if (step.deviceType == QStringLiteral("通用RPC")) { + expectedService = step.parameters.value(QStringLiteral("service")).toString(); + expectedMethod = step.parameters.value(QStringLiteral("method")).toString(); + } else if (step.deviceType == QStringLiteral("扬声器")) { + expectedService = QStringLiteral("cmvr.api.SpeakerService"); + if (step.action == QStringLiteral("播放服务端文件")) + expectedMethod = QStringLiteral("PlayAudio"); + else if (step.action == QStringLiteral("停止文件播放")) + expectedMethod = QStringLiteral("StopPlayback"); + } else if (step.deviceType == QStringLiteral("麦克风")) { + expectedService = QStringLiteral("cmvr.api.MicPhoneService"); + if (step.action == QStringLiteral("开始录音")) + expectedMethod = QStringLiteral("StartRecord"); + else if (step.action == QStringLiteral("停止录音")) + expectedMethod = QStringLiteral("StopRecord"); + } + if (service != expectedService || method != expectedMethod) + return; + completeCurrentTask(success, detail); +} + +void TaskOrchestrationWidget::failActiveTask(const QString &detail) +{ + if (m_runSteps.isEmpty()) + return; + const QString reason = detail.isEmpty() ? QStringLiteral("接口连接已中断") : detail; + if (m_waitingForResult) { + completeCurrentTask(false, reason); + return; + } + stopRun(QStringLiteral("执行失败:%1").arg(reason)); + emit statusMessage(QStringLiteral("ERROR"), m_status->text()); +} + +void TaskOrchestrationWidget::reportTaskFeedback(const QString &deviceId, + const QString &detail, bool success) +{ + if (!m_history || detail.isEmpty()) return; + m_history->addItem(QStringLiteral("%1 %2 · %3") + .arg(success ? QStringLiteral("●") : QStringLiteral("!"), deviceId, detail)); + m_history->scrollToBottom(); +} + +void TaskOrchestrationWidget::completeCameraStreamTask(const QString &deviceId, + bool running, + const QString &detail) +{ + if (!m_waitingForResult || m_runIndex <= 0 || m_runIndex > m_runSteps.size()) return; + const RunStep &step = m_runSteps.at(m_runIndex - 1); + if (step.deviceType != QStringLiteral("相机") || step.deviceId != deviceId) return; + if ((step.action == QStringLiteral("开始预览") && running) + || (step.action == QStringLiteral("停止预览") && !running)) { + completeCurrentTask(true, detail.isEmpty() + ? (running ? QStringLiteral("视频预览已启动") : QStringLiteral("视频预览已停止")) + : detail); + } else if (!detail.isEmpty() + && (step.action == QStringLiteral("开始预览") + || step.action == QStringLiteral("停止预览"))) { + completeCurrentTask(false, detail); + } +} + +void TaskOrchestrationWidget::completeActionTask(const QString &deviceType, + const QString &deviceId, + const QString &action, + bool success, + const QString &detail) +{ + if (!m_waitingForResult || m_runIndex <= 0 || m_runIndex > m_runSteps.size()) + return; + const RunStep &step = m_runSteps.at(m_runIndex - 1); + if (step.deviceType != deviceType || step.action != action) + return; + if (!deviceId.isEmpty() && step.deviceId != deviceId) + return; + completeCurrentTask(success, detail); +} + +void TaskOrchestrationWidget::stopRun(const QString &reason) +{ + m_runTimer->stop(); m_runSteps.clear(); m_runIndex = 0; m_waitingForResult = false; + m_runButton->setEnabled(true); m_stopButton->setEnabled(false); + m_status->setText(reason.isEmpty() ? QStringLiteral("未运行") : reason); +} + +QString TaskOrchestrationWidget::storagePath() const +{ return QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("data/task_orchestration.json")); } + +QJsonObject TaskOrchestrationWidget::itemToJson(QTreeWidgetItem *item) const +{ + QJsonObject object; const QString kind = item->data(0, KindRole).toString(); + object.insert(QStringLiteral("kind"), kind); object.insert(QStringLiteral("name"), item->text(0)); + if (kind == QStringLiteral("loop")) { + 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))); + object.insert(QStringLiteral("children"), children); + } else { + item->setFlags(item->flags() & ~Qt::ItemIsDropEnabled); + object.insert(QStringLiteral("deviceType"), item->data(0, DeviceTypeRole).toString()); + object.insert(QStringLiteral("deviceId"), item->data(0, DeviceIdRole).toString()); + object.insert(QStringLiteral("action"), item->data(0, ActionRole).toString()); + object.insert(QStringLiteral("parameters"), QJsonDocument::fromJson(item->data(0, ParametersRole).toString().toUtf8()).object()); + object.insert(QStringLiteral("waitMs"), item->data(0, WaitRole).toInt()); + object.insert(QStringLiteral("waitUnit"), normalizedWaitUnit(item->data(0, WaitUnitRole).toString())); + } return object; +} + +QTreeWidgetItem *TaskOrchestrationWidget::itemFromJson(const QJsonObject &object) const +{ + QTreeWidgetItem *item = new QTreeWidgetItem; const QString kind = object.value(QStringLiteral("kind")).toString(QStringLiteral("task")); + item->setData(0, KindRole, kind); item->setText(0, object.value(QStringLiteral("name")).toString()); + 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)); + for (const QJsonValue &child : object.value(QStringLiteral("children")).toArray()) item->addChild(itemFromJson(child.toObject())); + item->setExpanded(true); + } else { + const QString type = object.value(QStringLiteral("deviceType")).toString(); const QString id = object.value(QStringLiteral("deviceId")).toString(); + const QString action = object.value(QStringLiteral("action")).toString(); const int wait = object.value(QStringLiteral("waitMs")).toInt(); + const QString waitUnit = normalizedWaitUnit(object.value(QStringLiteral("waitUnit")).toString()); + item->setData(0, DeviceTypeRole, type); item->setData(0, DeviceIdRole, id); item->setData(0, ActionRole, action); + item->setData(0, ParametersRole, QString::fromUtf8(QJsonDocument(object.value(QStringLiteral("parameters")).toObject()).toJson(QJsonDocument::Compact))); + item->setData(0, WaitRole, wait); item->setData(0, WaitUnitRole, waitUnit); + item->setText(1, type); item->setText(2, type); item->setText(3, id); + item->setText(4, action); item->setText(5, waitDisplayText(wait, waitUnit)); + } return item; +} + +void TaskOrchestrationWidget::rebuildFlowScene() +{ + if (!m_flowScene) return; + QTreeWidgetItem *selected = m_tree->currentItem(); + m_flowScene->clear(); + QHash positions; + QHash widths; + std::function measure = [&](QTreeWidgetItem *item) -> qreal { + if (!item || item->childCount() == 0 || !item->isExpanded()) { + widths.insert(item, kTaskCardWidth); + return kTaskCardWidth; + } + qreal total = 0; + for (int i = 0; i < item->childCount(); ++i) + total += measure(item->child(i)) + (i ? 28.0 : 0.0); + const qreal width = qMax(kTaskCardWidth, total); + widths.insert(item, width); + return width; + }; + std::function place = + [&](QTreeWidgetItem *item, qreal left, qreal y) { + const qreal width = widths.value(item, kTaskCardWidth); + positions.insert(item, QPointF(left + (width - kTaskCardWidth) / 2.0, y)); + if (item->childCount() == 0 || !item->isExpanded()) return; + qreal childLeft = left; + for (int i = 0; i < item->childCount(); ++i) { + QTreeWidgetItem *child = item->child(i); + place(child, childLeft, y + 126.0); + childLeft += widths.value(child, kTaskCardWidth) + 28.0; + } + }; + qreal left = 36.0; + for (int i = 0; i < m_tree->topLevelItemCount(); ++i) { + QTreeWidgetItem *item = m_tree->topLevelItem(i); + const qreal width = measure(item); + place(item, left, 38.0); + left += width + 42.0; + } + for (auto it = positions.constBegin(); it != positions.constEnd(); ++it) { + QTreeWidgetItem *item = it.key(); + if (!item->parent()) continue; + const QPointF parent = positions.value(item->parent()); + QPainterPath path; + path.moveTo(parent.x() + kTaskCardWidth / 2.0, parent.y() + kTaskCardHeight); + path.cubicTo(parent.x() + kTaskCardWidth / 2.0, parent.y() + 100.0, + it.value().x() + kTaskCardWidth / 2.0, it.value().y() - 26.0, + it.value().x() + kTaskCardWidth / 2.0, it.value().y()); + QGraphicsPathItem *edge = m_flowScene->addPath(path, QPen(QColor("#9eb1c5"), 1.8)); + edge->setZValue(0); + } + for (auto it = positions.constBegin(); it != positions.constEnd(); ++it) { + QTreeWidgetItem *item = it.key(); + const bool loop = item->data(0, KindRole).toString() == QStringLiteral("loop"); + const QString subtitle = loop + ? QStringLiteral("循环 × %1").arg(item->data(0, LoopCountRole).toInt()) + : QStringLiteral("%1 · %2\n等待 %3") + .arg(item->data(0, DeviceIdRole).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](QTreeWidgetItem *source, const QPointF &position) { + QTimer::singleShot(0, this, [this, source, position]() { moveFlowItem(source, position); }); + }, + [this](QTreeWidgetItem *source) { + QTimer::singleShot(0, this, [this, source]() { m_tree->setCurrentItem(source); editSelected(); }); + }, + [this](QTreeWidgetItem *source) { + QTimer::singleShot(0, this, [this, source]() { + source->setExpanded(!source->isExpanded()); rebuildFlowScene(); + }); + }); + card->setPos(it.value()); + m_flowScene->addItem(card); + if (item == selected) card->setSelected(true); + } + const QRectF bounds = m_flowScene->itemsBoundingRect().adjusted(-30, -30, 30, 50); + m_flowScene->setSceneRect(bounds.isValid() ? bounds : QRectF(0, 0, 800, 360)); +} + +void TaskOrchestrationWidget::moveFlowItem(QTreeWidgetItem *item, const QPointF &position) +{ + if (!item) return; + QTreeWidgetItem *parent = item->parent(); + QList> siblings; + for (QGraphicsItem *graphicsItem : m_flowScene->items()) { + TaskFlowCard *card = dynamic_cast(graphicsItem); + if (card && card->source() != item && card->source()->parent() == parent) + siblings.append(qMakePair(card->scenePos().x(), card->source())); + } + std::sort(siblings.begin(), siblings.end(), [](const QPair &a, + const QPair &b) { + return a.first < b.first; + }); + int target = 0; + const qreal center = position.x() + kTaskCardWidth / 2.0; + while (target < siblings.size() && center > siblings.at(target).first + kTaskCardWidth / 2.0) ++target; + if (parent) { + const int old = parent->indexOfChild(item); + parent->takeChild(old); + parent->insertChild(qBound(0, target, parent->childCount()), item); + } else { + const int old = m_tree->indexOfTopLevelItem(item); + m_tree->takeTopLevelItem(old); + m_tree->insertTopLevelItem(qBound(0, target, m_tree->topLevelItemCount()), item); + } + m_tree->setCurrentItem(item); + save(); +} + +void TaskOrchestrationWidget::storeCurrentGroup() +{ + if (m_activeGroup < 0 || m_activeGroup >= m_groups.size()) + return; + QJsonArray nodes; + for (int i = 0; i < m_tree->topLevelItemCount(); ++i) nodes.append(itemToJson(m_tree->topLevelItem(i))); + m_groups[m_activeGroup].insert(QStringLiteral("nodes"), nodes); +} + +void TaskOrchestrationWidget::setAvailableDevices(const QVariantList &devices) +{ + m_availableDevices = devices; +} + +void TaskOrchestrationWidget::setCameraCapabilities(const QString &deviceId, + const QVariantMap &capabilities) +{ + if (deviceId.isEmpty()) { + if (m_cameraCapabilities.isEmpty()) return; + m_cameraCapabilities.clear(); + } else { + if (m_cameraCapabilities.contains(deviceId) + && m_cameraCapabilities.value(deviceId) == capabilities) return; + m_cameraCapabilities.insert(deviceId, capabilities); + } + emit cameraCapabilitiesChanged(); +} + +void TaskOrchestrationWidget::activateGroup(int index) +{ + if (m_switchingGroup || index < 0 || index >= m_groups.size()) return; + storeCurrentGroup(); m_activeGroup = index; m_tree->clear(); + for (const QJsonValue &node : m_groups.at(index).value(QStringLiteral("nodes")).toArray()) m_tree->addTopLevelItem(itemFromJson(node.toObject())); + save(); +} + +void TaskOrchestrationWidget::load() +{ + QFile file(storagePath()); if (file.open(QIODevice::ReadOnly)) { + const QJsonArray groups = QJsonDocument::fromJson(file.readAll()).object().value(QStringLiteral("groups")).toArray(); + for (const QJsonValue &group : groups) m_groups.append(group.toObject()); + } + if (m_groups.isEmpty()) { QJsonObject group; 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())); + rebuildFlowScene(); +} + +void TaskOrchestrationWidget::save() +{ + storeCurrentGroup(); QJsonArray groups; for (const QJsonObject &group : m_groups) groups.append(group); + QJsonObject root; root.insert(QStringLiteral("version"), 1); root.insert(QStringLiteral("groups"), groups); + QDir().mkpath(QFileInfo(storagePath()).absolutePath()); QSaveFile file(storagePath()); + if (!file.open(QIODevice::WriteOnly) || file.write(QJsonDocument(root).toJson(QJsonDocument::Indented)) < 0 || !file.commit()) + emit statusMessage(QStringLiteral("ERROR"), QStringLiteral("任务编排 JSON 保存失败:%1").arg(storagePath())); + rebuildFlowScene(); +} diff --git a/src/taskorchestrationwidget.h b/src/taskorchestrationwidget.h new file mode 100644 index 0000000..b26d1c2 --- /dev/null +++ b/src/taskorchestrationwidget.h @@ -0,0 +1,96 @@ +#pragma once + +#include +#include +#include +#include + +class QComboBox; +class QLabel; +class QPushButton; +class QTimer; +class QTreeWidget; +class QTreeWidgetItem; +class QGraphicsScene; +class QGraphicsView; +class QPointF; +class QListWidget; + +class TaskOrchestrationWidget final : public QWidget +{ + Q_OBJECT +public: + explicit TaskOrchestrationWidget(QWidget *parent = nullptr); + void setAvailableDevices(const QVariantList &devices); + void setCameraCapabilities(const QString &deviceId, const QVariantMap &capabilities); + void completeCurrentTask(bool success, const QString &detail); + void completeCommandTask(const QString &command, bool success, + const QString &detail); + void completeRpcTask(const QString &service, const QString &method, + bool success, const QString &detail); + void failActiveTask(const QString &detail); + void reportTaskFeedback(const QString &deviceId, const QString &detail, + bool success = true); + void completeCameraStreamTask(const QString &deviceId, bool running, + const QString &detail); + void completeActionTask(const QString &deviceType, const QString &deviceId, + const QString &action, bool success, + const QString &detail); + +signals: + void cameraCapabilitiesChanged(); + void taskRequested(const QString &deviceType, const QString &deviceId, + const QString &action, const QJsonObject ¶meters); + void statusMessage(const QString &level, const QString &message); + +private: + struct RunStep { + QString name; + QString deviceType; + QString deviceId; + QString action; + QJsonObject parameters; + int waitMs = 0; + QString waitUnit = QStringLiteral("ms"); + QTreeWidgetItem *source = nullptr; + }; + + 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(); + void appendRunSteps(QTreeWidgetItem *item, QList &steps) const; + void load(); + void save(); + void storeCurrentGroup(); + void activateGroup(int index); + QString storagePath() const; + QJsonObject itemToJson(QTreeWidgetItem *item) const; + QTreeWidgetItem *itemFromJson(const QJsonObject &object) const; + void rebuildFlowScene(); + void moveFlowItem(QTreeWidgetItem *item, const QPointF &position); + + QComboBox *m_groupCombo = nullptr; + QTreeWidget *m_tree = nullptr; + QGraphicsScene *m_flowScene = nullptr; + QGraphicsView *m_flowView = nullptr; + QPushButton *m_runButton = nullptr; + QPushButton *m_stopButton = nullptr; + QLabel *m_status = nullptr; + QListWidget *m_history = nullptr; + QTimer *m_runTimer = nullptr; + QList m_groups; + QList m_runSteps; + int m_activeGroup = -1; + int m_runIndex = 0; + bool m_switchingGroup = false; + bool m_waitingForResult = false; + int m_currentWaitMs = 0; + QString m_currentWaitUnit = QStringLiteral("ms"); + QVariantList m_availableDevices; + QHash m_cameraCapabilities; +}; diff --git a/src/tcpcalibrationwidget.cpp b/src/tcpcalibrationwidget.cpp index 54405be..883bd78 100644 --- a/src/tcpcalibrationwidget.cpp +++ b/src/tcpcalibrationwidget.cpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include "appmessagebox.h" #include #include #include @@ -532,7 +532,7 @@ void TcpCalibrationWidget::showResult(const TcpCalibration::Pose &offset, double void TcpCalibrationWidget::reportError(const QString &message) { emit logMessage(QStringLiteral("ERROR"), QStringLiteral("TCP 标定:%1").arg(message)); - QMessageBox::warning(this, QStringLiteral("工具坐标标定"), message); + AppMessageBox::warning(this, QStringLiteral("工具坐标标定"), message); } void TcpCalibrationWidget::saveTool() { @@ -549,9 +549,9 @@ void TcpCalibrationWidget::saveTool() tool.method = m_loadedResult ? m_loadedMethod : m_method->currentData().toString(); bool replace = false; for (const auto &saved : m_tools.tools) if (saved.name == tool.name) replace = true; - if (replace && QMessageBox::question(this, QStringLiteral("覆盖工具"), + if (replace && AppMessageBox::question(this, QStringLiteral("覆盖工具"), QStringLiteral("当前机械臂的工具“%1”已存在,是否覆盖?").arg(tool.name), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return; + AppMessageBox::Yes | AppMessageBox::No, AppMessageBox::No) != AppMessageBox::Yes) return; QSettings settings; QString error; // TODO(controller TCP): ArmService currently has only ListTCPFrame; @@ -564,7 +564,7 @@ void TcpCalibrationWidget::saveTool() emit toolsChanged(m_endpoint, m_device, tool.name); emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 本机工具“%1”已保存 · %2 / %3") .arg(tool.name, m_endpoint, m_device)); - QMessageBox::information(this, QStringLiteral("保存成功"), + AppMessageBox::information(this, QStringLiteral("保存成功"), QStringLiteral("已保存到当前机器人的工具配置,并同步到机械臂的工具坐标列表。选择该工具后可进行 TCP 点动。")); } void TcpCalibrationWidget::reloadTools(const QString &preferred) @@ -638,9 +638,9 @@ void TcpCalibrationWidget::deleteTool() const int index = m_toolCombo->currentIndex() - 1; if (index < 0 || index >= m_tools.tools.size()) return; const QString name = m_tools.tools.at(index).name; - if (QMessageBox::question(this, QStringLiteral("删除工具"), + if (AppMessageBox::question(this, QStringLiteral("删除工具"), QStringLiteral("删除当前机械臂的工具“%1”?对应的工具坐标选项也将移除。").arg(name), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return; + AppMessageBox::Yes | AppMessageBox::No, AppMessageBox::No) != AppMessageBox::Yes) return; QSettings settings; QString error; if (!TcpToolStore::remove(settings, m_endpoint, m_device, name, error)) { reportError(error); return; } diff --git a/src/touchoperationwidget.cpp b/src/touchoperationwidget.cpp index db5f4d5..b6e686b 100644 --- a/src/touchoperationwidget.cpp +++ b/src/touchoperationwidget.cpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include "appmessagebox.h" #include #include #include @@ -287,7 +287,7 @@ void TouchOperationWidget::stop() { } void TouchOperationWidget::fail(const QString &message) { stop(); m_status->setText(message); emit logMessage("ERROR",QStringLiteral("末端操作:%1").arg(message)); - QMessageBox::warning(this,QStringLiteral("末端操作"),message); + AppMessageBox::warning(this,QStringLiteral("末端操作"),message); } void TouchOperationWidget::setCameraIds(const QStringList &ids) { QStringList old; for(int i=0;icount();++i) old<itemText(i); diff --git a/src/uiicons.h b/src/uiicons.h index 3270d5b..26342d7 100644 --- a/src/uiicons.h +++ b/src/uiicons.h @@ -37,7 +37,9 @@ inline QIcon icon(const QString &resourcePath, const QPixmap selectedPixmap = tintedPixmap(resourcePath, selected, size); const QPixmap disabledPixmap = tintedPixmap(resourcePath, disabled, size); result.addPixmap(normalPixmap, QIcon::Normal, QIcon::Off); - result.addPixmap(selectedPixmap, QIcon::Active, QIcon::Off); + // Hovering a light control must keep its normal foreground. The selected + // white tint belongs to checked navigation/filled buttons only. + result.addPixmap(normalPixmap, QIcon::Active, QIcon::Off); result.addPixmap(selectedPixmap, QIcon::Normal, QIcon::On); result.addPixmap(selectedPixmap, QIcon::Active, QIcon::On); result.addPixmap(disabledPixmap, QIcon::Disabled, QIcon::Off); diff --git a/src/urdfviewerwidget.cpp b/src/urdfviewerwidget.cpp index 4f1a420..923b11e 100644 --- a/src/urdfviewerwidget.cpp +++ b/src/urdfviewerwidget.cpp @@ -1,4 +1,5 @@ #include "urdfviewerwidget.h" +#include "applicationsettings.h" #include "uiicons.h" #include @@ -83,6 +84,7 @@ #include namespace { + QVector3D toVector(const urdf::Vector3 &value) { return QVector3D(static_cast(value.x), @@ -278,6 +280,7 @@ const QStringList &motionDemoPoseNames() UrdfViewerWidget::UrdfViewerWidget(QWidget *parent) : QWidget(parent) { + m_modelPreviewEnabled = ApplicationSettings::instance().options().armModelPreview; m_layout = new QVBoxLayout(this); m_layout->setContentsMargins(0, 0, 0, 0); m_layout->setSpacing(0); @@ -382,6 +385,18 @@ UrdfViewerWidget::UrdfViewerWidget(QWidget *parent) connect(m_demoTimer, &QTimer::timeout, this, &UrdfViewerWidget::advanceMotionDemo); refreshBundledModels(); + + if (!m_modelPreviewEnabled) { + m_modelCombo->setEnabled(false); + openButton->setEnabled(false); + m_reloadButton->setEnabled(false); + resetButton->setEnabled(false); + m_demoButton->setEnabled(false); + m_pathEdit->setPlaceholderText(QStringLiteral("模型预览已关闭")); + m_loadingTitle->setText(QStringLiteral("机械臂模型预览已关闭")); + m_loadingDetail->setText(QStringLiteral("可在「软件设置 → 启动与机械臂」中开启,重启程序后生效")); + m_statusLabel->setText(QStringLiteral("URDF / Qt3D 已停用")); + } } void UrdfViewerWidget::ensureSceneInitialized() @@ -919,6 +934,11 @@ QString UrdfViewerWidget::currentFile() const void UrdfViewerWidget::prepareLoad(const QString &filePath) { + if (!m_modelPreviewEnabled) { + Q_UNUSED(filePath); + return; + } + const QString fileName = QFileInfo(filePath).fileName(); setLoading(true, fileName.isEmpty() ? QStringLiteral("正在准备模型资源…") @@ -928,6 +948,14 @@ void UrdfViewerWidget::prepareLoad(const QString &filePath) bool UrdfViewerWidget::loadUrdf(const QString &filePath) { + if (!m_modelPreviewEnabled) { + Q_UNUSED(filePath); + m_loadingTitle->setText(QStringLiteral("机械臂模型预览已关闭")); + m_loadingDetail->setText(QStringLiteral("请在软件设置中开启,重启程序后生效")); + m_statusLabel->setText(QStringLiteral("URDF / Qt3D 已停用")); + return false; + } + if (m_demoButton && m_demoButton->isChecked()) m_demoButton->setChecked(false); const QFileInfo fileInfo(filePath); @@ -1448,6 +1476,14 @@ bool UrdfViewerWidget::loadModelForIdentity(const QString &manufacturer, const QString &subtype, const QString &descriptionId) { + if (!m_modelPreviewEnabled) { + Q_UNUSED(manufacturer); + Q_UNUSED(model); + Q_UNUSED(subtype); + Q_UNUSED(descriptionId); + return false; + } + if (!m_modelCombo) return false; const auto normalized = [](QString value) { diff --git a/src/urdfviewerwidget.h b/src/urdfviewerwidget.h index 54ef713..2af92ea 100644 --- a/src/urdfviewerwidget.h +++ b/src/urdfviewerwidget.h @@ -39,6 +39,7 @@ class UrdfViewerWidget : public QWidget public: explicit UrdfViewerWidget(QWidget *parent = nullptr); + bool modelPreviewEnabled() const { return m_modelPreviewEnabled; } ~UrdfViewerWidget() override; QString currentFile() const; @@ -75,6 +76,7 @@ private slots: void resetView(); private: + bool m_modelPreviewEnabled = false; struct JointBinding { int type = 0; QVector3D axis; diff --git a/styles.qss b/styles.qss index 008fb36..e01d91e 100644 --- a/styles.qss +++ b/styles.qss @@ -1169,7 +1169,8 @@ QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox { border-radius: 4px; padding: 6px 8px; min-height: 20px; - selection-background-color: #1b6ef3; + selection-background-color: #e2edff; + selection-color: #165dcc; } QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus { border: 1px solid #1b6ef3; @@ -1790,3 +1791,182 @@ QLabel#bottomVersion { color: #68737e; font-family: Consolas; } + +/* Shared application theme: controls, standard dialogs, and preferences. */ +QDialog { + background: #ffffff; + border: 1px solid #cbd5e1; + border-radius: 8px; +} +QWidget#applicationDialogBody { + background: #ffffff; + border: none; +} +QWidget#applicationDialogTitleBar { + background: #f8fafc; + border: none; + border-bottom: 1px solid #dce3ed; + border-top-left-radius: 8px; + border-top-right-radius: 8px; +} +QLabel#applicationDialogTitle { + color: #253246; + font-weight: 600; + font-size: 13px; + background: transparent; +} +QPushButton#applicationDialogClose { + background: transparent; + border: none; + border-radius: 0; + border-top-right-radius: 8px; + min-height: 0; + padding: 0; +} +QPushButton#applicationDialogClose:hover { background: #fde8e8; } +QPushButton#applicationDialogClose:pressed { background: #fbd5d5; } +QMessageBox QLabel { color: #334155; background: transparent; } +QMessageBox QLabel#qt_msgbox_label { + min-width: 300px; + padding: 16px 8px; + line-height: 1.6; +} +QDialogButtonBox QPushButton { min-width: 64px; } +QDialog QCheckBox, QDialog QRadioButton { color: #334155; } +QLabel#settingsFontSample { + background: #f4f8ff; + border: 1px solid #d8e5f7; + border-radius: 8px; + color: #253246; + padding: 18px; + min-height: 44px; +} +QLabel#settingsFeedback { color: #bd343b; } +QTabWidget#settingsTabs::pane { + background: #ffffff; + border: 1px solid #dce3ed; + border-radius: 6px; +} +QTabWidget#settingsTabs QTabBar::tab { + color: #64748b; + background: #f5f7fb; + border: none; + border-bottom: 2px solid transparent; + min-width: 100px; + padding: 12px 18px; +} +QTabWidget#settingsTabs QTabBar::tab:selected { + color: #165dcc; + background: #ffffff; + border-bottom-color: #1b6ef3; + font-weight: 600; +} +QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox { + color: #334155; + border-color: #cbd5e1; + border-radius: 6px; + selection-background-color: #e2edff; + selection-color: #165dcc; +} +QLineEdit:hover, QSpinBox:hover, QDoubleSpinBox:hover, QComboBox:hover { + border-color: #94b7e2; +} +QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus { + border-color: #1b6ef3; +} +QTextEdit, QPlainTextEdit { + color: #334155; + background: #ffffff; + border: 1px solid #d8e0ea; + border-radius: 6px; + padding: 8px; + selection-background-color: #e2edff; + selection-color: #165dcc; +} +QTextEdit:focus, QPlainTextEdit:focus { border-color: #1b6ef3; } +QTextEdit#logView { + color: #334155; + background: #ffffff; + border: 1px solid #dce3ed; + border-radius: 6px; + font-family: "Microsoft YaHei UI"; + font-size: 12px; +} +QAbstractItemView { + color: #334155; + background: #ffffff; + alternate-background-color: #f7f9fc; + border: 1px solid #dce3ed; + selection-background-color: #e8f1ff; + selection-color: #165dcc; + outline: 0; +} +QTableView, QTreeView, QListView { + gridline-color: #e8edf4; + border-radius: 6px; +} +QTableView::item, QTreeView::item, QListView::item { padding: 5px 8px; } +QTableView::item:selected, QTreeView::item:selected, QListView::item:selected { + color: #165dcc; + background: #e8f1ff; +} +QHeaderView::section { + color: #52627a; + background: #f3f6fa; + border: none; + border-bottom: 1px solid #dce3ed; + padding: 8px; + font-weight: 600; +} +QGroupBox { + color: #334155; + background: #ffffff; + border: 1px solid #dce3ed; + border-radius: 7px; + margin-top: 14px; + padding: 14px 10px 10px; +} +QGroupBox::title { subcontrol-origin: margin; left: 12px; padding: 0 6px; } +QToolButton { + color: #475569; + background: #ffffff; + border: 1px solid #cbd5e1; + border-radius: 5px; + padding: 6px; +} +QToolButton:hover { color: #165dcc; background: #edf4ff; border-color: #94b7e2; } +QToolButton:checked { color: #165dcc; background: #e8f1ff; border-color: #8ab4ec; } +QMenu { + color: #334155; + background: #ffffff; + border: 1px solid #d8e0ea; + border-radius: 6px; + padding: 5px; +} +QMenu::item { min-height: 28px; padding: 4px 26px 4px 14px; border-radius: 4px; } +QMenu::item:selected { color: #165dcc; background: #e8f1ff; } +QMenu::separator { height: 1px; background: #e2e8f0; margin: 5px 8px; } +QCheckBox, QRadioButton { spacing: 8px; } +QRadioButton::indicator { + width: 15px; + height: 15px; + border: 1px solid #b9c7d8; + border-radius: 8px; + background: #ffffff; +} +QRadioButton::indicator:checked { + border: 4px solid #1b6ef3; + background: #ffffff; + width: 9px; + height: 9px; +} +QCheckBox:disabled, QRadioButton:disabled { color: #94a3b8; } +QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; } +QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; } +QScrollBar::handle:vertical { background: #c4cfdc; border-radius: 4px; min-height: 28px; } +QScrollBar::handle:horizontal { background: #c4cfdc; border-radius: 4px; min-width: 28px; } +QScrollBar::handle:hover { background: #94a8c0; } +QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; border: none; } +QScrollBar::add-page, QScrollBar::sub-page { background: transparent; } +QToolTip { color: #ffffff; background: #253246; border: none; border-radius: 4px; padding: 7px 10px; } +QSizeGrip { width: 14px; height: 14px; background: transparent; } diff --git a/tests/application_shell_test.cpp b/tests/application_shell_test.cpp new file mode 100644 index 0000000..f0c60eb --- /dev/null +++ b/tests/application_shell_test.cpp @@ -0,0 +1,110 @@ +#include "mainwindow.h" +#include "applicationstyle.h" +#include "urdfviewerwidget.h" +#include "taskorchestrationwidget.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + QApplication application(argc, argv); + application.setApplicationName(QStringLiteral("CMVR Theme Verification")); + application.setOrganizationName(QStringLiteral("CMVR Tests")); + ApplicationStyle::install(application); + if (application.windowIcon().pixmap(32, 32).isNull()) return 1; + MainWindow window; + if (auto *demo = window.findChild(QStringLiteral("demoCheck"))) + demo->setChecked(false); + window.resize(1600, 1000); + window.show(); + QTimer::singleShot(150, &window, [&]() { + int comboCount = 0; + QStringList audit; + for (QComboBox *combo : window.findChildren()) { + combo->ensurePolished(); + if (!combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"))) { + qCritical() << "Unthemed combo:" << combo->objectName(); application.exit(6); return; + } + ++comboCount; + audit.append(QStringLiteral("PASS %1 / %2").arg(combo->metaObject()->className(), combo->objectName())); + } + QFile report(QStringLiteral("combo-audit.txt")); + if (report.open(QIODevice::WriteOnly | QIODevice::Text)) { + QTextStream stream(&report); + stream << "Main-window combos: " << comboCount << '\n' << audit.join('\n') << '\n'; + } + report.close(); + qInfo() << "Themed main-window combo count:" << comboCount; + window.grab().save(QStringLiteral("application-system.png")); + QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 1)); + application.processEvents(); + const auto viewers = window.findChildren(); + for (const auto *viewer : viewers) if (viewer->modelPreviewEnabled()) { application.exit(2); return; } + window.grab().save(QStringLiteral("application-arm.png")); + QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 16)); + application.processEvents(); + window.grab().save(QStringLiteral("application-tasks.png")); + if (auto *tasks = window.findChild()) { + tasks->setAvailableDevices({QVariantMap{{"deviceId", "usb_cam1"}, {"type", 2}}, + QVariantMap{{"deviceId", "mic1"}, {"type", 5}}}); + QPushButton *add = nullptr; + for (auto *button : tasks->findChildren()) + if (button->text().contains(QStringLiteral("任务节点"))) { add = button; break; } + if (!add) { application.exit(7); return; } + bool taskInspected = false; + QTimer::singleShot(100, &window, [&]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (!dialog) return; + auto *title = dialog->findChild(QStringLiteral("jointFlowDialogTitle")); + taskInspected = title && title->text() == QStringLiteral("任务节点参数"); + int count = 0; + for (QComboBox *combo : dialog->findChildren()) { + combo->ensurePolished(); + taskInspected = taskInspected && combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff")); + ++count; + } + if (report.open(QIODevice::Append | QIODevice::Text)) { + QTextStream stream(&report); + stream << "Task-node dialog combos: " << count << " / " << (taskInspected ? "PASS" : "FAIL") << '\n'; + report.close(); + } + dialog->grab().save(QStringLiteral("task-node-dialog.png")); + dialog->reject(); + }); + add->click(); + if (!taskInspected) { application.exit(8); return; } + } + QPushButton *settings = nullptr; + for (QPushButton *button : window.findChildren()) + if (button->text() == QStringLiteral("软件设置")) settings = button; + if (!settings) { application.exit(3); return; } + bool inspected = false; + QTimer::singleShot(100, &window, [&]() { + auto *dialog = qobject_cast(QApplication::activeModalWidget()); + if (dialog && dialog->objectName() == QStringLiteral("applicationSettingsDialog")) { + inspected = dialog->property("applicationChrome").toBool() + && !(dialog->windowFlags() & Qt::WindowStaysOnTopHint); + for (QComboBox *combo : dialog->findChildren()) { + combo->ensurePolished(); + inspected = inspected && combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff")); + } + dialog->grab().save(QStringLiteral("application-settings.png")); + dialog->reject(); + } + }); + settings->click(); + qInfo() << "Theme shell: navigation, disabled model default, icon and settings verified"; + application.exit(inspected ? 0 : 4); + }); + QTimer::singleShot(12000, &application, [&]() { application.exit(5); }); + return application.exec(); +} diff --git a/tests/applicationtheme_test.cpp b/tests/applicationtheme_test.cpp new file mode 100644 index 0000000..510bcb0 --- /dev/null +++ b/tests/applicationtheme_test.cpp @@ -0,0 +1,217 @@ +#include "applicationsettings.h" +#include "applicationstyle.h" +#include "appmessagebox.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class ApplicationThemeTest : public QObject +{ + Q_OBJECT +private slots: + void initTestCase() { ApplicationStyle::install(*qApp); } + + void settingsPreserveGeometryAndUnknownFields() + { + QTemporaryDir directory; + QVERIFY(directory.isValid()); + const QString path = directory.filePath(QStringLiteral("preferences.json")); + QFile fixture(path); + QVERIFY(fixture.open(QIODevice::WriteOnly)); + fixture.write("{\"futureOption\":true,\"window\":{\"geometry\":\"YWJj\"}}"); + fixture.close(); + ApplicationSettings settings(path); + QVERIFY(!settings.options().armModelPreview); + QCOMPARE(settings.windowGeometry(), QByteArray("abc")); + ApplicationOptions options = settings.options(); + options.armModelPreview = true; + options.fontPixels = 16; + options.startupPage = 16; + options.logAutoScroll = false; + QString error; + QVERIFY2(settings.save(options, &error), qPrintable(error)); + ApplicationSettings loaded(path); + QVERIFY(loaded.options().armModelPreview); + QCOMPARE(loaded.options().fontPixels, 16); + QCOMPARE(loaded.options().startupPage, 16); + QVERIFY(!loaded.options().logAutoScroll); + QCOMPARE(loaded.windowGeometry(), QByteArray("abc")); + QVERIFY(fixture.open(QIODevice::ReadOnly)); + QVERIFY(QJsonDocument::fromJson(fixture.readAll()).object().value("futureOption").toBool()); + } + + void comboPopupPreservesSelectionDataAndDisabledItems() + { + QComboBox combo; + combo.addItem(QStringLiteral("相机"), QStringLiteral("camera-1")); + combo.addItem(QStringLiteral("不可用设备"), QStringLiteral("disabled")); + auto *model = qobject_cast(combo.model()); + QVERIFY(model); model->item(1)->setEnabled(false); + combo.show(); combo.showPopup(); QTest::qWait(30); + QVERIFY(qobject_cast(combo.view()->itemDelegate())); + QVERIFY(combo.view()->styleSheet().contains(QStringLiteral("#e8f1ff"))); + QVERIFY(combo.view()->styleSheet().contains(QStringLiteral("item:disabled"))); + QCOMPARE(combo.currentData().toString(), QStringLiteral("camera-1")); + QVERIFY(!(combo.model()->flags(combo.model()->index(1, 0)) & Qt::ItemIsEnabled)); + combo.view()->window()->grab().save(QStringLiteral("combo-popup-preview.png")); + combo.hidePopup(); + } + + void replacementPopupReceivesThemeOnOpen() + { + QComboBox combo; + combo.addItems({QStringLiteral("任务设备"), QStringLiteral("任务操作")}); + combo.show(); QTest::qWait(20); + auto *replacement = new QListView; + replacement->setStyleSheet(QStringLiteral("QListView { background: red; }")); + combo.setView(replacement); + combo.showPopup(); QTest::qWait(30); + QVERIFY(replacement->styleSheet().contains(QStringLiteral("#e8f1ff"))); + QVERIFY(!replacement->styleSheet().contains(QStringLiteral("background: red"))); + QCOMPARE(combo.currentText(), QStringLiteral("任务设备")); + combo.hidePopup(); + } + + void editableComboAndFontPreviewDelegateArePreserved() + { + QComboBox editable; + editable.setEditable(true); + editable.addItems({QStringLiteral("camera-1"), QStringLiteral("camera-2")}); + editable.setEditText(QStringLiteral("自定义相机名称")); + editable.show(); editable.showPopup(); QTest::qWait(20); + QVERIFY(editable.isEditable()); + QCOMPARE(editable.currentText(), QStringLiteral("自定义相机名称")); + editable.hidePopup(); + QFontComboBox fonts; + auto *delegate = fonts.view()->itemDelegate(); + fonts.show(); fonts.showPopup(); QTest::qWait(20); + QVERIFY(fonts.view()->property("applicationFontPreviewPreserved").toBool()); + QVERIFY(delegate); // Native preview renderer remains alive behind the adapter. + QCOMPARE(fonts.view()->objectName(), QStringLiteral("comboPopupView")); + const QPixmap popup = fonts.view()->window()->grab(); + popup.save(QStringLiteral("font-popup-preview.png")); + const QImage image = popup.toImage(); + int selectionPixels = 0; + for (int y = 0; y < image.height(); ++y) + for (int x = 0; x < image.width(); ++x) + if (image.pixelColor(x, y) == QColor("#e8f1ff")) ++selectionPixels; + QVERIFY2(selectionPixels > 50, "Font preview still uses a native selection background"); + fonts.hidePopup(); + } + + void corruptSettingsAreNotOverwrittenByWindowPersistence() + { + QTemporaryDir directory; + const QString path = directory.filePath(QStringLiteral("invalid.json")); + QFile file(path); + QVERIFY(file.open(QIODevice::WriteOnly)); + file.write("invalid original data"); file.close(); + ApplicationSettings settings(path); + QVERIFY(!settings.loadError().isEmpty()); + QVERIFY(settings.saveWindowGeometry("new geometry")); + QVERIFY(file.open(QIODevice::ReadOnly)); + QCOMPARE(file.readAll(), QByteArray("invalid original data")); + } + + void messageBoxUsesSharedChromeAndKeepsResult() + { + AppMessageBox dialog(QMessageBox::Information, QStringLiteral("操作提示"), + QStringLiteral("接口执行失败:设备离线"), QMessageBox::Ok | QMessageBox::Cancel); + dialog.show(); QTest::qWait(50); + QVERIFY(dialog.property("applicationChrome").toBool()); + QVERIFY(dialog.windowFlags() & Qt::FramelessWindowHint); + QVERIFY(!(dialog.windowFlags() & Qt::WindowStaysOnTopHint)); + auto *title = dialog.findChild("applicationDialogTitle"); + QVERIFY(title); QCOMPARE(title->text(), QStringLiteral("操作提示")); + QVERIFY(dialog.button(QMessageBox::Ok)); + QTest::mouseClick(dialog.button(QMessageBox::Ok), Qt::LeftButton); + QCOMPARE(dialog.result(), int(QMessageBox::Ok)); + } + + void inputDialogKeepsEditableValueAndCancel() + { + QInputDialog dialog; + dialog.setWindowTitle(QStringLiteral("节点名称")); + dialog.setTextValue(QStringLiteral("已有节点")); + dialog.show(); QTest::qWait(50); + QVERIFY(dialog.property("applicationChrome").toBool()); + auto *close = dialog.findChild("applicationDialogClose"); + QVERIFY(close); QVERIFY(!close->icon().isNull()); + QCOMPARE(dialog.textValue(), QStringLiteral("已有节点")); + QTest::mouseClick(close, Qt::LeftButton); + QCOMPARE(dialog.result(), int(QDialog::Rejected)); + } + + void confirmationPreservesNoAndDiscardResults() + { + AppMessageBox confirmation(AppMessageBox::Question, QStringLiteral("确认操作"), + QStringLiteral("是否继续?"), AppMessageBox::Yes | AppMessageBox::No); + confirmation.show(); QTest::qWait(20); + confirmation.reject(); + QCOMPARE(confirmation.result(), int(AppMessageBox::No)); + AppMessageBox discard(AppMessageBox::Warning, QStringLiteral("放弃修改"), + QStringLiteral("放弃当前内容?"), AppMessageBox::Discard | AppMessageBox::Cancel); + discard.show(); QTest::qWait(20); + QTest::mouseClick(discard.button(AppMessageBox::Discard), Qt::LeftButton); + QCOMPARE(discard.result(), int(AppMessageBox::Discard)); + } + + void customDialogIsNotWrappedAgain() + { + QDialog dialog(nullptr, Qt::Dialog | Qt::FramelessWindowHint); + auto *layout = new QVBoxLayout(&dialog); + layout->addWidget(new QLabel(QStringLiteral("已有标题栏"), &dialog)); + dialog.show(); QTest::qWait(20); + QVERIFY(!dialog.property("applicationChrome").toBool()); + QCOMPARE(dialog.layout(), static_cast(layout)); + } + + void fileDialogUsesQtChrome() + { + QFileDialog dialog; + dialog.setOption(QFileDialog::DontUseNativeDialog); + dialog.show(); QTest::qWait(50); + QVERIFY(dialog.property("applicationChrome").toBool()); + QVERIFY(dialog.findChild("applicationDialogClose")); + } + + void settingsDialogOpensAndCancelsWithoutSaving() + { + bool inspected = false; + QTimer::singleShot(100, this, [&]() { + for (QWidget *widget : qApp->topLevelWidgets()) { + if (widget->objectName() != QStringLiteral("applicationSettingsDialog")) continue; + auto *dialog = qobject_cast(widget); + inspected = dialog && dialog->property("applicationChrome").toBool() + && dialog->findChild("settingsArmModelPreview"); + if (dialog) { + dialog->grab().save(QStringLiteral("settings-preview.png")); + dialog->reject(); + } + } + }); + showApplicationSettings(nullptr, []() {}); + QVERIFY(inspected); + } +}; + +QTEST_MAIN(ApplicationThemeTest) +#include "applicationtheme_test.moc" diff --git a/tests/applicationtheme_test.pro b/tests/applicationtheme_test.pro new file mode 100644 index 0000000..679f065 --- /dev/null +++ b/tests/applicationtheme_test.pro @@ -0,0 +1,9 @@ +QT += core gui widgets testlib +CONFIG += console testcase c++17 +CONFIG -= app_bundle +TEMPLATE = app +TARGET = applicationtheme_test +INCLUDEPATH += ../src +SOURCES += applicationtheme_test.cpp ../src/applicationsettings.cpp ../src/applicationstyle.cpp +HEADERS += ../src/applicationsettings.h ../src/applicationstyle.h ../src/uiicons.h ../src/appmessagebox.h +RESOURCES += ../resources.qrc diff --git a/tests/run_theme_shell_test.py b/tests/run_theme_shell_test.py new file mode 100644 index 0000000..d153f7e --- /dev/null +++ b/tests/run_theme_shell_test.py @@ -0,0 +1,41 @@ +"""Reuse the actual Release app objects for a hardware-free theme smoke test.""" +import os +from pathlib import Path +import re +import shlex +import subprocess + +root = Path(__file__).resolve().parents[1] +qt = Path('C:/Qt/Qt5.12.4/5.12.4/mingw73_64') +toolchain = Path('C:/Qt/Qt5.12.4/Tools/mingw730_64/bin') +text = (root / 'Makefile.Release').read_text(encoding='utf-8') + + +def value(name): + return re.search(r'^' + name + r'\s*=\s*(.*)$', text, re.M).group(1).strip() + + +def args(text): + return [part.strip('"') for part in shlex.split(text, posix=False)] + + +if __name__ == '__main__': + env = dict(os.environ) + env['PATH'] = os.pathsep.join((str(toolchain), str(qt / 'bin'), str(root / 'bin/release'), env['PATH'])) + env['QT_QPA_PLATFORM'] = 'offscreen' + env['QT_QPA_FONTDIR'] = 'C:/Windows/Fonts' + output = root / 'build/application-theme-shell' + output.mkdir(parents=True, exist_ok=True) + obj = output / 'application_shell_test.o' + binary = output / 'application_shell_test.exe' + flags = value('CXXFLAGS').replace('$(DEFINES)', value('DEFINES')) + subprocess.run([str(toolchain / 'g++.exe'), '-c', *args(flags), *args(value('INCPATH')), + '-I' + str(root / 'src'), str(root / 'tests/application_shell_test.cpp'), '-o', str(obj)], + cwd=root, env=env, check=True) + objects = (root / 'object_script.CmvrControlStation.Release').read_text().splitlines() + objects = [item for item in objects if not item.replace('\\', '/').endswith('/main.o')] + response = output / 'objects.rsp' + response.write_text('\n'.join(objects), encoding='utf-8') + subprocess.run([str(toolchain / 'g++.exe'), '-mthreads', '-o', str(binary), str(obj), + '@' + str(response), *args(value('LIBS'))], cwd=root, env=env, check=True) + subprocess.run([str(binary)], cwd=output, env=env, check=True, timeout=30) diff --git a/tests/test_camera_modes_protocol.py b/tests/test_camera_modes_protocol.py index a893dfc..35dc636 100644 --- a/tests/test_camera_modes_protocol.py +++ b/tests/test_camera_modes_protocol.py @@ -55,6 +55,19 @@ class CameraProtocolTest(unittest.TestCase): self.assertFalse(state.HasField('capabilities')) self.assertEqual(state.DESCRIPTOR.fields_by_name['capabilities'].number, 11) + def test_depth_capture_and_stream_are_independent_of_alignment(self): + state = self.message('CameraState') + state.capabilities.depth_image = True + state.capabilities.depth_stream = False + copied = self.message('CameraState') + copied.ParseFromString(state.SerializeToString()) + self.assertTrue(copied.capabilities.depth_image) + self.assertFalse(copied.capabilities.depth_stream) + self.assertFalse(copied.capabilities.metric_aligned_depth) + copied.capabilities.depth_stream = True + state.ParseFromString(copied.SerializeToString()) + self.assertTrue(state.capabilities.depth_stream) + if __name__ == '__main__': unittest.main() diff --git a/ui/handeyecalibrationwidget.cpp b/ui/handeyecalibrationwidget.cpp index 262b1ea..d8095ba 100644 --- a/ui/handeyecalibrationwidget.cpp +++ b/ui/handeyecalibrationwidget.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include "../src/appmessagebox.h" #include #include #include @@ -226,7 +226,7 @@ HandEyeCalibrationWidget::HandEyeCalibrationWidget(QWidget *parent) }); connect(remove,&QPushButton::clicked,this,[this] { const QString name=m_savedCombo->currentData().toString(); if (name.isEmpty()) return; - if (QMessageBox::question(this,QStringLiteral("删除标定"),QStringLiteral("删除当前机械臂的“%1”?").arg(name))!=QMessageBox::Yes) return; + if (AppMessageBox::question(this,QStringLiteral("删除标定"),QStringLiteral("删除当前机械臂的“%1”?").arg(name))!=AppMessageBox::Yes) return; QSettings settings; QString error; if (!HandEyeStore::remove(settings,m_endpoint,m_device,name,error)) { fail(error); return; } reloadSaved(); emit calibrationsChanged(m_endpoint,m_device,QString()); @@ -574,12 +574,12 @@ void HandEyeCalibrationWidget::saveResult() if (!HandEyeStore::validateRecord(m_result,error)) { fail(error); return; } bool replace=false; for (const auto &record:m_saved.records) if (record.name==m_result.name) replace=true; - if (replace && QMessageBox::question(this,QStringLiteral("更新标定"),QStringLiteral("更新当前机械臂的“%1”?").arg(m_result.name))!=QMessageBox::Yes) return; + if (replace && AppMessageBox::question(this,QStringLiteral("更新标定"),QStringLiteral("更新当前机械臂的“%1”?").arg(m_result.name))!=AppMessageBox::Yes) return; QSettings settings; if (!HandEyeStore::save(settings,m_endpoint,m_device,m_result,replace,error)) { fail(error); return; } reloadSaved(m_result.name); emit calibrationsChanged(m_endpoint,m_device,m_result.name); emit logMessage("INFO",QStringLiteral("手眼标定已保存并同步至机械臂页面:%1 / %2").arg(m_device,m_result.name)); - QMessageBox::information(this,QStringLiteral("手眼标定"),QStringLiteral("已保存到当前机械臂,机械臂页面可立即选择。")); + AppMessageBox::information(this,QStringLiteral("手眼标定"),QStringLiteral("已保存到当前机械臂,机械臂页面可立即选择。")); } void HandEyeCalibrationWidget::reloadSaved(const QString &preferred) { @@ -614,7 +614,7 @@ void HandEyeCalibrationWidget::fail(const QString &message,bool popup) m_detection.clear(); m_pairFrame=VideoFrame(); if (m_requestOp=="pair") { m_requestId.clear(); m_requestOp.clear(); } m_errorMessage=message; emit logMessage("WARN",QStringLiteral("手眼标定:")+message); refresh(); - if (popup) QMessageBox::warning(this,QStringLiteral("手眼标定"),message); + if (popup) AppMessageBox::warning(this,QStringLiteral("手眼标定"),message); } void HandEyeCalibrationWidget::refresh() {