2026-10-26 10:56:56 +08:00
// MainWindow.cpp — 瘦主窗口 (v4 - 轮廓库由 MeasurePanel 自动加载)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "MainWindow.h"
#include "UserVisibleLog.h"
#include "CameraManager.h"
#include "LightController.h"
#include "YoloDetector.h"
#include "VisionGuideMatcher.h"
#include "StereoPoseFusion.h"
#include "OpcUaComm.h"
#include "AppSettings.h"
#include "CameraPanel.h"
#include "LightPanel.h"
#include "YoloPanel.h"
#include "VisionGuidePanel.h"
#include "MeasurePanel.h"
#include "CoordTransformPanel.h"
#include "OpcUaPanel.h"
#include "GroovePanel.h"
#include "VisionGuidanceCapturePanel.h"
#include "MeasurementOptionsPanel.h"
2026-10-27 22:14:53 +08:00
#include "VisionIpcServer.h"
2026-10-26 10:56:56 +08:00
#include "StereoCalibDialog.h"
#include "HandEyeCalibDialog.h"
#include "ShapeModelGenDialog.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QPainter>
#include <QDateTime>
#include <QTextCursor>
#include <QFile>
#include <QTextStream>
#include <QFileInfo>
#include <QCoreApplication>
#include <QTimer>
#include <QMetaObject>
2026-10-27 22:14:53 +08:00
#include <QThread>
2026-10-26 10:56:56 +08:00
MainWindow :: MainWindow ( QWidget * parent ) : QMainWindow ( parent )
{
ui . setupUi ( this );
this -> resize ( 1600 , 1200 );
ui . labelLeftPreview -> setMinimumSize ( 512 , 512 );
ui . labelLeftPreview -> setMaximumSize ( 512 , 512 );
ui . labelRightPreview -> setMinimumSize ( 512 , 512 );
ui . labelRightPreview -> setMaximumSize ( 512 , 512 );
ui . labelLeftPreview -> setScaledContents ( false );
ui . labelRightPreview -> setScaledContents ( false );
ui . labelLeftPreview -> setAlignment ( Qt :: AlignCenter );
ui . labelRightPreview -> setAlignment ( Qt :: AlignCenter );
ui . labelROIResult -> setSizePolicy ( QSizePolicy :: Expanding , QSizePolicy :: Expanding );
ui . labelROIResult -> setMinimumSize ( 400 , 200 );
ui . labelROIResult -> setScaledContents ( false );
ui . textLog -> setStyleSheet (
"background-color: white; color: black; "
"font-family: Consolas, monospace; font-size: 11px;" );
m_camMgr = new CameraManager ( this );
m_lightCtrl = new LightController ( this );
m_yoloDet = new YoloDetector ( this );
m_visionGuide = new VisionGuideMatcher ( this );
m_fusion = new StereoPoseFusion ( this );
m_opcua = new OpcUaCommManager ( this );
CameraManager :: initSDK ();
m_panelCam = new CameraPanel ( ui , m_camMgr , this );
m_panelLight = new LightPanel ( ui , m_lightCtrl , this );
m_panelYolo = new YoloPanel ( ui , m_yoloDet , m_camMgr , this );
m_panelGroove = new GroovePanel ( ui , m_camMgr , m_visionGuide , this );
m_panelVisionGuide = new VisionGuidePanel ( ui , m_visionGuide , this );
m_panelCoord = new CoordTransformPanel ( ui , this );
m_panelMeas = new MeasurePanel ( ui ,
m_panelCam , m_panelLight , m_panelYolo , m_panelVisionGuide , m_panelCoord ,
m_visionGuide , m_fusion , this );
m_panelOpc = new OpcUaPanel ( ui , m_opcua , this , this );
m_panelGuidanceCapture = new VisionGuidanceCapturePanel ( m_camMgr , m_visionGuide ,
m_panelMeas , [ this ]( const QString & message ){ appendLog ( message ); }, ui . tabWidget );
ui . tabWidget -> addTab ( m_panelGuidanceCapture , QString :: fromUtf8 ( "视觉引导" ));
connect ( m_panelGuidanceCapture , & VisionGuidanceCapturePanel :: resultImage ,
m_panelMeas , & MeasurePanel :: showExternalResultImage );
m_panelMeasurementOptions = new MeasurementOptionsPanel ( m_panelCam , m_yoloDet ,
m_visionGuide , m_fusion , m_panelMeas , ui . tabWidget );
ui . tabWidget -> addTab ( m_panelMeasurementOptions , QString :: fromUtf8 ( "测量" ));
connect ( m_panelMeasurementOptions , & MeasurementOptionsPanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelMeasurementOptions , & MeasurementOptionsPanel :: resultImage , m_panelMeas , & MeasurePanel :: showExternalResultImage );
connect ( m_panelMeasurementOptions , & MeasurementOptionsPanel :: busyChanged , this ,[ this ]( bool busy ){
for ( int i = 0 ; i < ui . tabWidget -> count (); ++ i ) ui . tabWidget -> setTabEnabled ( i , ! busy || ui . tabWidget -> widget ( i ) == m_panelMeasurementOptions );
ui . actionStereoCalib -> setEnabled ( ! busy ); ui . actionHandEyeCalib -> setEnabled ( ! busy ); ui . actionShapeModelGen -> setEnabled ( ! busy );
2026-10-27 22:14:53 +08:00
updateRemoteLock (); updateIpcState ();
2026-10-26 10:56:56 +08:00
});
2026-10-27 22:14:53 +08:00
connect ( m_panelMeasurementOptions , & MeasurementOptionsPanel :: remoteFinished , this , & MainWindow :: ipcFinished );
connect ( m_panelMeas , & MeasurePanel :: measureCompleted , this ,[ this ]( bool ){ QTimer :: singleShot ( 0 , this ,[ this ]{ updateRemoteLock (); updateIpcState ();});});
connect ( m_panelVisionGuide , & VisionGuidePanel :: busyChanged , this ,[ this ]( bool ){ updateRemoteLock (); updateIpcState ();});
connect ( m_panelYolo , & YoloPanel :: busyChanged , this ,[ this ]( bool ){ updateRemoteLock (); updateIpcState ();});
2026-10-26 10:56:56 +08:00
// 日志汇聚
connect ( m_panelCam , & CameraPanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelLight , & LightPanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelYolo , & YoloPanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelGroove , & GroovePanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelGroove , & GroovePanel :: resultImage , this ,
[ this ]( const QString & name , const QImage & img ) {
m_panelMeas -> showExternalResultImage ( name , img );
});
connect ( m_panelVisionGuide , & VisionGuidePanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelMeas , & MeasurePanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelCoord , & CoordTransformPanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_panelOpc , & OpcUaPanel :: logMessage , this , & MainWindow :: appendLog );
connect ( m_fusion , & StereoPoseFusion :: logMessage , this , & MainWindow :: appendLog );
connect ( m_camMgr , & CameraManager :: cameraConnected , this ,
2026-10-27 22:14:53 +08:00
[ this ]( CameraManager :: CamIndex ){ m_panelMeas -> updateActionButtons (); updateIpcState (); });
2026-10-26 10:56:56 +08:00
connect ( m_camMgr , & CameraManager :: cameraDisconnected , this ,
2026-10-27 22:14:53 +08:00
[ this ]( CameraManager :: CamIndex ){ m_panelMeas -> updateActionButtons (); updateIpcState (); });
// CameraPanel invalidates its initialization first; publish that new state even
// when no measurement is running and the controller only polls cached status.
connect ( m_camMgr , & CameraManager :: errorOccurred , this ,[ this ]( int , const QString & ){ updateIpcState ();}, Qt :: QueuedConnection );
2026-10-26 10:56:56 +08:00
// 菜单
connect ( ui . btnClearLog , & QPushButton :: clicked , this , & MainWindow :: onClearLog );
connect ( ui . actionSaveLog , & QAction :: triggered , this , & MainWindow :: onSaveLog );
connect ( ui . actionExit , & QAction :: triggered , this , & QMainWindow :: close );
connect ( ui . actionAbout , & QAction :: triggered , this , & MainWindow :: onAbout );
connect ( ui . actionStereoCalib , & QAction :: triggered , this , & MainWindow :: onStereoCalibration );
connect ( ui . actionHandEyeCalib , & QAction :: triggered , this , & MainWindow :: onHandEyeCalibration );
connect ( ui . actionShapeModelGen , & QAction :: triggered , this , & MainWindow :: onShapeModelGenerator );
// OPC-UA
connect ( m_panelOpc , & OpcUaPanel :: measureRequested , this , & MainWindow :: onOpcMeasureRequested );
connect ( m_panelOpc , & OpcUaPanel :: resetRequested , this , & MainWindow :: onOpcResetRequested );
2026-10-27 22:14:53 +08:00
// Native/file/calibration dialogs run nested event loops. Refresh on their exit as
// well as entry, even when they did not belong to a particular panel's busy signal.
auto modalWatch = new QTimer ( this ); modalWatch -> setInterval ( 200 );
connect ( modalWatch , & QTimer :: timeout , this ,[ this ]{
if ( m_modalObserved != ( QApplication :: activeModalWidget () != nullptr )){ updateRemoteLock (); updateIpcState ();}
});
modalWatch -> start ();
2026-10-26 10:56:56 +08:00
// ★ 延迟加载: 窗口先显示, 模型后台加载, 启动秒开
QTimer :: singleShot ( 0 , this , & MainWindow :: autoLoadModels );
appendLog ( QString :: fromUtf8 ( "系统已启动" ));
}
2026-10-27 22:14:53 +08:00
MainWindow ::~ MainWindow () {
if ( m_ipcThread ){ QMetaObject :: invokeMethod ( m_ipc , "close" , Qt :: BlockingQueuedConnection ); m_ipcThread -> quit (); m_ipcThread -> wait ();}
delete m_panelMeasurementOptions ; m_panelMeasurementOptions = nullptr ;
}
void MainWindow :: startIpc ( const QString & name )
{
if ( m_ipcThread ) return ;
m_ipcThread = new QThread ( this ); m_ipc = new VisionIpcServer ; m_ipc -> moveToThread ( m_ipcThread );
connect ( m_ipcThread , & QThread :: finished , m_ipc , & QObject :: deleteLater );
connect ( m_ipc , & VisionIpcServer :: commandReceived , this , & MainWindow :: onIpcCommand , Qt :: QueuedConnection );
connect ( this , & MainWindow :: ipcStateChanged , m_ipc , & VisionIpcServer :: setBackendState , Qt :: QueuedConnection );
connect ( this , & MainWindow :: ipcFinished , m_ipc , & VisionIpcServer :: finish , Qt :: QueuedConnection );
connect ( m_ipc , & VisionIpcServer :: controllerChanged , this ,[ this ]( bool attached ){ m_controllerAttached = attached ; updateRemoteLock (); updateIpcState ();}, Qt :: QueuedConnection );
connect ( m_ipc , & VisionIpcServer :: fatalError , this ,[ this ]( const QString & error ){ qCritical ( "IPC listen failed: %s" , qPrintable ( error )); QCoreApplication :: exit ( 4 );}, Qt :: QueuedConnection );
m_ipcThread -> start (); QMetaObject :: invokeMethod ( m_ipc ,[ this , name ]{ m_ipc -> listen ( name );}, Qt :: QueuedConnection );
updateIpcState ();
}
void MainWindow :: updateRemoteLock ()
{
m_modalObserved = QApplication :: activeModalWidget () != nullptr ;
// Modality itself already blocks user input; leave native/file dialogs enabled.
// It still counts as busy for incoming commands in resourceBusy().
const bool locked = m_controllerAttached || m_initializing || m_panelMeasurementOptions -> isBusy () ||
m_panelMeas -> isBusy () || m_panelVisionGuide -> isBusy () || m_panelYolo -> isBusy ();
m_panelVisionGuide -> setResourceBlocked ( locked ); m_panelYolo -> setResourceBlocked ( locked );
ui . centralWidget -> setEnabled ( ! locked );
ui . actionStereoCalib -> setEnabled ( ! locked ); ui . actionHandEyeCalib -> setEnabled ( ! locked ); ui . actionShapeModelGen -> setEnabled ( ! locked );
}
bool MainWindow :: resourceBusy () const
{
return m_initializing || m_panelMeasurementOptions -> isBusy () || m_panelMeas -> isBusy () ||
m_panelVisionGuide -> isBusy () || m_panelYolo -> isBusy () || QApplication :: activeModalWidget ();
}
void MainWindow :: updateIpcState ()
{
m_modalObserved = QApplication :: activeModalWidget () != nullptr ;
if ( ! m_ipc ) return ;
QString error ;
const bool ready = m_panelCam -> remoteInitialized () && m_panelMeasurementOptions -> remoteReady ( & error );
emit ipcStateChanged ( QJsonObject {{ "ready" , ready },{ "resource_busy" , resourceBusy ()},
{ "initialization" , m_initialization },{ "message" , error }});
}
void MainWindow :: onIpcCommand ( const QJsonObject & request )
{
const auto type = request [ "type" ]. toString ();
if ( type == "show_window" ){ show (); raise (); activateWindow (); return ;}
if ( type == "cancel" ){ m_panelMeasurementOptions -> cancelRemote (); return ;}
if ( resourceBusy ()){
emit ipcFinished ( QJsonObject {{ "type" , type },{ "request_id" , request [ "request_id" ]},{ "context" , request [ "context" ]},{ "status" , "error" },{ "error_code" , "BUSY" },{ "message" , "A local operation is already active" }}); updateIpcState (); return ;
}
if ( type == "shutdown" ){
emit ipcFinished ( QJsonObject {{ "type" , type },{ "request_id" , request [ "request_id" ]},{ "status" , "ok" }});
QCoreApplication :: quit (); return ;
}
if ( type == "initialize" ){
m_initializing = true ; updateRemoteLock (); updateIpcState ();
try { m_initialization = m_panelCam -> initializeRemote ();}
catch ( const std :: exception & e ){ m_initialization = {{ "initialized" , false },{ "error" , QString :: fromUtf8 ( e . what ())}};}
catch (...){ m_initialization = {{ "initialized" , false },{ "error" , "Unhandled camera initialization failure" }};}
QString error ; const bool ready = m_panelCam -> remoteInitialized () && m_panelMeasurementOptions -> remoteReady ( & error );
m_initializing = false ;
// Keep the transport's request active until its terminal response has been delivered.
emit ipcFinished ( QJsonObject {{ "type" , type },{ "request_id" , request [ "request_id" ]},{ "status" , ready ? "ok" : "error" },{ "ready" , ready },
{ "initialization" , m_initialization },{ "error_code" , ready ? "" : "INITIALIZATION" },{ "message" , error . isEmpty () &&! ready ? QStringLiteral ( "Camera initialization incomplete" ) : error }});
updateRemoteLock (); updateIpcState (); return ;
}
if ( type == "measure" ){
if ( ! m_panelCam -> remoteInitialized ()){
emit ipcFinished ( QJsonObject {{ "type" , type },{ "request_id" , request [ "request_id" ]},{ "context" , request [ "context" ]},{ "status" , "error" },{ "error_code" , "NOT_INITIALIZED" },{ "message" , "Initialize both cameras first" }});
} else m_panelMeasurementOptions -> startRemote ( request );
updateRemoteLock (); updateIpcState ();
}
}
2026-10-26 10:56:56 +08:00
void MainWindow :: autoLoadModels ()
{
auto & s = AppSettings :: instance ();
// YOLO
QString yolo = s . get ( AppSettings :: K_YoloModel , "" );
if ( ! yolo . isEmpty () && QFile :: exists ( yolo )) {
if ( m_yoloDet -> loadModel ( yolo )) {
ui . labelModelPath -> setText ( yolo );
appendLog ( QString :: fromUtf8 ( "自动加载YOLO: " ) + QFileInfo ( yolo ). fileName ());
}
}
// 手眼标定
QString he = s . get ( AppSettings :: K_HandEyeMatrix , "" );
if ( ! he . isEmpty () && QFile :: exists ( he ))
m_panelCoord -> loadFromFile ( he );
// 注意: 左右轮廓库 (.sm3) 的加载已移至 MeasurePanel::autoLoadShapeModels()
// 在 MeasurePanel 构造函数末尾自动调用, 同时更新动态创建的 UI 控件
}
// ── 日志 ──────────────────────────────────────────────────────
void MainWindow :: appendLog ( const QString & msg )
{
if ( ui . textLog -> document () -> blockCount () > 2000 ) {
QStringList lines = ui . textLog -> toPlainText (). split ( '\n' );
ui . textLog -> clear ();
int keep = qMin ( 500 , lines . size ());
ui . textLog -> append ( lines . mid ( lines . size () - keep ). join ( '\n' ));
}
QString ts = QDateTime :: currentDateTime (). toString ( "hh:mm:ss.zzz" );
ui . textLog -> append ( QString ( "[%1] %2" ). arg ( ts , sanitizeUserVisibleLog ( msg )));
QTextCursor c = ui . textLog -> textCursor ();
c . movePosition ( QTextCursor :: End );
ui . textLog -> setTextCursor ( c );
}
void MainWindow :: onClearLog () { ui . textLog -> clear (); }
void MainWindow :: onSaveLog ()
{
QString p = AppSettings :: instance (). saveFile ( this , AppSettings :: K_ExportDir ,
QString :: fromUtf8 ( "Save Log" ), "Text (*.txt)" );
if ( p . isEmpty ()) return ;
QFile f ( p );
if ( f . open ( QIODevice :: WriteOnly | QIODevice :: Text )) {
f . write ( ui . textLog -> toPlainText (). toUtf8 ());
f . close ();
}
}
void MainWindow :: onAbout ()
{
QMessageBox :: about ( this , QString :: fromUtf8 ( "关于" ),
QString :: fromUtf8 ( "三维视觉引导模块系统 V4.0 \n 模块化重构版 (VisionGuide+双目融合) \n 左右相机独立轮廓库" ));
}
// ── 工具菜单 ──────────────────────────────────────────────────
void MainWindow :: onStereoCalibration ()
{
2026-10-27 22:14:53 +08:00
if ( m_controllerAttached || resourceBusy ()) return ;
2026-10-26 10:56:56 +08:00
StereoCalibDialog dlg ( m_camMgr , this );
if ( dlg . exec () == QDialog :: Accepted && dlg . hasResult ())
appendLog ( QString :: fromUtf8 ( "[双目标定] 标定完成" ));
}
void MainWindow :: onHandEyeCalibration ()
{
2026-10-27 22:14:53 +08:00
if ( m_controllerAttached || resourceBusy ()) return ;
2026-10-26 10:56:56 +08:00
HandEyeCalibDialog dlg ( m_camMgr , this );
connect ( & dlg , & HandEyeCalibDialog :: calibrationDone ,
[ this ]( const QString & f ){ m_panelCoord -> loadFromFile ( f ); });
dlg . exec ();
}
void MainWindow :: onShapeModelGenerator ()
{
2026-10-27 22:14:53 +08:00
if ( m_controllerAttached || resourceBusy ()) return ;
2026-10-26 10:56:56 +08:00
ShapeModelGenDialog dlg ( this );
connect ( & dlg , & ShapeModelGenDialog :: modelApplied ,
[ this ]( const QString & leftPath , const QString & rightPath ){
if ( ! leftPath . isEmpty () && QFile :: exists ( leftPath )) {
if ( m_visionGuide -> loadShapeModel ( leftPath , CAM_LEFT )) {
ui . labelContourLibFile -> setText ( QString :: fromUtf8 ( "左: %1" ). arg ( QFileInfo ( leftPath ). fileName ()));
ui . labelContourLibStatus -> setText ( QString :: fromUtf8 ( "左模板已加载" ));
ui . labelContourLibStatus -> setStyleSheet ( "color:#00cc66;" );
appendLog ( QString :: fromUtf8 ( "[轮廓库] 左相机模板已应用: " ) + leftPath );
}
}
if ( ! rightPath . isEmpty () && QFile :: exists ( rightPath )) {
if ( m_visionGuide -> loadShapeModel ( rightPath , CAM_RIGHT ))
appendLog ( QString :: fromUtf8 ( "[轮廓库] 右相机模板已应用: " ) + rightPath );
}
m_panelVisionGuide -> updateStepButtons ();
});
dlg . exec ();
}
// ── OPC-UA ───────────────────────────────────────────────────
void MainWindow :: onOpcMeasureRequested ( uint32_t timeoutMs )
{
2026-10-27 22:14:53 +08:00
if ( m_controllerAttached || resourceBusy ()){ appendLog ( QString :: fromUtf8 ( "[OPC UA] 视觉由 ssp 控制或正在运行,拒绝并发测量。" )); return ;}
2026-10-26 10:56:56 +08:00
appendLog ( QString :: fromUtf8 ( "[OPC UA] 收到测量指令, timeout=%1ms" ). arg ( timeoutMs ));
m_opcua -> server () -> setSystemState ( VisionSystemState :: Measuring );
auto * doneConn = new QMetaObject :: Connection ;
* doneConn = connect ( m_panelMeas , & MeasurePanel :: measureCompleted , this ,
[ this , doneConn ]( bool ) {
QObject :: disconnect ( * doneConn );
delete doneConn ;
m_panelOpc -> handleMeasureResult (
m_panelMeas -> lastPose (). valid , m_panelMeas -> lastPose (),
m_panelCoord -> robotPose (), m_panelCoord -> robotPoseReady (),
ui . editResultClass -> text (), m_panelMeas -> lastFusion ());
});
m_panelMeas -> onStartMeasure ();
}
void MainWindow :: onOpcResetRequested ()
{
2026-10-27 22:14:53 +08:00
if ( m_controllerAttached || resourceBusy ()) return ;
2026-10-26 10:56:56 +08:00
m_opcua -> resetToIdle ();
appendLog ( QString :: fromUtf8 ( "[OPC UA] 系统已重置为Idle" ));
}