LAPTOP-SNT8I5JK\Boounion
2024-12-02 aedb3b85fed48cb2cf0abb5fafa8e7591644c9f4
Merge branch 'liuyang' into clh

# Conflicts:
# SourceCode/Bond/BondEq/AxisSettingsDlg.cpp
# SourceCode/Bond/BondEq/AxisSettingsDlg.h
# SourceCode/Bond/BondEq/BondEq.rc
# SourceCode/Bond/BondEq/BondEq.vcxproj
# SourceCode/Bond/BondEq/BondEqDlg.cpp
# SourceCode/Bond/BondEq/Model.cpp
# SourceCode/Bond/BondEq/Resource.h
# SourceCode/Bond/x64/Debug/Config/BondEq.db
已重命名1个文件
已添加20个文件
已修改11个文件
已删除1个文件
20151 ■■■■■ 文件已修改
SourceCode/Bond/BLControlsSDK/include/BLLabel.h 105 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/BondEq.vcxproj 29 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/BondEqDlg.cpp 142 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/BondEqDlg.h 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/DBManager/AxisManager.cpp 246 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/DBManager/AxisManager.h 75 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/DBManager/SystemLogManager.cpp 205 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/DBManager/SystemLogManager.h 76 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/DBManager/UserManager.cpp 55 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/DBManager/UserManager.h 14 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/IOManager.cpp 401 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/IOManager.h 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/RecipeManager.cpp 213 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/RecipeManager.h 70 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/pugiconfig.hpp 77 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/pugixml.cpp 13226 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/FileManager/pugixml.hpp 1516 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/InputDialog.cpp 68 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/InputDialog.h 37 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/ToolUnits.cpp 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/UserManagerDlg.cpp 498 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/AxisSettingsDlg.cpp 964 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/AxisSettingsDlg.h 108 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/ChangePasswordDlg.cpp 4 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/IOMonitoringDlg.cpp 568 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/IOMonitoringDlg.h 69 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/LoginDlg.cpp 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/LoginDlg.h 12 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/SystemLogManagerDlg.cpp 498 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/SystemLogManagerDlg.h 61 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/UserManagerDlg.cpp 730 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/View/UserManagerDlg.h 9 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BondEq/stdafx.h 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SourceCode/Bond/BLControlsSDK/include/BLLabel.h
@@ -4,74 +4,71 @@
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// Label.h : header file
//
#include <functional>
/////////////////////////////////////////////////////////////////////////////
// CBLLabel window
enum FlashType {None, Text, Background };
enum TextAlign { AlignLeft, AlignCenter, AlignRight };
class AFX_EXT_CLASS CBLLabel : public CStatic
{
// Construction
    DECLARE_DYNCREATE(CBLLabel) // æ”¯æŒåŠ¨æ€åˆ›å»º
public:
    // æž„造与析构
    CBLLabel();
    CBLLabel& SetBkColor(COLORREF crBkgnd);
    CBLLabel& SetTextColor(COLORREF crText);
    CBLLabel& SetText(const CString& strText);
    CBLLabel& SetFontBold(BOOL bBold);
    CBLLabel& SetFontName(const CString& strFont);
    CBLLabel& SetFontUnderline(BOOL bSet);
    CBLLabel& SetFontItalic(BOOL bSet);
    CBLLabel& SetFontSize(int nSize);
    CBLLabel& SetSunken(BOOL bSet);
    CBLLabel& SetBorder(BOOL bSet);
    CBLLabel& FlashText(BOOL bActivate);
    CBLLabel& FlashBackground(BOOL bActivate);
    CBLLabel& SetLink(BOOL bLink);
    CBLLabel& SetLinkCursor(HCURSOR hCursor);
// Attributes
public:
protected:
    void ReconstructFont();
    COLORREF    m_crText;
    HBRUSH        m_hBrush;
    HBRUSH        m_hwndBrush;
    LOGFONT        m_lf;
    CFont        m_font;
    CString        m_strText;
    BOOL        m_bState;
    BOOL        m_bTimer;
    BOOL        m_bLink;
    FlashType    m_Type;
    HCURSOR        m_hCursor;
            // Operations
public:
// Overrides
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CBLLabel)
    //}}AFX_VIRTUAL
// Implementation
public:
    virtual ~CBLLabel();
    // Generated message map functions
    void SetClickCallback(std::function<void()> callback); // è®¾ç½®ç‚¹å‡»äº‹ä»¶çš„回调函数
    // å±žæ€§è®¾ç½®æŽ¥å£
    CBLLabel& SetBkColor(COLORREF crBkgnd);             // è®¾ç½®èƒŒæ™¯é¢œè‰²
    CBLLabel& SetTextColor(COLORREF crText);            // è®¾ç½®æ–‡æœ¬é¢œè‰²
    CBLLabel& SetText(const CString& strText);          // è®¾ç½®æ–‡æœ¬å†…容
    CBLLabel& SetFontBold(BOOL bBold);                  // è®¾ç½®å­—体加粗
    CBLLabel& SetFontName(const CString& strFont);      // è®¾ç½®å­—体名称
    CBLLabel& SetFontUnderline(BOOL bSet);              // è®¾ç½®ä¸‹åˆ’线
    CBLLabel& SetFontItalic(BOOL bSet);                 // è®¾ç½®æ–œä½“
    CBLLabel& SetFontSize(int nSize);                   // è®¾ç½®å­—体大小
    CBLLabel& SetAlignment(TextAlign alignment);        // è®¾ç½®æ–‡æœ¬å¯¹é½æ–¹å¼
    CBLLabel& SetDynamicFont(BOOL bDynamic);            // è®¾ç½®æ˜¯å¦åŠ¨æ€è°ƒæ•´å­—ä½“
    CBLLabel& FlashText(BOOL bActivate);                // é—ªçƒæ–‡æœ¬
    CBLLabel& FlashBackground(BOOL bActivate);          // é—ªçƒèƒŒæ™¯
    CBLLabel& SetLink(BOOL bLink);                      // è®¾ç½®æ˜¯å¦å¯ç”¨è¶…链接
    CBLLabel& SetLinkCursor(HCURSOR hCursor);           // è®¾ç½®è¶…链接光标
protected:
    //{{AFX_MSG(CBLLabel)
    afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
    afx_msg void OnTimer(UINT_PTR nIDEvent);
    afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
    afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
    //}}AFX_MSG
    // å·¥å…·å‡½æ•°
    void ReconstructFont();       // é‡æ–°æž„造字体
    void UpdateFontSize();        // åŠ¨æ€è°ƒæ•´å­—ä½“å¤§å°
    virtual void OnPaint();       // è‡ªå®šä¹‰ç»˜åˆ¶æ–‡æœ¬
    // å±žæ€§
    COLORREF m_crText;            // æ–‡æœ¬é¢œè‰²
    COLORREF m_crBkColor;         // èƒŒæ™¯é¢œè‰²
    HBRUSH   m_hBrush;            // èƒŒæ™¯ç”»åˆ·
    LOGFONT  m_lf;                // å­—体信息
    CFont    m_font;              // å­—体对象
    CString  m_strText;           // æ–‡æœ¬å†…容
    BOOL     m_bState;            // çŠ¶æ€ï¼Œç”¨äºŽé—ªçƒ
    BOOL     m_bTimer;            // å®šæ—¶å™¨çŠ¶æ€
    BOOL     m_bLink;             // æ˜¯å¦ä¸ºè¶…链接
    BOOL     m_bDynamicFont;      // æ˜¯å¦åŠ¨æ€è°ƒæ•´å­—ä½“å¤§å°
    TextAlign m_alignment;        // æ–‡æœ¬å¯¹é½æ–¹å¼
    FlashType m_Type;             // é—ªçƒç±»åž‹
    HCURSOR  m_hCursor;           // è¶…链接光标
    std::function<void()> m_clickCallback; // ç‚¹å‡»äº‹ä»¶çš„回调函数
protected:
    // MFC æ¶ˆæ¯æ˜ å°„
    virtual HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);  // èƒŒæ™¯å’Œæ–‡æœ¬é¢œè‰²è®¾ç½®
    afx_msg void OnTimer(UINT_PTR nIDEvent);            // å®šæ—¶å™¨äº‹ä»¶
    afx_msg void OnLButtonDown(UINT nFlags, CPoint point); // é¼ æ ‡ç‚¹å‡»äº‹ä»¶
    afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); // è®¾ç½®å…‰æ ‡äº‹ä»¶
    DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BLLABEL_H__A4EABEC5_2E8C_11D1_B79F_00805F9ECE10__INCLUDED_)
SourceCode/Bond/BondEq/BondEq.vcxproj
@@ -115,7 +115,7 @@
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <SDLCheck>true</SDLCheck>
      <AdditionalIncludeDirectories>.;.\View;.\DBManager;..\DatabaseSDK\include;..\BLControlsSDK\include;..\BLControlsSDK\GridControl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
      <AdditionalIncludeDirectories>.;.\View;.\DBManager;.\FileManager;..\DatabaseSDK\include;..\BLControlsSDK\include;..\BLControlsSDK\GridControl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ClCompile>
    <Link>
      <SubSystem>Windows</SubSystem>
@@ -196,7 +196,6 @@
    <ClInclude Include="Alarm.h" />
    <ClInclude Include="AlarmMonitor.h" />
    <ClInclude Include="ApredTreeCtrl.h" />
    <ClInclude Include="AxisSettingsDlg.h" />
    <ClInclude Include="BaseSetPage.h" />
    <ClInclude Include="BlButton.h" />
    <ClInclude Include="BondEq.h" />
@@ -218,13 +217,20 @@
    <ClInclude Include="Common.h" />
    <ClInclude Include="Configuration.h" />
    <ClInclude Include="CPanelProject.h" />
    <ClInclude Include="DBManager\AxisManager.h" />
    <ClInclude Include="DBManager\SystemLogManager.h" />
    <ClInclude Include="DBManager\UserManager.h" />
    <ClInclude Include="EQState.h" />
    <ClInclude Include="EQStateMonitor.h" />
    <ClInclude Include="FileManager\IOManager.h" />
    <ClInclude Include="FileManager\pugiconfig.hpp" />
    <ClInclude Include="FileManager\pugixml.hpp" />
    <ClInclude Include="FileManager\RecipeManager.h" />
    <ClInclude Include="GB2860SQLite.h" />
    <ClInclude Include="HmTab.h" />
    <ClInclude Include="HmVerticalTab.h" />
    <ClInclude Include="HorizontalLine.h" />
    <ClInclude Include="InputDialog.h" />
    <ClInclude Include="Intent.h" />
    <ClInclude Include="LoadMonitor.h" />
    <ClInclude Include="Log.h" />
@@ -246,10 +252,13 @@
    <ClInclude Include="targetver.h" />
    <ClInclude Include="ToolUnits.h" />
    <ClInclude Include="TopToolbar.h" />
    <ClInclude Include="UserManagerDlg.h" />
    <ClInclude Include="VerticalLine.h" />
    <ClInclude Include="View\AxisSettingsDlg.h" />
    <ClInclude Include="View\ChangePasswordDlg.h" />
    <ClInclude Include="View\IOMonitoringDlg.h" />
    <ClInclude Include="View\LoginDlg.h" />
    <ClInclude Include="View\SystemLogManagerDlg.h" />
    <ClInclude Include="View\UserManagerDlg.h" />
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="CPLC.cpp" />
@@ -257,7 +266,6 @@
    <ClCompile Include="Alarm.cpp" />
    <ClCompile Include="AlarmMonitor.cpp" />
    <ClCompile Include="ApredTreeCtrl.cpp" />
    <ClCompile Include="AxisSettingsDlg.cpp" />
    <ClCompile Include="BaseSetPage.cpp" />
    <ClCompile Include="BlButton.cpp" />
    <ClCompile Include="BondEq.cpp" />
@@ -278,13 +286,21 @@
    <ClCompile Include="CProjectPageRemoteEqs.cpp" />
    <ClCompile Include="Configuration.cpp" />
    <ClCompile Include="CPanelProject.cpp" />
    <ClCompile Include="DBManager\AxisManager.cpp" />
    <ClCompile Include="DBManager\SystemLogManager.cpp" />
    <ClCompile Include="DBManager\UserManager.cpp" />
    <ClCompile Include="EQState.cpp" />
    <ClCompile Include="EQStateMonitor.cpp" />
    <ClCompile Include="FileManager\IOManager.cpp" />
    <ClCompile Include="FileManager\pugixml.cpp">
      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
    </ClCompile>
    <ClCompile Include="FileManager\RecipeManager.cpp" />
    <ClCompile Include="GB2860SQLite.cpp" />
    <ClCompile Include="HmTab.cpp" />
    <ClCompile Include="HmVerticalTab.cpp" />
    <ClCompile Include="HorizontalLine.cpp" />
    <ClCompile Include="InputDialog.cpp" />
    <ClCompile Include="Intent.cpp" />
    <ClCompile Include="LoadMonitor.cpp" />
    <ClCompile Include="Log.cpp" />
@@ -310,10 +326,13 @@
    </ClCompile>
    <ClCompile Include="ToolUnits.cpp" />
    <ClCompile Include="TopToolbar.cpp" />
    <ClCompile Include="UserManagerDlg.cpp" />
    <ClCompile Include="VerticalLine.cpp" />
    <ClCompile Include="View\AxisSettingsDlg.cpp" />
    <ClCompile Include="View\ChangePasswordDlg.cpp" />
    <ClCompile Include="View\IOMonitoringDlg.cpp" />
    <ClCompile Include="View\LoginDlg.cpp" />
    <ClCompile Include="View\SystemLogManagerDlg.cpp" />
    <ClCompile Include="View\UserManagerDlg.cpp" />
  </ItemGroup>
  <ItemGroup>
    <ResourceCompile Include="BondEq.rc" />
SourceCode/Bond/BondEq/BondEqDlg.cpp
@@ -8,14 +8,17 @@
#include "afxdialogex.h"
#include "Common.h"
#include "CBonder.h"
#include "ToolUnits.h"
#include "SettingsDlg.h"
#include "UserManager.h"
#include "InputDialog.h"
#include "LoginDlg.h"
#include "ChangePasswordDlg.h"
#include "UserManagerDlg.h"
#include "SystemLogManagerDlg.h"
// test
#include "AxisSettingsDlg.h"
#include "UserManagerDlg.h"
#include "IOMonitoringDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
@@ -182,6 +185,31 @@
    SetTimer(1, 60000, nullptr);
#endif
    userManager.loadSession();
    std::unique_ptr<BL::Database>& db = userManager.getDatabaseInstance();
    // è®¾ç½®è¿è¡Œæ—¥å¿—模块的数据库连接
    SystemLogManager& logManager = SystemLogManager::getInstance();
    logManager.setDatabase(db.get());
    // åˆå§‹åŒ–运行日志表
    try {
        if (!logManager.initializeLogTable()) {
            AfxMessageBox("初始化系统日志模块失败!");
            return FALSE;
        }
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("初始化系统日志模块失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
        return FALSE;
    }
    // è®¾ç½®é…æ–¹æ–‡ä»¶å¤¹è·¯å¾„
    RecipeManager& recipeManager = RecipeManager::getInstance();
    std::string strRecipePath =  CToolUnits::getCurrentExePath() + _T("\\Recipe");
    CToolUnits::createDir(strRecipePath.c_str());
    recipeManager.setRecipeFolder(strRecipePath);
    // èœå•
@@ -224,10 +252,9 @@
    InitRxWindows();
    // ç™»å½•管理
    if (userManager.isLoggedIn()) {
        m_pTopToolbar->SetOperatorBtnText(userManager.getCurrentUser().c_str());
    }
    // æ›´æ–°ç™»å½•状态
    UpdateLoginStatus();
    logManager.log(SystemLogManager::LogType::Info, _T("BondEq启动..."));
    return TRUE;  // é™¤éžå°†ç„¦ç‚¹è®¾ç½®åˆ°æŽ§ä»¶ï¼Œå¦åˆ™è¿”回 TRUE
@@ -352,6 +379,8 @@
    UserManager::getInstance().terminateIdleDetection();
    KillTimer(1);
#endif
    SystemLogManager::getInstance().log(SystemLogManager::LogType::Info, _T("BondEq关闭..."));
}
void CBondEqDlg::OnSize(UINT nType, int cx, int cy)
@@ -456,6 +485,16 @@
    CAxisSettingsDlg axisDlg;
    axisDlg.SetPLC(theApp.m_model.getBonder().getPLC("PLC(1)"));
    axisDlg.DoModal();
    // Cavity VacuumBake AfterBake AOI
    CIOMonitoringDlg dlg;
    dlg.SetIOManager("Cavity");
    dlg.SetPLC(theApp.m_model.getBonder().getPLC("PLC(1)"));
    dlg.DoModal();
    //CAxisSettingsDlg dlg;
    //dlg.SetPLC(theApp.m_model.getBonder().getPLC("PLC(1)"));
    //dlg.SetRecipeName(_T("Default"));
    //dlg.DoModal();
    /*
    CSettingsDlg dlg;
@@ -518,13 +557,33 @@
LRESULT CBondEqDlg::OnToolbarBtnClicked(WPARAM wParam, LPARAM lParam)
{
    int id = (int)lParam;
    SystemLogManager& logManager = SystemLogManager::getInstance();
    if (id == IDC_BUTTON_RUN || id == IDC_BUTTON_STOP || id == IDC_BUTTON_SETTINGS)
    {
        CInputDialog inputDialog(_T("验证用户"), _T("请输入用户密码:"));
        if (inputDialog.DoModal() != IDOK) {
            AfxMessageBox(_T("取消验证!"));
            return 0;
        }
        CString inputText = inputDialog.GetInputText();
        std::string strPass = UserManager::getInstance().getCurrentPass();
        if (inputText.Compare(strPass.c_str()) != 0) {
            AfxMessageBox(_T("密码错误!"));
            logManager.log(SystemLogManager::LogType::Info, _T("验证时,密码错误!"));
            return 0;
        }
    }
    if (id == IDC_BUTTON_RUN) {
        m_pTopToolbar->GetBtn(IDC_BUTTON_RUN)->EnableWindow(FALSE);
        m_pTopToolbar->GetBtn(IDC_BUTTON_STOP)->EnableWindow(TRUE);
        logManager.log(SystemLogManager::LogType::Operation, _T("运行..."));
    }
    else if (id == IDC_BUTTON_STOP) {
        m_pTopToolbar->GetBtn(IDC_BUTTON_RUN)->EnableWindow(TRUE);
        m_pTopToolbar->GetBtn(IDC_BUTTON_STOP)->EnableWindow(FALSE);
        logManager.log(SystemLogManager::LogType::Operation, _T("Í£Ö¹..."));
    }
    else if (id == IDC_BUTTON_SETTINGS) {
        CSettingsDlg dlg;
@@ -534,20 +593,51 @@
        int menuId = (int)wParam;
        UserManager& userManager = UserManager::getInstance();
        if (menuId == 0) {
            ShowLoginDlg();
            CLoginDlg loginDlg;
            loginDlg.DoModal();
        }
        else if (1 == menuId) {
            CChangePasswordDlg changePasswordDlg;
            changePasswordDlg.DoModal();
        }
        else if (2 == menuId) {
            CUserManagerDlg dlg;
            if (dlg.DoModal()!= IDOK) {
                logManager.log(SystemLogManager::LogType::Operation, _T("用户管理的预操作被取消!"));
            }
        }
        else if (3 == menuId) {
            CSystemLogManagerDlg dlg;
            dlg.DoModal();
        }
        else if (4 == menuId) {
            int ret = AfxMessageBox(_T("是否切换用户?切换用户会退出当前账号!"), MB_OKCANCEL | MB_ICONEXCLAMATION);
            if (ret != IDOK) {
                return 0;
            }
            logManager.log(SystemLogManager::LogType::Operation, _T("确认切换角色!"));
            if (userManager.isLoggedIn()) {
                logManager.log(SystemLogManager::LogType::Info, _T("退出登录!"));
                userManager.logout();
            }
            ShowLoginDlg();
            CLoginDlg loginDlg;
            loginDlg.DoModal();
        }
        else if (2 == menuId) {
            // test
            CUserManagerDlg dlg;
            dlg.DoModal();
        else {
            CString cstrMessage;
            cstrMessage.Format(_T("是否退出用户 [%s]?"), userManager.getCurrentUser().c_str());
            int ret = AfxMessageBox(_T(cstrMessage), MB_OKCANCEL | MB_ICONEXCLAMATION);
            if (ret != IDOK) {
                return 0;
        }
            logManager.log(SystemLogManager::LogType::Info, _T("退出登录!"));
            userManager.logout();
        }
        UpdateLoginStatus();
    }
    return 0;
@@ -619,17 +709,35 @@
    return pDlg;
}
void CBondEqDlg::ShowLoginDlg()
void CBondEqDlg::UpdateLoginStatus()
{
    CLoginDlg loginDlg;
    loginDlg.DoModal();
    HMENU hMenu = m_pTopToolbar->GetOperatorMenu();
    UserManager& userManager = UserManager::getInstance();
    if (userManager.isLoggedIn())
    {
        ::EnableMenuItem(hMenu, ID_OPEATOR_LOGIN, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        ::EnableMenuItem(hMenu, ID_OPERATOR_CHANGE_PASSWORD, MF_BYCOMMAND | MF_ENABLED);
        ::EnableMenuItem(hMenu, ID_OPERATOR_SYSTEM_LOG, MF_BYCOMMAND | MF_ENABLED);
        ::EnableMenuItem(hMenu, ID_OPEATOR_SWITCH, MF_BYCOMMAND | MF_ENABLED);
        ::EnableMenuItem(hMenu, ID_OPERATOR_LOGOUT, MF_BYCOMMAND | MF_ENABLED);
        if (userManager.getCurrentUserRole() == UserRole::SuperAdmin) {
            ::EnableMenuItem(hMenu, ID_OPEATOR_USER_MANAGER, MF_BYCOMMAND | MF_ENABLED);
        }
        else {
            ::EnableMenuItem(hMenu, ID_OPEATOR_USER_MANAGER, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        }
        m_pTopToolbar->SetOperatorBtnText(userManager.getCurrentUser().c_str());
    }
    else {
        ::EnableMenuItem(hMenu, ID_OPEATOR_LOGIN, MF_BYCOMMAND | MF_ENABLED);
        ::EnableMenuItem(hMenu, ID_OPERATOR_CHANGE_PASSWORD, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        ::EnableMenuItem(hMenu, ID_OPEATOR_USER_MANAGER, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        ::EnableMenuItem(hMenu, ID_OPERATOR_SYSTEM_LOG, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        ::EnableMenuItem(hMenu, ID_OPEATOR_SWITCH, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        ::EnableMenuItem(hMenu, ID_OPERATOR_LOGOUT, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
        m_pTopToolbar->SetOperatorBtnText(_T("未登录"));
    }
}
SourceCode/Bond/BondEq/BondEqDlg.h
@@ -24,7 +24,7 @@
    void CloseView(CBaseView* pView);
    CHomeDialog* CreateHomeDlg();
    CBaseView* CreateRemoteEqView(BEQ::IRemoteEquipment* pEquipment);
    void ShowLoginDlg();
    void UpdateLoginStatus();
private:
    COLORREF m_crBkgnd;
SourceCode/Bond/BondEq/DBManager/AxisManager.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,246 @@
#include "stdafx.h"
#include "AxisManager.h"
#include <sstream>
#include <stdexcept>
#include <mutex>
// é™æ€æˆå‘˜åˆå§‹åŒ–
std::mutex AxisManager::m_mutex;
// èŽ·å–å•ä¾‹å®žä¾‹
AxisManager& AxisManager::getInstance() {
    static AxisManager instance;
    return instance;
}
AxisManager::AxisManager() : m_pDB(nullptr) {}
AxisManager::~AxisManager() {
    m_pDB = nullptr;
}
// è®¾ç½®æ•°æ®åº“连接
void AxisManager::setDatabase(BL::Database* db) {
    std::lock_guard<std::mutex> lock(m_mutex);
    m_pDB = db;
}
// åˆå§‹åŒ–轴表和定位点表
bool AxisManager::initializeTables() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    const std::string createAxesTableQuery = R"(
        CREATE TABLE IF NOT EXISTS axes (
            axis_id INTEGER PRIMARY KEY,
            axis_no TEXT NOT NULL,
            description TEXT NOT NULL,
            start_address TEXT,
            jog_distance REAL,
            manual_speed REAL,
            max_manual_speed REAL,
            min_manual_speed REAL,
            auto_speed REAL,
            max_auto_speed REAL,
            min_auto_speed REAL,
            acceleration_time REAL,
            deceleration_time REAL
        )
    )";
    const std::string createPositionsTableQuery = R"(
        CREATE TABLE IF NOT EXISTS positions (
            position_id INTEGER PRIMARY KEY AUTOINCREMENT,
            axis_id INTEGER NOT NULL,
            description TEXT,
            position_value REAL,
            plc_address TEXT,
            FOREIGN KEY (axis_id) REFERENCES axes(axis_id)
        )
    )";
    return m_pDB->executeQuery(createAxesTableQuery) && m_pDB->executeQuery(createPositionsTableQuery);
}
// åˆå§‹åŒ–默认数据
bool AxisManager::initializeDefaultData() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    for (int axisId = 1; axisId <= 12; ++axisId) {
        std::ostringstream axisQuery;
        axisQuery << "INSERT OR IGNORE INTO axes (axis_id, axis_no, description, start_address, jog_distance, manual_speed, "
            << "max_manual_speed, min_manual_speed, auto_speed, max_auto_speed, min_auto_speed, acceleration_time, deceleration_time) "
            << "VALUES (" << axisId << ", 'M" << axisId * 10 << "', 'è½´ " << axisId << "', 'D" << (5090 + axisId * 2) << "', "
            << "0.5, 10.0, 20.0, 5.0, 15.0, 25.0, 10.0, 0.2, 0.3)";
        m_pDB->executeQuery(axisQuery.str());
    }
    for (int axisId = 1; axisId <= 12; ++axisId) {
        for (int positionIndex = 1; positionIndex <= 25; ++positionIndex) {
            std::ostringstream positionQuery;
            positionQuery << "INSERT OR IGNORE INTO positions (axis_id, description, position_value, plc_address) "
                << "VALUES (" << axisId << ", '定位点 " << positionIndex << "', " << (positionIndex * 10.0) << ", "
                << "'D" << (5240 + positionIndex * 2) << "')";
            m_pDB->executeQuery(positionQuery.str());
        }
    }
    return true;
}
// æ·»åŠ æˆ–æ›´æ–°è½´ä¿¡æ¯
bool AxisManager::saveAxis(int axisId, const std::string& axisNo, const std::string& description,
    const std::string& startAddress, double jogDistance, double manualSpeed,
    double maxManualSpeed, double minManualSpeed, double autoSpeed,
    double maxAutoSpeed, double minAutoSpeed, double accelerationTime,
    double decelerationTime) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "INSERT INTO axes (axis_id, axis_no, description, start_address, jog_distance, manual_speed, "
        << "max_manual_speed, min_manual_speed, auto_speed, max_auto_speed, min_auto_speed, acceleration_time, deceleration_time) "
        << "VALUES (" << axisId << ", '" << axisNo << "', '" << description << "', '" << startAddress << "', "
        << jogDistance << ", " << manualSpeed << ", " << maxManualSpeed << ", " << minManualSpeed << ", " << autoSpeed
        << ", " << maxAutoSpeed << ", " << minAutoSpeed << ", " << accelerationTime << ", " << decelerationTime << ") "
        << "ON CONFLICT(axis_id) DO UPDATE SET "
        << "axis_no=excluded.axis_no, description=excluded.description, start_address=excluded.start_address, "
        << "jog_distance=excluded.jog_distance, manual_speed=excluded.manual_speed, max_manual_speed=excluded.max_manual_speed, "
        << "min_manual_speed=excluded.min_manual_speed, auto_speed=excluded.auto_speed, max_auto_speed=excluded.max_auto_speed, "
        << "min_auto_speed=excluded.min_auto_speed, acceleration_time=excluded.acceleration_time, deceleration_time=excluded.deceleration_time";
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_pDB->executeQuery(query.str());
}
// èŽ·å–å•ä¸ªè½´ä¿¡æ¯
std::vector<std::string> AxisManager::getAxis(int axisId) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "SELECT * FROM axes WHERE axis_id = " << axisId;
    auto result = m_pDB->fetchResults(query.str());
    return !result.empty() ? result[0] : std::vector<std::string>();
}
// èŽ·å–æ‰€æœ‰è½´ä¿¡æ¯
std::vector<std::vector<std::string>> AxisManager::getAllAxes() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    return m_pDB->fetchResults("SELECT * FROM axes ORDER BY axis_id");
}
// åˆ é™¤æŒ‡å®šè½´
bool AxisManager::deleteAxis(int axisId) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "DELETE FROM axes WHERE axis_id = " << axisId;
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_pDB->executeQuery(query.str());
}
// æ·»åŠ æˆ–æ›´æ–°å®šä½ç‚¹
bool AxisManager::savePosition(int axisId, const std::string& description, double positionValue, const std::string& plcAddress) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "INSERT INTO positions (axis_id, description, position_value, plc_address) VALUES ("
        << axisId << ", '" << description << "', " << positionValue << ", '" << plcAddress << "') "
        << "ON CONFLICT(axis_id) DO UPDATE SET "
        << "description=excluded.description, position_value=excluded.position_value, plc_address=excluded.plc_address";
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_pDB->executeQuery(query.str());
}
// èŽ·å–è½´çš„æ‰€æœ‰å®šä½ç‚¹
std::vector<std::vector<std::string>> AxisManager::getPositions(int axisId, int pageNumber, int pageSize) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    int offset = (pageNumber - 1) * pageSize;
    std::ostringstream query;
    query << "SELECT * FROM positions WHERE axis_id = " << axisId << " LIMIT " << pageSize << " OFFSET " << offset;
    return m_pDB->fetchResults(query.str());
}
// èŽ·å–å®šä½ç‚¹æ€»æ•°
int AxisManager::getTotalPositionCount(int axisId) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "SELECT COUNT(*) FROM positions WHERE axis_id = " << axisId;
    auto result = m_pDB->fetchResults(query.str());
    return (!result.empty() && !result[0].empty()) ? std::stoi(result[0][0]) : 0;
}
// åˆ é™¤æŒ‡å®šå®šä½ç‚¹
bool AxisManager::deletePosition(int positionId) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "DELETE FROM positions WHERE position_id = " << positionId;
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_pDB->executeQuery(query.str());
}
// èŽ·å–æ‰€æœ‰çš„è½´ID
std::vector<int> AxisManager::getUsedAxisIds() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::vector<int> usedAxisIds;
    std::string query = "SELECT axis_id FROM axes ORDER BY axis_id";
    auto results = m_pDB->fetchResults(query);
    for (const auto& row : results) {
        if (!row.empty()) {
            usedAxisIds.push_back(std::stoi(row[0]));
        }
    }
    return usedAxisIds;
}
// èŽ·å–æ‰€æœ‰è½´çš„è½´NO
std::vector<std::string> AxisManager::getAllAxisNumbers() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::vector<std::string> axisNumbers;
    std::string query = "SELECT axis_no FROM axes ORDER BY axis_id";
    auto results = m_pDB->fetchResults(query);
    for (const auto& row : results) {
        if (!row.empty()) {
            axisNumbers.push_back(row[0]);
        }
    }
    return axisNumbers;
}
SourceCode/Bond/BondEq/DBManager/AxisManager.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,75 @@
#ifndef AXIS_MANAGER_H
#define AXIS_MANAGER_H
#include <string>
#include <vector>
#include <mutex>
#include "Database.h"
// è½´ç®¡ç†ç±»
class AxisManager {
public:
    // èŽ·å–å•ä¾‹å®žä¾‹
    static AxisManager& getInstance();
    // è®¾ç½®æ•°æ®åº“连接
    void setDatabase(BL::Database* db);
    // åˆå§‹åŒ–轴表和定位点表
    bool initializeTables();
    // åˆå§‹åŒ–默认数据
    bool initializeDefaultData();
    // æ·»åŠ æˆ–æ›´æ–°è½´ä¿¡æ¯
    bool saveAxis(int axisId, const std::string& axisNo, const std::string& description,
        const std::string& startAddress, double jogDistance, double manualSpeed,
        double maxManualSpeed, double minManualSpeed, double autoSpeed,
        double maxAutoSpeed, double minAutoSpeed, double accelerationTime,
        double decelerationTime);
    // èŽ·å–å•ä¸ªè½´ä¿¡æ¯
    std::vector<std::string> getAxis(int axisId);
    // èŽ·å–æ‰€æœ‰è½´ä¿¡æ¯
    std::vector<std::vector<std::string>> getAllAxes();
    // åˆ é™¤æŒ‡å®šè½´
    bool deleteAxis(int axisId);
    // æ·»åŠ æˆ–æ›´æ–°å®šä½ç‚¹
    bool savePosition(int axisId, const std::string& description, double positionValue,
        const std::string& plcAddress);
    // èŽ·å–è½´çš„æ‰€æœ‰å®šä½ç‚¹
    std::vector<std::vector<std::string>> getPositions(int axisId, int pageNumber, int pageSize);
    // èŽ·å–å®šä½ç‚¹æ€»æ•°
    int getTotalPositionCount(int axisId);
    // åˆ é™¤æŒ‡å®šå®šä½ç‚¹
    bool deletePosition(int positionId);
    // èŽ·å–æ‰€æœ‰çš„è½´ID
    std::vector<int> getUsedAxisIds();
    // èŽ·å–æ‰€æœ‰è½´çš„è½´NO
    std::vector<std::string> getAllAxisNumbers();
private:
    // ç§æœ‰æž„造函数和析构函数
    AxisManager();
    ~AxisManager();
    // ç¦æ­¢æ‹·è´å’Œèµ‹å€¼
    AxisManager(const AxisManager&) = delete;
    AxisManager& operator=(const AxisManager&) = delete;
    // æ•°æ®åº“连接
    BL::Database* m_pDB;
    // çº¿ç¨‹å®‰å…¨é”
    static std::mutex m_mutex;
};
#endif // AXIS_MANAGER_H
SourceCode/Bond/BondEq/DBManager/SystemLogManager.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,205 @@
#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <ctime>
// é™æ€æˆå‘˜åˆå§‹åŒ–
std::mutex SystemLogManager::m_mutex;
// èŽ·å–å•ä¾‹å®žä¾‹
SystemLogManager& SystemLogManager::getInstance() {
    static SystemLogManager instance;
    return instance;
}
// æž„造函数
SystemLogManager::SystemLogManager() : m_pDB(nullptr) {}
// æžæž„函数
SystemLogManager::~SystemLogManager() {
    m_pDB = nullptr; // æ¸…除指针引用
}
// è®¾ç½®æ•°æ®åº“连接
void SystemLogManager::setDatabase(BL::Database* db) {
    std::lock_guard<std::mutex> lock(m_mutex);
    m_pDB = db;
}
// åˆå§‹åŒ–日志表
bool SystemLogManager::initializeLogTable() {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    const std::string createTableQuery = R"(
        CREATE TABLE IF NOT EXISTS system_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            log_type TEXT NOT NULL,
            event TEXT NOT NULL,
            username TEXT NOT NULL,
            timestamp DATETIME DEFAULT (datetime('now', 'localtime'))
        )
    )";
    return m_pDB->executeQuery(createTableQuery);
}
// æ·»åŠ æ—¥å¿—ï¼ˆä½¿ç”¨å½“å‰ç”¨æˆ·ï¼‰
bool SystemLogManager::log(LogType logType, const std::string& event) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    cleanOldLogs();
    std::string username = UserManager::getInstance().getCurrentUser();
    if (username.empty()) {
        username = "SYSTEM";
    }
    std::ostringstream query;
    query << "INSERT INTO system_logs (log_type, event, username) VALUES ("
        << "'" << logTypeToString(logType) << "', "
        << "'" << event << "', "
        << "'" << username << "')";
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_pDB->executeQuery(query.str());
}
// æ·»åŠ æ—¥å¿—ï¼ˆæŒ‡å®šç”¨æˆ·ï¼‰
bool SystemLogManager::log(LogType logType, const std::string& event, const std::string& username) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    cleanOldLogs();
    std::ostringstream query;
    query << "INSERT INTO system_logs (log_type, event, username) VALUES ("
        << "'" << logTypeToString(logType) << "', "
        << "'" << event << "', "
        << "'" << username << "')";
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_pDB->executeQuery(query.str());
}
// èŽ·å–æ—¥å¿—å†…å®¹
std::vector<std::vector<std::string>> SystemLogManager::getLogs(int startPosition, int count) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    if (startPosition == -1 && count == -1) {
        query << "SELECT id, log_type, event, username, datetime(timestamp, 'localtime') FROM system_logs";
    }
    else {
        query << "SELECT id, log_type, event, username, datetime(timestamp, 'localtime') FROM system_logs "
            << "LIMIT " << count << " OFFSET " << startPosition;
    }
    return m_pDB->fetchResults(query.str());
}
// èŽ·å–ç­›é€‰åŽçš„æ—¥å¿—æ•°æ®
std::vector<std::vector<std::string>> SystemLogManager::getFilteredLogs(
    const std::string& logType,
    const std::string& username,
    const std::string& description,
    const std::string& startTime,
    const std::string& endTime,
    int pageNumber,
    int pageSize)
{
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "SELECT id, log_type, event, username, datetime(timestamp, 'localtime') FROM system_logs WHERE 1=1";
    if (logType != "ALL") {
        query << " AND log_type = '" << logType << "'";
    }
    if (username != "ALL") {
        query << " AND username = '" << username << "'";
    }
    if (!description.empty()) {
        query << " AND event LIKE '%" << description << "%'";
    }
    if (!startTime.empty()) {
        query << " AND timestamp >= '" << startTime << "'";
    }
    if (!endTime.empty()) {
        query << " AND timestamp <= '" << endTime << "'";
    }
    int offset = (pageNumber - 1) * pageSize;
    query << " ORDER BY timestamp DESC LIMIT " << pageSize << " OFFSET " << offset;
    return m_pDB->fetchResults(query.str());
}
// èŽ·å–ç¬¦åˆæ¡ä»¶çš„æ—¥å¿—æ€»æ•°
int SystemLogManager::getTotalLogCount(
    const std::string& logType,
    const std::string& username,
    const std::string& description,
    const std::string& startTime,
    const std::string& endTime)
{
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "SELECT COUNT(*) FROM system_logs WHERE 1=1";
    if (logType != "ALL") {
        query << " AND log_type = '" << logType << "'";
    }
    if (username != "ALL") {
        query << " AND username = '" << username << "'";
    }
    if (!description.empty()) {
        query << " AND event LIKE '%" << description << "%'";
    }
    if (!startTime.empty()) {
        query << " AND timestamp >= '" << startTime << "'";
    }
    if (!endTime.empty()) {
        query << " AND timestamp <= '" << endTime << "'";
    }
    auto results = m_pDB->fetchResults(query.str());
    return (!results.empty() && !results[0].empty()) ? std::stoi(results[0][0]) : 0;
}
// æ¸…理超过指定天数的旧日志
void SystemLogManager::cleanOldLogs(int daysToKeep) {
    if (!m_pDB) {
        throw std::runtime_error("Database connection is not set.");
    }
    std::ostringstream query;
    query << "DELETE FROM system_logs WHERE timestamp < datetime('now', '-" << daysToKeep << " days')";
    m_pDB->executeQuery(query.str());
}
// è½¬æ¢æ—¥å¿—类型为字符串
std::string SystemLogManager::logTypeToString(LogType logType) {
    switch (logType) {
    case LogType::Info:
        return "信息";
    case LogType::Error:
        return "错误";
    case LogType::Operation:
        return "操作";
    default:
        return "δ֪";
    }
}
SourceCode/Bond/BondEq/DBManager/SystemLogManager.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,76 @@
#ifndef SYSTEM_LOG_MANAGER_H
#define SYSTEM_LOG_MANAGER_H
#include <string>
#include <vector>
#include <mutex>
#include "Database.h"
// ç³»ç»Ÿæ—¥å¿—管理类
class SystemLogManager {
public:
    // æ—¥å¿—类型定义
    enum class LogType {
        Info,
        Error,
        Operation,
        Unknown
    };
    // èŽ·å–å•ä¾‹å®žä¾‹
    static SystemLogManager& getInstance();
    // è®¾ç½®æ•°æ®åº“连接
    void setDatabase(BL::Database* db);
    // åˆå§‹åŒ–日志表
    bool initializeLogTable();
    // æ·»åŠ æ—¥å¿—
    bool log(LogType logType, const std::string& event);
    bool log(LogType logType, const std::string& event, const std::string& username);
    // èŽ·å–æ—¥å¿—å†…å®¹
    std::vector<std::vector<std::string>> getLogs(int startPosition = -1, int count = -1);
    // èŽ·å–ç­›é€‰åŽçš„æ—¥å¿—æ•°æ®
    std::vector<std::vector<std::string>> getFilteredLogs(
        const std::string& logType,
        const std::string& username,
        const std::string& description,
        const std::string& startTime,
        const std::string& endTime,
        int pageNumber,
        int pageSize);
    // èŽ·å–ç¬¦åˆæ¡ä»¶çš„æ—¥å¿—æ€»æ•°
    int getTotalLogCount(
        const std::string& logType,
        const std::string& username,
        const std::string& description,
        const std::string& startTime,
        const std::string& endTime);
    // æ¸…理超过指定天数的旧日志
    void cleanOldLogs(int daysToKeep = 30);
    // è½¬æ¢æ—¥å¿—类型为字符串
    static std::string logTypeToString(LogType logType);
private:
    // æž„造函数和析构函数
    SystemLogManager();
    ~SystemLogManager();
    // ç¦æ­¢æ‹·è´å’Œèµ‹å€¼
    SystemLogManager(const SystemLogManager&) = delete;
    SystemLogManager& operator=(const SystemLogManager&) = delete;
    // æ•°æ®åº“连接
    BL::Database* m_pDB = nullptr;
    // çº¿ç¨‹å®‰å…¨é”
    static std::mutex m_mutex;
};
#endif // SYSTEM_LOG_MANAGER_H
SourceCode/Bond/BondEq/DBManager/UserManager.cpp
@@ -29,6 +29,11 @@
    terminateIdleDetection();
}
// æä¾›æ•°æ®åº“连接
std::unique_ptr<BL::Database>& UserManager::getDatabaseInstance() {
    return m_pDB;
}
// åˆå§‹åŒ–数据库,创建用户表并插入初始管理员用户
bool UserManager::initializeDatabase() {
    std::string dbFilePath = getDatabaseFilePath();
@@ -43,7 +48,7 @@
            role INT NOT NULL,
            session_timeout INT DEFAULT 30,
            session_expiration INT DEFAULT 72,
            last_login TIMESTAMP
            last_login DATETIME DEFAULT (datetime('now', 'localtime'))
        )
    )";
    m_pDB->executeQuery(createTableQuery);
@@ -406,6 +411,39 @@
    return success;
}
// èŽ·å–æ‰€æœ‰ç”¨æˆ·åç§°
std::vector<std::string> UserManager::getUsernames() {
    std::vector<std::string> usernames;
    std::string query = "SELECT username FROM users";
    auto results = m_pDB->fetchResults(query);
    for (const auto& row : results) {
        if (!row.empty()) {
            usernames.push_back(row[0]); // èŽ·å–ç”¨æˆ·ååˆ—çš„å€¼
        }
    }
    return usernames;
}
// èŽ·å–æŒ‡å®šç”¨æˆ·åçš„ç”¨æˆ·ä¿¡æ¯
std::vector<std::string> UserManager::getUserInfo(const std::string& username)
{
    // æž„建查询语句
    std::ostringstream query;
    query << "SELECT username, password, role, session_timeout, session_expiration, last_login "
        << "FROM users WHERE username = '" << username << "'";
    // æ‰§è¡ŒæŸ¥è¯¢å¹¶èŽ·å–ç»“æžœ
    auto results = m_pDB->fetchResults(query.str());
    if (results.empty()) {
        return {};
    }
    // è¿”回查询到的第一行数据
    return results[0];
}
// æ›´æ–°æœ€åŽæ´»åŠ¨æ—¶é—´ï¼Œç”¨äºŽæ— æ“ä½œè¶…æ—¶æ£€æµ‹
void UserManager::updateActivityTime() {
    m_tpLastActivity = std::chrono::system_clock::now();
@@ -450,16 +488,31 @@
    return m_strCurrentUser;
}
// ä¿®æ”¹å½“前登录用户名
void UserManager::setCurrentUser(const std::string& strName) {
    m_strCurrentUser = strName;
}
// èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·å¯†ç 
std::string UserManager::getCurrentPass() const {
    return m_strCurrentPass;
}
// ä¿®æ”¹å½“前登录用户密码
void UserManager::setCurrentPass(const std::string& strPass) {
    m_strCurrentPass = strPass;
}
// èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·è§’è‰²
UserRole UserManager::getCurrentUserRole() const {
    return m_enCurrentUserRole;
}
// ä¿®æ”¹å½“前登录用户角色
void UserManager::setCurrentUserRole(UserRole emRole) {
    m_enCurrentUserRole = emRole;
}
// èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·çš„æ— æ“ä½œè¶…æ—¶æ—¶é—´
std::chrono::minutes UserManager::getSessionTimeout() const {
    return m_tmSessionTimeout;
SourceCode/Bond/BondEq/DBManager/UserManager.h
@@ -22,6 +22,9 @@
    UserManager(const UserManager&) = delete;
    UserManager& operator=(const UserManager&) = delete;
    // æä¾›æ•°æ®åº“连接
    std::unique_ptr<BL::Database>& getDatabaseInstance();
    // ç”¨æˆ·æ“ä½œ
    bool login(const std::string& username, const std::string& password, bool rememberMe = false);
    void logout();
@@ -38,6 +41,8 @@
    bool changeUserRole(const std::string& username, UserRole newRole);
    bool changeUserSessionTimeout(const std::string& username, int newTimeoutMinutes);
    bool changeUserSessionExpiration(const std::string& username, int newExpirationHours);
    std::vector<std::string> getUsernames();
    std::vector<std::string> getUserInfo(const std::string& username);
    // ä¼šè¯æ–‡ä»¶æ“ä½œ
    bool loadSession();     // ä»Žä¼šè¯æ–‡ä»¶åŠ è½½ä¼šè¯ä¿¡æ¯
@@ -67,12 +72,21 @@
    // èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·å
    std::string getCurrentUser() const;
    // ä¿®æ”¹å½“前登录用户名
    void setCurrentUser(const std::string& strName);
    // èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·å¯†ç 
    std::string getCurrentPass() const;
    // ä¿®æ”¹å½“前登录用户密码
    void setCurrentPass(const std::string& strPass);
    // èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·è§’è‰²
    UserRole getCurrentUserRole() const;
    // ä¿®æ”¹å½“前登录用户角色
    void setCurrentUserRole(UserRole emRole);
    // èŽ·å–å½“å‰ç™»å½•ç”¨æˆ·çš„æ— æ“ä½œè¶…æ—¶æ—¶é—´
    std::chrono::minutes getSessionTimeout() const;
SourceCode/Bond/BondEq/FileManager/IOManager.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,401 @@
#include "stdafx.h"
#include "IOManager.h"
#include <fstream>
#include <iostream>
#include "ToolUnits.h"
IOManager::IOManager() {
    m_directory = CToolUnits::getCurrentExePath() + _T("\\Config");
    if (!CToolUnits::isDirectory(m_directory)) {
        CToolUnits::createDir(m_directory.c_str());
    }
}
void IOManager::addMachine(const std::string& machineName, const std::vector<IOData>& data) {
    m_machines[machineName] = data;
}
void IOManager::addDefaultMachineData(const std::string& machineName) {
    if (machineName == "Cavity") {
        std::vector<IOData> defaultData = {
            {"X1000", "Unit1_急停 EMO", "Y1010", "Unit1_四色灯-红"},
            {"X1001", "Unit1_总进气压力检", "Y1011", "Unit1_四色灯-黄"},
            {"X1002", "Unit1_伺服电柜烟感报警", "Y1012", "Unit1_四色灯-绿"},
            {"X1003", "Unit1_加热电柜烟感报警", "Y1013", "Unit1_四色灯-蓝"},
            {"X1004", "安全继电器检", "Y1014", "Unit1_蜂鸣器-1"},
            {"X1005", "", "Y1015", "Unit1_蜂鸣器-2"},
            {"X1006", "", "Y1016", "Unit1_蜂鸣器-3"},
            {"X1007", "Unit1_安全门磁检1", "Y1017", "Unit1_蜂鸣器-4"},
            {"X1008", "Unit1_安全门磁检2", "Y1018", "Unit1_机台照明"},
            {"X1009", "Unit1_安全门磁检3", "Y1019", "Unit1_安全门锁屏蔽"},
            {"X100A", "Unit1_安全门磁检4", "Y101A", ""},
            {"X100B", "Unit1_安全门磁检5", "Y101B", ""},
            {"X100C", "Unit1_安全门磁检6", "Y101C", ""},
            {"X100D", "Unit1_安全门锁检1", "Y101D", "Unit1_安全门锁1"},
            {"X100E", "Unit1_安全门锁检2", "Y101E", "Unit1_安全门锁2"},
            {"X100F", "Unit1_安全门锁检3", "Y101F", "Unit1_安全门锁3"},
            {"X1020", "Unit1_分子泵-Alam(8-14)", "Y1030", "Unit1_分子泵启动(1-9)"},
            {"X1021", "Unit1_分子泵-远程/本地模式(7-15)", "Y1031", "Unit1_分子泵联锁装置(2-10)"},
            {"X1022", "Unit1_分子泵-正常运行(4-12)", "Y1032", "Unit1_分子泵通断插板阀"},
            {"X1023", "Unit1_分子泵通断插板阀原位", "Y1033", "Unit1_气囊通断阀"},
            {"X1024", "Unit1_分子泵通断插板阀到位", "Y1034", ""},
            {"X1025", "Unit1_腔体托片左气缸原位", "Y1035", "Unit1_腔体托片左气缸原位"},
            {"X1026", "Unit1_腔体托片左气缸到位", "Y1036", "Unit1_腔体托片左气缸到位"},
            {"X1027", "Unit1_腔体托片右气缸原位", "Y1037", "Unit1_腔体托片右气缸原位"},
            {"X1028", "Unit1_腔体托片右气缸到位", "Y1038", "Unit1_腔体托片右气缸到位"},
            {"X1029", "Unit1_门阀升降气缸原位", "Y1039", "Unit1_门阀升降气缸"},
            {"X102A", "Unit1_门阀升降气缸到位", "Y103A", ""},
            {"X102B", "Unit1_腔体破真空气阀原位", "Y103B", "Unit1_腔体破真空气阀"},
            {"X102C", "Unit1_腔体破真空气阀到位", "Y103C", "Unit1_分子泵排气阀"},
            {"X102D", "Unit1_下腔平台真空检", "Y103D", "Unit1_下腔平台吸真空"},
            {"X102E", "Unit1_分子泵排气阀原位", "Y103E", "Unit1_下腔平台破真空"},
            {"X102F", "Unit1_分子泵排气阀到位", "Y103F", ""},
            {"X1040", "Unit1_上加热已上电", "Y1050", "Unit1_上加热上电"},
            {"X1041", "Unit1_上主温控表报警", "Y1051", "Unit1_下加热上电"},
            {"X1042", "Unit1_上监控温控表报警1", "Y1052", ""},
            {"X1043", "Unit1_上监控温控表报警2", "Y1053", ""},
            {"X1044", "Unit1_上监控温控表报警3", "Y1054", ""},
            {"X1045", "Unit1_上监控温控表报警4", "Y1055", ""},
            {"X1046", "Unit1_上监控温控表报警5", "Y1056", ""},
            {"X1047", "Unit1_下加热已上电", "Y1057", ""},
            {"X1048", "Unit1_下主温控表报警", "Y1058", ""},
            {"X1049", "Unit1_下监控温控表报警1", "Y1059", ""},
            {"X104A", "Unit1_下监控温控表报警2", "Y105A", ""},
            {"X104B", "Unit1_下监控温控表报警3", "Y105B", ""},
            {"X104C", "Unit1_下监控温控表报警4", "Y105C", ""},
            {"X104D", "Unit1_下监控温控表报警5", "Y105D", ""},
            {"X104E", "", "Y105E", ""},
            {"X104F", "", "Y105F", ""},
            {"X1060", "Unit1_干泵-DVP运行检测-11", "Y1070", "Unit1_干泵-DVP启动-1"},
            {"X1061", "Unit1_干泵-MBP运行检测-12", "Y1071", "Unit1_干泵-MBP启动-2"},
            {"X1062", "Unit1_干泵-错误报警中-14", "Y1072", "Unit1_干泵-异常解除-3"},
            {"X1063", "Unit1_干泵-错误警告中-16", "Y1073", ""},
            {"X1064", "Unit1_干泵-远程/本地模式-18", "Y1074", "Unit1_氮气通断电磁阀1"},
            {"X1065", "Unit1_干泵-紧急停止中-20", "Y1075", "Unit1_氮气通断电磁阀2"},
            {"X1066", "", "Y1076", "Unit1_氮气通断电磁阀3"},
            {"X1067", "", "Y1077", "Unit1_氮气通断电磁阀4"},
            {"X1068", "", "Y1078", "Unit1_加热板水冷通断电磁阀1"},
            {"X1069", "", "Y1079", "Unit1_加热板水冷通断电磁阀2"},
            {"X106A", "", "Y107A", "Unit1_加热板水冷通断电磁阀3"},
            {"X106B", "", "Y107B", "Unit1_加热板水冷通断电磁阀4"},
            {"X106C", "", "Y107C", "Unit1_腔体底板通断电磁阀1"},
            {"X106D", "Unit1_水箱上液位检", "Y107D", "Unit1_腔体底板通断电磁阀2"},
            {"X106E", "Unit1_水箱中液位检", "Y107E", "Unit1_水箱进水阀"},
            {"X106F", "Unit1_水箱下液位检", "Y107F", "Unit1_水箱出水阀"},
            {"X1080", "Unit2_急停 EMO", "Y1090", "Unit2_四色灯-红"},
            {"X1081", "Unit2_总进气压力检", "Y1091", "Unit2_四色灯-黄"},
            {"X1082", "Unit2_伺服电柜烟感报警", "Y1092", "Unit2_四色灯-绿"},
            {"X1083", "Unit2_加热电柜烟感报警", "Y1093", "Unit2_四色灯-蓝"},
            {"X1084", "安全继电器检", "Y1094", "Unit2_蜂鸣器-1"},
            {"X1085", "", "Y1095", "Unit2_蜂鸣器-2"},
            {"X1086", "", "Y1096", "Unit2_蜂鸣器-3"},
            {"X1087", "Unit2_安全门磁检1", "Y1097", "Unit2_蜂鸣器-4"},
            {"X1088", "Unit2_安全门磁检2", "Y1098", "Unit2_机台照明"},
            {"X1089", "Unit2_安全门磁检3", "Y1099", "Unit2_安全门锁屏蔽"},
            {"X108A", "Unit2_安全门磁检4", "Y109A", ""},
            {"X108B", "Unit2_安全门磁检5", "Y109B", ""},
            {"X108C", "Unit2_安全门磁检6", "Y109C", ""},
            {"X108D", "Unit2_安全门锁检1", "Y109D", "Unit2_安全门锁1"},
            {"X108E", "Unit2_安全门锁检2", "Y109E", "Unit2_安全门锁2"},
            {"X108F", "Unit2_安全门锁检3", "Y109F", "Unit2_安全门锁3"},
            {"X10A0", "Unit2_分子泵-Alam(8-14)", "Y10B0", "Unit2_分子泵启动(1-9)"},
            {"X10A1", "Unit2_分子泵-远程/本地模式(7-15)", "Y10B1", "Unit2_分子泵联锁装置(2-10)"},
            {"X10A2", "Unit2_分子泵-正常运行(4-12)", "Y10B2", "Unit2_分子泵通断插板阀"},
            {"X10A3", "", "Y10B3", "Unit2_气囊通断阀"},
            {"X10A4", "", "Y10B4", ""},
            {"X10A5", "Unit2_腔体托片左气缸原位", "Y10B5", "Unit2_腔体托片左气缸原位"},
            {"X10A6", "Unit2_腔体托片左气缸到位", "Y10B6", "Unit2_腔体托片左气缸到位"},
            {"X10A7", "Unit2_腔体托片右气缸原位", "Y10B7", "Unit2_腔体托片右气缸原位"},
            {"X10A8", "Unit2_腔体托片右气缸到位", "Y10B8", "Unit2_腔体托片右气缸到位"},
            {"X10A9", "Unit2_门阀升降气缸原位", "Y10B9", "Unit2_门阀升降气缸"},
            {"X10AA", "Unit2_门阀升降气缸到位", "Y10BA", ""},
            {"X10AB", "Unit2_腔体破真空气阀原位", "Y10BB", "Unit2_腔体破真空气阀"},
            {"X10AC", "Unit2_腔体破真空气阀到位", "Y10BC", "Unit2_分子泵排气阀"},
            {"X10AD", "Unit2_下腔平台真空检", "Y10BD", "Unit2_下腔平台吸真空"},
            {"X10AE", "Unit2_分子泵排气阀原位", "Y10BE", "Unit2_下腔平台破真空"},
            {"X10AF", "Unit2_分子泵排气阀到位", "Y10BF", ""},
            {"X10C0", "Unit2_上加热已上电", "Y10D0", "Unit2_上加热上电"},
            {"X10C1", "Unit2_上主温控表报警", "Y10D1", "Unit2_下加热上电"},
            {"X10C2", "Unit2_上监控温控表报警1", "Y10D2", ""},
            {"X10C3", "Unit2_上监控温控表报警2", "Y10D3", ""},
            {"X10C4", "Unit2_上监控温控表报警3", "Y10D4", ""},
            {"X10C5", "Unit2_上监控温控表报警4", "Y10D5", ""},
            {"X10C6", "Unit2_上监控温控表报警5", "Y10D6", ""},
            {"X10C7", "Unit2_下加热已上电", "Y10D7", ""},
            {"X10C8", "Unit2_下主温控表报警", "Y10D8", ""},
            {"X10C9", "Unit2_下监控温控表报警1", "Y10D9", ""},
            {"X10CA", "Unit2_下监控温控表报警2", "Y10DA", ""},
            {"X10CB", "Unit2_下监控温控表报警3", "Y10DB", ""},
            {"X10CC", "Unit2_下监控温控表报警4", "Y10DC", ""},
            {"X10CD", "Unit2_下监控温控表报警5", "Y10DD", ""},
            {"X10CE", "", "Y10DE", ""},
            {"X10CF", "", "Y10DF", ""},
            {"X10E0", "Unit2_干泵-DVP运行检测-11", "Y10F0", "Unit2_干泵-DVP启动-1"},
            {"X10E1", "Unit2_干泵-MBP运行检测-12", "Y10F1", "Unit2_干泵-MBP启动-2"},
            {"X10E2", "Unit2_干泵-错误报警中-14", "Y10F2", "Unit2_干泵-异常解除-3"},
            {"X10E3", "Unit2_干泵-错误警告中-16", "Y10F3", ""},
            {"X10E4", "Unit2_干泵-远程/本地模式-18", "Y10F4", "Unit2_氮气通断电磁阀1"},
            {"X10E5", "Unit2_干泵-紧急停止中-20", "Y10F5", "Unit2_氮气通断电磁阀2"},
            {"X10E6", "", "Y10F6", "Unit2_氮气通断电磁阀3"},
            {"X10E7", "", "Y10F7", "Unit2_氮气通断电磁阀4"},
            {"X10E8", "", "Y10F8", "Unit2_加热板水冷通断电磁阀1"},
            {"X10E9", "", "Y10F9", "Unit2_加热板水冷通断电磁阀2"},
            {"X10EA", "", "Y10FA", "Unit2_加热板水冷通断电磁阀3"},
            {"X10EB", "", "Y10FB", "Unit2_加热板水冷通断电磁阀4"},
            {"X10EC", "", "Y10FC", "Unit2_腔体底板通断电磁阀1"},
            {"X10ED", "Unit2_水箱上液位检", "Y10FD", "Unit2_腔体底板通断电磁阀2"},
            {"X10EE", "Unit2_水箱中液位检", "Y10FE", "Unit2_水箱进水阀"},
            {"X10EF", "Unit2_水箱下液位检", "Y10FF", "Unit2_水箱出水阀"}
        };
        m_machines[machineName] = defaultData;
    }
    else if (machineName == "VacuumBake") {
        std::vector<IOData> defaultData = {
            {"X1100", "急停 EMO", "Y1110", "四色灯-红"},
            {"X1101", "总进气压力检", "Y1111", "四色灯-黄"},
            {"X1102", "A加热电柜烟感报警", "Y1112", "四色灯-绿"},
            {"X1103", "B加热电柜烟感报警", "Y1113", "四色灯-蓝"},
            {"X1104", "安全继电器检", "Y1114", "蜂鸣器-1"},
            {"X1105", "", "Y1115", "蜂鸣器-2"},
            {"X1106", "", "Y1116", "蜂鸣器-3"},
            {"X1107", "", "Y1117", "蜂鸣器-4"},
            {"X1108", "", "Y1118", "机台照明"},
            {"X1109", "", "Y1119", "安全门锁屏蔽"},
            {"X110A", "安全门磁检1", "Y111A", ""},
            {"X110B", "安全门磁检2", "Y111B", ""},
            {"X110C", "安全门锁检1", "Y111C", "安全门锁1"},
            {"X110D", "安全门锁检2", "Y111D", "安全门锁2"},
            {"X110E", "安全门锁检3", "Y111E", "安全门锁3"},
            {"X110F", "安全门锁检4", "Y111F", "安全门锁4"},
            {"X1120", "A腔门阀升降气缸原位", "Y1130", "A腔门阀升降气缸"},
            {"X1121", "A腔门阀升降气缸到位", "Y1131", ""},
            {"X1122", "A腔腔体总吸真空气阀原位", "Y1132", "A腔腔体总吸真空气阀"},
            {"X1123", "A腔腔体总吸真空气阀到位", "Y1133", "A腔腔体总破真空气阀"},
            {"X1124", "A腔腔体总破真空气阀原位", "Y1134", "A腔冷却水阀"},
            {"X1125", "A腔腔体总破真空气阀到位", "Y1135", ""},
            {"X1126", "A腔加热已上电", "Y1136", "A腔加热上电"},
            {"X1127", "A腔主温控表报警", "Y1137", ""},
            {"X1128", "A腔监控温控表报警1", "Y1138", ""},
            {"X1129", "A腔监控温控表报警2", "Y1139", ""},
            {"X112A", "A腔监控温控表报警3", "Y113A", ""},
            {"X112B", "A腔监控温控表报警4", "Y113B", ""},
            {"X112C", "A腔监控温控表报警5", "Y113C", ""},
            {"X112D", "", "Y113D", ""},
            {"X112E", "", "Y113E", ""},
            {"X112F", "", "Y113F", ""},
            {"X1140", "B腔门阀升降气缸原位", "Y1150", "B腔门阀升降气缸"},
            {"X1141", "B腔门阀升降气缸到位", "Y1151", ""},
            {"X1142", "B腔腔体总吸真空气阀原位", "Y1152", "B腔腔体总吸真空气阀"},
            {"X1143", "B腔腔体总吸真空气阀到位", "Y1153", "B腔腔体总破真空气阀"},
            {"X1144", "B腔腔体总破真空气阀原位", "Y1154", "B腔冷却水阀"},
            {"X1145", "B腔腔体总破真空气阀到位", "Y1155", ""},
            {"X1146", "B腔加热已上电", "Y1156", "B腔加热上电"},
            {"X1147", "B腔主温控表报警", "Y1157", ""},
            {"X1148", "B腔监控温控表报警1", "Y1158", ""},
            {"X1149", "B腔监控温控表报警2", "Y1159", ""},
            {"X114A", "B腔监控温控表报警3", "Y115A", ""},
            {"X114B", "B腔监控温控表报警4", "Y115B", ""},
            {"X114C", "B腔监控温控表报警5", "Y115C", ""},
            {"X114D", "", "Y115D", ""},
            {"X114E", "", "Y115E", ""},
            {"X114F", "", "Y115F", ""},
            {"X1160", "干泵-DVP运行检测-11", "Y1170", "干泵-DVP启动-1"},
            {"X1161", "干泵-MBP运行检测-12", "Y1171", "干泵-MBP启动-2"},
            {"X1162", "干泵-错误报警中-14", "Y1172", "干泵-异常解除-3"},
            {"X1163", "干泵-错误警告中-16", "Y1173", ""},
            {"X1164", "干泵-远程/本地模式-18", "Y1174", ""},
            {"X1165", "干泵-紧急停止中-20", "Y1175", ""},
            {"X1166", "", "Y1176", ""},
            {"X1167", "", "Y1177", ""},
            {"X1168", "", "Y1178", ""},
            {"X1169", "", "Y1179", ""},
            {"X116A", "", "Y117A", ""},
            {"X116B", "", "Y117B", ""},
            {"X116C", "", "Y117C", ""},
            {"X116D", "", "Y117D", ""},
            {"X116E", "", "Y117E", ""},
            {"X116F", "", "Y117F", ""}
        };
        m_machines[machineName] = defaultData;
    }
    else if (machineName == "AfterBake") {
        std::vector<IOData> defaultData = {
            {"X200", "急停 EMO", "Y400", "四色灯-红"},
            {"X201", "总进气压力检", "Y401", "四色灯-黄"},
            {"X202", "A加热电柜烟感报警", "Y402", "四色灯-绿"},
            {"X203", "B加热电柜烟感报警", "Y403", "四色灯-蓝"},
            {"X204", "安全继电器检", "Y404", "蜂鸣器-1"},
            {"X205", "上电箱温控报警", "Y405", "蜂鸣器-2"},
            {"X206", "下电箱温控报警", "Y406", "蜂鸣器-3"},
            {"X207", "", "Y407", "蜂鸣器-4"},
            {"X208", "安全门磁检1", "Y408", "机台照明"},
            {"X209", "安全门磁检2", "Y409", "安全门锁屏蔽"},
            {"X20A", "安全门磁检3", "Y40A", ""},
            {"X20B", "安全门磁检4", "Y40B", ""},
            {"X20C", "安全门锁检1", "Y40C", "安全门锁1"},
            {"X20D", "安全门锁检2", "Y40D", "安全门锁2"},
            {"X20E", "安全门锁检3", "Y40E", "安全门锁3"},
            {"X20F", "安全门锁检4", "Y40F", "安全门锁4"},
            {"X210", "A上腔夹持气缸1原位", "Y410", "A上腔夹持气缸"},
            {"X211", "A上腔夹持气缸1到位", "Y411", ""},
            {"X212", "A上腔夹持气缸2原位", "Y412", "A腔水路通断阀"},
            {"X213", "A上腔夹持气缸2到位", "Y413", ""},
            {"X214", "A下腔加热已上电", "Y414", ""},
            {"X215", "A下主温控表报警", "Y415", ""},
            {"X216", "A下腔监控温控表报警1", "Y416", ""},
            {"X217", "A下腔监控温控表报警2", "Y417", ""},
            {"X218", "A下腔监控温控表报警3", "Y418", ""},
            {"X219", "A下腔监控温控表报警4", "Y419", ""},
            {"X21A", "A下腔监控温控表报警5", "Y41A", ""},
            {"X21B", "", "Y41B", ""},
            {"X21C", "腔体左上门磁", "Y41C", ""},
            {"X21D", "腔体左下门磁", "Y41D", ""},
            {"X21E", "腔体右上门磁", "Y41E", ""},
            {"X21F", "腔体右下门磁", "Y41F", ""},
            {"X220", "B上腔夹持气缸1原位", "Y420", "B上腔夹持气缸"},
            {"X221", "B上腔夹持气缸1到位", "Y421", ""},
            {"X222", "B上腔夹持气缸2原位", "Y422", "B腔水路通断阀"},
            {"X223", "B上腔夹持气缸2到位", "Y423", ""},
            {"X224", "B下腔加热已上电", "Y424", ""},
            {"X225", "B下主温控表报警", "Y425", ""},
            {"X226", "B下腔监控温控表报警1", "Y426", ""},
            {"X227", "B下腔监控温控表报警2", "Y427", ""},
            {"X228", "B下腔监控温控表报警3", "Y428", ""},
            {"X229", "B下腔监控温控表报警4", "Y429", ""},
            {"X22A", "B下腔监控温控表报警5", "Y42A", ""},
            {"X22B", "", "Y42B", ""},
            {"X22C", "A上腔有料检", "Y42C", ""},
            {"X22D", "", "Y42D", ""},
            {"X22E", "", "Y42E", ""},
            {"X22F", "", "Y42F", ""}
        };
        m_machines[machineName] = defaultData;
    }
    else if (machineName == "AOI") {
        std::vector<IOData> defaultData = {
            {"X240", "急停 EMO", "Y440", "四色灯-红"},
            {"X241", "总进气压力表", "Y441", "四色灯-黄"},
            {"X242", "烟感报警", "Y442", "四色灯-绿"},
            {"X243", "", "Y443", "四色灯-蓝"},
            {"X244", "", "Y444", "蜂鸣器-1"},
            {"X245", "左上门磁检", "Y445", "蜂鸣器-2"},
            {"X246", "左下门磁检", "Y446", "蜂鸣器-3"},
            {"X247", "右上门磁检", "Y447", "蜂鸣器-4"},
            {"X248", "右下门磁检", "Y448", "机台照明"},
            {"X249", "安全门磁检1", "Y449", "安全门锁屏蔽"},
            {"X24A", "安全门磁检2", "Y44A", ""},
            {"X24B", "安全门锁检1", "Y44B", "安全门锁1"},
            {"X24C", "安全门锁检2", "Y44C", "安全门锁2"},
            {"X24D", "检测搬臂压力检", "Y44D", ""},
            {"X24E", "检测平台真空检", "Y44E", "检测平台吸真空"},
            {"X24F", "检测平台有料检", "Y44F", "检测平台破真空"},
            {"X250", "检测平台对位气缸A1原位", "Y450", "检测平台对位气缸A"},
            {"X251", "检测平台对位气缸A1到位", "Y451", ""},
            {"X252", "检测平台对位气缸A2原位", "Y452", ""},
            {"X253", "检测平台对位气缸A2到位", "Y453", ""},
            {"X254", "检测平台对位升降气缸A1原位", "Y454", "检测平台对位升降气缸A"},
            {"X255", "检测平台对位升降气缸A1到位", "Y455", ""},
            {"X256", "检测平台对位升降气缸A2原位", "Y456", ""},
            {"X257", "检测平台对位升降气缸A2到位", "Y457", ""},
            {"X258", "检测平台对位气缸B1原位", "Y458", "检测平台对位气缸B"},
            {"X259", "检测平台对位气缸B1到位", "Y459", ""},
            {"X25A", "检测平台对位气缸B2原位", "Y45A", ""},
            {"X25B", "检测平台对位气缸B2到位", "Y45B", ""},
            {"X25C", "检测平台对位升降气缸B1原位", "Y45C", "检测平台对位升降气缸B"},
            {"X25D", "检测平台对位升降气缸B1到位", "Y45D", ""},
            {"X25E", "检测平台对位升降气缸B2原位", "Y45E", ""},
            {"X25F", "检测平台对位升降气缸B2到位", "Y45F", ""},
            {"X260", "", "Y460", ""},
            {"X261", "", "Y461", ""},
            {"X262", "", "Y462", ""},
            {"X263", "", "Y463", ""},
            {"X264", "", "Y464", ""},
            {"X265", "", "Y465", ""},
            {"X266", "", "Y466", ""},
            {"X267", "", "Y467", ""},
            {"X268", "", "Y468", ""},
            {"X269", "", "Y469", ""},
            {"X26A", "", "Y46A", ""},
            {"X26B", "", "Y46B", ""},
            {"X26C", "", "Y46C", ""},
            {"X26D", "", "Y46D", ""},
            {"X26E", "", "Y46E", ""},
            {"X26F", "", "Y46F", ""}
        };
        m_machines[machineName] = defaultData;
    }
}
void IOManager::saveToFile(const std::string& machineName) {
    std::ofstream file(m_directory + "/" + machineName + ".iom");
    if (!file.is_open()) {
        std::cerr << "Failed to open file for writing: " << machineName << ".iom" << std::endl;
        return;
    }
    for (const auto& entry : m_machines[machineName]) {
        file << entry.inputAddress << ","
            << entry.inputDescription << ","
            << entry.outputAddress << ","
            << entry.outputDescription << "\n";
    }
    file.close();
}
bool IOManager::loadFromFile(const std::string& machineName) {
    std::ifstream file(m_directory + "/" + machineName + ".iom");
    if (!file.is_open()) {
        std::cerr << "Failed to open file for reading: " << machineName << ".iom" << std::endl;
        return false;
    }
    std::vector<IOData> data;
    std::string line;
    while (std::getline(file, line)) {
        IOData entry;
        size_t pos = 0;
        pos = line.find(",");
        entry.inputAddress = line.substr(0, pos);
        line.erase(0, pos + 1);
        pos = line.find(",");
        entry.inputDescription = line.substr(0, pos);
        line.erase(0, pos + 1);
        pos = line.find(",");
        entry.outputAddress = line.substr(0, pos);
        line.erase(0, pos + 1);
        entry.outputDescription = line;
        data.push_back(entry);
    }
    m_machines[machineName] = data;
    file.close();
    return true;
}
void IOManager::printMachineData(const std::string& machineName) const {
    auto it = m_machines.find(machineName);
    if (it != m_machines.end()) {
        for (const auto& entry : it->second) {
            std::cout << "Input Address: " << entry.inputAddress
                << ", Input Description: " << entry.inputDescription
                << ", Output Address: " << entry.outputAddress
                << ", Output Description: " << entry.outputDescription << std::endl;
        }
    }
    else {
        std::cerr << "Machine not found: " << machineName << std::endl;
    }
}
std::vector<IOData> IOManager::GetMachineData(const std::string& machineName) const
{
    auto it = m_machines.find(machineName);
    if (it != m_machines.end()) {
        return it->second;
    }
    return {};
}
SourceCode/Bond/BondEq/FileManager/IOManager.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,31 @@
#ifndef IOMANAGER_H
#define IOMANAGER_H
#include <string>
#include <vector>
#include <map>
struct IOData {
    std::string inputAddress;
    std::string inputDescription;
    std::string outputAddress;
    std::string outputDescription;
};
class IOManager {
public:
    IOManager();
    void addMachine(const std::string& machineName, const std::vector<IOData>& data);
    void addDefaultMachineData(const std::string& machineName);
    void saveToFile(const std::string& machineName);
    bool loadFromFile(const std::string& machineName);
    void printMachineData(const std::string& machineName) const;
    std::vector<IOData> GetMachineData(const std::string& machineName) const;
private:
    std::string m_directory;
    std::map<std::string, std::vector<IOData>> m_machines;
};
#endif // IOMANAGER_H
SourceCode/Bond/BondEq/FileManager/RecipeManager.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,213 @@
#include "stdafx.h"
#include <sstream>
#include <fstream>
#include <iostream>
// å•例获取
RecipeManager& RecipeManager::getInstance() {
    static RecipeManager instance;
    return instance;
}
// æž„造函数
RecipeManager::RecipeManager() : m_recipeFolder("Recipe") {}
// è®¾ç½®é…æ–¹æ–‡ä»¶å¤¹
void RecipeManager::setRecipeFolder(const std::string& folderPath) {
    m_recipeFolder = folderPath;
}
// åŠ è½½é…æ–¹ï¼ˆå¦‚æžœæ–‡ä»¶ä¸å­˜åœ¨ï¼ŒåŠ è½½é»˜è®¤æ•°æ®ï¼‰
bool RecipeManager::loadRecipe(const std::string& recipeName) {
    std::string filePath = m_recipeFolder + "/" + recipeName + ".xml";
    pugi::xml_document doc;
    if (!doc.load_file(filePath.c_str())) {
        std::cerr << "Recipe file not found: " << filePath << ". Loading default recipe." << std::endl;
        generateDefaultRecipe();
        return false; // æ–‡ä»¶ä¸å­˜åœ¨ï¼Œä½†åŠ è½½äº†é»˜è®¤æ•°æ®
    }
    m_axes.clear();
    auto recipe = doc.child("Recipe");
    for (auto axisNode : recipe.child("Axes").children("Axis")) {
        AxisInfo axisInfo;
        axisInfo.id = axisNode.attribute("id").as_int();
        axisInfo.number = axisNode.attribute("number").value();
        axisInfo.description = axisNode.attribute("description").value();
        axisInfo.startAddress = axisNode.attribute("start_address").value();
        axisInfo.jogDistance = axisNode.attribute("jog_distance").as_double();
        axisInfo.manualSpeed = axisNode.attribute("manual_speed").as_double();
        axisInfo.autoSpeed = axisNode.attribute("auto_speed").as_double();
        axisInfo.accelerationTime = axisNode.attribute("acceleration_time").as_double();
        axisInfo.decelerationTime = axisNode.attribute("deceleration_time").as_double();
        for (auto positionNode : axisNode.child("Positions").children("Position")) {
            std::string description = positionNode.attribute("description").value();
            double positionValue = positionNode.attribute("value").as_double();
            axisInfo.positions.emplace_back(description, positionValue);
        }
        m_axes[axisInfo.id] = axisInfo;
    }
    return true;
}
// ä¿å­˜é…æ–¹
bool RecipeManager::saveRecipe(const std::string& recipeName) {
    // ç”Ÿæˆæ–‡ä»¶è·¯å¾„
    std::string filePath = m_recipeFolder + "/" + recipeName + ".xml";
    // åˆ›å»º XML æ–‡æ¡£å¯¹è±¡
    pugi::xml_document doc;
    // å¦‚果轴数据为空,生成默认配方
    if (m_axes.empty()) {
        generateDefaultRecipe();
    }
    // æ·»åŠ é…æ–¹æ ¹èŠ‚ç‚¹
    auto recipe = doc.append_child("Recipe");
    // æ·»åŠ è½´åˆ—è¡¨èŠ‚ç‚¹
    auto axesNode = recipe.append_child("Axes");
    // éåŽ†æ‰€æœ‰è½´æ•°æ®å¹¶å†™å…¥ XML
    for (const auto& axisEntry : m_axes) {
        const AxisInfo& axisInfo = axisEntry.second;
        auto axisNode = axesNode.append_child("Axis");
        axisNode.append_attribute("id") = axisInfo.id;
        axisNode.append_attribute("number") = axisInfo.number.c_str();
        axisNode.append_attribute("description") = axisInfo.description.c_str();
        axisNode.append_attribute("start_address") = axisInfo.startAddress.c_str();
        axisNode.append_attribute("jog_distance") = axisInfo.jogDistance;
        axisNode.append_attribute("manual_speed") = axisInfo.manualSpeed;
        axisNode.append_attribute("auto_speed") = axisInfo.autoSpeed;
        axisNode.append_attribute("acceleration_time") = axisInfo.accelerationTime;
        axisNode.append_attribute("deceleration_time") = axisInfo.decelerationTime;
        // æ·»åŠ å®šä½ç‚¹åˆ—è¡¨
        auto positionsNode = axisNode.append_child("Positions");
        for (const auto& position : axisInfo.positions) {
            auto positionNode = positionsNode.append_child("Position");
            positionNode.append_attribute("description") = position.first.c_str();
            positionNode.append_attribute("value") = position.second;
        }
    }
    // ä¿å­˜ XML æ–‡ä»¶
    return doc.save_file(filePath.c_str());
}
// ç”Ÿæˆé»˜è®¤é…æ–¹
void RecipeManager::generateDefaultRecipe() {
    m_axes.clear();
    for (int axisId = 1; axisId <= 12; ++axisId) {
        AxisInfo axisInfo;
        axisInfo.id = axisId;
        axisInfo.number = "M100-M" + std::to_string(axisId);
        axisInfo.description = "Default_Axis" + std::to_string(axisId);
        axisInfo.startAddress = "D" + std::to_string(5000 + axisId * 10);
        axisInfo.jogDistance = 0.5;
        axisInfo.manualSpeed = 10.0;
        axisInfo.autoSpeed = 15.0;
        axisInfo.accelerationTime = 0.2;
        axisInfo.decelerationTime = 0.3;
        for (int posId = 1; posId <= 25; ++posId) {
            axisInfo.positions.emplace_back("Position " + std::to_string(posId), posId * 10.0);
        }
        m_axes[axisId] = axisInfo;
    }
}
// èŽ·å–æ‰€æœ‰è½´ä¿¡æ¯
const std::map<int, AxisInfo>& RecipeManager::getAxes() const {
    return m_axes;
}
// èŽ·å–å•ä¸ªè½´ä¿¡æ¯
AxisInfo RecipeManager::getAxis(int axisId) const {
    auto it = m_axes.find(axisId);
    if (it != m_axes.end()) {
        return it->second;
    }
    // è¿”回一个无效的 AxisInfo
    return AxisInfo{ -1, "", "", "", 0.0, 0.0, 0.0, 0.0, 0.0, {}};
}
// æ›´æ–°è½´ä¿¡æ¯
bool RecipeManager::updateAxis(const AxisInfo& axisInfo) {
    if (m_axes.find(axisInfo.id) == m_axes.end()) {
        return false; // è½´ä¸å­˜åœ¨
    }
    m_axes[axisInfo.id] = axisInfo;
    return true;
}
// æ·»åŠ æ–°çš„è½´ä¿¡æ¯
bool RecipeManager::addAxis(const AxisInfo& axisInfo) {
    if (m_axes.find(axisInfo.id) != m_axes.end()) {
        return false; // è½´å·²å­˜åœ¨
    }
    m_axes[axisInfo.id] = axisInfo;
    return true;
}
// åˆ é™¤è½´ä¿¡æ¯
bool RecipeManager::deleteAxis(int axisId) {
    return m_axes.erase(axisId) > 0;
}
// èŽ·å–æ‰€æœ‰è½´ç¼–å·
std::vector<int> RecipeManager::getAllAxisID() const {
    std::vector<int> axisNumbers;
    for (const auto& axis : m_axes) {
        int axisId = axis.first;
        axisNumbers.push_back(axisId);
    }
    return axisNumbers;
}
// èŽ·å–æŒ‡å®šé¡µçš„å®šä½ç‚¹
std::vector<std::pair<std::string, double>> RecipeManager::getPositions(int axisId, int pageNumber, int pageSize) const {
    std::vector<std::pair<std::string, double>> result;
    // æ£€æŸ¥è½´æ˜¯å¦å­˜åœ¨
    auto it = m_axes.find(axisId);
    if (it == m_axes.end()) {
        return result; // å¦‚果轴 ID ä¸å­˜åœ¨ï¼Œè¿”回空结果
    }
    // èŽ·å–æŒ‡å®šè½´çš„æ‰€æœ‰å®šä½ç‚¹
    const auto& positions = it->second.positions;
    // ç¡®å®šåˆ†é¡µèŒƒå›´
    int startIndex = (pageNumber - 1) * pageSize;
    int endIndex = startIndex + pageSize;
    // éåŽ†å®šä½ç‚¹ï¼ŒæŒ‰åˆ†é¡µæå–æ•°æ®
    int index = 0;
    for (const auto& pos : positions) {
        const std::string& description = pos.first; // é”®ï¼šæè¿°
        double value = pos.second;                  // å€¼ï¼šä½ç½®å€¼
        if (index >= startIndex && index < endIndex) {
            result.emplace_back(description, value);
        }
        ++index;
        if (index >= endIndex) {
            break; // è¾¾åˆ°åˆ†é¡µç»“束点
        }
    }
    return result;
}
SourceCode/Bond/BondEq/FileManager/RecipeManager.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,70 @@
#ifndef RECIPE_MANAGER_H
#define RECIPE_MANAGER_H
#include <string>
#include <vector>
#include <map>
#include "pugixml.hpp"
// è½´ä¿¡æ¯ç»“构体
struct AxisInfo {
    int id;                                    // è½´ID
    std::string number;                        // è½´ç¼–号
    std::string description;                   // è½´æè¿°
    std::string startAddress;                  // èµ·å§‹åœ°å€
    double jogDistance;                        // å¾®åŠ¨é‡
    double manualSpeed;                        // æ‰‹åŠ¨é€Ÿåº¦
    double autoSpeed;                          // è‡ªåŠ¨é€Ÿåº¦
    double accelerationTime;                   // åŠ é€Ÿæ—¶é—´
    double decelerationTime;                   // å‡é€Ÿæ—¶é—´
    std::vector<std::pair<std::string, double>> positions; // å®šä½ç‚¹ï¼šæè¿°å’Œä½ç½®
};
// é…æ–¹ç®¡ç†ç±»
class RecipeManager {
public:
    // å•例模式获取实例
    static RecipeManager& getInstance();
    // è®¾ç½®é…æ–¹æ–‡ä»¶å¤¹è·¯å¾„
    void setRecipeFolder(const std::string& folderPath);
    // åŠ è½½é…æ–¹ï¼ˆæ–‡ä»¶ä¸å­˜åœ¨æ—¶åŠ è½½é»˜è®¤æ•°æ®ï¼‰
    bool loadRecipe(const std::string& recipeName);
    // ä¿å­˜é…æ–¹
    bool saveRecipe(const std::string& recipeName);
    // ç”Ÿæˆé»˜è®¤é…æ–¹
    void generateDefaultRecipe();
    // èŽ·å–æ‰€æœ‰è½´ä¿¡æ¯
    const std::map<int, AxisInfo>& getAxes() const;
    // èŽ·å–å•ä¸ªè½´ä¿¡æ¯
    AxisInfo getAxis(int axisId) const;
    // æ›´æ–°è½´ä¿¡æ¯
    bool updateAxis(const AxisInfo& axisInfo);
    // æ·»åŠ æ–°çš„è½´ä¿¡æ¯
    bool addAxis(const AxisInfo& axisInfo);
    // åˆ é™¤è½´ä¿¡æ¯
    bool deleteAxis(int axisId);
    // èŽ·å–æ‰€æœ‰è½´ID
    std::vector<int> getAllAxisID() const;
    // èŽ·å–æŒ‡å®šé¡µçš„å®šä½ç‚¹
    std::vector<std::pair<std::string, double>> getPositions(int axisId, int pageNumber, int pageSize) const;
private:
    RecipeManager();
private:
    std::string m_recipeFolder;      // é…æ–¹æ–‡ä»¶å¤¹è·¯å¾„
    std::map<int, AxisInfo> m_axes;  // è½´ä¿¡æ¯ç¼“å­˜
};
#endif // RECIPE_MANAGER_H
SourceCode/Bond/BondEq/FileManager/pugiconfig.hpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,77 @@
/**
 * pugixml parser - version 1.14
 * --------------------------------------------------------
 * Copyright (C) 2006-2023, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
 * Report bugs and download new versions at https://pugixml.org/
 *
 * This library is distributed under the MIT License. See notice at the end
 * of this file.
 *
 * This work is based on the pugxml parser, which is:
 * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
 */
#ifndef HEADER_PUGICONFIG_HPP
#define HEADER_PUGICONFIG_HPP
// Uncomment this to enable wchar_t mode
// #define PUGIXML_WCHAR_MODE
// Uncomment this to enable compact mode
// #define PUGIXML_COMPACT
// Uncomment this to disable XPath
// #define PUGIXML_NO_XPATH
// Uncomment this to disable STL
// #define PUGIXML_NO_STL
// Uncomment this to disable exceptions
// #define PUGIXML_NO_EXCEPTIONS
// Set this to control attributes for public classes/functions, i.e.:
// #define PUGIXML_API __declspec(dllexport) // to export all public symbols from DLL
// #define PUGIXML_CLASS __declspec(dllimport) // to import all classes from DLL
// #define PUGIXML_FUNCTION __fastcall // to set calling conventions to all public functions to fastcall
// In absence of PUGIXML_CLASS/PUGIXML_FUNCTION definitions PUGIXML_API is used instead
// Tune these constants to adjust memory-related behavior
// #define PUGIXML_MEMORY_PAGE_SIZE 32768
// #define PUGIXML_MEMORY_OUTPUT_STACK 10240
// #define PUGIXML_MEMORY_XPATH_PAGE_SIZE 4096
// Tune this constant to adjust max nesting for XPath queries
// #define PUGIXML_XPATH_DEPTH_LIMIT 1024
// Uncomment this to switch to header-only version
// #define PUGIXML_HEADER_ONLY
// Uncomment this to enable long long support
// #define PUGIXML_HAS_LONG_LONG
#endif
/**
 * Copyright (c) 2006-2023 Arseny Kapoulkine
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
SourceCode/Bond/BondEq/FileManager/pugixml.cpp
¶Ô±ÈÐÂÎļþ
ÎļþÌ«´ó
SourceCode/Bond/BondEq/FileManager/pugixml.hpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,1516 @@
/**
 * pugixml parser - version 1.14
 * --------------------------------------------------------
 * Copyright (C) 2006-2023, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
 * Report bugs and download new versions at https://pugixml.org/
 *
 * This library is distributed under the MIT License. See notice at the end
 * of this file.
 *
 * This work is based on the pugxml parser, which is:
 * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
 */
// Define version macro; evaluates to major * 1000 + minor * 10 + patch so that it's safe to use in less-than comparisons
// Note: pugixml used major * 100 + minor * 10 + patch format up until 1.9 (which had version identifier 190); starting from pugixml 1.10, the minor version number is two digits
#ifndef PUGIXML_VERSION
#    define PUGIXML_VERSION 1140 // 1.14
#endif
// Include user configuration file (this can define various configuration macros)
#include "pugiconfig.hpp"
#ifndef HEADER_PUGIXML_HPP
#define HEADER_PUGIXML_HPP
// Include stddef.h for size_t and ptrdiff_t
#include <stddef.h>
// Include exception header for XPath
#if !defined(PUGIXML_NO_XPATH) && !defined(PUGIXML_NO_EXCEPTIONS)
#    include <exception>
#endif
// Include STL headers
#ifndef PUGIXML_NO_STL
#    include <iterator>
#    include <iosfwd>
#    include <string>
#endif
// Macro for deprecated features
#ifndef PUGIXML_DEPRECATED
#    if defined(__GNUC__)
#        define PUGIXML_DEPRECATED __attribute__((deprecated))
#    elif defined(_MSC_VER) && _MSC_VER >= 1300
#        define PUGIXML_DEPRECATED __declspec(deprecated)
#    else
#        define PUGIXML_DEPRECATED
#    endif
#endif
// If no API is defined, assume default
#ifndef PUGIXML_API
#    define PUGIXML_API
#endif
// If no API for classes is defined, assume default
#ifndef PUGIXML_CLASS
#    define PUGIXML_CLASS PUGIXML_API
#endif
// If no API for functions is defined, assume default
#ifndef PUGIXML_FUNCTION
#    define PUGIXML_FUNCTION PUGIXML_API
#endif
// If the platform is known to have long long support, enable long long functions
#ifndef PUGIXML_HAS_LONG_LONG
#    if __cplusplus >= 201103
#        define PUGIXML_HAS_LONG_LONG
#    elif defined(_MSC_VER) && _MSC_VER >= 1400
#        define PUGIXML_HAS_LONG_LONG
#    endif
#endif
// If the platform is known to have move semantics support, compile move ctor/operator implementation
#ifndef PUGIXML_HAS_MOVE
#    if __cplusplus >= 201103
#        define PUGIXML_HAS_MOVE
#    elif defined(_MSC_VER) && _MSC_VER >= 1600
#        define PUGIXML_HAS_MOVE
#    endif
#endif
// If C++ is 2011 or higher, add 'noexcept' specifiers
#ifndef PUGIXML_NOEXCEPT
#    if __cplusplus >= 201103
#        define PUGIXML_NOEXCEPT noexcept
#    elif defined(_MSC_VER) && _MSC_VER >= 1900
#        define PUGIXML_NOEXCEPT noexcept
#    else
#        define PUGIXML_NOEXCEPT
#    endif
#endif
// Some functions can not be noexcept in compact mode
#ifdef PUGIXML_COMPACT
#    define PUGIXML_NOEXCEPT_IF_NOT_COMPACT
#else
#    define PUGIXML_NOEXCEPT_IF_NOT_COMPACT PUGIXML_NOEXCEPT
#endif
// If C++ is 2011 or higher, add 'override' qualifiers
#ifndef PUGIXML_OVERRIDE
#    if __cplusplus >= 201103
#        define PUGIXML_OVERRIDE override
#    elif defined(_MSC_VER) && _MSC_VER >= 1700
#        define PUGIXML_OVERRIDE override
#    else
#        define PUGIXML_OVERRIDE
#    endif
#endif
// If C++ is 2011 or higher, use 'nullptr'
#ifndef PUGIXML_NULL
#    if __cplusplus >= 201103
#        define PUGIXML_NULL nullptr
#    elif defined(_MSC_VER) && _MSC_VER >= 1600
#        define PUGIXML_NULL nullptr
#    else
#        define PUGIXML_NULL 0
#    endif
#endif
// Character interface macros
#ifdef PUGIXML_WCHAR_MODE
#    define PUGIXML_TEXT(t) L ## t
#    define PUGIXML_CHAR wchar_t
#else
#    define PUGIXML_TEXT(t) t
#    define PUGIXML_CHAR char
#endif
namespace pugi
{
    // Character type used for all internal storage and operations; depends on PUGIXML_WCHAR_MODE
    typedef PUGIXML_CHAR char_t;
#ifndef PUGIXML_NO_STL
    // String type used for operations that work with STL string; depends on PUGIXML_WCHAR_MODE
    typedef std::basic_string<PUGIXML_CHAR, std::char_traits<PUGIXML_CHAR>, std::allocator<PUGIXML_CHAR> > string_t;
#endif
}
// The PugiXML namespace
namespace pugi
{
    // Tree node types
    enum xml_node_type
    {
        node_null,            // Empty (null) node handle
        node_document,        // A document tree's absolute root
        node_element,        // Element tag, i.e. '<node/>'
        node_pcdata,        // Plain character data, i.e. 'text'
        node_cdata,            // Character data, i.e. '<![CDATA[text]]>'
        node_comment,        // Comment tag, i.e. '<!-- text -->'
        node_pi,            // Processing instruction, i.e. '<?name?>'
        node_declaration,    // Document declaration, i.e. '<?xml version="1.0"?>'
        node_doctype        // Document type declaration, i.e. '<!DOCTYPE doc>'
    };
    // Parsing options
    // Minimal parsing mode (equivalent to turning all other flags off).
    // Only elements and PCDATA sections are added to the DOM tree, no text conversions are performed.
    const unsigned int parse_minimal = 0x0000;
    // This flag determines if processing instructions (node_pi) are added to the DOM tree. This flag is off by default.
    const unsigned int parse_pi = 0x0001;
    // This flag determines if comments (node_comment) are added to the DOM tree. This flag is off by default.
    const unsigned int parse_comments = 0x0002;
    // This flag determines if CDATA sections (node_cdata) are added to the DOM tree. This flag is on by default.
    const unsigned int parse_cdata = 0x0004;
    // This flag determines if plain character data (node_pcdata) that consist only of whitespace are added to the DOM tree.
    // This flag is off by default; turning it on usually results in slower parsing and more memory consumption.
    const unsigned int parse_ws_pcdata = 0x0008;
    // This flag determines if character and entity references are expanded during parsing. This flag is on by default.
    const unsigned int parse_escapes = 0x0010;
    // This flag determines if EOL characters are normalized (converted to #xA) during parsing. This flag is on by default.
    const unsigned int parse_eol = 0x0020;
    // This flag determines if attribute values are normalized using CDATA normalization rules during parsing. This flag is on by default.
    const unsigned int parse_wconv_attribute = 0x0040;
    // This flag determines if attribute values are normalized using NMTOKENS normalization rules during parsing. This flag is off by default.
    const unsigned int parse_wnorm_attribute = 0x0080;
    // This flag determines if document declaration (node_declaration) is added to the DOM tree. This flag is off by default.
    const unsigned int parse_declaration = 0x0100;
    // This flag determines if document type declaration (node_doctype) is added to the DOM tree. This flag is off by default.
    const unsigned int parse_doctype = 0x0200;
    // This flag determines if plain character data (node_pcdata) that is the only child of the parent node and that consists only
    // of whitespace is added to the DOM tree.
    // This flag is off by default; turning it on may result in slower parsing and more memory consumption.
    const unsigned int parse_ws_pcdata_single = 0x0400;
    // This flag determines if leading and trailing whitespace is to be removed from plain character data. This flag is off by default.
    const unsigned int parse_trim_pcdata = 0x0800;
    // This flag determines if plain character data that does not have a parent node is added to the DOM tree, and if an empty document
    // is a valid document. This flag is off by default.
    const unsigned int parse_fragment = 0x1000;
    // This flag determines if plain character data is be stored in the parent element's value. This significantly changes the structure of
    // the document; this flag is only recommended for parsing documents with many PCDATA nodes in memory-constrained environments.
    // This flag is off by default.
    const unsigned int parse_embed_pcdata = 0x2000;
    // This flag determines whether determines whether the the two pcdata should be merged or not, if no intermediatory data are parsed in the document.
    // This flag is off by default.
    const unsigned int parse_merge_pcdata = 0x4000;
    // The default parsing mode.
    // Elements, PCDATA and CDATA sections are added to the DOM tree, character/reference entities are expanded,
    // End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
    const unsigned int parse_default = parse_cdata | parse_escapes | parse_wconv_attribute | parse_eol;
    // The full parsing mode.
    // Nodes of all types are added to the DOM tree, character/reference entities are expanded,
    // End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
    const unsigned int parse_full = parse_default | parse_pi | parse_comments | parse_declaration | parse_doctype;
    // These flags determine the encoding of input data for XML document
    enum xml_encoding
    {
        encoding_auto,        // Auto-detect input encoding using BOM or < / <? detection; use UTF8 if BOM is not found
        encoding_utf8,        // UTF8 encoding
        encoding_utf16_le,    // Little-endian UTF16
        encoding_utf16_be,    // Big-endian UTF16
        encoding_utf16,        // UTF16 with native endianness
        encoding_utf32_le,    // Little-endian UTF32
        encoding_utf32_be,    // Big-endian UTF32
        encoding_utf32,        // UTF32 with native endianness
        encoding_wchar,        // The same encoding wchar_t has (either UTF16 or UTF32)
        encoding_latin1
    };
    // Formatting flags
    // Indent the nodes that are written to output stream with as many indentation strings as deep the node is in DOM tree. This flag is on by default.
    const unsigned int format_indent = 0x01;
    // Write encoding-specific BOM to the output stream. This flag is off by default.
    const unsigned int format_write_bom = 0x02;
    // Use raw output mode (no indentation and no line breaks are written). This flag is off by default.
    const unsigned int format_raw = 0x04;
    // Omit default XML declaration even if there is no declaration in the document. This flag is off by default.
    const unsigned int format_no_declaration = 0x08;
    // Don't escape attribute values and PCDATA contents. This flag is off by default.
    const unsigned int format_no_escapes = 0x10;
    // Open file using text mode in xml_document::save_file. This enables special character (i.e. new-line) conversions on some systems. This flag is off by default.
    const unsigned int format_save_file_text = 0x20;
    // Write every attribute on a new line with appropriate indentation. This flag is off by default.
    const unsigned int format_indent_attributes = 0x40;
    // Don't output empty element tags, instead writing an explicit start and end tag even if there are no children. This flag is off by default.
    const unsigned int format_no_empty_element_tags = 0x80;
    // Skip characters belonging to range [0; 32) instead of "&#xNN;" encoding. This flag is off by default.
    const unsigned int format_skip_control_chars = 0x100;
    // Use single quotes ' instead of double quotes " for enclosing attribute values. This flag is off by default.
    const unsigned int format_attribute_single_quote = 0x200;
    // The default set of formatting flags.
    // Nodes are indented depending on their depth in DOM tree, a default declaration is output if document has none.
    const unsigned int format_default = format_indent;
    const int default_double_precision = 17;
    const int default_float_precision = 9;
    // Forward declarations
    struct xml_attribute_struct;
    struct xml_node_struct;
    class xml_node_iterator;
    class xml_attribute_iterator;
    class xml_named_node_iterator;
    class xml_tree_walker;
    struct xml_parse_result;
    class xml_node;
    class xml_text;
    #ifndef PUGIXML_NO_XPATH
    class xpath_node;
    class xpath_node_set;
    class xpath_query;
    class xpath_variable_set;
    #endif
    // Range-based for loop support
    template <typename It> class xml_object_range
    {
    public:
        typedef It const_iterator;
        typedef It iterator;
        xml_object_range(It b, It e): _begin(b), _end(e)
        {
        }
        It begin() const { return _begin; }
        It end() const { return _end; }
        bool empty() const { return _begin == _end; }
    private:
        It _begin, _end;
    };
    // Writer interface for node printing (see xml_node::print)
    class PUGIXML_CLASS xml_writer
    {
    public:
        virtual ~xml_writer();
        // Write memory chunk into stream/file/whatever
        virtual void write(const void* data, size_t size) = 0;
    };
    // xml_writer implementation for FILE*
    class PUGIXML_CLASS xml_writer_file: public xml_writer
    {
    public:
        // Construct writer from a FILE* object; void* is used to avoid header dependencies on stdio
        xml_writer_file(void* file);
        virtual void write(const void* data, size_t size) PUGIXML_OVERRIDE;
    private:
        void* file;
    };
    #ifndef PUGIXML_NO_STL
    // xml_writer implementation for streams
    class PUGIXML_CLASS xml_writer_stream: public xml_writer
    {
    public:
        // Construct writer from an output stream object
        xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream);
        xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream);
        virtual void write(const void* data, size_t size) PUGIXML_OVERRIDE;
    private:
        std::basic_ostream<char, std::char_traits<char> >* narrow_stream;
        std::basic_ostream<wchar_t, std::char_traits<wchar_t> >* wide_stream;
    };
    #endif
    // A light-weight handle for manipulating attributes in DOM tree
    class PUGIXML_CLASS xml_attribute
    {
        friend class xml_attribute_iterator;
        friend class xml_node;
    private:
        xml_attribute_struct* _attr;
        typedef void (*unspecified_bool_type)(xml_attribute***);
    public:
        // Default constructor. Constructs an empty attribute.
        xml_attribute();
        // Constructs attribute from internal pointer
        explicit xml_attribute(xml_attribute_struct* attr);
        // Safe bool conversion operator
        operator unspecified_bool_type() const;
        // Borland C++ workaround
        bool operator!() const;
        // Comparison operators (compares wrapped attribute pointers)
        bool operator==(const xml_attribute& r) const;
        bool operator!=(const xml_attribute& r) const;
        bool operator<(const xml_attribute& r) const;
        bool operator>(const xml_attribute& r) const;
        bool operator<=(const xml_attribute& r) const;
        bool operator>=(const xml_attribute& r) const;
        // Check if attribute is empty
        bool empty() const;
        // Get attribute name/value, or "" if attribute is empty
        const char_t* name() const;
        const char_t* value() const;
        // Get attribute value, or the default value if attribute is empty
        const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const;
        // Get attribute value as a number, or the default value if conversion did not succeed or attribute is empty
        int as_int(int def = 0) const;
        unsigned int as_uint(unsigned int def = 0) const;
        double as_double(double def = 0) const;
        float as_float(float def = 0) const;
    #ifdef PUGIXML_HAS_LONG_LONG
        long long as_llong(long long def = 0) const;
        unsigned long long as_ullong(unsigned long long def = 0) const;
    #endif
        // Get attribute value as bool (returns true if first character is in '1tTyY' set), or the default value if attribute is empty
        bool as_bool(bool def = false) const;
        // Set attribute name/value (returns false if attribute is empty or there is not enough memory)
        bool set_name(const char_t* rhs);
        bool set_name(const char_t* rhs, size_t size);
        bool set_value(const char_t* rhs);
        bool set_value(const char_t* rhs, size_t size);
        // Set attribute value with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
        bool set_value(int rhs);
        bool set_value(unsigned int rhs);
        bool set_value(long rhs);
        bool set_value(unsigned long rhs);
        bool set_value(double rhs);
        bool set_value(double rhs, int precision);
        bool set_value(float rhs);
        bool set_value(float rhs, int precision);
        bool set_value(bool rhs);
    #ifdef PUGIXML_HAS_LONG_LONG
        bool set_value(long long rhs);
        bool set_value(unsigned long long rhs);
    #endif
        // Set attribute value (equivalent to set_value without error checking)
        xml_attribute& operator=(const char_t* rhs);
        xml_attribute& operator=(int rhs);
        xml_attribute& operator=(unsigned int rhs);
        xml_attribute& operator=(long rhs);
        xml_attribute& operator=(unsigned long rhs);
        xml_attribute& operator=(double rhs);
        xml_attribute& operator=(float rhs);
        xml_attribute& operator=(bool rhs);
    #ifdef PUGIXML_HAS_LONG_LONG
        xml_attribute& operator=(long long rhs);
        xml_attribute& operator=(unsigned long long rhs);
    #endif
        // Get next/previous attribute in the attribute list of the parent node
        xml_attribute next_attribute() const;
        xml_attribute previous_attribute() const;
        // Get hash value (unique for handles to the same object)
        size_t hash_value() const;
        // Get internal pointer
        xml_attribute_struct* internal_object() const;
    };
#ifdef __BORLANDC__
    // Borland C++ workaround
    bool PUGIXML_FUNCTION operator&&(const xml_attribute& lhs, bool rhs);
    bool PUGIXML_FUNCTION operator||(const xml_attribute& lhs, bool rhs);
#endif
    // A light-weight handle for manipulating nodes in DOM tree
    class PUGIXML_CLASS xml_node
    {
        friend class xml_attribute_iterator;
        friend class xml_node_iterator;
        friend class xml_named_node_iterator;
    protected:
        xml_node_struct* _root;
        typedef void (*unspecified_bool_type)(xml_node***);
    public:
        // Default constructor. Constructs an empty node.
        xml_node();
        // Constructs node from internal pointer
        explicit xml_node(xml_node_struct* p);
        // Safe bool conversion operator
        operator unspecified_bool_type() const;
        // Borland C++ workaround
        bool operator!() const;
        // Comparison operators (compares wrapped node pointers)
        bool operator==(const xml_node& r) const;
        bool operator!=(const xml_node& r) const;
        bool operator<(const xml_node& r) const;
        bool operator>(const xml_node& r) const;
        bool operator<=(const xml_node& r) const;
        bool operator>=(const xml_node& r) const;
        // Check if node is empty.
        bool empty() const;
        // Get node type
        xml_node_type type() const;
        // Get node name, or "" if node is empty or it has no name
        const char_t* name() const;
        // Get node value, or "" if node is empty or it has no value
        // Note: For <node>text</node> node.value() does not return "text"! Use child_value() or text() methods to access text inside nodes.
        const char_t* value() const;
        // Get attribute list
        xml_attribute first_attribute() const;
        xml_attribute last_attribute() const;
        // Get children list
        xml_node first_child() const;
        xml_node last_child() const;
        // Get next/previous sibling in the children list of the parent node
        xml_node next_sibling() const;
        xml_node previous_sibling() const;
        // Get parent node
        xml_node parent() const;
        // Get root of DOM tree this node belongs to
        xml_node root() const;
        // Get text object for the current node
        xml_text text() const;
        // Get child, attribute or next/previous sibling with the specified name
        xml_node child(const char_t* name) const;
        xml_attribute attribute(const char_t* name) const;
        xml_node next_sibling(const char_t* name) const;
        xml_node previous_sibling(const char_t* name) const;
        // Get attribute, starting the search from a hint (and updating hint so that searching for a sequence of attributes is fast)
        xml_attribute attribute(const char_t* name, xml_attribute& hint) const;
        // Get child value of current node; that is, value of the first child node of type PCDATA/CDATA
        const char_t* child_value() const;
        // Get child value of child with specified name. Equivalent to child(name).child_value().
        const char_t* child_value(const char_t* name) const;
        // Set node name/value (returns false if node is empty, there is not enough memory, or node can not have name/value)
        bool set_name(const char_t* rhs);
        bool set_name(const char_t* rhs, size_t size);
        bool set_value(const char_t* rhs);
        bool set_value(const char_t* rhs, size_t size);
        // Add attribute with specified name. Returns added attribute, or empty attribute on errors.
        xml_attribute append_attribute(const char_t* name);
        xml_attribute prepend_attribute(const char_t* name);
        xml_attribute insert_attribute_after(const char_t* name, const xml_attribute& attr);
        xml_attribute insert_attribute_before(const char_t* name, const xml_attribute& attr);
        // Add a copy of the specified attribute. Returns added attribute, or empty attribute on errors.
        xml_attribute append_copy(const xml_attribute& proto);
        xml_attribute prepend_copy(const xml_attribute& proto);
        xml_attribute insert_copy_after(const xml_attribute& proto, const xml_attribute& attr);
        xml_attribute insert_copy_before(const xml_attribute& proto, const xml_attribute& attr);
        // Add child node with specified type. Returns added node, or empty node on errors.
        xml_node append_child(xml_node_type type = node_element);
        xml_node prepend_child(xml_node_type type = node_element);
        xml_node insert_child_after(xml_node_type type, const xml_node& node);
        xml_node insert_child_before(xml_node_type type, const xml_node& node);
        // Add child element with specified name. Returns added node, or empty node on errors.
        xml_node append_child(const char_t* name);
        xml_node prepend_child(const char_t* name);
        xml_node insert_child_after(const char_t* name, const xml_node& node);
        xml_node insert_child_before(const char_t* name, const xml_node& node);
        // Add a copy of the specified node as a child. Returns added node, or empty node on errors.
        xml_node append_copy(const xml_node& proto);
        xml_node prepend_copy(const xml_node& proto);
        xml_node insert_copy_after(const xml_node& proto, const xml_node& node);
        xml_node insert_copy_before(const xml_node& proto, const xml_node& node);
        // Move the specified node to become a child of this node. Returns moved node, or empty node on errors.
        xml_node append_move(const xml_node& moved);
        xml_node prepend_move(const xml_node& moved);
        xml_node insert_move_after(const xml_node& moved, const xml_node& node);
        xml_node insert_move_before(const xml_node& moved, const xml_node& node);
        // Remove specified attribute
        bool remove_attribute(const xml_attribute& a);
        bool remove_attribute(const char_t* name);
        // Remove all attributes
        bool remove_attributes();
        // Remove specified child
        bool remove_child(const xml_node& n);
        bool remove_child(const char_t* name);
        // Remove all children
        bool remove_children();
        // Parses buffer as an XML document fragment and appends all nodes as children of the current node.
        // Copies/converts the buffer, so it may be deleted or changed after the function returns.
        // Note: append_buffer allocates memory that has the lifetime of the owning document; removing the appended nodes does not immediately reclaim that memory.
        xml_parse_result append_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        // Find attribute using predicate. Returns first attribute for which predicate returned true.
        template <typename Predicate> xml_attribute find_attribute(Predicate pred) const
        {
            if (!_root) return xml_attribute();
            for (xml_attribute attrib = first_attribute(); attrib; attrib = attrib.next_attribute())
                if (pred(attrib))
                    return attrib;
            return xml_attribute();
        }
        // Find child node using predicate. Returns first child for which predicate returned true.
        template <typename Predicate> xml_node find_child(Predicate pred) const
        {
            if (!_root) return xml_node();
            for (xml_node node = first_child(); node; node = node.next_sibling())
                if (pred(node))
                    return node;
            return xml_node();
        }
        // Find node from subtree using predicate. Returns first node from subtree (depth-first), for which predicate returned true.
        template <typename Predicate> xml_node find_node(Predicate pred) const
        {
            if (!_root) return xml_node();
            xml_node cur = first_child();
            while (cur._root && cur._root != _root)
            {
                if (pred(cur)) return cur;
                if (cur.first_child()) cur = cur.first_child();
                else if (cur.next_sibling()) cur = cur.next_sibling();
                else
                {
                    while (!cur.next_sibling() && cur._root != _root) cur = cur.parent();
                    if (cur._root != _root) cur = cur.next_sibling();
                }
            }
            return xml_node();
        }
        // Find child node by attribute name/value
        xml_node find_child_by_attribute(const char_t* name, const char_t* attr_name, const char_t* attr_value) const;
        xml_node find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const;
    #ifndef PUGIXML_NO_STL
        // Get the absolute node path from root as a text string.
        string_t path(char_t delimiter = '/') const;
    #endif
        // Search for a node by path consisting of node names and . or .. elements.
        xml_node first_element_by_path(const char_t* path, char_t delimiter = '/') const;
        // Recursively traverse subtree with xml_tree_walker
        bool traverse(xml_tree_walker& walker);
    #ifndef PUGIXML_NO_XPATH
        // Select single node by evaluating XPath query. Returns first node from the resulting node set.
        xpath_node select_node(const char_t* query, xpath_variable_set* variables = PUGIXML_NULL) const;
        xpath_node select_node(const xpath_query& query) const;
        // Select node set by evaluating XPath query
        xpath_node_set select_nodes(const char_t* query, xpath_variable_set* variables = PUGIXML_NULL) const;
        xpath_node_set select_nodes(const xpath_query& query) const;
        // (deprecated: use select_node instead) Select single node by evaluating XPath query.
        PUGIXML_DEPRECATED xpath_node select_single_node(const char_t* query, xpath_variable_set* variables = PUGIXML_NULL) const;
        PUGIXML_DEPRECATED xpath_node select_single_node(const xpath_query& query) const;
    #endif
        // Print subtree using a writer object
        void print(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
    #ifndef PUGIXML_NO_STL
        // Print subtree to stream
        void print(std::basic_ostream<char, std::char_traits<char> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
        void print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, unsigned int depth = 0) const;
    #endif
        // Child nodes iterators
        typedef xml_node_iterator iterator;
        iterator begin() const;
        iterator end() const;
        // Attribute iterators
        typedef xml_attribute_iterator attribute_iterator;
        attribute_iterator attributes_begin() const;
        attribute_iterator attributes_end() const;
        // Range-based for support
        xml_object_range<xml_node_iterator> children() const;
        xml_object_range<xml_attribute_iterator> attributes() const;
        // Range-based for support for all children with the specified name
        // Note: name pointer must have a longer lifetime than the returned object; be careful with passing temporaries!
        xml_object_range<xml_named_node_iterator> children(const char_t* name) const;
        // Get node offset in parsed file/string (in char_t units) for debugging purposes
        ptrdiff_t offset_debug() const;
        // Get hash value (unique for handles to the same object)
        size_t hash_value() const;
        // Get internal pointer
        xml_node_struct* internal_object() const;
    };
#ifdef __BORLANDC__
    // Borland C++ workaround
    bool PUGIXML_FUNCTION operator&&(const xml_node& lhs, bool rhs);
    bool PUGIXML_FUNCTION operator||(const xml_node& lhs, bool rhs);
#endif
    // A helper for working with text inside PCDATA nodes
    class PUGIXML_CLASS xml_text
    {
        friend class xml_node;
        xml_node_struct* _root;
        typedef void (*unspecified_bool_type)(xml_text***);
        explicit xml_text(xml_node_struct* root);
        xml_node_struct* _data_new();
        xml_node_struct* _data() const;
    public:
        // Default constructor. Constructs an empty object.
        xml_text();
        // Safe bool conversion operator
        operator unspecified_bool_type() const;
        // Borland C++ workaround
        bool operator!() const;
        // Check if text object is empty
        bool empty() const;
        // Get text, or "" if object is empty
        const char_t* get() const;
        // Get text, or the default value if object is empty
        const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const;
        // Get text as a number, or the default value if conversion did not succeed or object is empty
        int as_int(int def = 0) const;
        unsigned int as_uint(unsigned int def = 0) const;
        double as_double(double def = 0) const;
        float as_float(float def = 0) const;
    #ifdef PUGIXML_HAS_LONG_LONG
        long long as_llong(long long def = 0) const;
        unsigned long long as_ullong(unsigned long long def = 0) const;
    #endif
        // Get text as bool (returns true if first character is in '1tTyY' set), or the default value if object is empty
        bool as_bool(bool def = false) const;
        // Set text (returns false if object is empty or there is not enough memory)
        bool set(const char_t* rhs);
        bool set(const char_t* rhs, size_t size);
        // Set text with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
        bool set(int rhs);
        bool set(unsigned int rhs);
        bool set(long rhs);
        bool set(unsigned long rhs);
        bool set(double rhs);
        bool set(double rhs, int precision);
        bool set(float rhs);
        bool set(float rhs, int precision);
        bool set(bool rhs);
    #ifdef PUGIXML_HAS_LONG_LONG
        bool set(long long rhs);
        bool set(unsigned long long rhs);
    #endif
        // Set text (equivalent to set without error checking)
        xml_text& operator=(const char_t* rhs);
        xml_text& operator=(int rhs);
        xml_text& operator=(unsigned int rhs);
        xml_text& operator=(long rhs);
        xml_text& operator=(unsigned long rhs);
        xml_text& operator=(double rhs);
        xml_text& operator=(float rhs);
        xml_text& operator=(bool rhs);
    #ifdef PUGIXML_HAS_LONG_LONG
        xml_text& operator=(long long rhs);
        xml_text& operator=(unsigned long long rhs);
    #endif
        // Get the data node (node_pcdata or node_cdata) for this object
        xml_node data() const;
    };
#ifdef __BORLANDC__
    // Borland C++ workaround
    bool PUGIXML_FUNCTION operator&&(const xml_text& lhs, bool rhs);
    bool PUGIXML_FUNCTION operator||(const xml_text& lhs, bool rhs);
#endif
    // Child node iterator (a bidirectional iterator over a collection of xml_node)
    class PUGIXML_CLASS xml_node_iterator
    {
        friend class xml_node;
    private:
        mutable xml_node _wrap;
        xml_node _parent;
        xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent);
    public:
        // Iterator traits
        typedef ptrdiff_t difference_type;
        typedef xml_node value_type;
        typedef xml_node* pointer;
        typedef xml_node& reference;
    #ifndef PUGIXML_NO_STL
        typedef std::bidirectional_iterator_tag iterator_category;
    #endif
        // Default constructor
        xml_node_iterator();
        // Construct an iterator which points to the specified node
        xml_node_iterator(const xml_node& node);
        // Iterator operators
        bool operator==(const xml_node_iterator& rhs) const;
        bool operator!=(const xml_node_iterator& rhs) const;
        xml_node& operator*() const;
        xml_node* operator->() const;
        xml_node_iterator& operator++();
        xml_node_iterator operator++(int);
        xml_node_iterator& operator--();
        xml_node_iterator operator--(int);
    };
    // Attribute iterator (a bidirectional iterator over a collection of xml_attribute)
    class PUGIXML_CLASS xml_attribute_iterator
    {
        friend class xml_node;
    private:
        mutable xml_attribute _wrap;
        xml_node _parent;
        xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent);
    public:
        // Iterator traits
        typedef ptrdiff_t difference_type;
        typedef xml_attribute value_type;
        typedef xml_attribute* pointer;
        typedef xml_attribute& reference;
    #ifndef PUGIXML_NO_STL
        typedef std::bidirectional_iterator_tag iterator_category;
    #endif
        // Default constructor
        xml_attribute_iterator();
        // Construct an iterator which points to the specified attribute
        xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent);
        // Iterator operators
        bool operator==(const xml_attribute_iterator& rhs) const;
        bool operator!=(const xml_attribute_iterator& rhs) const;
        xml_attribute& operator*() const;
        xml_attribute* operator->() const;
        xml_attribute_iterator& operator++();
        xml_attribute_iterator operator++(int);
        xml_attribute_iterator& operator--();
        xml_attribute_iterator operator--(int);
    };
    // Named node range helper
    class PUGIXML_CLASS xml_named_node_iterator
    {
        friend class xml_node;
    public:
        // Iterator traits
        typedef ptrdiff_t difference_type;
        typedef xml_node value_type;
        typedef xml_node* pointer;
        typedef xml_node& reference;
    #ifndef PUGIXML_NO_STL
        typedef std::bidirectional_iterator_tag iterator_category;
    #endif
        // Default constructor
        xml_named_node_iterator();
        // Construct an iterator which points to the specified node
        // Note: name pointer is stored in the iterator and must have a longer lifetime than iterator itself
        xml_named_node_iterator(const xml_node& node, const char_t* name);
        // Iterator operators
        bool operator==(const xml_named_node_iterator& rhs) const;
        bool operator!=(const xml_named_node_iterator& rhs) const;
        xml_node& operator*() const;
        xml_node* operator->() const;
        xml_named_node_iterator& operator++();
        xml_named_node_iterator operator++(int);
        xml_named_node_iterator& operator--();
        xml_named_node_iterator operator--(int);
    private:
        mutable xml_node _wrap;
        xml_node _parent;
        const char_t* _name;
        xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name);
    };
    // Abstract tree walker class (see xml_node::traverse)
    class PUGIXML_CLASS xml_tree_walker
    {
        friend class xml_node;
    private:
        int _depth;
    protected:
        // Get current traversal depth
        int depth() const;
    public:
        xml_tree_walker();
        virtual ~xml_tree_walker();
        // Callback that is called when traversal begins
        virtual bool begin(xml_node& node);
        // Callback that is called for each node traversed
        virtual bool for_each(xml_node& node) = 0;
        // Callback that is called when traversal ends
        virtual bool end(xml_node& node);
    };
    // Parsing status, returned as part of xml_parse_result object
    enum xml_parse_status
    {
        status_ok = 0,                // No error
        status_file_not_found,        // File was not found during load_file()
        status_io_error,            // Error reading from file/stream
        status_out_of_memory,        // Could not allocate memory
        status_internal_error,        // Internal error occurred
        status_unrecognized_tag,    // Parser could not determine tag type
        status_bad_pi,                // Parsing error occurred while parsing document declaration/processing instruction
        status_bad_comment,            // Parsing error occurred while parsing comment
        status_bad_cdata,            // Parsing error occurred while parsing CDATA section
        status_bad_doctype,            // Parsing error occurred while parsing document type declaration
        status_bad_pcdata,            // Parsing error occurred while parsing PCDATA section
        status_bad_start_element,    // Parsing error occurred while parsing start element tag
        status_bad_attribute,        // Parsing error occurred while parsing element attribute
        status_bad_end_element,        // Parsing error occurred while parsing end element tag
        status_end_element_mismatch,// There was a mismatch of start-end tags (closing tag had incorrect name, some tag was not closed or there was an excessive closing tag)
        status_append_invalid_root,    // Unable to append nodes since root type is not node_element or node_document (exclusive to xml_node::append_buffer)
        status_no_document_element    // Parsing resulted in a document without element nodes
    };
    // Parsing result
    struct PUGIXML_CLASS xml_parse_result
    {
        // Parsing status (see xml_parse_status)
        xml_parse_status status;
        // Last parsed offset (in char_t units from start of input data)
        ptrdiff_t offset;
        // Source document encoding
        xml_encoding encoding;
        // Default constructor, initializes object to failed state
        xml_parse_result();
        // Cast to bool operator
        operator bool() const;
        // Get error description
        const char* description() const;
    };
    // Document class (DOM tree root)
    class PUGIXML_CLASS xml_document: public xml_node
    {
    private:
        char_t* _buffer;
        char _memory[192];
        // Non-copyable semantics
        xml_document(const xml_document&);
        xml_document& operator=(const xml_document&);
        void _create();
        void _destroy();
        void _move(xml_document& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT;
    public:
        // Default constructor, makes empty document
        xml_document();
        // Destructor, invalidates all node/attribute handles to this document
        ~xml_document();
    #ifdef PUGIXML_HAS_MOVE
        // Move semantics support
        xml_document(xml_document&& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT;
        xml_document& operator=(xml_document&& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT;
    #endif
        // Removes all nodes, leaving the empty document
        void reset();
        // Removes all nodes, then copies the entire contents of the specified document
        void reset(const xml_document& proto);
    #ifndef PUGIXML_NO_STL
        // Load document from stream.
        xml_parse_result load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        xml_parse_result load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options = parse_default);
    #endif
        // (deprecated: use load_string instead) Load document from zero-terminated string. No encoding conversions are applied.
        PUGIXML_DEPRECATED xml_parse_result load(const char_t* contents, unsigned int options = parse_default);
        // Load document from zero-terminated string. No encoding conversions are applied.
        xml_parse_result load_string(const char_t* contents, unsigned int options = parse_default);
        // Load document from file
        xml_parse_result load_file(const char* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        xml_parse_result load_file(const wchar_t* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        // Load document from buffer. Copies/converts the buffer, so it may be deleted or changed after the function returns.
        xml_parse_result load_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        // Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
        // You should ensure that buffer data will persist throughout the document's lifetime, and free the buffer memory manually once document is destroyed.
        xml_parse_result load_buffer_inplace(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        // Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
        // You should allocate the buffer with pugixml allocation function; document will free the buffer when it is no longer needed (you can't use it anymore).
        xml_parse_result load_buffer_inplace_own(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
        // Save XML document to writer (semantics is slightly different from xml_node::print, see documentation for details).
        void save(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
    #ifndef PUGIXML_NO_STL
        // Save XML document to stream (semantics is slightly different from xml_node::print, see documentation for details).
        void save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
        void save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default) const;
    #endif
        // Save XML to file
        bool save_file(const char* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
        bool save_file(const wchar_t* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
        // Get document element
        xml_node document_element() const;
    };
#ifndef PUGIXML_NO_XPATH
    // XPath query return type
    enum xpath_value_type
    {
        xpath_type_none,      // Unknown type (query failed to compile)
        xpath_type_node_set,  // Node set (xpath_node_set)
        xpath_type_number,      // Number
        xpath_type_string,      // String
        xpath_type_boolean      // Boolean
    };
    // XPath parsing result
    struct PUGIXML_CLASS xpath_parse_result
    {
        // Error message (0 if no error)
        const char* error;
        // Last parsed offset (in char_t units from string start)
        ptrdiff_t offset;
        // Default constructor, initializes object to failed state
        xpath_parse_result();
        // Cast to bool operator
        operator bool() const;
        // Get error description
        const char* description() const;
    };
    // A single XPath variable
    class PUGIXML_CLASS xpath_variable
    {
        friend class xpath_variable_set;
    protected:
        xpath_value_type _type;
        xpath_variable* _next;
        xpath_variable(xpath_value_type type);
        // Non-copyable semantics
        xpath_variable(const xpath_variable&);
        xpath_variable& operator=(const xpath_variable&);
    public:
        // Get variable name
        const char_t* name() const;
        // Get variable type
        xpath_value_type type() const;
        // Get variable value; no type conversion is performed, default value (false, NaN, empty string, empty node set) is returned on type mismatch error
        bool get_boolean() const;
        double get_number() const;
        const char_t* get_string() const;
        const xpath_node_set& get_node_set() const;
        // Set variable value; no type conversion is performed, false is returned on type mismatch error
        bool set(bool value);
        bool set(double value);
        bool set(const char_t* value);
        bool set(const xpath_node_set& value);
    };
    // A set of XPath variables
    class PUGIXML_CLASS xpath_variable_set
    {
    private:
        xpath_variable* _data[64];
        void _assign(const xpath_variable_set& rhs);
        void _swap(xpath_variable_set& rhs);
        xpath_variable* _find(const char_t* name) const;
        static bool _clone(xpath_variable* var, xpath_variable** out_result);
        static void _destroy(xpath_variable* var);
    public:
        // Default constructor/destructor
        xpath_variable_set();
        ~xpath_variable_set();
        // Copy constructor/assignment operator
        xpath_variable_set(const xpath_variable_set& rhs);
        xpath_variable_set& operator=(const xpath_variable_set& rhs);
    #ifdef PUGIXML_HAS_MOVE
        // Move semantics support
        xpath_variable_set(xpath_variable_set&& rhs) PUGIXML_NOEXCEPT;
        xpath_variable_set& operator=(xpath_variable_set&& rhs) PUGIXML_NOEXCEPT;
    #endif
        // Add a new variable or get the existing one, if the types match
        xpath_variable* add(const char_t* name, xpath_value_type type);
        // Set value of an existing variable; no type conversion is performed, false is returned if there is no such variable or if types mismatch
        bool set(const char_t* name, bool value);
        bool set(const char_t* name, double value);
        bool set(const char_t* name, const char_t* value);
        bool set(const char_t* name, const xpath_node_set& value);
        // Get existing variable by name
        xpath_variable* get(const char_t* name);
        const xpath_variable* get(const char_t* name) const;
    };
    // A compiled XPath query object
    class PUGIXML_CLASS xpath_query
    {
    private:
        void* _impl;
        xpath_parse_result _result;
        typedef void (*unspecified_bool_type)(xpath_query***);
        // Non-copyable semantics
        xpath_query(const xpath_query&);
        xpath_query& operator=(const xpath_query&);
    public:
        // Construct a compiled object from XPath expression.
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on compilation errors.
        explicit xpath_query(const char_t* query, xpath_variable_set* variables = PUGIXML_NULL);
        // Constructor
        xpath_query();
        // Destructor
        ~xpath_query();
    #ifdef PUGIXML_HAS_MOVE
        // Move semantics support
        xpath_query(xpath_query&& rhs) PUGIXML_NOEXCEPT;
        xpath_query& operator=(xpath_query&& rhs) PUGIXML_NOEXCEPT;
    #endif
        // Get query expression return type
        xpath_value_type return_type() const;
        // Evaluate expression as boolean value in the specified context; performs type conversion if necessary.
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
        bool evaluate_boolean(const xpath_node& n) const;
        // Evaluate expression as double value in the specified context; performs type conversion if necessary.
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
        double evaluate_number(const xpath_node& n) const;
    #ifndef PUGIXML_NO_STL
        // Evaluate expression as string value in the specified context; performs type conversion if necessary.
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
        string_t evaluate_string(const xpath_node& n) const;
    #endif
        // Evaluate expression as string value in the specified context; performs type conversion if necessary.
        // At most capacity characters are written to the destination buffer, full result size is returned (includes terminating zero).
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
        // If PUGIXML_NO_EXCEPTIONS is defined, returns empty  set instead.
        size_t evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const;
        // Evaluate expression as node set in the specified context.
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
        // If PUGIXML_NO_EXCEPTIONS is defined, returns empty node set instead.
        xpath_node_set evaluate_node_set(const xpath_node& n) const;
        // Evaluate expression as node set in the specified context.
        // Return first node in document order, or empty node if node set is empty.
        // If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
        // If PUGIXML_NO_EXCEPTIONS is defined, returns empty node instead.
        xpath_node evaluate_node(const xpath_node& n) const;
        // Get parsing result (used to get compilation errors in PUGIXML_NO_EXCEPTIONS mode)
        const xpath_parse_result& result() const;
        // Safe bool conversion operator
        operator unspecified_bool_type() const;
        // Borland C++ workaround
        bool operator!() const;
    };
    #ifndef PUGIXML_NO_EXCEPTIONS
        #if defined(_MSC_VER)
          // C4275 can be ignored in Visual C++ if you are deriving
          // from a type in the Standard C++ Library
          #pragma warning(push)
          #pragma warning(disable: 4275)
        #endif
    // XPath exception class
    class PUGIXML_CLASS xpath_exception: public std::exception
    {
    private:
        xpath_parse_result _result;
    public:
        // Construct exception from parse result
        explicit xpath_exception(const xpath_parse_result& result);
        // Get error message
        virtual const char* what() const throw() PUGIXML_OVERRIDE;
        // Get parse result
        const xpath_parse_result& result() const;
    };
        #if defined(_MSC_VER)
          #pragma warning(pop)
        #endif
    #endif
    // XPath node class (either xml_node or xml_attribute)
    class PUGIXML_CLASS xpath_node
    {
    private:
        xml_node _node;
        xml_attribute _attribute;
        typedef void (*unspecified_bool_type)(xpath_node***);
    public:
        // Default constructor; constructs empty XPath node
        xpath_node();
        // Construct XPath node from XML node/attribute
        xpath_node(const xml_node& node);
        xpath_node(const xml_attribute& attribute, const xml_node& parent);
        // Get node/attribute, if any
        xml_node node() const;
        xml_attribute attribute() const;
        // Get parent of contained node/attribute
        xml_node parent() const;
        // Safe bool conversion operator
        operator unspecified_bool_type() const;
        // Borland C++ workaround
        bool operator!() const;
        // Comparison operators
        bool operator==(const xpath_node& n) const;
        bool operator!=(const xpath_node& n) const;
    };
#ifdef __BORLANDC__
    // Borland C++ workaround
    bool PUGIXML_FUNCTION operator&&(const xpath_node& lhs, bool rhs);
    bool PUGIXML_FUNCTION operator||(const xpath_node& lhs, bool rhs);
#endif
    // A fixed-size collection of XPath nodes
    class PUGIXML_CLASS xpath_node_set
    {
    public:
        // Collection type
        enum type_t
        {
            type_unsorted,            // Not ordered
            type_sorted,            // Sorted by document order (ascending)
            type_sorted_reverse        // Sorted by document order (descending)
        };
        // Constant iterator type
        typedef const xpath_node* const_iterator;
        // We define non-constant iterator to be the same as constant iterator so that various generic algorithms (i.e. boost foreach) work
        typedef const xpath_node* iterator;
        // Default constructor. Constructs empty set.
        xpath_node_set();
        // Constructs a set from iterator range; data is not checked for duplicates and is not sorted according to provided type, so be careful
        xpath_node_set(const_iterator begin, const_iterator end, type_t type = type_unsorted);
        // Destructor
        ~xpath_node_set();
        // Copy constructor/assignment operator
        xpath_node_set(const xpath_node_set& ns);
        xpath_node_set& operator=(const xpath_node_set& ns);
    #ifdef PUGIXML_HAS_MOVE
        // Move semantics support
        xpath_node_set(xpath_node_set&& rhs) PUGIXML_NOEXCEPT;
        xpath_node_set& operator=(xpath_node_set&& rhs) PUGIXML_NOEXCEPT;
    #endif
        // Get collection type
        type_t type() const;
        // Get collection size
        size_t size() const;
        // Indexing operator
        const xpath_node& operator[](size_t index) const;
        // Collection iterators
        const_iterator begin() const;
        const_iterator end() const;
        // Sort the collection in ascending/descending order by document order
        void sort(bool reverse = false);
        // Get first node in the collection by document order
        xpath_node first() const;
        // Check if collection is empty
        bool empty() const;
    private:
        type_t _type;
        xpath_node _storage[1];
        xpath_node* _begin;
        xpath_node* _end;
        void _assign(const_iterator begin, const_iterator end, type_t type);
        void _move(xpath_node_set& rhs) PUGIXML_NOEXCEPT;
    };
#endif
#ifndef PUGIXML_NO_STL
    // Convert wide string to UTF8
    std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const wchar_t* str);
    std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >& str);
    // Convert UTF8 to wide string
    std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const char* str);
    std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >& str);
#endif
    // Memory allocation function interface; returns pointer to allocated memory or NULL on failure
    typedef void* (*allocation_function)(size_t size);
    // Memory deallocation function interface
    typedef void (*deallocation_function)(void* ptr);
    // Override default memory management functions. All subsequent allocations/deallocations will be performed via supplied functions.
    void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate);
    // Get current memory management functions
    allocation_function PUGIXML_FUNCTION get_memory_allocation_function();
    deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function();
}
#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
namespace std
{
    // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
    std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_node_iterator&);
    std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_attribute_iterator&);
    std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_named_node_iterator&);
}
#endif
#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
namespace std
{
    // Workarounds for (non-standard) iterator category detection
    std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_node_iterator&);
    std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_attribute_iterator&);
    std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_named_node_iterator&);
}
#endif
#endif
// Make sure implementation is included in header-only mode
// Use macro expansion in #include to work around QMake (QTBUG-11923)
#if defined(PUGIXML_HEADER_ONLY) && !defined(PUGIXML_SOURCE)
#    define PUGIXML_SOURCE "pugixml.cpp"
#    include PUGIXML_SOURCE
#endif
/**
 * Copyright (c) 2006-2023 Arseny Kapoulkine
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
SourceCode/Bond/BondEq/InputDialog.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,68 @@
// InputDialog.cpp: å®žçŽ°æ–‡ä»¶
//
#include "stdafx.h"
#include "BondEq.h"
#include "afxdialogex.h"
#include "InputDialog.h"
// CInputDialog å¯¹è¯æ¡†
IMPLEMENT_DYNAMIC(CInputDialog, CDialogEx)
CInputDialog::CInputDialog(const CString& strTitle, const CString& strPrompt, CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_INPUT, pParent), m_strTitle(strTitle), m_strPrompt(strPrompt), m_strInput(_T(""))
{
}
CInputDialog::~CInputDialog()
{
}
CString CInputDialog::GetInputText() const
{
    return m_strInput;
}
void CInputDialog::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_EDIT_INPUT, m_editInput);
    DDX_Control(pDX, IDC_STATIC_PROMPT, m_staticPrompt);
}
BEGIN_MESSAGE_MAP(CInputDialog, CDialogEx)
    ON_BN_CLICKED(IDOK, &CInputDialog::OnBnClickedOk)
END_MESSAGE_MAP()
// CInputDialog æ¶ˆæ¯å¤„理程序
BOOL CInputDialog::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    // TODO:  åœ¨æ­¤æ·»åŠ é¢å¤–çš„åˆå§‹åŒ–
    SetWindowText(m_strTitle);
    m_staticPrompt.SetWindowText(m_strPrompt);
    return TRUE;  // return TRUE unless you set the focus to a control
    // å¼‚常: OCX å±žæ€§é¡µåº”返回 FALSE
}
void CInputDialog::OnBnClickedOk()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    m_editInput.GetWindowText(m_strInput);
    if (m_strInput.IsEmpty()) {
        AfxMessageBox(_T("输入不能为空!"));
        return;
    }
    CDialogEx::OnOK();
}
SourceCode/Bond/BondEq/InputDialog.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,37 @@
#pragma once
#include "afxdialogex.h"
// CInputDialog å¯¹è¯æ¡†
class CInputDialog : public CDialogEx
{
    DECLARE_DYNAMIC(CInputDialog)
public:
    CInputDialog(const CString& strTitle, const CString& strPrompt, CWnd* pParent = nullptr);
    virtual ~CInputDialog();
    CString GetInputText() const; // èŽ·å–è¾“å…¥å†…å®¹
// å¯¹è¯æ¡†æ•°æ®
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_DIALOG_INPUT };
#endif
private:
    CEdit m_editInput;
    CStatic m_staticPrompt;
    CString m_strTitle;   // å¯¹è¯æ¡†æ ‡é¢˜
    CString m_strPrompt;  // æç¤ºæ–‡æœ¬
    CString m_strInput;   // è¾“入的文本
protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV æ”¯æŒ
    DECLARE_MESSAGE_MAP()
public:
    virtual BOOL OnInitDialog();
    afx_msg void OnBnClickedOk();
};
SourceCode/Bond/BondEq/ToolUnits.cpp
@@ -80,6 +80,10 @@
void CToolUnits::createDir(const char* pszDir)
{
    if (isDirectory(std::string(pszDir))) {
        return;
    }
    CString strDir = pszDir;
    int lastIndex = 0;
    int index = strDir.Find(_T("\\"), lastIndex);
SourceCode/Bond/BondEq/UserManagerDlg.cpp
ÎļþÒÑɾ³ý
SourceCode/Bond/BondEq/View/AxisSettingsDlg.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,964 @@
// AxisSettingsDlg.cpp: å®žçŽ°æ–‡ä»¶
//
#include "stdafx.h"
#include "BondEq.h"
#include "afxdialogex.h"
#include "AxisSettingsDlg.h"
#include "ToolUnits.h"
#include <cctype>
#include <algorithm>
#define TIMER_INIT                1
#define TIMER_READ_PLC_DATA        2
#define TIMER_JOG_ADD           3
#define TIMER_JOG_SUB           4
// CAxisSettingsDlg å¯¹è¯æ¡†
IMPLEMENT_DYNAMIC(CAxisSettingsDlg, CDialogEx)
CAxisSettingsDlg::CAxisSettingsDlg(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_AXIS_SETTINGS, pParent)
{
    m_nInitialWidth = 0;
    m_nInitialHeight = 0;
    m_pPLC = nullptr;
}
CAxisSettingsDlg::~CAxisSettingsDlg()
{
    for (auto& pair : m_mapFonts) {
        if (pair.second) {
            pair.second->DeleteObject();
            delete pair.second;
        }
    }
    m_mapFonts.clear();
}
void CAxisSettingsDlg::SetPLC(CPLC* pPLC)
{
    ASSERT(pPLC);
    m_pPLC = pPLC;
}
void CAxisSettingsDlg::SetRecipeName(const CString& strRecipeName)
{
    m_strRecipeName = strRecipeName;
}
void CAxisSettingsDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_STATIC_AXIS_TEST_FLS, m_staticFLS);
    DDX_Control(pDX, IDC_STATIC_AXIS_TEST_DOG, m_staticDOG);
    DDX_Control(pDX, IDC_STATIC_AXIS_TEST_RLS, m_staticRLS);
    DDX_Control(pDX, IDC_STATIC_AXIS_TEST_READY, m_staticReady);
    DDX_Control(pDX, IDC_STATIC_AXIS_TEST_BUSY, m_staticBusy);
    DDX_Control(pDX, IDC_STATIC_AXIS_TEST_ERR, m_staticErr);
    DDX_Control(pDX, IDC_COMBO_AXIS_NAME, m_comboAxisNO);
    DDX_Control(pDX, IDC_STATIC_AXIS_NUMBER, m_staticAxisNO);
    DDX_Control(pDX, IDC_STATIC_AXIS_DESCRIP, m_staticAxisDescription);
    DDX_Control(pDX, IDC_STATIC_START_ADDRESS, m_staticStartAddress);
    DDX_Control(pDX, IDC_EDIT_AXIS_MODITFY_POS, m_editManualSpeed);
    DDX_Control(pDX, IDC_EDIT_AXIS_MODITFY_AUTO_SPEED, m_editAutoSpeed);
    DDX_Control(pDX, IDC_EDIT_AXIS_MODITFY_ACCE_TIME, m_editAccelerationTime);
    DDX_Control(pDX, IDC_EDIT_AXIS_MODITFY_DECE_TIME, m_editDecelerationTime);
    DDX_Control(pDX, IDC_EDIT_AXIS_MODITFY_MICROMENTUM, m_editJogDistance);
    DDX_Control(pDX, IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP1, m_pageButtons[0]);
    DDX_Control(pDX, IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP2, m_pageButtons[1]);
    DDX_Control(pDX, IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP3, m_pageButtons[2]);
    DDX_Control(pDX, IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP4, m_pageButtons[3]);
    DDX_Control(pDX, IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP5, m_pageButtons[4]);
}
UINT CAxisSettingsDlg::FindIDByName(const CString& strControlID)
{
    // å°†èµ„源文件中定义的控件名称和 ID åŠ è½½åˆ°ä¸€ä¸ªæ˜ å°„ä¸­
    static const std::map<CString, UINT> controlIdMap = {
        {"IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP1", IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP1},
        {"IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP2", IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP2},
        {"IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP3", IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP3},
        {"IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP4", IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP4},
        {"IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP5", IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP5},
        {"IDC_EDIT_AXIS_ANCHOR_POINT1", IDC_EDIT_AXIS_ANCHOR_POINT1},
        {"IDC_EDIT_AXIS_ANCHOR_POINT2", IDC_EDIT_AXIS_ANCHOR_POINT2},
        {"IDC_EDIT_AXIS_ANCHOR_POINT3", IDC_EDIT_AXIS_ANCHOR_POINT3},
        {"IDC_EDIT_AXIS_ANCHOR_POINT4", IDC_EDIT_AXIS_ANCHOR_POINT4},
        {"IDC_EDIT_AXIS_ANCHOR_POINT5", IDC_EDIT_AXIS_ANCHOR_POINT5}
        // å¯ä»¥ç»§ç»­æ·»åŠ å…¶ä»–æŽ§ä»¶åç§°å’Œ ID
    };
    // æŸ¥æ‰¾æŽ§ä»¶åç§°æ˜¯å¦åœ¨æ˜ å°„中
    auto it = controlIdMap.find(strControlID);
    if (it != controlIdMap.end()) {
        return it->second;
    }
    return 0;
}
CFont* CAxisSettingsDlg::GetOrCreateFont(int nFontSize)
{
    auto it = m_mapFonts.find(nFontSize);
    if (it != m_mapFonts.end()) {
        return it->second;
    }
    CFont* font = new CFont();
    LOGFONT logFont = { 0 };
    _tcscpy_s(logFont.lfFaceName, _T("Segoe UI"));
    logFont.lfHeight = -nFontSize;
    logFont.lfQuality = CLEARTYPE_QUALITY;
    font->CreateFontIndirect(&logFont);
    m_mapFonts[nFontSize] = font;
    return font;
}
void CAxisSettingsDlg::SetDefaultFont()
{
    CFont* defaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰æŽ§ä»¶ï¼Œåº”ç”¨é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        pWnd->SetFont(defaultFont, TRUE);
        pWnd = pWnd->GetNextWindow();
    }
}
void CAxisSettingsDlg::AdjustControls(float dScaleX, float dScaleY)
{
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1 && m_mapCtrlLayouts.find(nCtrlID) != m_mapCtrlLayouts.end())
        {
            CRect originalRect = m_mapCtrlLayouts[nCtrlID];
            CRect newRect(
                static_cast<int>(originalRect.left * dScaleX),
                static_cast<int>(originalRect.top * dScaleY),
                static_cast<int>(originalRect.right * dScaleX),
                static_cast<int>(originalRect.bottom * dScaleY));
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("ComboBox")) == 0) {
                CComboBox* pComboBox = (CComboBox*)pWnd;
                pComboBox->SetItemHeight(-1, newRect.Height());  // -1 è¡¨ç¤ºæ‰€æœ‰é¡¹çš„高度
            }
            pWnd->MoveWindow(&newRect);
            AdjustControlFont(pWnd, newRect.Width(), newRect.Height());
        }
        pWnd = pWnd->GetNextWindow();
    }
}
void CAxisSettingsDlg::AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight)
{
    // æ ¹æ®æŽ§ä»¶é«˜åº¦åŠ¨æ€è°ƒæ•´å­—ä½“å¤§å°
    int fontSize = nHeight / 2;
    if (fontSize < 8) fontSize = 8;
    if (fontSize > 24) fontSize = 24;  // æœ€å¤§å­—体大小
    // èŽ·å–æˆ–åˆ›å»ºå­—ä½“
    CFont* pFont = GetOrCreateFont(fontSize);
    pWnd->SetFont(pFont);
    pWnd->Invalidate(); // åˆ·æ–°æŽ§ä»¶æ˜¾ç¤º
}
void CAxisSettingsDlg::AdjustLabelFont(CBLLabel& label)
{
    // èŽ·å–æŽ§ä»¶çš„çŸ©å½¢åŒºåŸŸ
    CRect rect;
    label.GetClientRect(&rect);
    // åŠ¨æ€è®¡ç®—å­—ä½“å¤§å°ï¼ŒåŸºäºŽæŽ§ä»¶çš„é«˜åº¦
    int fontSize = rect.Height() / 2; // æŽ§ä»¶é«˜åº¦çš„一半作为字体大小
    if (fontSize < 8) fontSize = 8;   // æœ€å°å­—体大小
    if (fontSize > 30) fontSize = 30; // æœ€å¤§å­—体大小
    // è®¾ç½®å­—体大小
    label.SetFontSize(fontSize);
    // åˆ·æ–°æŽ§ä»¶æ˜¾ç¤º
    label.Invalidate();
    label.UpdateWindow();
}
void CAxisSettingsDlg::SetStatusColor(CBLLabel& label, BOOL bStatus)
{
    if (bStatus) {
        label.SetBkColor(RGB(0, 255, 0)); // ç»¿è‰²
    }
    else {
        label.SetBkColor(RGB(255, 0, 0)); // çº¢è‰²
    }
    label.Invalidate();              // æ ‡è®°åŒºåŸŸæ— æ•ˆ
    label.UpdateWindow();            // ç«‹å³åˆ·æ–°
}
void CAxisSettingsDlg::updatePageButtonStates()
{
    for (int i = 0; i < 5; ++i) {
        if (i + 1 == m_currentPage) {
            m_pageButtons[i].SetFaceColor(RGB(0, 122, 204));    // é€‰ä¸­èƒŒæ™¯è‰²ï¼ˆè“è‰²ï¼‰
        }
        else {
            m_pageButtons[i].SetFaceColor(RGB(240, 240, 240));    // é»˜è®¤èƒŒæ™¯è‰²
        }
        m_pageButtons[i].Invalidate();
    }
}
int CAxisSettingsDlg::getCurrentSelectedAxisID()
{
    int currentIndex = m_comboAxisNO.GetCurSel();
    if (currentIndex == CB_ERR) {
        return -1;
    }
    CString strAxisIDStr;
    m_comboAxisNO.GetLBText(currentIndex, strAxisIDStr);
    return _ttoi(strAxisIDStr);
}
void CAxisSettingsDlg::initializeAxisIDCombo()
{
    // æ£€æŸ¥é…æ–¹æ˜¯å¦åŠ è½½æˆåŠŸ
    RecipeManager& recipeManager = RecipeManager::getInstance();
    if (m_strRecipeName.IsEmpty() || !recipeManager.loadRecipe(std::string(CT2A(m_strRecipeName)))) {
        AfxMessageBox(_T("加载配方失败!"));
        return;
    }
    // èŽ·å–æ‰€æœ‰è½´çš„ç¼–å·
    auto axisNumbers = recipeManager.getAllAxisID();
    // æ¸…空下拉框
    m_comboAxisNO.ResetContent();
    // å¡«å……数据到下拉框
    for (const auto& axisID : axisNumbers) {
        CString axisCString;
        axisCString.Format(_T("%d"), axisID);
        m_comboAxisNO.AddString(axisCString);
    }
    // é»˜è®¤é€‰æ‹©ç¬¬ä¸€é¡¹
    if (m_comboAxisNO.GetCount() > 0) {
        m_comboAxisNO.SetCurSel(0);
    }
}
void CAxisSettingsDlg::refreshAxisDetails(int nAxisId)
{
    // èŽ·å–è½´æ•°æ®
    RecipeManager& recipeManager = RecipeManager::getInstance();
    auto axisDetails = recipeManager.getAxis(nAxisId);
    auto formatDouble = [](double value) -> CString {
        CString str;
        str.Format(_T("%.3f"), value);
        return str;
    };
    // æ›´æ–°æŽ§ä»¶æ˜¾ç¤º
    m_staticAxisNO.SetWindowText(CString(axisDetails.number.c_str()));                    // è½´ç¼–号
    m_staticAxisDescription.SetWindowText(CString(axisDetails.description.c_str()));    // è½´æè¿°
    m_staticStartAddress.SetWindowText(CString(axisDetails.startAddress.c_str()));        // èµ·å§‹åœ°å€
    m_editJogDistance.SetWindowText(formatDouble(axisDetails.jogDistance));                // å¾®åŠ¨é‡
    m_editManualSpeed.SetWindowText(formatDouble(axisDetails.manualSpeed));                // æ‰‹åŠ¨é€Ÿåº¦
    m_editAutoSpeed.SetWindowText(formatDouble(axisDetails.autoSpeed));                    // è‡ªåŠ¨é€Ÿåº¦
    m_editAccelerationTime.SetWindowText(formatDouble(axisDetails.accelerationTime));    // åŠ é€Ÿæ—¶é—´
    m_editDecelerationTime.SetWindowText(formatDouble(axisDetails.decelerationTime));    // å‡é€Ÿæ—¶é—´
}
void CAxisSettingsDlg::refreshPositionDetails(int nAxisId, int pageNumber)
{
    RecipeManager& recipeManager = RecipeManager::getInstance();
    // æ¯é¡µæ˜¾ç¤ºçš„定位点数量
    const int pageSize = 5;
    // èŽ·å–å®šä½ç‚¹æ•°æ®
    auto positions = recipeManager.getPositions(nAxisId, pageNumber, pageSize);
    // åˆ·æ–° UI
    for (int i = 0; i < pageSize; ++i) {
        CString descriptionCtrlName, positionCtrlName;
        descriptionCtrlName.Format(_T("IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP%d"), i + 1);
        positionCtrlName.Format(_T("IDC_EDIT_AXIS_ANCHOR_POINT%d"), i + 1);
        UINT descriptionCtrlId = FindIDByName(descriptionCtrlName);
        UINT positionCtrlId = FindIDByName(positionCtrlName);
        CWnd* pDescriptionCtrl = GetDlgItem(descriptionCtrlId);
        CWnd* pPositionCtrl = GetDlgItem(positionCtrlId);
        if (i < positions.size()) {
            CString description = CString(positions[i].first.c_str());
            CString value;
            value.Format(_T("%.3f"), positions[i].second);
            if (pDescriptionCtrl) pDescriptionCtrl->SetWindowText(description);
            if (pPositionCtrl) pPositionCtrl->SetWindowText(value);
        }
        else {
            if (pDescriptionCtrl) pDescriptionCtrl->SetWindowText(_T(""));
            if (pPositionCtrl) pPositionCtrl->SetWindowText(_T(""));
        }
    }
}
void CAxisSettingsDlg::updateAxisSelection(int offset)
{
    int currentIndex = m_comboAxisNO.GetCurSel();
    if (currentIndex == CB_ERR) {
        AfxMessageBox(_T("请选择一个有效的轴编号!"));
        return;
    }
    int newIndex = currentIndex + offset;
    if (newIndex < 0 || newIndex >= m_comboAxisNO.GetCount()) {
        CString error;
        error.Format(_T("已经到达%s一个轴!"), offset < 0 ? _T("上") : _T("下"));
        AfxMessageBox(error);
        return;
    }
    m_comboAxisNO.SetCurSel(newIndex);
    refreshAxisDetails(newIndex + 1);
    refreshPositionDetails(newIndex + 1, m_currentPage);
    updatePageButtonStates();
}
void CAxisSettingsDlg::updateDataFromUI(int nAxisId)
{
    const int pageSize = 5; // æ¯é¡µæ˜¾ç¤º 5 ä¸ªå®šä½ç‚¹
    RecipeManager& recipeManager = RecipeManager::getInstance();
    auto axisData = recipeManager.getAxis(nAxisId);
    // èŽ·å–ç•Œé¢ä¸Šçš„ä¿®æ”¹å‚æ•°
    CString text;
    m_editManualSpeed.GetWindowText(text);
    axisData.manualSpeed = _ttof(text);
    m_editAutoSpeed.GetWindowText(text);
    axisData.autoSpeed = _ttof(text);
    m_editAccelerationTime.GetWindowText(text);
    axisData.accelerationTime = _ttof(text);
    m_editDecelerationTime.GetWindowText(text);
    axisData.decelerationTime = _ttof(text);
    m_editJogDistance.GetWindowText(text);
    axisData.jogDistance = _ttof(text);
    // æ›´æ–°å®šä½ç‚¹æ•°æ®
    for (int i = 0; i < pageSize; ++i) {
        int index = (m_currentPage - 1) * pageSize + i;
        if (index < axisData.positions.size()) {
            CString descriptionName, positionName;
            descriptionName.Format(_T("IDC_EDIT_AXIS_ANCHOR_POINT_DESCRIP%d"), i + 1);
            positionName.Format(_T("IDC_EDIT_AXIS_ANCHOR_POINT%d"), i + 1);
            CEdit* pDescriptionEdit = (CEdit*)GetDlgItem(FindIDByName(descriptionName));
            CEdit* pPositionEdit = (CEdit*)GetDlgItem(FindIDByName(positionName));
            if (pDescriptionEdit && pPositionEdit) {
                CString description, positionValue;
                pDescriptionEdit->GetWindowText(description);
                pPositionEdit->GetWindowText(positionValue);
                // æ›´æ–° RecipeManager ä¸­çš„æ•°æ®
                axisData.positions[index].first = CT2A(description);
                axisData.positions[index].second = _ttof(positionValue);
            }
        }
    }
    // ä¿å­˜å›ž RecipeManager
    recipeManager.updateAxis(axisData);
}
void CAxisSettingsDlg::switchToPage(int targetPage)
{
    try {
        // å¦‚果当前页面已经是目标页面,直接返回
        if (m_currentPage == targetPage) {
            return;
        }
        // èŽ·å–å½“å‰é€‰ä¸­çš„è½´ ID
        int axisId = getCurrentSelectedAxisID();
        if (axisId == -1) {
            AfxMessageBox(_T("请选择一个有效的轴编号!"));
            return;
        }
        // æ›´æ–° UI æ•°æ®åˆ°å†…å­˜
        updateDataFromUI(axisId);
        // åˆ‡æ¢é¡µé¢
        m_currentPage = targetPage;
        refreshPositionDetails(axisId, targetPage);
        updatePageButtonStates();
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("刷新定位组%d失败:%s"), targetPage, CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
void CAxisSettingsDlg::writeAxisDataToPLC(int nAxisId)
{
    // ä»Ž RecipeManager èŽ·å–è½´æ•°æ®
    RecipeManager& recipeManager = RecipeManager::getInstance();
    auto axisData = recipeManager.getAxis(nAxisId);
    // åŽ»é™¤éžæ•°å­—å­—ç¬¦å¹¶è½¬æ¢èµ·å§‹åœ°å€
    std::string cleanAddress = axisData.startAddress;
    cleanAddress.erase(std::remove_if(cleanAddress.begin(), cleanAddress.end(),
        [](char c) { return !std::isdigit(c); }), cleanAddress.end());
    if (cleanAddress.empty()) {
        AfxMessageBox(_T("无效的起始地址!"));
        return;
    }
    int startAddress = std::stoi(cleanAddress);
    // å†™å…¥æ‰‹åŠ¨é€Ÿåº¦
    m_pPLC->writeWord(MC::SOFT_COMPONENT::D, 5120, (int)axisData.manualSpeed, [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
        if (flag == 0) {
            TRACE("\n写入成功: æ‰‹åŠ¨é€Ÿåº¦, åœ°å€: %d, å€¼: %lu\n", addr, value);
        }
        else {
            TRACE("\n写入失败: æ‰‹åŠ¨é€Ÿåº¦, åœ°å€: %d, é”™è¯¯ç : %d\n", addr, flag);
        }
    });
    // å†™å…¥è‡ªåŠ¨é€Ÿåº¦
    m_pPLC->writeWord(MC::SOFT_COMPONENT::D, startAddress + 2, (int)axisData.autoSpeed, [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
        if (flag == 0) {
            TRACE("\n写入成功: è‡ªåŠ¨é€Ÿåº¦, åœ°å€: %d, å€¼: %lu\n", addr, value);
        }
        else {
            TRACE("\n写入失败: è‡ªåŠ¨é€Ÿåº¦, åœ°å€: %d, é”™è¯¯ç : %d\n", addr, flag);
        }
    });
    // å†™å…¥åŠ é€Ÿæ—¶é—´, è½¬æ¢ä¸ºæ¯«ç§’
    m_pPLC->writeWord(MC::SOFT_COMPONENT::D, startAddress + 4, (int)(axisData.accelerationTime * 1000), [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
        if (flag == 0) {
            TRACE("\n写入成功: åŠ é€Ÿæ—¶é—´, åœ°å€: %d, å€¼: %lu\n", addr, value);
        }
        else {
            TRACE("\n写入失败: åŠ é€Ÿæ—¶é—´, åœ°å€: %d, é”™è¯¯ç : %d\n", addr, flag);
        }
    });
    // å†™å…¥å‡é€Ÿæ—¶é—´, è½¬æ¢ä¸ºæ¯«ç§’
    m_pPLC->writeWord(MC::SOFT_COMPONENT::D, startAddress + 6, (int)(axisData.decelerationTime * 1000), [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
        if (flag == 0) {
            TRACE("\n写入成功: å‡é€Ÿæ—¶é—´, åœ°å€: %d, å€¼: %lu\n", addr, value);
        }
        else {
            TRACE("\n写入失败: å‡é€Ÿæ—¶é—´, åœ°å€: %d, é”™è¯¯ç : %d\n", addr, flag);
        }
    });
    // å†™å…¥å¾®åŠ¨é‡
    m_pPLC->writeWord(MC::SOFT_COMPONENT::D, startAddress + 8, (int)axisData.jogDistance, [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
        if (flag == 0) {
            TRACE("\n写入成功: å¾®åŠ¨é‡, åœ°å€: %d, å€¼: %lu\n", addr, value);
        }
        else {
            TRACE("\n写入失败: å¾®åŠ¨é‡, åœ°å€: %d, é”™è¯¯ç : %d\n", addr, flag);
        }
    });
    // å†™å…¥å®šä½ç‚¹æ•°æ®
    int positionStartAddress = startAddress + 10;
    for (size_t i = 0; i < axisData.positions.size(); ++i) {
        const auto& position = axisData.positions[i];
        int positionAddress = positionStartAddress + (i * 2);
        m_pPLC->writeWord(MC::SOFT_COMPONENT::D, positionAddress, (int)position.second, [i](IMcChannel* pChannel, int addr, DWORD value, int flag) {
            if (flag == 0) {
                TRACE("\n写入成功: å®šä½ç‚¹ %d, åœ°å€: %d, å€¼: %lu\n", i + 1, addr, value);
            }
            else {
                TRACE("\n写入失败: å®šä½ç‚¹ %d, åœ°å€: %d, é”™è¯¯ç : %d\n", i + 1, addr, flag);
            }
        });
    }
}
void CAxisSettingsDlg::handleAxisOperation(AxisOperationType eOpType, bool bPressed)
{
    int nAxisId = getCurrentSelectedAxisID();
    if (nAxisId == -1) {
        AfxMessageBox(_T("未选择有效的轴编号!"));
        return;
    }
    // èŽ·å–è½´æ•°æ®
    RecipeManager& recipeManager = RecipeManager::getInstance();
    auto axisData = recipeManager.getAxis(nAxisId);
    std::string strCleanAddress = axisData.startAddress;
    strCleanAddress.erase(std::remove_if(strCleanAddress.begin(), strCleanAddress.end(),
        [](unsigned char c) { return !std::isdigit(c); }), strCleanAddress.end());
    if (strCleanAddress.empty()) {
        AfxMessageBox(_T("无效的起始地址!"));
        return;
    }
    int nStartAddress = std::stoi(strCleanAddress);
    // æ ¹æ®æ“ä½œç±»åž‹è®¡ç®—目标地址
    int nTargetAddress = nStartAddress;
    switch (eOpType) {
    case AxisOperationType::OPR:
        nTargetAddress += 10; // OPR ä¿¡å·åœ°å€
        break;
    case AxisOperationType::JOG_ADD:
        nTargetAddress += 12; // JOG+ ä¿¡å·åœ°å€
        break;
    case AxisOperationType::JOG_SUB:
        nTargetAddress += 13; // JOG- ä¿¡å·åœ°å€
        break;
    case AxisOperationType::STOP:
        nTargetAddress += 14; // STOP ä¿¡å·åœ°å€
        break;
    case AxisOperationType::POSITION_1:
        nTargetAddress += 16; // å®šä½ç‚¹ 1 ä¿¡å·åœ°å€
        break;
    case AxisOperationType::POSITION_2:
        nTargetAddress += 18; // å®šä½ç‚¹ 2 ä¿¡å·åœ°å€
        break;
    case AxisOperationType::POSITION_3:
        nTargetAddress += 20; // å®šä½ç‚¹ 3 ä¿¡å·åœ°å€
        break;
    case AxisOperationType::POSITION_4:
        nTargetAddress += 22; // å®šä½ç‚¹ 4 ä¿¡å·åœ°å€
        break;
    case AxisOperationType::POSITION_5:
        nTargetAddress += 24; // å®šä½ç‚¹ 5 ä¿¡å·åœ°å€
        break;
    default:
        AfxMessageBox(_T("未知操作类型!"));
        return;
    }
    // å‘ PLC å†™å…¥ä¿¡å·
    m_pPLC->writeBit(MC::SOFT_COMPONENT::D, nTargetAddress, bPressed, [eOpType, nTargetAddress, bPressed](IMcChannel* pChannel, int nAddr, DWORD nValue, int nFlag) {
        if (nFlag == 0) {
            TRACE("操作成功:类型=%d,地址=%d,值=%d\n", static_cast<int>(eOpType), nAddr, bPressed);
        }
        else {
            TRACE("操作失败:类型=%d,地址=%d,错误码=%d\n", static_cast<int>(eOpType), nAddr, nFlag);
        }
    });
}
BEGIN_MESSAGE_MAP(CAxisSettingsDlg, CDialogEx)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_LAST, &CAxisSettingsDlg::OnBnClickedButtonAxisLast)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_NEXT, &CAxisSettingsDlg::OnBnClickedButtonAxisNext)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP1, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup1)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP2, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup2)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP3, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup3)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP4, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup4)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT_GROUP5, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup5)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT1, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint1)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT2, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint2)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT3, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint3)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT4, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint4)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_ANCHOR_POINT5, &CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint5)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_TEST_OPR, &CAxisSettingsDlg::OnBnClickedButtonAxisTestOpr)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_TEST_STOP, &CAxisSettingsDlg::OnBnClickedButtonAxisTestStop)
    ON_CBN_SELCHANGE(IDC_COMBO_AXIS_NAME, &CAxisSettingsDlg::OnSelchangeComboAxisName)
    ON_BN_CLICKED(IDC_BUTTON_AXIS_SAVE, &CAxisSettingsDlg::OnBnClickedButtonAxisSave)
    ON_WM_SIZE()
    ON_WM_CTLCOLOR()
    ON_WM_SIZING()
    ON_WM_TIMER()
END_MESSAGE_MAP()
// CAxisSettingsDlg æ¶ˆæ¯å¤„理程序
BOOL CAxisSettingsDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    // TODO:  åœ¨æ­¤æ·»åŠ é¢å¤–çš„åˆå§‹åŒ–
    CString strTitle;
    strTitle.Format(_T("Axis设定(配方: %s)"), m_strRecipeName);
    SetWindowText(strTitle);
    // è®¾ç½®æµ‹è¯•状态
    CBLLabel* pLabels[] = { &m_staticFLS, &m_staticDOG, &m_staticRLS, &m_staticReady, &m_staticBusy, &m_staticErr };
    for (auto pLabel : pLabels) {
        SetStatusColor(*pLabel, FALSE);
        pLabel->ModifyStyle(0, SS_NOTIFY);
        pLabel->SetTextColor(RGB(255, 255, 255));
        pLabel->SetAlignment(AlignCenter);
        pLabel->SetDynamicFont(TRUE);
    }
    // åˆå§‹åŒ–当前页面为第一页
    m_currentPage = 1;
    updatePageButtonStates();
    initializeAxisIDCombo();
    refreshAxisDetails(1);
    refreshPositionDetails(1, m_currentPage);
    CRect screenRect, dlgRect, clientRect;
    GetClientRect(&clientRect);
    m_nInitialWidth = clientRect.Width();
    m_nInitialHeight = clientRect.Height();
    // åˆå§‹åŒ–默认字体
    CFont* pDefaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰å­æŽ§ä»¶ï¼Œè®°å½•åˆå§‹ä½ç½®å¹¶è®¾ç½®é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1) {
            // è®°å½•控件初始布局
            CRect ctrlRect;
            pWnd->GetWindowRect(&ctrlRect);
            ScreenToClient(&ctrlRect);
            m_mapCtrlLayouts[nCtrlID] = ctrlRect;
            // è®¾ç½®é»˜è®¤å­—体
            pWnd->SetFont(pDefaultFont);
        }
        pWnd = pWnd->GetNextWindow();
    }
    GetWindowRect(&dlgRect);
    int dlgWidth = dlgRect.Width() * 2;
    int dlgHeight = dlgRect.Height() * 2;
    SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRect, 0);
    if (dlgWidth > screenRect.Width()) {
        dlgWidth = screenRect.Width();
    }
    if (dlgHeight > screenRect.Height()) {
        dlgHeight = screenRect.Height();
    }
    int centerX = screenRect.left + (screenRect.Width() - dlgWidth) / 2;
    int centerY = screenRect.top + (screenRect.Height() - dlgHeight) / 2;
    MoveWindow(centerX, centerY, dlgWidth, dlgHeight);
    SetTimer(TIMER_READ_PLC_DATA, 500, nullptr);
    return TRUE;  // return TRUE unless you set the focus to a control
    // å¼‚常: OCX å±žæ€§é¡µåº”返回 FALSE
}
BOOL CAxisSettingsDlg::PreTranslateMessage(MSG* pMsg)
{
    // TODO: åœ¨æ­¤æ·»åŠ ä¸“ç”¨ä»£ç å’Œ/或调用基类
    if (pMsg->message == WM_LBUTTONDOWN)
    {
        if (pMsg->hwnd == GetDlgItem(IDC_BUTTON_AXIS_TEST_JOG_ADD)->m_hWnd)
        {
            TRACE("JOG+ æŒ‰é’®æŒ‰ä¸‹\n");
            m_bJogAddPressed = TRUE;
            // å¯åŠ¨å®šæ—¶å™¨è¿žç»­å‘é€ä¿¡å·
            SetTimer(TIMER_JOG_ADD, 200, nullptr);
            handleAxisOperation(AxisOperationType::JOG_ADD, true);
        }
        else if (pMsg->hwnd == GetDlgItem(IDC_BUTTON_AXIS_TEST_JOG_SUB)->m_hWnd)
        {
            TRACE("JOG- æŒ‰é’®æŒ‰ä¸‹\n");
            m_bJogSubPressed = TRUE;
            // å¯åŠ¨å®šæ—¶å™¨è¿žç»­å‘é€ä¿¡å·
            SetTimer(TIMER_JOG_SUB, 200, nullptr);
            handleAxisOperation(AxisOperationType::JOG_SUB, true);
        }
    }
    else if (pMsg->message == WM_LBUTTONUP)
    {
        if (pMsg->hwnd == GetDlgItem(IDC_BUTTON_AXIS_TEST_JOG_ADD)->m_hWnd)
        {
            TRACE("JOG+ æŒ‰é’®æ¾å¼€\n");
            m_bJogAddPressed = FALSE;
            // åœæ­¢å®šæ—¶å™¨
            KillTimer(TIMER_JOG_ADD);
            handleAxisOperation(AxisOperationType::JOG_ADD, false);
        }
        else if (pMsg->hwnd == GetDlgItem(IDC_BUTTON_AXIS_TEST_JOG_SUB)->m_hWnd)
        {
            TRACE("JOG- æŒ‰é’®æ¾å¼€\n");
            m_bJogSubPressed = FALSE;
            // åœæ­¢å®šæ—¶å™¨
            KillTimer(TIMER_JOG_SUB);
            handleAxisOperation(AxisOperationType::JOG_SUB, false);
        }
    }
    return CDialogEx::PreTranslateMessage(pMsg);
}
void CAxisSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);
    // TODO: åœ¨æ­¤å¤„添加消息处理程序代码
    if (nType == SIZE_MINIMIZED || m_mapCtrlLayouts.empty()) {
        return;
    }
    float dScaleX = static_cast<float>(cx) / m_nInitialWidth;
    float dScaleY = static_cast<float>(cy) / m_nInitialHeight;
    // éåŽ†å¯¹è¯æ¡†ä¸­çš„æ‰€æœ‰æŽ§ä»¶
    AdjustControls(dScaleX, dScaleY);
    // åŠ¨æ€è°ƒæ•´å„ä¸ª CBLLabel çš„字体大小
    CBLLabel* pLabels[] = { &m_staticFLS, &m_staticDOG, &m_staticRLS, &m_staticReady, &m_staticBusy, &m_staticErr };
    for (auto pLabel : pLabels) {
        AdjustLabelFont(*pLabel);
    }
    // è°ƒæ•´ä¸‹æ‹‰æ¡†é«˜åº¦
    CComboBox* pComboBox = (CComboBox*)GetDlgItem(IDC_COMBO_AXIS_NAME);
    CButton* pButtonLeft = (CButton*)GetDlgItem(IDC_BUTTON_AXIS_LAST);
    CButton* pButtonRight = (CButton*)GetDlgItem(IDC_BUTTON_AXIS_NEXT);
    if (pComboBox && pButtonLeft && pButtonRight) {
        CRect rectButton;
        pButtonLeft->GetWindowRect(&rectButton);    // èŽ·å–æŒ‰é’®å°ºå¯¸
        ScreenToClient(&rectButton);                // è½¬æ¢ä¸ºå®¢æˆ·ç«¯åæ ‡
        CRect rectComboBox;
        pComboBox->GetWindowRect(&rectComboBox);
        ScreenToClient(&rectComboBox);
        // è°ƒæ•´ä¸‹æ‹‰æ¡†é«˜åº¦
        int heightAdjustment = 2;
        rectComboBox.top = rectButton.top;
        rectComboBox.bottom = rectButton.bottom + heightAdjustment;
        pComboBox->MoveWindow(&rectComboBox);
        pComboBox->SetItemHeight(-1, rectButton.Height() - 6);
    }
}
void CAxisSettingsDlg::OnSizing(UINT fwSide, LPRECT pRect)
{
    if (fwSide == WMSZ_BOTTOMRIGHT) {
        if (pRect->right - pRect->left < 200) {
            pRect->right = pRect->left + 200;
        }
        if (pRect->bottom - pRect->top < 150) {
            pRect->bottom = pRect->top + 150;
        }
    }
    CDialogEx::OnSizing(fwSide, pRect);
}
HBRUSH CAxisSettingsDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
    // TODO:  åœ¨æ­¤æ›´æ”¹ DC çš„任何特性
    // TODO:  å¦‚果默认的不是所需画笔,则返回另一个画笔
    return hbr;
}
void CAxisSettingsDlg::OnBnClickedButtonAxisLast()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    updateAxisSelection(-1);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisNext()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    updateAxisSelection(1);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup1()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    switchToPage(1);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup2()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    switchToPage(2);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup3()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    switchToPage(3);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup4()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    switchToPage(4);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPointGroup5()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    switchToPage(5);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint1()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::POSITION_1, true);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint2()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::POSITION_2, true);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint3()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::POSITION_3, true);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint4()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::POSITION_4, true);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisAnchorPoint5()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::POSITION_5, true);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisTestOpr()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::OPR, true);
}
void CAxisSettingsDlg::OnBnClickedButtonAxisTestStop()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    handleAxisOperation(AxisOperationType::STOP, true);
}
void CAxisSettingsDlg::OnSelchangeComboAxisName()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    int axisId = getCurrentSelectedAxisID();
    if (axisId == -1) {
        AfxMessageBox(_T("请选择一个有效的轴编号!"));
        return;
    }
    refreshAxisDetails(axisId);
    refreshPositionDetails(axisId, m_currentPage);
    updatePageButtonStates();
}
void CAxisSettingsDlg::OnBnClickedButtonAxisSave()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    int axisId = getCurrentSelectedAxisID();
    if (axisId == -1) {
        AfxMessageBox(_T("请选择一个有效的轴编号!"));
        return;
    }
    CString cstrMessage;
    cstrMessage.Format(_T("是否保存轴 [%d] å‚数?"), axisId);
    int ret = AfxMessageBox(_T(cstrMessage), MB_OKCANCEL | MB_ICONEXCLAMATION);
    if (ret != IDOK) {
        return;
    }
    updateDataFromUI(axisId);
    if (RecipeManager::getInstance().saveRecipe(std::string(CT2A(m_strRecipeName)))) {
        writeAxisDataToPLC(axisId);
        cstrMessage.Format(_T("保存轴 [%d] å‚数成功!"), axisId);
        SystemLogManager::getInstance().log(SystemLogManager::LogType::Operation, std::string(CT2A(cstrMessage)));
    }
    else {
        cstrMessage.Format(_T("保存轴 [%d] å‚数失败!"), axisId);
        SystemLogManager::getInstance().log(SystemLogManager::LogType::Error, std::string(CT2A(cstrMessage)));
    }
    AfxMessageBox(cstrMessage);
}
void CAxisSettingsDlg::OnTimer(UINT_PTR nIDEvent)
{
    if (TIMER_READ_PLC_DATA == nIDEvent) {
        ASSERT(m_pPLC);
        int addr1, addr2, readSize;
        addr1 = 5120;
        addr2 = 5425;
        readSize = (addr2 - addr1 + 1) * 2;
        auto funOnReadData = [&, addr1, readSize](IMcChannel* pChannel, int addr, char* pData, unsigned int nDataSize, int flag) -> void {
            if (nDataSize == readSize && flag == 0) {
                double fCurPos = CToolUnits::toInt32(pData) * 0.001;
                double fManualSpeed = CToolUnits::toInt32(&pData[(5422- addr1)*2]) * 0.001;
                double fAutoSpeed = CToolUnits::toInt32(&pData[(5424 - addr1) * 2]) * 0.001;
                double fPrm = CToolUnits::toInt32(&pData[(5150 - addr1) * 2]) * 0.1;
                int nLoad = CToolUnits::toInt16(&pData[(5154 - addr1) * 2]);
                int nErrCode = CToolUnits::toInt16(&pData[(5126 - addr1) * 2]);
                int nAlarmCode = CToolUnits::toInt16(&pData[(5127 - addr1) * 2]);
                CToolUnits::setDlgItemDouble(this, IDC_EDIT_AXIS_CURR_POS, fCurPos);
                CToolUnits::setDlgItemDouble(this, IDC_EDIT_AXIS_CURR_MANUAL_SPEED, fManualSpeed);
                CToolUnits::setDlgItemDouble(this, IDC_EDIT_AXIS_CURR_AUTO_SPEED, fAutoSpeed);
                CToolUnits::setDlgItemDouble(this, IDC_EDIT_AXIS_CURR_ROTA_SPEED, fPrm);
                SetDlgItemInt(IDC_EDIT_AXIS_CURR_LOAD, nLoad);
                SetDlgItemInt(IDC_EDIT_AXIS_CURR_ERROR_NUMBER, nErrCode);
                SetDlgItemInt(IDC_EDIT_AXIS_CURR_ALARM_NUMBER, nAlarmCode);
            }
        };
        m_pPLC->readData(MC::SOFT_COMPONENT::D, addr1, readSize, funOnReadData);
    }
    else if (nIDEvent == TIMER_JOG_ADD && m_bJogAddPressed) {
        TRACE("持续发送 JOG+\n");
        handleAxisOperation(AxisOperationType::JOG_ADD, true); // æŒç»­å‘送 JOG+
        Sleep(20);
    }
    else if (nIDEvent == TIMER_JOG_SUB && m_bJogSubPressed) {
        TRACE("持续发送 JOG-\n");
        handleAxisOperation(AxisOperationType::JOG_SUB, true); // æŒç»­å‘送 JOG-
        Sleep(20);
    }
    CDialogEx::OnTimer(nIDEvent);
}
SourceCode/Bond/BondEq/View/AxisSettingsDlg.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,108 @@
#pragma once
#include "afxdialogex.h"
#include "BlButton.h"
#include "BLLabel.h"
#include "CPLC.h"
// CAxisSettingsDlg å¯¹è¯æ¡†
enum class AxisOperationType {
    OPR = 0,    // å›žåŽŸç‚¹
    JOG_ADD,    // æ­£å‘点动
    JOG_SUB,    // åå‘点动
    STOP,        // åœæ­¢æ“ä½œ
    POSITION_1, // å®šä½ç‚¹1
    POSITION_2, // å®šä½ç‚¹2
    POSITION_3, // å®šä½ç‚¹3
    POSITION_4, // å®šä½ç‚¹4
    POSITION_5  // å®šä½ç‚¹5
};
class CAxisSettingsDlg : public CDialogEx
{
    DECLARE_DYNAMIC(CAxisSettingsDlg)
public:
    CAxisSettingsDlg(CWnd* pParent = nullptr);   // æ ‡å‡†æž„造函数
    virtual ~CAxisSettingsDlg();
public:
    void SetPLC(CPLC* pPLC);
    void SetRecipeName(const CString& strRecipeName);
// å¯¹è¯æ¡†æ•°æ®
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_DIALOG_AXIS_SETTINGS };
#endif
private:
    UINT FindIDByName(const CString& strControlID);
    CFont* GetOrCreateFont(int nFontSize);
    void SetDefaultFont();
    void AdjustControls(float dScaleX, float dScaleY);
    void AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight);
    void AdjustLabelFont(CBLLabel& label);
    void SetStatusColor(CBLLabel& label, BOOL bStatus);
    void updatePageButtonStates();
    int getCurrentSelectedAxisID();
    void initializeAxisIDCombo();
    void refreshAxisDetails(int nAxisId);
    void refreshPositionDetails(int nAxisId, int pageNumber);
    void updateAxisSelection(int offset);
    void updateDataFromUI(int nAxisId);
    void switchToPage(int targetPage);
    void writeAxisDataToPLC(int nAxisId);
    void handleAxisOperation(AxisOperationType eOpType, bool bPressed);
private:
    CPLC* m_pPLC;
    int m_nInitialWidth;
    int m_nInitialHeight;
    // å½“前选中的定位页面索引
    int m_currentPage;
    // é…æ–¹åç§°
    CString m_strRecipeName;
    // æŒ‰ä¸‹æ ‡è¯†
    BOOL m_bJogAddPressed;
    BOOL m_bJogSubPressed;
    // æŽ§ä»¶
    CBLLabel m_staticFLS, m_staticDOG, m_staticRLS, m_staticReady, m_staticBusy, m_staticErr;
    CComboBox m_comboAxisNO;
    CStatic m_staticAxisNO, m_staticAxisDescription, m_staticStartAddress;
    CEdit m_editManualSpeed, m_editAutoSpeed, m_editAccelerationTime, m_editDecelerationTime, m_editJogDistance;
    CBlButton m_pageButtons[5];
    std::map<int, CRect> m_mapCtrlLayouts;
    std::map<int, CFont*> m_mapFonts;
protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV æ”¯æŒ
    virtual BOOL OnInitDialog();
    virtual BOOL PreTranslateMessage(MSG* pMsg);
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnSizing(UINT fwSide, LPRECT pRect);
    afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
    afx_msg void OnBnClickedButtonAxisLast();
    afx_msg void OnBnClickedButtonAxisNext();
    afx_msg void OnBnClickedButtonAxisAnchorPointGroup1();
    afx_msg void OnBnClickedButtonAxisAnchorPointGroup2();
    afx_msg void OnBnClickedButtonAxisAnchorPointGroup3();
    afx_msg void OnBnClickedButtonAxisAnchorPointGroup4();
    afx_msg void OnBnClickedButtonAxisAnchorPointGroup5();
    afx_msg void OnBnClickedButtonAxisAnchorPoint1();
    afx_msg void OnBnClickedButtonAxisAnchorPoint2();
    afx_msg void OnBnClickedButtonAxisAnchorPoint3();
    afx_msg void OnBnClickedButtonAxisAnchorPoint4();
    afx_msg void OnBnClickedButtonAxisAnchorPoint5();
    afx_msg void OnBnClickedButtonAxisTestOpr();
    afx_msg void OnBnClickedButtonAxisTestStop();
    afx_msg void OnSelchangeComboAxisName();
    afx_msg void OnBnClickedButtonAxisSave();
    afx_msg void OnTimer(UINT_PTR nIDEvent);
    DECLARE_MESSAGE_MAP()
};
SourceCode/Bond/BondEq/View/ChangePasswordDlg.cpp
@@ -5,7 +5,6 @@
#include "BondEq.h"
#include "afxdialogex.h"
#include "ChangePasswordDlg.h"
#include "UserManager.h"
// CChangePasswordDlg å¯¹è¯æ¡†
@@ -82,6 +81,7 @@
        return;
    }
    SystemLogManager& logManager = SystemLogManager::getInstance();
    if (newPassword.Compare(currentPassword) == 0) {
        EndDialog(IDCANCEL);
        return;
@@ -101,12 +101,14 @@
    if (userManager.isLoggedIn() && strCurrentPassword.compare(userManager.getCurrentPass()) == 0) {
        if (changeUserPassword(userManager, strUsername, strNewPassword)) {
            EndDialog(IDOK);
            logManager.log(SystemLogManager::LogType::Info, "修改密码成功!", strUsername);
        }
    }
    else {
        if (userManager.login(strUsername, strCurrentPassword)) {
            if (changeUserPassword(userManager, strUsername, strNewPassword)) {
                EndDialog(IDOK);
                logManager.log(SystemLogManager::LogType::Info, "修改密码成功!", strUsername);
            }
            else {
                userManager.logout();
SourceCode/Bond/BondEq/View/IOMonitoringDlg.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,568 @@
// IOMonitoringDlg.cpp: å®žçŽ°æ–‡ä»¶
//
#include "stdafx.h"
#include "BondEq.h"
#include "afxdialogex.h"
#include "IOMonitoringDlg.h"
#include "ToolUnits.h"
#define TIMER_INIT                1
#define TIMER_READ_PLC_DATA        2
// CIOMonitoringDlg å¯¹è¯æ¡†
IMPLEMENT_DYNAMIC(CIOMonitoringDlg, CDialogEx)
CIOMonitoringDlg::CIOMonitoringDlg(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_IO_MONITORING, pParent)
{
    m_nCurrentPage = 1;
    m_nTotalPages = 1;
    m_nRowsPerPage = 10;
    m_nCols = 6;
}
CIOMonitoringDlg::~CIOMonitoringDlg()
{
    for (auto& pair : m_mapFonts) {
        if (pair.second) {
            pair.second->DeleteObject();
            delete pair.second;
        }
    }
    m_mapFonts.clear();
    ClearDynamicControls();
}
void CIOMonitoringDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_STATIC_PAGE_NUMBER, m_staticPageNum);
}
void CIOMonitoringDlg::SetIOManager(const std::string& machineName)
{
    IOManager manager;
    manager.loadFromFile(machineName);
    m_machineName = machineName;
    // åŠ è½½æ•°æ®
    m_displayData = manager.GetMachineData(machineName);
    // è®¡ç®—页数
    m_nCurrentPage = 1;
    m_nTotalPages = (m_displayData.size() + m_nRowsPerPage - 1) / m_nRowsPerPage;
}
void CIOMonitoringDlg::SetPLC(CPLC* pPLC)
{
    ASSERT(pPLC);
    m_pPLC = pPLC;
}
CFont* CIOMonitoringDlg::GetOrCreateFont(int nFontSize)
{
    auto it = m_mapFonts.find(nFontSize);
    if (it != m_mapFonts.end()) {
        return it->second;
    }
    CFont* font = new CFont();
    LOGFONT logFont = { 0 };
    _tcscpy_s(logFont.lfFaceName, _T("Segoe UI"));
    logFont.lfHeight = -nFontSize;
    logFont.lfQuality = CLEARTYPE_QUALITY;
    font->CreateFontIndirect(&logFont);
    m_mapFonts[nFontSize] = font;
    return font;
}
void CIOMonitoringDlg::SetDefaultFont()
{
    CFont* defaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰æŽ§ä»¶ï¼Œåº”ç”¨é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        pWnd->SetFont(defaultFont, TRUE);
        pWnd = pWnd->GetNextWindow();
    }
}
void CIOMonitoringDlg::AdjustControls(float dScaleX, float dScaleY)
{
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1 && m_mapCtrlLayouts.find(nCtrlID) != m_mapCtrlLayouts.end()) {
            CRect originalRect = m_mapCtrlLayouts[nCtrlID];
            CRect newRect(
                static_cast<int>(originalRect.left * dScaleX),
                static_cast<int>(originalRect.top * dScaleY),
                static_cast<int>(originalRect.right * dScaleX),
                static_cast<int>(originalRect.bottom * dScaleY));
            pWnd->MoveWindow(&newRect);
            AdjustControlFont(pWnd, newRect.Width(), newRect.Height());
        }
        pWnd = pWnd->GetNextWindow();
    }
}
void CIOMonitoringDlg::AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight)
{
    TCHAR szClassName[256];
    GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
    // æ ¹æ®æŽ§ä»¶é«˜åº¦åŠ¨æ€è°ƒæ•´å­—ä½“å¤§å°
    int fontSize = nHeight / 2;
    if (fontSize < 8) fontSize = 8;
    if (fontSize < 24) fontSize = 24;
    // èŽ·å–æˆ–åˆ›å»ºå­—ä½“
    CFont* pFont = GetOrCreateFont(fontSize);
    pWnd->SetFont(pFont);
    pWnd->Invalidate(); // åˆ·æ–°æŽ§ä»¶æ˜¾ç¤º
}
void CIOMonitoringDlg::UpdatePageInfo()
{
    // æ ¼å¼åŒ–页码信息为 "当前页/总页数"
    CString pageInfo;
    pageInfo.Format(_T("%d/%d é¡µ"), m_nCurrentPage, m_nTotalPages);
    m_staticPageNum.SetWindowText(pageInfo);
}
void CIOMonitoringDlg::CreateDynamicControls()
{
    CRect rect;
    GetClientRect(&rect);
    // èŽ·å–æŒ‰é’®çš„å¤§å°
    CWnd* pPrevButton = GetDlgItem(IDC_BUTTON_PREV_PAGE);
    CWnd* pNextButton = GetDlgItem(IDC_BUTTON_NEXT_PAGE);
    CRect prevButtonRect, nextButtonRect;
    pPrevButton->GetWindowRect(&prevButtonRect);
    pNextButton->GetWindowRect(&nextButtonRect);
    // è½¬æ¢æŒ‰é’®åæ ‡åˆ°å¯¹è¯æ¡†çš„坐标系统
    ScreenToClient(&prevButtonRect);
    ScreenToClient(&nextButtonRect);
    int buttonHeight = prevButtonRect.Height();     // æŒ‰é’®çš„高度
    int topMargin = rect.Height() * 0.05;           // é¡¶éƒ¨ä¿ç•™ 5% çš„高度
    int bottomMargin = buttonHeight + topMargin;    // åº•部保留按钮高度加间距
    int sideMargin = topMargin;                     // å·¦å³é—´è·ä¸Žé¡¶éƒ¨é—´è·ç›¸åŒ
    int groupSpacing = 20;                          // ä¸¤ç»„之间的间距
    int verticalSpacing = 10;                       // åž‚直间距
    // æ¯è¡Œé«˜åº¦å’Œåˆ—宽度
    int availableHeight = rect.Height() - topMargin - bottomMargin;
    int rowHeight = (availableHeight / m_nRowsPerPage) - verticalSpacing; // æŽ§ä»¶é«˜åº¦åŒ…含间距
    int availableWidth = rect.Width() - 2 * sideMargin; // å¯ç”¨å®½åº¦ï¼ˆå‡åŽ»å·¦å³é—´è·ï¼‰
    int colWidthSmall = availableWidth / 14;            // å°å®½åº¦åˆ—更小
    int colWidthLarge = availableWidth * 4 / 14;        // å¤§å®½åº¦åˆ—比例
    int groupWidth = colWidthSmall * 2 + colWidthLarge; // æ¯ç»„总宽度
    for (int i = 0; i < m_nRowsPerPage; ++i) {
        // æ¯ä¸€è¡Œçš„èµ·å§‹ Y åæ ‡
        int y = topMargin + i * (rowHeight + verticalSpacing);
        // åˆ›å»ºç¬¬ 1 ç»„ (0, 1, 2)
        int x = sideMargin; // ä»Žå·¦è¾¹è·å¼€å§‹
        CreateStaticControl(x, y, colWidthSmall, rowHeight, _T("OFF"), true, AlignCenter);
        x += colWidthSmall;
        CreateStaticControl(x, y, colWidthSmall, rowHeight, _T("X1000"), false, AlignCenter);
        x += colWidthSmall;
        CreateStaticControl(x, y, colWidthLarge, rowHeight, _T("描述文本"), false);
        // ç¬¬ 2 ç»„起始位置,加上组间距
        x += colWidthLarge + groupSpacing;
        // åˆ›å»ºç¬¬ 2 ç»„ (3, 4, 5)
        CreateStaticControl(x, y, colWidthSmall, rowHeight, _T("OFF"), true, AlignCenter, [this, i]() {
            // è‡ªå®šä¹‰ç‚¹å‡»äº‹ä»¶çš„逻辑
            auto* pControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 3]);
            CString currentText;
            pControl->GetWindowText(currentText);
            BOOL bOn = FALSE;
            if (currentText == _T("OFF")) {
                //pControl->SetBkColor(RGB(0, 255, 0)); // ç»¿è‰²èƒŒæ™¯
                //pControl->SetText(_T("ON"));          // æ›´æ–°æ–‡æœ¬ä¸º ON
                bOn = TRUE;
            }
            else {
                //pControl->SetBkColor(RGB(255, 0, 0)); // çº¢è‰²èƒŒæ™¯
                //pControl->SetText(_T("OFF"));         // æ›´æ–°æ–‡æœ¬ä¸º OFF
                bOn = FALSE;
            }
            pControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 4]);
            pControl->GetWindowText(currentText);
            int nAddress;
            MC::SOFT_COMPONENT component;
            if (ParsePLCAddress(currentText, component, nAddress) && m_pPLC) {
                TRACE("地址解析成功: %s\n", currentText);
                m_pPLC->writeBit(component, nAddress, bOn, [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
                    if (flag == 0) {
                        TRACE("写入成功: åœ°å€: %d, å€¼: %lu\n", addr, value);
                    }
                    else {
                        TRACE("写入失败: åœ°å€: %d, é”™è¯¯ç : %d\n", addr, flag);
                    }
                });
            }
        });
        x += colWidthSmall;
        CreateStaticControl(x, y, colWidthSmall, rowHeight, _T("Y1010"), false, AlignCenter);
        x += colWidthSmall;
        CreateStaticControl(x, y, colWidthLarge, rowHeight, _T("描述文本"), false);
    }
}
void CIOMonitoringDlg::CreateStaticControl(int x, int y, int width, int height, const CString& text, bool hasBorder, TextAlign alignment, std::function<void()> clickCallback)
{
    // åˆ›å»ºåŠ¨æ€æŽ§ä»¶
    CBLLabel* pStatic = new CBLLabel();
    DWORD style = WS_CHILD | WS_VISIBLE | SS_CENTERIMAGE; // ç¡®ä¿åž‚直居中
    if (hasBorder) {
        style |= WS_BORDER; // æ·»åŠ è¾¹æ¡†
    }
    pStatic->Create(text, style, CRect(x, y, x + width, y + height), this);
    // è®¾ç½®æ–‡æœ¬å¯¹é½æ–¹å¼
    pStatic->SetAlignment(alignment);
    // è®¾ç½®åŠ¨æ€å­—ä½“è°ƒæ•´ï¼Œå¹¶è®¾ç½®å­—ä½“å¤§å°ï¼ˆåŠ¨æ€å­—ä½“ä¼šæ ¹æ®æŽ§ä»¶å¤§å°è°ƒæ•´ï¼‰
    int nSize = height / 3;
    CFont* pFont = GetOrCreateFont(nSize);
    pStatic->SetFont(pFont);
    pStatic->SetFontSize(nSize);
    pStatic->SetDynamicFont(TRUE);
    // è®¾ç½®å›žè°ƒ
    if (clickCallback) {
        pStatic->SetClickCallback(clickCallback);
    }
    // å­˜å‚¨æŽ§ä»¶æŒ‡é’ˆ
    m_staticControls.push_back(pStatic);
}
void CIOMonitoringDlg::DisplayCurrentPage()
{
    int startIndex = (m_nCurrentPage - 1) * m_nRowsPerPage;
    int endIndex = min(startIndex + m_nRowsPerPage, static_cast<int>(m_displayData.size()));
    m_inputPLCAddresses.clear();
    m_outputPLCAddresses.clear();
    for (int i = 0; i < m_nRowsPerPage; ++i) {
        int row = i;
        if (startIndex + i < endIndex) {
            const auto& data = m_displayData[startIndex + i];
            // æ·»åŠ  PLC åœ°å€åˆ°å®¹å™¨ä¸­
            m_inputPLCAddresses.push_back(CString(data.inputAddress.c_str()));        // 1 åˆ—
            m_outputPLCAddresses.push_back(CString(data.outputAddress.c_str()));    // 4 åˆ—
            // æ˜¾ç¤ºæŽ§ä»¶å¹¶è®¾ç½®å†…容
            m_staticControls[row * m_nCols + 0]->SetWindowText(_T("OFF"));
            m_staticControls[row * m_nCols + 0]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 0]->SetBkColor(RGB(255, 0, 0));
            m_staticControls[row * m_nCols + 1]->SetWindowText(CString(data.inputAddress.c_str()));
            m_staticControls[row * m_nCols + 1]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 2]->SetWindowText(CString(data.inputDescription.c_str()));
            m_staticControls[row * m_nCols + 2]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 3]->SetWindowText(_T("OFF"));
            m_staticControls[row * m_nCols + 3]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 3]->SetBkColor(RGB(255, 0, 0));
            m_staticControls[row * m_nCols + 4]->SetWindowText(CString(data.outputAddress.c_str()));
            m_staticControls[row * m_nCols + 4]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 5]->SetWindowText(CString(data.outputDescription.c_str()));
            m_staticControls[row * m_nCols + 5]->ShowWindow(SW_SHOW);
        }
        else {
            // éšè—è¿™ä¸€è¡Œçš„æ‰€æœ‰æŽ§ä»¶
            for (int col = 0; col < m_nCols; ++col) {
                m_staticControls[row * m_nCols + col]->ShowWindow(SW_HIDE);
            }
        }
    }
    UpdatePageInfo();
}
void CIOMonitoringDlg::ClearDynamicControls()
{
    for (auto* pStatic : m_staticControls) {
        if (pStatic) {
            pStatic->DestroyWindow();
            delete pStatic;
        }
    }
    m_staticControls.clear();
}
bool CIOMonitoringDlg::ParsePLCAddress(const CString& address, MC::SOFT_COMPONENT& component, int& addr)
{
    if (address.GetLength() < 2) {
        return false;
    }
    // æå–组件类型(第一个字符)
    TCHAR componentChar = address[0];
    switch (componentChar) {
    case 'D':
        component = MC::SOFT_COMPONENT::D;
        break;
    case 'M':
        component = MC::SOFT_COMPONENT::M;
        break;
    case 'X':
        component = MC::SOFT_COMPONENT::X;
        break;
    case 'Y':
        component = MC::SOFT_COMPONENT::Y;
        break;
    default:
        return false;
    }
    CString hexAddress = address.Mid(1);
    addr = _tcstoul(hexAddress, nullptr, 16);
    return true;
}
void CIOMonitoringDlg::UpdatePLCStates()
{
    // ç¤ºä¾‹ï¼šä»Ž PLC èŽ·å–å€¼ï¼Œè¿™é‡Œç”¨éšæœºå€¼æ¨¡æ‹Ÿ
    //for (size_t i = 0; i < m_inputPLCAddresses.size(); ++i) {
    //    // æ¨¡æ‹ŸèŽ·å–è¾“å…¥çŠ¶æ€
    //    bool inputState = (rand() % 2 == 0); // å¶å°”为 true/false
    //    auto* inputControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 0]);
    //    inputControl->SetBkColor(inputState ? RGB(0, 255, 0) : RGB(255, 0, 0));
    //    inputControl->SetText(inputState ? _T("ON") : _T("OFF"));
    //}
    //for (size_t i = 0; i < m_outputPLCAddresses.size(); ++i) {
    //    // æ¨¡æ‹ŸèŽ·å–è¾“å‡ºçŠ¶æ€
    //    bool outputState = (rand() % 2 == 0); // å¶å°”为 true/false
    //    auto* outputControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 3]);
    //    outputControl->SetBkColor(outputState ? RGB(0, 255, 0) : RGB(255, 0, 0));
    //    outputControl->SetText(outputState ? _T("ON") : _T("OFF"));
    //}
    // è¾“入地址的读取
    if (!m_inputPLCAddresses.empty()) {
        // èŽ·å–èµ·å§‹åœ°å€å’Œé•¿åº¦
        CString startAddressStr = m_inputPLCAddresses.front();
        CString endAddressStr = m_inputPLCAddresses.back();
        MC::SOFT_COMPONENT component;
        int startAddress, endAddress;
        // è§£æžèµ·å§‹å’Œç»“束地址
        if (ParsePLCAddress(startAddressStr, component, startAddress) &&
            ParsePLCAddress(endAddressStr, component, endAddress)) {
            int inputSize = endAddress - startAddress + 1;
            // å›žè°ƒå¤„理输入数据
            auto funOnReadInput = [this, startAddress](IMcChannel* pChannel, int addr, char* pData, unsigned int nDataSize, int flag) {
                if (nDataSize == (unsigned int)(m_inputPLCAddresses.size()) && flag == 0) {
                    for (size_t i = 0; i < m_inputPLCAddresses.size(); ++i) {
                        int offset = i;
                        int value = CToolUnits::toInt16(&pData[offset]);
                        auto* inputControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 0]); // ç¬¬ 0 åˆ—
                        inputControl->SetBkColor(value ? RGB(0, 255, 0) : RGB(255, 0, 0)); // æ›´æ–°èƒŒæ™¯é¢œè‰²
                        inputControl->SetText(value ? _T("ON") : _T("OFF"));               // æ›´æ–°æ–‡æœ¬
                    }
                }
            };
            // è¯»å–输入数据
            m_pPLC->readData(component, startAddress, inputSize, funOnReadInput);
        }
    }
    // è¾“出地址的读取
    if (!m_outputPLCAddresses.empty()) {
        // èŽ·å–èµ·å§‹åœ°å€å’Œé•¿åº¦
        CString startAddressStr = m_outputPLCAddresses.front();
        CString endAddressStr = m_outputPLCAddresses.back();
        MC::SOFT_COMPONENT component;
        int startAddress, endAddress;
        // è§£æžèµ·å§‹å’Œç»“束地址
        if (ParsePLCAddress(startAddressStr, component, startAddress) &&
            ParsePLCAddress(endAddressStr, component, endAddress)) {
            int outputSize = endAddress - startAddress + 1;
            // å›žè°ƒå¤„理输出数据
            auto funOnReadOutput = [this, startAddress](IMcChannel* pChannel, int addr, char* pData, unsigned int nDataSize, int flag) {
                if (nDataSize == (unsigned int)(m_outputPLCAddresses.size()) && flag == 0) {
                    for (size_t i = 0; i < m_outputPLCAddresses.size(); ++i) {
                        int offset = i;
                        int value = CToolUnits::toInt16(&pData[offset]);
                        auto* outputControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 3]); // ç¬¬ 3 åˆ—
                        outputControl->SetBkColor(value ? RGB(0, 255, 0) : RGB(255, 0, 0)); // æ›´æ–°èƒŒæ™¯é¢œè‰²
                        outputControl->SetText(value ? _T("ON") : _T("OFF"));               // æ›´æ–°æ–‡æœ¬
                    }
                }
            };
            // è¯»å–输出数据
            m_pPLC->readData(component, startAddress, outputSize, funOnReadOutput);
        }
    }
}
BEGIN_MESSAGE_MAP(CIOMonitoringDlg, CDialogEx)
    ON_BN_CLICKED(IDC_BUTTON_PREV_PAGE, &CIOMonitoringDlg::OnBnClickedButtonPrevPage)
    ON_BN_CLICKED(IDC_BUTTON_NEXT_PAGE, &CIOMonitoringDlg::OnBnClickedButtonNextPage)
    ON_WM_SIZE()
    ON_WM_TIMER()
    ON_WM_CLOSE()
END_MESSAGE_MAP()
// CIOMonitoringDlg æ¶ˆæ¯å¤„理程序
BOOL CIOMonitoringDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    // TODO:  åœ¨æ­¤æ·»åŠ é¢å¤–çš„åˆå§‹åŒ–
    CRect screenRect, dlgRect, clientRect;
    SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRect, 0);
    GetClientRect(&clientRect);
    m_nInitialWidth = clientRect.Width();
    m_nInitialHeight = clientRect.Height();
    // åˆå§‹åŒ–默认字体
    CFont* pDefaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰å­æŽ§ä»¶ï¼Œè®°å½•åˆå§‹ä½ç½®å¹¶è®¾ç½®é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1) {
            // è®°å½•控件初始布局
            CRect ctrlRect;
            pWnd->GetWindowRect(&ctrlRect);
            ScreenToClient(&ctrlRect);
            m_mapCtrlLayouts[nCtrlID] = ctrlRect;
            // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
                pWnd = pWnd->GetNextWindow();
                continue;
            }
            // è®¾ç½®é»˜è®¤å­—体
            pWnd->SetFont(pDefaultFont);
        }
        pWnd = pWnd->GetNextWindow();
    }
    GetWindowRect(&dlgRect);
    int dlgWidth = dlgRect.Width() * 2;
    int dlgHeight = dlgRect.Height() * 2;
    if (dlgWidth > screenRect.Width()) {
        dlgWidth = screenRect.Width();
    }
    if (dlgHeight > screenRect.Height()) {
        dlgHeight = screenRect.Height();
    }
    int centerX = screenRect.left + (screenRect.Width() - dlgWidth) / 2;
    int centerY = screenRect.top + (screenRect.Height() - dlgHeight) / 2;
    MoveWindow(centerX, centerY, dlgWidth, dlgHeight);
    CreateDynamicControls();
    DisplayCurrentPage();
    SetTimer(TIMER_READ_PLC_DATA, 500, nullptr);
    return TRUE;  // return TRUE unless you set the focus to a control
    // å¼‚常: OCX å±žæ€§é¡µåº”返回 FALSE
}
void CIOMonitoringDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);
    // TODO: åœ¨æ­¤å¤„添加消息处理程序代码
    if (nType == SIZE_MINIMIZED || m_mapCtrlLayouts.empty()) {
        return;
    }
    float dScaleX = static_cast<float>(cx) / m_nInitialWidth;
    float dScaleY = static_cast<float>(cy) / m_nInitialHeight;
    // éåŽ†å¯¹è¯æ¡†ä¸­çš„æ‰€æœ‰æŽ§ä»¶
    AdjustControls(dScaleX, dScaleY);
}
void CIOMonitoringDlg::OnBnClickedButtonPrevPage()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    if (m_nCurrentPage > 1) {
        --m_nCurrentPage;
        DisplayCurrentPage();
    }
    else {
        AfxMessageBox(_T("已经是第一页!"));
    }
}
void CIOMonitoringDlg::OnBnClickedButtonNextPage()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    if (m_nCurrentPage < m_nTotalPages) {
        ++m_nCurrentPage;
        DisplayCurrentPage();
    }
    else {
        AfxMessageBox(_T("已经是最后一页!"));
    }
}
void CIOMonitoringDlg::OnTimer(UINT_PTR nIDEvent)
{
    // TODO: åœ¨æ­¤æ·»åŠ æ¶ˆæ¯å¤„ç†ç¨‹åºä»£ç å’Œ/或调用默认值
    if (TIMER_READ_PLC_DATA == nIDEvent) {
        ASSERT(m_pPLC);
        UpdatePLCStates();
        Sleep(100);
    }
    CDialogEx::OnTimer(nIDEvent);
}
void CIOMonitoringDlg::OnClose()
{
    // TODO: åœ¨æ­¤æ·»åŠ æ¶ˆæ¯å¤„ç†ç¨‹åºä»£ç å’Œ/或调用默认值
    KillTimer(TIMER_READ_PLC_DATA);
    CDialogEx::OnClose();
}
SourceCode/Bond/BondEq/View/IOMonitoringDlg.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,69 @@
#pragma once
#include "afxdialogex.h"
#include "IOManager.h"
#include "BLLabel.h"
#include "CPLC.h"
// CIOMonitoringDlg å¯¹è¯æ¡†
class CIOMonitoringDlg : public CDialogEx
{
    DECLARE_DYNAMIC(CIOMonitoringDlg)
public:
    CIOMonitoringDlg(CWnd* pParent = nullptr);   // æ ‡å‡†æž„造函数
    virtual ~CIOMonitoringDlg();
    void SetIOManager(const std::string& machineName); // è®¾ç½® IOManager å’Œæœºå™¨å
    void SetPLC(CPLC* pPLC); // è®¾ç½® PLC
// å¯¹è¯æ¡†æ•°æ®
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_DIALOG_IO_MONITORING };
#endif
private:
    CFont* GetOrCreateFont(int nFontSize);                            // èŽ·å–æˆ–åˆ›å»ºå­—ä½“
    void SetDefaultFont();                                            // è®¾ç½®é»˜è®¤å­—体
    void AdjustControls(float dScaleX, float dScaleY);                // è°ƒæ•´æŽ§ä»¶å¤§å°
    void AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight);    // è°ƒæ•´æŽ§ä»¶å­—体大小
    void UpdatePageInfo();            // æ›´æ–°åˆ†é¡µä¿¡æ¯
    void CreateDynamicControls();    // åŠ¨æ€åˆ›å»ºæŽ§ä»¶
    void CreateStaticControl(int x, int y, int width, int height, const CString& text, bool hasBorder = false, TextAlign alignment = AlignLeft, std::function<void()> clickCallback = nullptr); // åˆ›å»ºé™æ€æŽ§ä»¶
    void DisplayCurrentPage();        // æ˜¾ç¤ºå½“前页数据
    void ClearDynamicControls();    // æ¸…除动态创建的控件
    bool ParsePLCAddress(const CString& address, MC::SOFT_COMPONENT& component, int& addr); // è§£æž PLC åœ°å€
    void UpdatePLCStates();            // å®šæ—¶å™¨æ›´æ–°çŠ¶æ€çš„æ–¹æ³•
private:
    CPLC* m_pPLC;
    int m_nInitialWidth;
    int m_nInitialHeight;
    int m_nCurrentPage; // å½“前页
    int m_nTotalPages;    // æ€»é¡µæ•°
    int m_nRowsPerPage; // æ¯é¡µæ˜¾ç¤ºçš„行数
    int m_nCols;        // æ¯è¡Œçš„æŽ§ä»¶ç»„æ•°
    std::string m_machineName; // å½“前机器名
    std::map<int, CFont*> m_mapFonts;        // å­—体映射
    std::map<int, CRect> m_mapCtrlLayouts;    // æŽ§ä»¶å¸ƒå±€æ˜ å°„
    std::vector<IOData> m_displayData;        // å½“前显示的数据
    std::vector<CString> m_inputPLCAddresses;  // å­˜å‚¨ 1 åˆ— PLC åœ°å€
    std::vector<CString> m_outputPLCAddresses; // å­˜å‚¨ 4 åˆ— PLC åœ°å€
private:
    CStatic m_staticPageNum;
    std::vector<CBLLabel*> m_staticControls; // åŠ¨æ€åˆ›å»ºçš„é™æ€æŽ§ä»¶
protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV æ”¯æŒ
    DECLARE_MESSAGE_MAP()
public:
    virtual BOOL OnInitDialog();
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnBnClickedButtonPrevPage();
    afx_msg void OnBnClickedButtonNextPage();
    afx_msg void OnTimer(UINT_PTR nIDEvent);
    afx_msg void OnClose();
};
SourceCode/Bond/BondEq/View/LoginDlg.cpp
@@ -5,7 +5,6 @@
#include "BondEq.h"
#include "afxdialogex.h"
#include "LoginDlg.h"
#include "UserManager.h"
#include "ChangePasswordDlg.h"
@@ -25,9 +24,9 @@
void CLoginDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_STATIC_IMAGE, m_staticImage);
    DDX_Control(pDX, IDC_EDIT_USERNAME, m_editUsername);
    DDX_Control(pDX, IDC_EDIT_PASSWORD, m_editPassword);
    DDX_Control(pDX, IDC_COMBO_ROLE, m_comboRole);
    DDX_Control(pDX, IDC_CHECK_REMEMBER_PASSWORD, m_checkRememberPassword);
}
@@ -47,10 +46,24 @@
    // è®¾ç½®çª—口标题和初始值
    SetWindowText(_T("登录"));
    m_comboRole.AddString(_T("管理员"));
    m_comboRole.AddString(_T("工程师"));
    m_comboRole.AddString(_T("操作员"));
    m_comboRole.SetCurSel(0);
    CString strIconPath;
    strIconPath.Format(_T("%s\\Res\\Operator_High_32.ico"), (LPTSTR)(LPCTSTR)theApp.m_strAppDir);
    // åŠ è½½å›¾æ ‡
    HICON hIcon = (HICON)::LoadImage(
        nullptr,
        strIconPath,
        IMAGE_ICON,
        32, // å›¾æ ‡å®½åº¦
        32, // å›¾æ ‡é«˜åº¦
        LR_LOADFROMFILE);
    if (hIcon) {
        // è®¾ç½® CStatic æŽ§ä»¶ä¸ºå›¾æ ‡æ ·å¼
        m_staticImage.ModifyStyle(0xF, SS_ICON);
        m_staticImage.SetIcon(hIcon);
    }
    // æ·»åŠ SS_NOTIFY样式
    CStatic* pStatic = (CStatic*)GetDlgItem(IDC_STATIC_CHANGE_PASSWORD);
@@ -60,11 +73,6 @@
    UserManager& userManager = UserManager::getInstance();
    if (userManager.isLoggedIn()) {
        int nRole = (int)userManager.getCurrentUserRole();
        if (nRole <= m_comboRole.GetCount()) {
            m_comboRole.SetCurSel(nRole);
        }
        if (userManager.isRememberMe()) {
            m_checkRememberPassword.SetCheck(BST_CHECKED);
        }
@@ -82,7 +90,6 @@
    CString username, password, role;
    m_editUsername.GetWindowText(username);
    m_editPassword.GetWindowText(password);
    m_comboRole.GetLBText(m_comboRole.GetCurSel(), role);
    if (username.IsEmpty() || password.IsEmpty()) {
        AfxMessageBox(_T("请输入用户名和密码。"));
@@ -98,12 +105,14 @@
#endif
    UserManager& userManager = UserManager::getInstance();
    SystemLogManager& logManager = SystemLogManager::getInstance();
    if (!userManager.login(strUsername, strPassword, (m_checkRememberPassword.GetCheck() == BST_CHECKED))) {
        AfxMessageBox(_T("登录失败。"));
        return;
    }
    EndDialog(IDOK);
    logManager.log(SystemLogManager::LogType::Info, _T("登录成功..."));
}
void CLoginDlg::OnBnClickedChangePassword()
SourceCode/Bond/BondEq/View/LoginDlg.h
@@ -17,16 +17,16 @@
    enum { IDD = IDD_DIALOG_LOGIN };
#endif
private:
    CStatic m_staticImage;
    CEdit m_editUsername;
    CEdit m_editPassword;
    CButton m_checkRememberPassword;
protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV æ”¯æŒ
    virtual BOOL OnInitDialog();
    afx_msg void OnBnClickedLogin();
    afx_msg void OnBnClickedChangePassword();
    DECLARE_MESSAGE_MAP()
private:
    CEdit m_editUsername;
    CEdit m_editPassword;
    CComboBox m_comboRole;
    CButton m_checkRememberPassword;
};
SourceCode/Bond/BondEq/View/SystemLogManagerDlg.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,498 @@
// SystemLogManagerDlg.cpp: å®žçŽ°æ–‡ä»¶
//
#include "stdafx.h"
#include "BondEq.h"
#include "afxdialogex.h"
#include "SystemLogManagerDlg.h"
// CSystemLogManagerDlg å¯¹è¯æ¡†
IMPLEMENT_DYNAMIC(CSystemLogManagerDlg, CDialogEx)
CSystemLogManagerDlg::CSystemLogManagerDlg(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_SYSTEM_LOG_MANAGER, pParent)
{
    m_nInitialWidth = 0;
    m_nInitialHeight = 0;
}
CSystemLogManagerDlg::~CSystemLogManagerDlg()
{
    for (auto& pair : m_mapFonts) {
        if (pair.second) {
            pair.second->DeleteObject();
            delete pair.second;
        }
    }
    m_mapFonts.clear();
}
void CSystemLogManagerDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_COMBO_TYPE, m_comboType);
    DDX_Control(pDX, IDC_COMBO_USER, m_comboUser);
    DDX_Control(pDX, IDC_DATETIMEPICKER_START, m_dateTimeStart);
    DDX_Control(pDX, IDC_DATETIMEPICKER_END, m_dateTimeEnd);
    DDX_Control(pDX, IDC_EDIT_DESCRIPTION, m_editDescription);
    DDX_Control(pDX, IDC_CUSTOM_LIST_LOGS, m_listLogs);
    DDX_Control(pDX, IDC_STATIC_PAGE_NUMBER, m_staticPageNum);
}
void CSystemLogManagerDlg::InitSystemLogManager()
{
    if (m_listLogs.GetSafeHwnd() == NULL)
        return;
    int nRows = 21; // åŒ…括表头(1 è¡Œï¼‰å’Œæ•°æ®ï¼ˆ20 è¡Œï¼‰
    int nCols = 5;
    int nFixRows = 1;
    int nFixCols = 0;
    int nRowIdx = 0;
    int nColIdx = 0;
    m_listLogs.DeleteAllItems();
    m_listLogs.SetVirtualMode(FALSE);
    m_listLogs.GetDefaultCell(TRUE, FALSE)->SetBackClr(g_nGridFixCellColor); // è®¾ç½®å›ºå®šè¡ŒèƒŒæ™¯è‰²
    m_listLogs.GetDefaultCell(FALSE, TRUE)->SetBackClr(g_nGridFixCellColor); // è®¾ç½®å›ºå®šåˆ—背景色
    m_listLogs.GetDefaultCell(FALSE, FALSE)->SetBackClr(g_nGridCellColor);    // è®¾ç½®å•元格背景色
    m_listLogs.SetFixedTextColor(g_nGridFixFontColor); // è®¾ç½®å›ºå®šè¡Œåˆ—字体颜色
    m_listLogs.SetRowCount(nRows);
    m_listLogs.SetColumnCount(nCols);
    m_listLogs.SetFixedRowCount(nFixRows);
    m_listLogs.SetFixedColumnCount(nFixCols);
    // Col
    m_listLogs.SetColumnWidth(nColIdx, 10);
    m_listLogs.SetItemText(nRowIdx, nColIdx++, _T("No."));
    m_listLogs.SetColumnWidth(nColIdx, 10);
    m_listLogs.SetItemText(nRowIdx, nColIdx++, _T("类型"));
    m_listLogs.SetColumnWidth(nColIdx, 100);
    m_listLogs.SetItemText(nRowIdx, nColIdx++, _T("事件"));
    m_listLogs.SetColumnWidth(nColIdx, 30);
    m_listLogs.SetItemText(nRowIdx, nColIdx++, _T("用户"));
    m_listLogs.SetColumnWidth(nColIdx, 50);
    m_listLogs.SetItemText(nRowIdx, nColIdx++, _T("时间"));
    // åˆ›å»º 20 è¡Œç©ºç™½æ•°æ®è¡Œ
    for (int i = 1; i < nRows; ++i) {
        for (int j = 0; j < nCols; ++j) {
            m_listLogs.SetItemText(i, j, _T("")); // åˆå§‹åŒ–为空字符串
        }
    }
    m_listLogs.SetFixedRowSelection(FALSE);
    m_listLogs.SetFixedColumnSelection(FALSE);
    m_listLogs.SetEditable(FALSE);
    m_listLogs.SetRowResize(FALSE);
    m_listLogs.SetColumnResize(TRUE);
    m_listLogs.ExpandColumnsToFit(TRUE);
    m_listLogs.SetListMode(TRUE);                // å¯ç”¨åˆ—表模式
    m_listLogs.EnableSelection(TRUE);            // å¯ç”¨é€‰æ‹©
    m_listLogs.SetSingleRowSelection(TRUE);        // è‡ªåŠ¨æ•´è¡Œé«˜äº®ï¼ˆé™åˆ¶ä¸ºå•è¡Œé€‰æ‹©ï¼‰
    m_listLogs.ExpandLastColumn();                // æœ€åŽä¸€åˆ—填充网格
    try {
        FillSystemLogManager();
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("初始化运行日志失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
void CSystemLogManagerDlg::FillSystemLogManager()
{
    // èŽ·å–ç­›é€‰æ¡ä»¶
    CString selectedType, selectedUser, description;
    m_comboType.GetLBText(m_comboType.GetCurSel(), selectedType);
    m_comboUser.GetLBText(m_comboUser.GetCurSel(), selectedUser);
    m_editDescription.GetWindowText(description);
    COleDateTime startTime, endTime;
    m_dateTimeStart.GetTime(startTime);
    m_dateTimeEnd.GetTime(endTime);
    CString strStartTime = startTime.Format(_T("%Y-%m-%d %H:%M:%S"));
    CString strEndTime = endTime.Format(_T("%Y-%m-%d %H:%M:%S"));
    std::string type = CT2A(selectedType);
    std::string user = CT2A(selectedUser);
    std::string desc = CT2A(description);
    std::string start = CT2A(strStartTime);
    std::string end = CT2A(strEndTime);
    // èŽ·å–æ—¥å¿—ç®¡ç†å®žä¾‹
    SystemLogManager& logManager = SystemLogManager::getInstance();
    int pageSize = 20; // æ¯é¡µæ˜¾ç¤º 20 æ¡è®°å½•
    int totalRecords = logManager.getTotalLogCount(type, user, desc, start, end);
    m_nTotalPages = (totalRecords + pageSize - 1) / pageSize;
    auto logs = logManager.getFilteredLogs(type, user, desc, start, end, m_nCurrentPage, pageSize);
    // æ›´æ–°è¡¨æ ¼æ•°æ®
    int rowIdx = 1;
    for (const auto& log : logs) {
        m_listLogs.SetItemText(rowIdx, 0, CString(std::to_string(rowIdx).c_str())); // åºå·
        m_listLogs.SetItemText(rowIdx, 1, CString(log[1].c_str()));                 // ç±»åž‹
        m_listLogs.SetItemText(rowIdx, 2, CString(log[2].c_str()));                 // äº‹ä»¶
        m_listLogs.SetItemText(rowIdx, 3, CString(log[3].c_str()));                 // ç”¨æˆ·
        m_listLogs.SetItemText(rowIdx, 4, CString(log[4].c_str()));                 // æ—¶é—´
        ++rowIdx;
    }
    // æ¸…空多余行
    for (; rowIdx <= 20; ++rowIdx) {
        m_listLogs.SetItemText(rowIdx, 0, CString(std::to_string(rowIdx).c_str())); // åºå·åˆ—
        for (int colIdx = 1; colIdx < m_listLogs.GetColumnCount(); ++colIdx) {
            m_listLogs.SetItemText(rowIdx, colIdx, _T(""));
        }
    }
    m_listLogs.ExpandColumnsToFit(FALSE);
    m_listLogs.ExpandLastColumn();
    m_listLogs.Invalidate();
    m_listLogs.UpdateWindow();
    UpdatePageInfo();
}
CFont* CSystemLogManagerDlg::GetOrCreateFont(int nFontSize)
{
    auto it = m_mapFonts.find(nFontSize);
    if (it != m_mapFonts.end()) {
        return it->second;
    }
    CFont* font = new CFont();
    LOGFONT logFont = { 0 };
    _tcscpy_s(logFont.lfFaceName, _T("Segoe UI"));
    logFont.lfHeight = -nFontSize;
    logFont.lfQuality = CLEARTYPE_QUALITY;
    font->CreateFontIndirect(&logFont);
    m_mapFonts[nFontSize] = font;
    return font;
}
void CSystemLogManagerDlg::UpdatePageInfo()
{
    // æ ¼å¼åŒ–页码信息为 "当前页/总页数"
    CString pageInfo;
    pageInfo.Format(_T("%d/%d é¡µ"), m_nCurrentPage, m_nTotalPages);
    m_staticPageNum.SetWindowText(pageInfo);
}
void CSystemLogManagerDlg::SetDefaultFont()
{
    CFont* defaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰æŽ§ä»¶ï¼Œåº”ç”¨é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
        TCHAR szClassName[256];
        GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
        if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
            pWnd = pWnd->GetNextWindow();
            continue;
        }
        pWnd->SetFont(defaultFont, TRUE);
        pWnd = pWnd->GetNextWindow();
    }
}
void CSystemLogManagerDlg::AdjustControls(float dScaleX, float dScaleY)
{
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1 && m_mapCtrlLayouts.find(nCtrlID) != m_mapCtrlLayouts.end())
        {
            CRect originalRect = m_mapCtrlLayouts[nCtrlID];
            CRect newRect(
                static_cast<int>(originalRect.left * dScaleX),
                static_cast<int>(originalRect.top * dScaleY),
                static_cast<int>(originalRect.right * dScaleX),
                static_cast<int>(originalRect.bottom * dScaleY));
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("ComboBox")) == 0) {
                CComboBox* pComboBox = (CComboBox*)pWnd;
                pComboBox->SetItemHeight(-1, newRect.Height());  // -1 è¡¨ç¤ºæ‰€æœ‰é¡¹çš„高度
            }
            if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
                CGridCtrl* pGridCtrl = (CGridCtrl*)pWnd;
                pGridCtrl->SetDefCellHeight(newRect.Height() / 21);
                pGridCtrl->ExpandColumnsToFit(TRUE);
                pGridCtrl->ExpandLastColumn();
                pGridCtrl->Invalidate();
                pGridCtrl->UpdateWindow();
            }
            pWnd->MoveWindow(&newRect);
            AdjustControlFont(pWnd, newRect.Width(), newRect.Height());
        }
        pWnd = pWnd->GetNextWindow();
    }
}
void CSystemLogManagerDlg::AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight)
{
    TCHAR szClassName[256];
    GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
    // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
    if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
        return;
    }
    // æ ¹æ®æŽ§ä»¶é«˜åº¦åŠ¨æ€è°ƒæ•´å­—ä½“å¤§å°
    int fontSize = nHeight / 2;
    if (fontSize < 8) fontSize = 8;
    // èŽ·å–æˆ–åˆ›å»ºå­—ä½“
    CFont* pFont = GetOrCreateFont(fontSize);
    pWnd->SetFont(pFont);
    pWnd->Invalidate(); // åˆ·æ–°æŽ§ä»¶æ˜¾ç¤º
}
void CSystemLogManagerDlg::AdjustComboBoxStyle(CComboBox& comboBox)
{
    DWORD dwStyle = comboBox.GetStyle();
    comboBox.ModifyStyle(0, CBS_DROPDOWNLIST | CBS_HASSTRINGS | CBS_OWNERDRAWFIXED);
    comboBox.Invalidate();
    comboBox.UpdateWindow();
}
void CSystemLogManagerDlg::AdjustDateTimeCtrlStyle(CDateTimeCtrl& dateTimeCtrl)
{
    dateTimeCtrl.ModifyStyle(0, DTS_RIGHTALIGN);
    dateTimeCtrl.Invalidate();
    dateTimeCtrl.UpdateWindow();
}
BEGIN_MESSAGE_MAP(CSystemLogManagerDlg, CDialogEx)
    ON_BN_CLICKED(IDC_BUTTON_SEARCH, &CSystemLogManagerDlg::OnBnClickedButtonSearch)
    ON_BN_CLICKED(IDC_BUTTON_PREV_PAGE, &CSystemLogManagerDlg::OnBnClickedButtonPrevPage)
    ON_BN_CLICKED(IDC_BUTTON_NEXT_PAGE, &CSystemLogManagerDlg::OnBnClickedButtonNextPage)
    ON_CBN_SELCHANGE(IDC_COMBO_TYPE, &CSystemLogManagerDlg::OnSelchangeComboType)
    ON_CBN_SELCHANGE(IDC_COMBO_USER, &CSystemLogManagerDlg::OnSelchangeComboUser)
    ON_WM_SIZE()
    ON_WM_GETMINMAXINFO()
END_MESSAGE_MAP()
// CSystemLogManagerDlg æ¶ˆæ¯å¤„理程序
BOOL CSystemLogManagerDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    // TODO:  åœ¨æ­¤æ·»åŠ é¢å¤–çš„åˆå§‹åŒ–
    SetWindowText(_T("系统运行日志"));
    m_nCurrentPage = 1;  // ä»Žç¬¬ä¸€é¡µå¼€å§‹
    m_nTotalPages = 1;   // é»˜è®¤æ€»é¡µæ•°ä¸º 1
    m_comboType.AddString(_T("ALL"));
    m_comboType.AddString(_T("信息"));
    m_comboType.AddString(_T("操作"));
    m_comboType.AddString(_T("错误"));
    m_comboType.AddString(_T("未知"));
    m_comboType.SetCurSel(0);
    m_comboUser.AddString(_T("ALL"));
    m_comboUser.AddString(_T("SYSTEM"));
    auto usernames = UserManager::getInstance().getUsernames();
    for (const auto& username : usernames) {
        CString cstrUsername(username.c_str());
        m_comboUser.AddString(cstrUsername);
    }
    m_comboUser.SetCurSel(0);
    // è®¾ç½®ä¸º 30 å¤©å‰
    COleDateTime currentTime = COleDateTime::GetCurrentTime();
    COleDateTime defaultStartTime = currentTime - COleDateTimeSpan(30, 0, 0, 0);
    m_dateTimeStart.SetTime(defaultStartTime);
    CRect screenRect, dlgRect, clientRect;
    GetClientRect(&clientRect);
    m_nInitialWidth = clientRect.Width();
    m_nInitialHeight = clientRect.Height();
    // åˆå§‹åŒ–默认字体
    CFont* pDefaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰å­æŽ§ä»¶ï¼Œè®°å½•åˆå§‹ä½ç½®å¹¶è®¾ç½®é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1) {
            // è®°å½•控件初始布局
            CRect ctrlRect;
            pWnd->GetWindowRect(&ctrlRect);
            ScreenToClient(&ctrlRect);
            m_mapCtrlLayouts[nCtrlID] = ctrlRect;
            // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
                pWnd = pWnd->GetNextWindow();
                continue;
            }
            // è®¾ç½®é»˜è®¤å­—体
            pWnd->SetFont(pDefaultFont);
        }
        pWnd = pWnd->GetNextWindow();
    }
    GetWindowRect(&dlgRect);
    int dlgWidth = dlgRect.Width() * 2;
    int dlgHeight = dlgRect.Height() * 2;
    SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRect, 0);
    if (dlgWidth > screenRect.Width()) {
        dlgWidth = screenRect.Width();
    }
    if (dlgHeight > screenRect.Height()) {
        dlgHeight = screenRect.Height();
    }
    int centerX = screenRect.left + (screenRect.Width() - dlgWidth) / 2;
    int centerY = screenRect.top + (screenRect.Height() - dlgHeight) / 2;
    MoveWindow(centerX, centerY, dlgWidth, dlgHeight);
    InitSystemLogManager();
    return TRUE;  // return TRUE unless you set the focus to a control
    // å¼‚常: OCX å±žæ€§é¡µåº”返回 FALSE
}
void CSystemLogManagerDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);
    // TODO: åœ¨æ­¤å¤„添加消息处理程序代码
    if (nType == SIZE_MINIMIZED || m_mapCtrlLayouts.empty()) {
        return;
    }
    float dScaleX = static_cast<float>(cx) / m_nInitialWidth;
    float dScaleY = static_cast<float>(cy) / m_nInitialHeight;
    // éåŽ†å¯¹è¯æ¡†ä¸­çš„æ‰€æœ‰æŽ§ä»¶
    AdjustControls(dScaleX, dScaleY);
}
void CSystemLogManagerDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
    // TODO: åœ¨æ­¤æ·»åŠ æ¶ˆæ¯å¤„ç†ç¨‹åºä»£ç å’Œ/或调用默认值
    lpMMI->ptMinTrackSize.x = 400; // æœ€å°å®½åº¦
    lpMMI->ptMinTrackSize.y = 300; // æœ€å°é«˜åº¦
    CDialogEx::OnGetMinMaxInfo(lpMMI);
}
void CSystemLogManagerDlg::OnBnClickedButtonSearch()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    try {
        m_nCurrentPage = 1;
        FillSystemLogManager();
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("搜索失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
void CSystemLogManagerDlg::OnBnClickedButtonPrevPage()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    try {
        if (m_nCurrentPage > 1) {
            m_nCurrentPage--;
            FillSystemLogManager();
        }
        else {
            AfxMessageBox(_T("已经是第一页!"));
        }
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("切换到上一页失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
void CSystemLogManagerDlg::OnBnClickedButtonNextPage()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    try {
        if (m_nCurrentPage < m_nTotalPages) {
            m_nCurrentPage++;
            FillSystemLogManager();
        }
        else {
            AfxMessageBox(_T("已经是最后一页!"));
        }
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("切换到下一页失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
void CSystemLogManagerDlg::OnSelchangeComboType()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    try {
        m_nCurrentPage = 1;
        FillSystemLogManager();
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("切换类型失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
void CSystemLogManagerDlg::OnSelchangeComboUser()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    try {
        m_nCurrentPage = 1;
        FillSystemLogManager();
    }
    catch (const std::exception& ex) {
        CString errorMsg;
        errorMsg.Format(_T("切换角色失败:%s"), CString(ex.what()));
        AfxMessageBox(errorMsg, MB_ICONERROR);
    }
}
SourceCode/Bond/BondEq/View/SystemLogManagerDlg.h
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,61 @@
#pragma once
#include "afxdialogex.h"
#include "GridCtrl.h"
// CSystemLogManagerDlg å¯¹è¯æ¡†
class CSystemLogManagerDlg : public CDialogEx
{
    DECLARE_DYNAMIC(CSystemLogManagerDlg)
public:
    CSystemLogManagerDlg(CWnd* pParent = nullptr);   // æ ‡å‡†æž„造函数
    virtual ~CSystemLogManagerDlg();
// å¯¹è¯æ¡†æ•°æ®
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_DIALOG_SYSTEM_LOG_MANAGER };
#endif
private:
    void InitSystemLogManager();
    void FillSystemLogManager();
    CFont* GetOrCreateFont(int nFontSize);
    void UpdatePageInfo();
    void SetDefaultFont();
    void AdjustControls(float dScaleX, float dScaleY);
    void AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight);
    void AdjustComboBoxStyle(CComboBox& comboBox);
    void AdjustDateTimeCtrlStyle(CDateTimeCtrl& dateTimeCtrl);
private:
    int m_nInitialWidth;   // åˆå§‹å®½åº¦
    int m_nInitialHeight;  // åˆå§‹é«˜åº¦
    int m_nCurrentPage;    // å½“前页码
    int m_nTotalPages;     // æ€»é¡µæ•°
    std::map<int, CRect> m_mapCtrlLayouts;    // å­˜å‚¨æŽ§ä»¶çš„初始布局信息
    std::map<int, CFont*> m_mapFonts;        // ç®¡ç†å­—体的容器,键为字体大小
private:
    CComboBox m_comboType;
    CComboBox m_comboUser;
    CDateTimeCtrl m_dateTimeStart;
    CDateTimeCtrl m_dateTimeEnd;
    CEdit m_editDescription;
    CGridCtrl m_listLogs;
    CStatic m_staticPageNum;
protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV æ”¯æŒ
    DECLARE_MESSAGE_MAP()
public:
    virtual BOOL OnInitDialog();
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnGetMinMaxInfo(MINMAXINFO* lpMMI);
    afx_msg void OnBnClickedButtonSearch();
    afx_msg void OnBnClickedButtonPrevPage();
    afx_msg void OnBnClickedButtonNextPage();
    afx_msg void OnSelchangeComboType();
    afx_msg void OnSelchangeComboUser();
};
SourceCode/Bond/BondEq/View/UserManagerDlg.cpp
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,730 @@
// UserManagerDlg.cpp: å®žçŽ°æ–‡ä»¶
//
#include "stdafx.h"
#include "BondEq.h"
#include "afxdialogex.h"
#include "UserManagerDlg.h"
#include "InputDialog.h"
#include "NewCellTypes/GridCellCombo.h"
#include "NewCellTypes/GridCellNumeric.h"
#include <set>
const COLORREF CURR_USER_BK_COLOR = RGB(0, 255, 0);
// CUserManagerDlg å¯¹è¯æ¡†
IMPLEMENT_DYNAMIC(CUserManagerDlg, CDialogEx)
CUserManagerDlg::CUserManagerDlg(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_USER_MANAGER, pParent)
{
    m_nInitialWidth = 0;
    m_nInitialHeight = 0;
}
CUserManagerDlg::~CUserManagerDlg()
{
    for (auto& pair : m_mapFonts) {
        if (pair.second) {
            pair.second->DeleteObject();
            delete pair.second;
        }
    }
    m_mapFonts.clear();
}
void CUserManagerDlg::DoDataExchange(CDataExchange* pDX)
{
    DDX_Control(pDX, IDC_CUSTOM_USER, m_gridUserManager);
    CDialogEx::DoDataExchange(pDX);
}
void CUserManagerDlg::InitUserManager()
{
    if (m_gridUserManager.GetSafeHwnd() == NULL)
        return;
    int nRows = 1;
    int nCols = 8;
    int nFixRows = 1;
    int nFixCols = 0;
    int nRowIdx = 0;
    int nColIdx = 0;
    m_gridUserManager.DeleteAllItems();
    m_gridUserManager.SetVirtualMode(FALSE);
    m_gridUserManager.GetDefaultCell(TRUE, FALSE)->SetBackClr(g_nGridFixCellColor); // è®¾ç½®å›ºå®šè¡ŒèƒŒæ™¯è‰²
    m_gridUserManager.GetDefaultCell(FALSE, TRUE)->SetBackClr(g_nGridFixCellColor); // è®¾ç½®å›ºå®šåˆ—背景色
    m_gridUserManager.GetDefaultCell(FALSE, FALSE)->SetBackClr(g_nGridCellColor);    // è®¾ç½®å•元格背景色
    m_gridUserManager.SetFixedTextColor(g_nGridFixFontColor); // è®¾ç½®å›ºå®šè¡Œåˆ—字体颜色
    m_gridUserManager.SetRowCount(nRows);
    m_gridUserManager.SetColumnCount(nCols);
    m_gridUserManager.SetFixedRowCount(nFixRows);
    m_gridUserManager.SetFixedColumnCount(nFixCols);
    // Col
    m_gridUserManager.SetColumnWidth(nColIdx, 20);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("No."));
    m_gridUserManager.SetColumnWidth(nColIdx, 70);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("用户名"));
    m_gridUserManager.SetColumnWidth(nColIdx, 70);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("密码"));
    m_gridUserManager.SetColumnWidth(nColIdx, 70);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("权限"));
    m_gridUserManager.SetColumnWidth(nColIdx, 70);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("会话超时(分钟)"));
    m_gridUserManager.SetColumnWidth(nColIdx, 70);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("会话过期(小时)"));
    m_gridUserManager.SetColumnWidth(nColIdx, 70);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("最后一次登录时间"));
    m_gridUserManager.SetColumnWidth(nColIdx, 100);
    m_gridUserManager.SetItemText(nRowIdx, nColIdx++, _T("角色描述"));
    m_gridUserManager.SetFixedRowSelection(FALSE);
    m_gridUserManager.SetFixedColumnSelection(FALSE);
    m_gridUserManager.SetEditable(TRUE);
    m_gridUserManager.SetRowResize(FALSE);
    m_gridUserManager.SetColumnResize(TRUE);
    m_gridUserManager.ExpandColumnsToFit(TRUE);
    m_gridUserManager.SetListMode(TRUE);                // å¯ç”¨åˆ—表模式
    m_gridUserManager.EnableSelection(TRUE);            // å¯ç”¨é€‰æ‹©
    m_gridUserManager.SetSingleRowSelection(TRUE);        // è‡ªåŠ¨æ•´è¡Œé«˜äº®ï¼ˆé™åˆ¶ä¸ºå•è¡Œé€‰æ‹©ï¼‰
    m_gridUserManager.ExpandLastColumn();                // æœ€åŽä¸€åˆ—填充网格
    m_mapRoleDescriptions.clear();
    m_mapRoleDescriptions.emplace(_T("管理员"), _T("管理所有用户,分配权限"));
    m_mapRoleDescriptions.emplace(_T("工程师"), _T("维护系统,解决技术问题"));
    m_mapRoleDescriptions.emplace(_T("操作员"), _T("执行日常操作任务"));
    FillUserManager();
}
void CUserManagerDlg::FillUserManager()
{
    UserManager& userManager = UserManager::getInstance();
    if (!userManager.isLoggedIn()) {
        AfxMessageBox(_T("未登录"));
        return;
    }
    if (userManager.getCurrentUserRole() != UserRole::SuperAdmin) {
        AfxMessageBox(_T("非管理员用户"));
        return;
    }
    int nCurrNameRow = -1;
    std::vector<std::vector<std::string>> usersData = userManager.getUsers();
    if (!usersData.empty()) {
        m_gridUserManager.SetRowCount(usersData.size() + 1);
        for (int i = 0; i < usersData.size(); i++) {
            int nRowIdx = i + 1;
            int nColIdx = 0;
            m_gridUserManager.SetItemText(nRowIdx, nColIdx++, std::to_string(i + 1).c_str());
            for (int j = 0; j < usersData[i].size(); j++) {
                if (usersData[i][1].empty()) {
                    continue;
                }
                m_gridUserManager.SetItemText(nRowIdx, nColIdx++, usersData[i][j].c_str());
            }
            // å½“前登录用户高亮
            if (nCurrNameRow == -1 && usersData[i][0] == userManager.getCurrentUser()) {
                nCurrNameRow = nRowIdx;
            }
        }
    }
    CStringArray permissions;
    permissions.Add(_T("管理员"));
    permissions.Add(_T("工程师"));
    permissions.Add(_T("操作员"));
    int nCols = m_gridUserManager.GetColumnCount();
    for (int i = 1; i < m_gridUserManager.GetRowCount(); ++i) {
        m_gridUserManager.SetItemState(i, 0, GVIS_READONLY); // ç¬¬ä¸€åˆ—只读
        m_gridUserManager.SetItemState(i, nCols - 2, GVIS_READONLY); // å€’数第二列只读
        m_gridUserManager.SetItemState(i, nCols - 1, GVIS_READONLY); // æœ€åŽä¸€åˆ—只读
        // ç¬¬å››åˆ—设置权限列为下拉框
        if (m_gridUserManager.SetCellType(i, 3, RUNTIME_CLASS(CGridCellCombo))) {
            CGridCellCombo* pCell = static_cast<CGridCellCombo*>(m_gridUserManager.GetCell(i, 3));
            pCell->SetOptions(permissions);
            pCell->SetStyle(CBS_DROPDOWNLIST);
            CString cstrRole = m_gridUserManager.GetItemText(i, 3);
            int nRole = _ttoi(cstrRole);
            if (nRole < 0 || nRole > 2) {
                CString cstrMessage;
                cstrMessage.Format(_T("用户 [%s],权限异常!将设置成操作员!"), m_gridUserManager.GetItemText(i, 1));
                AfxMessageBox(cstrMessage);
                nRole = 2;
            }
            m_gridUserManager.SetItemText(i, 3, permissions.GetAt(nRole));
            auto it = m_mapRoleDescriptions.find(permissions.GetAt(nRole));
            if (it != m_mapRoleDescriptions.end()) {
                m_gridUserManager.SetItemText(i, 7, it->second);
            }
        }
        // ç¬¬äº”、六列(会话超时)设置为Numeric
        //m_gridUserManager.SetCellType(i, 4, RUNTIME_CLASS(CGridCellNumeric));
        //m_gridUserManager.SetCellType(i, 5, RUNTIME_CLASS(CGridCellNumeric));
        m_gridUserManager.SetItemState(i, 4, GVIS_READONLY); // ç¬¬äº”列只读
        m_gridUserManager.SetItemState(i, 5, GVIS_READONLY); // ç¬¬å…­åˆ—只读
        m_gridUserManager.ExpandColumnsToFit(FALSE);
        m_gridUserManager.ExpandLastColumn();
    }
    for (int i = 0; i < nCols; i++) {
        m_gridUserManager.SetItemBkColour(nCurrNameRow, i, CURR_USER_BK_COLOR);
    }
    m_gridUserManager.SetItemState(nCurrNameRow, 3, GVIS_READONLY);
    m_gridUserManager.Invalidate();
    m_gridUserManager.UpdateWindow();
}
void CUserManagerDlg::AddRow(CGridCtrl* pGridCtrl)
{
    if (!pGridCtrl) return;
    if (pGridCtrl->GetRowCount() <= 0 || pGridCtrl->GetColumnCount() <= 0) {
        AfxMessageBox(_T("网格控件未正确初始化,请检查初始化逻辑!"));
        return;
    }
    CInputDialog inputDialog(_T("添加用户"), _T("请输入用户名:"));
    if (inputDialog.DoModal() != IDOK) {
        return;
    }
    CString inputText = inputDialog.GetInputText();
    if (inputText.IsEmpty()) {
        AfxMessageBox(_T("用户名不能为空!"));
        return;
    }
    if (IsUsernameDuplicate(inputText)) {
        AfxMessageBox(_T("用户名重复!"));
        return;
    }
    int nRowCount = pGridCtrl->GetRowCount();
    pGridCtrl->SetRowCount(nRowCount + 1);
    int newRowIndex = nRowCount;
    CString strText;
    strText.Format(_T("%d"), newRowIndex);
    pGridCtrl->SetItemText(newRowIndex, 0, strText);
    pGridCtrl->SetItemText(newRowIndex, 1, inputText);
    pGridCtrl->SetItemText(newRowIndex, 2, _T("123456"));
    pGridCtrl->SetItemText(newRowIndex, 3, _T("操作员"));
    pGridCtrl->SetItemText(newRowIndex, 4, _T("30"));
    pGridCtrl->SetItemText(newRowIndex, 5, _T("72"));
    pGridCtrl->SetItemText(newRowIndex, 6, _T("2024-01-01 00:00:00"));
    auto it = m_mapRoleDescriptions.find(_T("操作员"));
    if (it != m_mapRoleDescriptions.end()) {
        pGridCtrl->SetItemText(newRowIndex, 7, it->second);
    }
    int nCols = pGridCtrl->GetColumnCount();
    pGridCtrl->SetItemState(newRowIndex, 0, GVIS_READONLY); // ç¬¬ä¸€åˆ—只读
    pGridCtrl->SetItemState(newRowIndex, nCols - 2, GVIS_READONLY); // å€’数第二列只读
    pGridCtrl->SetItemState(newRowIndex, nCols - 1, GVIS_READONLY); // æœ€åŽä¸€åˆ—只读
    // ç¬¬å››åˆ—设置(权限列)为下拉框
    CStringArray permissions;
    permissions.Add(_T("管理员"));
    permissions.Add(_T("工程师"));
    permissions.Add(_T("操作员"));
    if (pGridCtrl->SetCellType(newRowIndex, 3, RUNTIME_CLASS(CGridCellCombo))) {
        CGridCellCombo* pCell = static_cast<CGridCellCombo*>(pGridCtrl->GetCell(newRowIndex, 3));
        pCell->SetOptions(permissions);
        pCell->SetStyle(CBS_DROPDOWNLIST);
        pGridCtrl->SetItemText(newRowIndex, 3, permissions.GetAt(2));
    }
    // ç¬¬äº”、六列(会话超时)设置为Numeric
    //pGridCtrl->SetCellType(newRowIndex, 4, RUNTIME_CLASS(CGridCellNumeric));
    //pGridCtrl->SetCellType(newRowIndex, 5, RUNTIME_CLASS(CGridCellNumeric));
    pGridCtrl->SetItemState(newRowIndex, 4, GVIS_READONLY); // ç¬¬äº”列只读
    pGridCtrl->SetItemState(newRowIndex, 5, GVIS_READONLY); // ç¬¬å…­åˆ—只读
    pGridCtrl->ExpandColumnsToFit(FALSE);
    pGridCtrl->ExpandLastColumn();
    pGridCtrl->Invalidate();
    pGridCtrl->UpdateWindow();
    CString cstrMessage;
    cstrMessage.Format(_T("预添加用户 [%s]!"), inputText);
    std::string strMessage = CT2A(cstrMessage);
    SystemLogManager::getInstance().log(SystemLogManager::LogType::Operation, strMessage);
}
void CUserManagerDlg::DeleteSelectedRow(CGridCtrl* pGridCtrl)
{
    if (!pGridCtrl) return;
    CCellRange selectedRange = pGridCtrl->GetSelectedCellRange();
    if (selectedRange.IsValid()) {
        CString currentUser = UserManager::getInstance().getCurrentUser().c_str();
        std::vector<int> rowsToDelete;
        for (int row = selectedRange.GetMinRow(); row <= selectedRange.GetMaxRow(); ++row) {
            BOOL isRowSelected = FALSE;
            for (int col = selectedRange.GetMinCol(); col <= selectedRange.GetMaxCol(); ++col) {
                if (pGridCtrl->IsCellSelected(row, col)) {
                    isRowSelected = TRUE;
                    break;
                }
            }
            if (!isRowSelected) {
                continue;
            }
            CString selectedUser = pGridCtrl->GetItemText(row, 1);
            if (selectedUser == currentUser) {
                CString message;
                message.Format(_T("用户 [%s] æ˜¯å½“前登录用户,不能删除!"), currentUser);
                AfxMessageBox(message);
                return;
            }
            rowsToDelete.push_back(row);
        }
        if (rowsToDelete.empty()) {
            AfxMessageBox(_T("请先选择要删除的行!"));
            return;
        }
        CString message;
        if (rowsToDelete.size() == 1) {
            CString selectedUser = pGridCtrl->GetItemText(rowsToDelete[0], 1);
            message.Format(_T("确定要删除选中用户 [%s] å—?"), selectedUser);
            CString cstrMessage;
            cstrMessage.Format(_T("预删除用户 [%s]!"), selectedUser);
            std::string strMessage = CT2A(cstrMessage);
            SystemLogManager::getInstance().log(SystemLogManager::LogType::Operation, strMessage);
        }
        else {
            message.Format(_T("确定要删除选中的 %d ä¸ªç”¨æˆ·å—?"), rowsToDelete.size());
        }
        if (AfxMessageBox(message, MB_YESNO | MB_ICONQUESTION) == IDYES) {
            for (auto it = rowsToDelete.rbegin(); it != rowsToDelete.rend(); ++it) {
                pGridCtrl->DeleteRow(*it);
            }
            pGridCtrl->ExpandColumnsToFit(FALSE);
            pGridCtrl->ExpandLastColumn();
            pGridCtrl->Invalidate();
            pGridCtrl->UpdateWindow();
        }
    }
    else {
        AfxMessageBox(_T("请先选择要删除的用户!"));
    }
}
bool CUserManagerDlg::IsUsernameDuplicate(const CString& username)
{
    for (int row = 1; row < m_gridUserManager.GetRowCount(); ++row) {
        if (m_gridUserManager.GetItemText(row, 1) == username) {
            return true;
        }
    }
    return false;
}
CFont* CUserManagerDlg::GetOrCreateFont(int nFontSize)
{
    auto it = m_mapFonts.find(nFontSize);
    if (it != m_mapFonts.end()) {
        return it->second;
    }
    CFont* font = new CFont();
    LOGFONT logFont = { 0 };
    _tcscpy_s(logFont.lfFaceName, _T("Segoe UI"));
    logFont.lfHeight = -nFontSize;
    logFont.lfQuality = CLEARTYPE_QUALITY;
    font->CreateFontIndirect(&logFont);
    m_mapFonts[nFontSize] = font;
    return font;
}
void CUserManagerDlg::SetDefaultFont()
{
    CFont* defaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰æŽ§ä»¶ï¼Œåº”ç”¨é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
        TCHAR szClassName[256];
        GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
        if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
            pWnd = pWnd->GetNextWindow();
            continue;
        }
        pWnd->SetFont(defaultFont, TRUE);
        pWnd = pWnd->GetNextWindow();
    }
}
void CUserManagerDlg::AdjustControls(float dScaleX, float dScaleY)
{
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1 && m_mapCtrlLayouts.find(nCtrlID) != m_mapCtrlLayouts.end())
        {
            CRect originalRect = m_mapCtrlLayouts[nCtrlID];
            CRect newRect(
                static_cast<int>(originalRect.left * dScaleX),
                static_cast<int>(originalRect.top * dScaleY),
                static_cast<int>(originalRect.right * dScaleX),
                static_cast<int>(originalRect.bottom * dScaleY));
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("ComboBox")) == 0) {
                CComboBox* pComboBox = (CComboBox*)pWnd;
                pComboBox->SetItemHeight(-1, newRect.Height());  // -1 è¡¨ç¤ºæ‰€æœ‰é¡¹çš„高度
            }
            if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
                CGridCtrl* pGridCtrl = (CGridCtrl*)pWnd;
                pGridCtrl->SetDefCellHeight(newRect.Height() / 21);
                pGridCtrl->ExpandColumnsToFit(TRUE);
                pGridCtrl->ExpandLastColumn();
                pGridCtrl->Invalidate();
                pGridCtrl->UpdateWindow();
            }
            pWnd->MoveWindow(&newRect);
            AdjustControlFont(pWnd, newRect.Width(), newRect.Height());
        }
        pWnd = pWnd->GetNextWindow();
    }
}
void CUserManagerDlg::AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight)
{
    TCHAR szClassName[256];
    GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
    // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
    if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
        return;
    }
    // æ ¹æ®æŽ§ä»¶é«˜åº¦åŠ¨æ€è°ƒæ•´å­—ä½“å¤§å°
    int fontSize = nHeight / 2;
    if (fontSize < 8) fontSize = 8;
    // èŽ·å–æˆ–åˆ›å»ºå­—ä½“
    CFont* pFont = GetOrCreateFont(fontSize);
    pWnd->SetFont(pFont);
    pWnd->Invalidate(); // åˆ·æ–°æŽ§ä»¶æ˜¾ç¤º
}
BEGIN_MESSAGE_MAP(CUserManagerDlg, CDialogEx)
    ON_WM_SIZE()
    ON_NOTIFY(GVN_COMBOSELCHANGE, IDC_CUSTOM_USER, &CUserManagerDlg::OnGridComboSelChange)
    ON_BN_CLICKED(IDC_BUTTON_ADD, &CUserManagerDlg::OnBnClickedButtonAdd)
    ON_BN_CLICKED(IDC_BUTTON_DEL, &CUserManagerDlg::OnBnClickedButtonDel)
    ON_BN_CLICKED(IDOK, &CUserManagerDlg::OnBnClickedOk)
    ON_BN_CLICKED(IDC_BUTTON_INSERT, &CUserManagerDlg::OnBnClickedButtonInsert)
    ON_WM_GETMINMAXINFO()
END_MESSAGE_MAP()
// CUserManagerDlg æ¶ˆæ¯å¤„理程序
BOOL CUserManagerDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    // TODO:  åœ¨æ­¤æ·»åŠ é¢å¤–çš„åˆå§‹åŒ–
    CRect screenRect, dlgRect, clientRect;
    SetWindowText(_T("用户管理"));
    SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRect, 0);
    GetClientRect(&clientRect);
    m_nInitialWidth = clientRect.Width();
    m_nInitialHeight = clientRect.Height();
    // åˆå§‹åŒ–默认字体
    CFont* pDefaultFont = GetOrCreateFont(12);
    // éåŽ†æ‰€æœ‰å­æŽ§ä»¶ï¼Œè®°å½•åˆå§‹ä½ç½®å¹¶è®¾ç½®é»˜è®¤å­—ä½“
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1) {
            // è®°å½•控件初始布局
            CRect ctrlRect;
            pWnd->GetWindowRect(&ctrlRect);
            ScreenToClient(&ctrlRect);
            m_mapCtrlLayouts[nCtrlID] = ctrlRect;
            // è·³è¿‡ç‰¹æ®ŠæŽ§ä»¶ï¼ˆå¦‚ MFCGridCtrl)
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
                pWnd = pWnd->GetNextWindow();
                continue;
            }
            // è®¾ç½®é»˜è®¤å­—体
            pWnd->SetFont(pDefaultFont);
        }
        pWnd = pWnd->GetNextWindow();
    }
    GetWindowRect(&dlgRect);
    int dlgWidth = dlgRect.Width() * 3;
    int dlgHeight = dlgRect.Height() * 3;
    if (dlgWidth > screenRect.Width()) {
        dlgWidth = screenRect.Width();
    }
    if (dlgHeight > screenRect.Height()) {
        dlgHeight = screenRect.Height();
    }
    int centerX = screenRect.left + (screenRect.Width() - dlgWidth) / 2;
    int centerY = screenRect.top + (screenRect.Height() - dlgHeight) / 2;
    MoveWindow(centerX, centerY, dlgWidth, dlgHeight);
    // åˆå§‹åŒ–用户管理表格
    InitUserManager();
    return TRUE;  // return TRUE unless you set the focus to a control
    // å¼‚常: OCX å±žæ€§é¡µåº”返回 FALSE
}
void CUserManagerDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);
    // TODO: åœ¨æ­¤å¤„添加消息处理程序代码
    if (nType == SIZE_MINIMIZED || m_mapCtrlLayouts.empty()) {
        return;
    }
    float dScaleX = static_cast<float>(cx) / m_nInitialWidth;
    float dScaleY = static_cast<float>(cy) / m_nInitialHeight;
    // éåŽ†å¯¹è¯æ¡†ä¸­çš„æ‰€æœ‰æŽ§ä»¶
    AdjustControls(dScaleX, dScaleY);
}
void CUserManagerDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
    // TODO: åœ¨æ­¤æ·»åŠ æ¶ˆæ¯å¤„ç†ç¨‹åºä»£ç å’Œ/或调用默认值
    lpMMI->ptMinTrackSize.x = 400; // æœ€å°å®½åº¦
    lpMMI->ptMinTrackSize.y = 300; // æœ€å°é«˜åº¦
    CDialogEx::OnGetMinMaxInfo(lpMMI);
}
void CUserManagerDlg::OnGridComboSelChange(NMHDR* pNMHDR, LRESULT* pResult)
{
    NM_GRIDVIEW* pItem = (NM_GRIDVIEW*)pNMHDR;
    int nRow = pItem->iRow;
    int nCol = pItem->iColumn;
    // ç¬¬4列为权限列, ç¬¬8列为角色描述列, ä»Žæ˜ å°„中查找对应描述
    if (nCol == 3) {
        if (m_gridUserManager.GetItemBkColour(nRow, nCol) == CURR_USER_BK_COLOR) {
            AfxMessageBox(_T("当前登录用户权限不能修改!"));
        }
        else {
            CString selectedRole = m_gridUserManager.GetItemText(nRow, nCol);
            auto it = m_mapRoleDescriptions.find(selectedRole);
            if (it != m_mapRoleDescriptions.end()) {
                m_gridUserManager.SetItemText(nRow, 7, it->second);
                m_gridUserManager.RedrawCell(nRow, 7);
            }
            else {
                m_gridUserManager.SetItemText(nRow, 7, _T(""));
                m_gridUserManager.RedrawCell(nRow, 7);
            }
        }
    }
    *pResult = 0;
}
void CUserManagerDlg::OnBnClickedButtonAdd()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    AddRow(&m_gridUserManager);
}
void CUserManagerDlg::OnBnClickedButtonInsert()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    if (!m_gridUserManager.GetSafeHwnd()) return;
    CCellRange selectedRange = m_gridUserManager.GetSelectedCellRange();
    if (!selectedRange.IsValid()) {
        AfxMessageBox(_T("请先选择要插入的位置!"));
        return;
    }
    int minRow = selectedRange.GetMinRow();
    int maxRow = selectedRange.GetMaxRow();
    if (minRow < 1) {
        AfxMessageBox(_T("请选择有效的行!"));
        return;
    }
    for (int row = maxRow; row >= minRow; --row) {
        std::vector<CString> rowData;
        for (int col = 0; col < m_gridUserManager.GetColumnCount(); ++col) {
            rowData.push_back(m_gridUserManager.GetItemText(row, col));
        }
        m_gridUserManager.InsertRow(_T("新用户"), row);
        CString newUsername = rowData[1];
        int suffix = 1;
        while (IsUsernameDuplicate(newUsername)) {
            newUsername.Format(_T("%s_%d"), rowData[1], suffix++);
        }
        rowData[1] = newUsername;
        for (int col = 0; col < m_gridUserManager.GetColumnCount(); ++col) {
            m_gridUserManager.SetItemText(row, col, rowData[col]);
        }
        CStringArray permissions;
        permissions.Add(_T("管理员"));
        permissions.Add(_T("工程师"));
        permissions.Add(_T("操作员"));
        if (m_gridUserManager.SetCellType(row, 3, RUNTIME_CLASS(CGridCellCombo))) {
            CGridCellCombo* pCell = static_cast<CGridCellCombo*>(m_gridUserManager.GetCell(row, 3));
            pCell->SetOptions(permissions);
            pCell->SetStyle(CBS_DROPDOWNLIST);
            m_gridUserManager.SetItemText(row, 3, rowData[3]);
        }
        m_gridUserManager.SetCellType(row, 4, RUNTIME_CLASS(CGridCellNumeric));
        m_gridUserManager.SetCellType(row, 5, RUNTIME_CLASS(CGridCellNumeric));
    }
    for (int row = 1; row < m_gridUserManager.GetRowCount(); ++row) {
        CString strIndex;
        strIndex.Format(_T("%d"), row);
        m_gridUserManager.SetItemText(row, 0, strIndex);
    }
    m_gridUserManager.Invalidate();
    m_gridUserManager.UpdateWindow();
}
void CUserManagerDlg::OnBnClickedButtonDel()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    DeleteSelectedRow(&m_gridUserManager);
}
void CUserManagerDlg::OnBnClickedOk()
{
    // TODO: åœ¨æ­¤æ·»åŠ æŽ§ä»¶é€šçŸ¥å¤„ç†ç¨‹åºä»£ç 
    std::vector<std::vector<std::string>> vecData;
    std::set<std::string> usernameSet; // ç”¨äºŽå­˜å‚¨ç”¨æˆ·åï¼Œæ£€æŸ¥æ˜¯å¦é‡å¤
    int nCurrUserRow = -1;
    UserManager& userManager = UserManager::getInstance();
    for (int i = 1; i < m_gridUserManager.GetRowCount(); ++i) {
        std::vector<std::string> rowData;
        CString cellText = m_gridUserManager.GetItemText(i, 1);
        std::string username = CT2A(cellText.GetString());
        cellText = m_gridUserManager.GetItemText(i, 2);
        std::string userpass = CT2A(cellText.GetString());
        if (username.empty() || userpass.empty()) {
            AfxMessageBox(_T("用户名和密码不能为空!"));
            return;
        }
        if (usernameSet.find(username) != usernameSet.end()) {
            CString message;
            message.Format(_T("用户名 [%s] é‡å¤ï¼Œè¯·ä¿®æ”¹åŽä¿å­˜ï¼"), cellText);
            AfxMessageBox(message, MB_ICONEXCLAMATION);
            return;
        }
        usernameSet.insert(username);
        if (nCurrUserRow == -1 && m_gridUserManager.GetItemBkColour(i, 0) == CURR_USER_BK_COLOR){
            nCurrUserRow = i;
            if (username.compare(userManager.getCurrentUser()) != 0) {
                userManager.setCurrentUser(username);
            }
            if (userpass.compare(userManager.getCurrentPass()) != 0) {
                userManager.setCurrentPass(userpass);
            }
            userManager.clearSession();
            userManager.saveSession();
        }
        for (int j = 1; j < m_gridUserManager.GetColumnCount() - 1; ++j) {
            CString cellText = m_gridUserManager.GetItemText(i, j);
            std::string cellString = CT2A(cellText.GetString());
            // ç¬¬4列是权限,转换为数字字符串
            if (j == 3) {
                if (cellText == _T("管理员"))
                    cellString = "0";
                else if (cellText == _T("工程师"))
                    cellString = "1";
                else if (cellText == _T("操作员"))
                    cellString = "2";
                else
                    cellString = "2";
            }
            rowData.push_back(cellString);
        }
        vecData.push_back(rowData);
    }
    userManager.setUsers(vecData);
    CDialogEx::OnOK();
}
SourceCode/Bond/BondEq/View/UserManagerDlg.h
ÎļþÃû´Ó SourceCode/Bond/BondEq/UserManagerDlg.h ÐÞ¸Ä
@@ -23,12 +23,17 @@
    void AddRow(CGridCtrl* pGridCtrl);
    void DeleteSelectedRow(CGridCtrl* pGridCtrl);
    bool IsUsernameDuplicate(const CString& username);
    void AdjustControls(int nWidth, int nHeight);
    CFont* GetOrCreateFont(int nFontSize);
    void SetDefaultFont();
    void AdjustControls(float dScaleX, float dScaleY);
    void AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight);
private:
    int m_nInitialWidth;
    int m_nInitialHeight;
    std::map<int, CRect> m_mapCtrlLayouts;
    std::map<int, CFont*> m_mapFonts;
    std::map<CString, CString> m_mapRoleDescriptions;
private:
    CGridCtrl m_gridUserManager;
@@ -40,6 +45,8 @@
public:
    virtual BOOL OnInitDialog();
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnGetMinMaxInfo(MINMAXINFO* lpMMI);
    afx_msg void OnGridComboSelChange(NMHDR* pNMHDR, LRESULT* pResult);
    afx_msg void OnBnClickedButtonAdd();
    afx_msg void OnBnClickedButtonInsert();
    afx_msg void OnBnClickedButtonDel();
SourceCode/Bond/BondEq/stdafx.h
@@ -47,6 +47,11 @@
#include "..\DatabaseSDK\include\MySQLDatabase.h"
#include "..\DatabaseSDK\include\SQLiteDatabase.h"
// å•例模式的数据库管理类
#include "UserManager.h"
#include "RecipeManager.h"
#include "SystemLogManager.h"
// æŽ§ä»¶æ ·å¼
static UINT g_nGridFixCellColor = RGB(144, 200, 246);
static UINT g_nGridFixFontColor = RGB(0, 0, 0);