Import CBB refresh verify r4 stability baseline

Preserve tested Verify source, authoritative READY checks, bounded bridge retries, diagnostics and failure-only reporting. Include 336-test suite and packaging assets; exclude live Mentor samples, field logs, backups and distributions.
This commit is contained in:
阿白叔 committed 2026-09-29 15:05:20 +08:00
commit 11a2b2e46e
130 files changed
+19267

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
[CmdletBinding()]
param([string]$Output = (Join-Path $PSScriptRoot '..\build\mentor-ui-watch.jsonl'), [int]$IntervalMs = 250)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
$typeDef=@'
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public static class MentorWindowProbe {
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
public static IntPtr[] ForProcess(int processId) { var r=new List<IntPtr>(); EnumWindows((h,p)=>{uint id;GetWindowThreadProcessId(h,out id);if(id==(uint)processId && IsWindowVisible(h))r.Add(h);return true;},IntPtr.Zero);return r.ToArray(); }
}
'@
if($null -eq ('MentorWindowProbe' -as [type])){Add-Type -TypeDefinition $typeDef}
$parent=Split-Path -Parent ([IO.Path]::GetFullPath($Output)); New-Item -ItemType Directory -Path $parent -Force | Out-Null
$last=@{}
function Snapshot($p) {
$proc=Get-Process -Id $p.Id -ErrorAction SilentlyContinue
if($null -eq $proc){return @()}
$all=[Collections.Generic.List[object]]::new()
foreach($hwnd in [MentorWindowProbe]::ForProcess($p.Id)){try{$window=[System.Windows.Automation.AutomationElement]::FromHandle($hwnd);if($null -ne $window){$all.Add($window);foreach($child in $window.FindAll([System.Windows.Automation.TreeScope]::Descendants,[System.Windows.Automation.Condition]::TrueCondition)){$all.Add($child)}}}catch{}}
$rows=@()
foreach($e in $all){try{if([int]$e.Current.ProcessId -ne $p.Id){continue};$r=$e.Current;$row=[ordered]@{name=[string]$r.Name;type=[string]$r.ControlType.ProgrammaticName;id=[string]$r.AutomationId;class=[string]$r.ClassName;enabled=[bool]$r.IsEnabled;hwnd=[int]$r.NativeWindowHandle;help=[string]$r.HelpText;focused=[bool]$r.HasKeyboardFocus;patterns=@($e.GetSupportedPatterns() | ForEach-Object {$_.ProgrammaticName})};$pattern=$null;if($e.TryGetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern,[ref]$pattern)){$row.selected=$pattern.Current.IsSelected};$pattern=$null;if($e.TryGetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern,[ref]$pattern)){$row.expansion=[string]$pattern.Current.ExpandCollapseState};$rows += $row}catch{}}
return $rows
}
[ordered]@{event='listener_started';listenerPid=$PID;timestampUtc=[datetime]::UtcNow.ToString('o')}|ConvertTo-Json -Compress|Add-Content -LiteralPath $Output -Encoding UTF8
$heartbeat=[datetime]::MinValue
while(-not (Test-Path -LiteralPath ($Output + '.stop'))){
try {
$procs=@(Get-Process LibraryManager,ExpeditionPCB,pcbui -ErrorAction SilentlyContinue)
foreach($p in $procs){$rows=@(Snapshot $p);$key="$($p.ProcessName):$($p.Id)";$json=ConvertTo-Json -InputObject $rows -Compress -Depth 5;$hash=([string]$json).GetHashCode();if(-not $last.ContainsKey($key) -or $last[$key] -ne $hash){$last[$key]=$hash;$line=([ordered]@{timestampUtc=[datetime]::UtcNow.ToString('o');process=$p.ProcessName;pid=$p.Id;windowTitle=$p.MainWindowTitle;elements=$rows}|ConvertTo-Json -Compress -Depth 6)+[Environment]::NewLine;[IO.File]::AppendAllText($Output,$line,(New-Object Text.UTF8Encoding($false)))}}
if(([datetime]::UtcNow-$heartbeat).TotalSeconds -ge 5){$heartbeat=[datetime]::UtcNow;$line=([ordered]@{event='heartbeat';listenerPid=$PID;timestampUtc=$heartbeat.ToString('o');targetPids=@($procs | ForEach-Object {$_.Id})}|ConvertTo-Json -Compress)+[Environment]::NewLine;[IO.File]::AppendAllText($Output,$line,(New-Object Text.UTF8Encoding($false)))}
} catch {$line=([ordered]@{event='listener_error';timestampUtc=[datetime]::UtcNow.ToString('o');message=$_.Exception.Message}|ConvertTo-Json -Compress)+[Environment]::NewLine;[IO.File]::AppendAllText($Output,$line,(New-Object Text.UTF8Encoding($false)))}
Start-Sleep -Milliseconds $IntervalMs
}
+73
View File
@@ -0,0 +1,73 @@
"""Synthetic throughput benchmark for the batch status/checkpoint layer."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import statistics
import tempfile
import time
from cbb_refresh_verify.batch_status import BatchStatusSession
from cbb_refresh_verify.status_bridge import BridgeResult
class SyntheticBridge:
def __init__(self, rotate_every: int):
self.rotate_every = rotate_every
self.restart_count = 0
self.latencies_ms: list[float] = []
def start(self):
return None
def restart(self):
self.restart_count += 1
def close(self):
return None
def query(self, lmc_file, block_name, **kwargs):
started = time.perf_counter()
result = BridgeResult("READY" if int(block_name[3:]) % 3 == 0 else "PENDING", "synthetic")
self.latencies_ms.append((time.perf_counter() - started) * 1000)
return result
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--count", type=int, required=True)
parser.add_argument("--rotate-every", type=int, default=500)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.count < 1:
raise SystemExit("--count must be positive")
with tempfile.TemporaryDirectory(prefix="cbb-status-benchmark-") as root:
root_path = Path(root)
lmc = root_path / "library.lmc"; lmc.write_bytes(b"synthetic-library")
bridge = SyntheticBridge(args.rotate_every)
started = time.perf_counter()
records = BatchStatusSession(bridge, rotate_every=args.rotate_every).scan(
[f"CBB{i}" for i in range(args.count)], lmc, root_path / "scan.jsonl")
elapsed = time.perf_counter() - started
values = bridge.latencies_ms
p95 = sorted(values)[max(0, int(len(values) * 0.95) - 1)] if values else 0
payload = {
"count": args.count,
"elapsed_seconds": elapsed,
"completed_count": len(records),
"error_count": sum(record.status not in {"READY", "PENDING"} for record in records),
"mean_latency_ms": statistics.mean(values) if values else 0,
"p95_latency_ms": p95,
"bridge_restart_count": bridge.restart_count,
"synthetic": True,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(payload, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+10
View File
@@ -0,0 +1,10 @@
Option Explicit
Dim app, doc, lic, token
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
If InStr(LCase(doc.ProjectIntegration.ProjectFile), "\build\background-fixture\") = 0 Then WScript.Quit 2
Set lic = CreateObject("MGCPCBAutomationLicensing.Application")
token = lic.GetToken(doc.Validate(0))
doc.Validate token
doc.Close False
app.Quit
+24
View File
@@ -0,0 +1,24 @@
Option Explicit
Dim app, doc, pi, lic, token, fso, log, info, bar, ctl
Set fso = CreateObject("Scripting.FileSystemObject")
Set log = fso.CreateTextFile(WScript.Arguments(0), True)
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
Set pi = doc.ProjectIntegration
log.WriteLine pi.ProjectFile
log.WriteLine "Forward: " & pi.ForwardAnnotationStatus & " Allowed=" & pi.IsForwardAnnotationAllowed
log.WriteLine "SynchCES: " & pi.SynchCESStatus & " Allowed=" & pi.IsSynchCESAllowed
log.WriteLine "LoadCES: " & pi.LoadCESStatus & " Allowed=" & pi.IsLoadCESAllowed
log.WriteLine "Back: " & pi.BackAnnotationStatus & " Allowed=" & pi.IsBackAnnotationAllowed
Set lic = CreateObject("MGCPCBAutomationLicensing.Application")
token = lic.GetToken(doc.Validate(0))
doc.Validate token
log.WriteLine "Licensed Forward Allowed=" & pi.IsForwardAnnotationAllowed
log.WriteLine "Open PI=" & app.Gui.ProcessCommand("Project Integration", False)
For Each bar In app.Gui.CommandBars
log.WriteLine "BAR " & bar.Name
For Each ctl In bar.Controls
log.WriteLine "CONTROL " & ctl.Caption & " ID=" & ctl.Id
Next
Next
log.Close
+13
View File
@@ -0,0 +1,13 @@
cmake_minimum_required(VERSION 3.20)
project(NativeVerifyProbe32 LANGUAGES CXX)
add_executable(NativeVerifyProbe32 NativeVerifyProbe32.cpp)
target_compile_features(NativeVerifyProbe32 PRIVATE cxx_std_17)
set_target_properties(NativeVerifyProbe32 PROPERTIES
MSVC_RUNTIME_LIBRARY "MultiThreadedDLL"
WIN32_EXECUTABLE FALSE
)
if (MSVC)
target_compile_options(NativeVerifyProbe32 PRIVATE /EHsc /MD /utf-8)
endif()
@@ -0,0 +1,346 @@
// Isolated, read-only ABI sanity probe for Mentor EE 7.9 CLibServer.
//
// This program intentionally does not call VerifyRCCells, SetVerifyRCCellsFlag,
// Save, VerifyReuseBlock, or UnVerifyReuseBlock. It only reproduces the
// constructor/Init/Load/Close/destructor lifecycle observed in Mentor's own
// x86 RFSymMergeUtility.exe caller.
#include <windows.h>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
namespace {
constexpr std::size_t kCLibServerObjectSize = 0x0c;
using CtorFn = void(__thiscall*)(void*, const char*);
using InitFn = long(__thiscall*)(void*);
using LoadFn = long(__thiscall*)(void*, const char*, int);
using CloseFn = void(__thiscall*)(void*);
using DtorFn = void(__thiscall*)(void*);
using SetVerifyFlagFn = void(__thiscall*)(void*, int);
using SaveFn = long(__thiscall*)(void*, const char*, int, int);
struct Functions {
CtorFn ctor = nullptr;
InitFn init = nullptr;
LoadFn load = nullptr;
CloseFn close = nullptr;
DtorFn dtor = nullptr;
SetVerifyFlagFn setVerifyFlag = nullptr;
SaveFn save = nullptr;
};
struct LifecycleResult {
long initReturn;
long loadReturn;
int constructed;
int closed;
int destroyed;
DWORD exceptionCode;
};
// Keep the SEH boundary free of C++ objects. MSVC rejects __try in a function
// that would need automatic object unwinding.
int invokeLifecycle(const Functions* fn, void* object, const char* path,
LifecycleResult* result) {
result->initReturn = -1;
result->loadReturn = -1;
result->constructed = 0;
result->closed = 0;
result->destroyed = 0;
result->exceptionCode = ERROR_SUCCESS;
__try {
fn->ctor(object, path);
result->constructed = 1;
result->initReturn = fn->init(object);
if (result->initReturn == 0) {
// The observed Mentor caller pushes mode 1 for Load(path, mode).
result->loadReturn = fn->load(object, path, 1);
}
fn->close(object);
result->closed = 1;
fn->dtor(object);
result->destroyed = 1;
} __except (EXCEPTION_EXECUTE_HANDLER) {
result->exceptionCode = GetExceptionCode();
}
return result->exceptionCode == ERROR_SUCCESS ? 0 : 1;
}
struct WriteResult {
long initReturn;
long loadReturn;
long saveReturn;
int constructed;
int flagSet;
int closed;
int destroyed;
DWORD exceptionCode;
};
int invokeWriteLifecycle(const Functions* fn, void* object, const char* path,
int verifyFlag, WriteResult* result) {
result->initReturn = -1;
result->loadReturn = -1;
result->saveReturn = -1;
result->constructed = 0;
result->flagSet = 0;
result->closed = 0;
result->destroyed = 0;
result->exceptionCode = ERROR_SUCCESS;
__try {
fn->ctor(object, path);
result->constructed = 1;
result->initReturn = fn->init(object);
if (result->initReturn == 0) {
result->loadReturn = fn->load(object, path, 1);
}
if (result->loadReturn == 0) {
fn->setVerifyFlag(object, verifyFlag);
result->flagSet = 1;
// RFSymMergeUtility.exe uses Save(NULL, 0, 0). The verify flag
// makes CLibServer::Save enter its internal VerifyRCCells path.
result->saveReturn = fn->save(object, nullptr, 0, 0);
}
fn->close(object);
result->closed = 1;
fn->dtor(object);
result->destroyed = 1;
} __except (EXCEPTION_EXECUTE_HANDLER) {
result->exceptionCode = GetExceptionCode();
}
return result->exceptionCode == ERROR_SUCCESS ? 0 : 1;
}
std::string envValue(const char* key) {
const char* value = std::getenv(key);
return value && *value ? value : std::string();
}
std::wstring widen(const std::string& value) {
if (value.empty()) return {};
const int count = MultiByteToWideChar(CP_UTF8, 0, value.data(),
static_cast<int>(value.size()), nullptr, 0);
if (count <= 0) return {};
std::wstring result(static_cast<std::size_t>(count), L'\0');
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()),
result.data(), count);
return result;
}
std::string jsonEscape(const std::string& value) {
std::ostringstream out;
for (const char ch : value) {
switch (ch) {
case '\\': out << "\\\\"; break;
case '"': out << "\\\""; break;
case '\n': out << "\\n"; break;
case '\r': out << "\\r"; break;
default: out << ch; break;
}
}
return out.str();
}
void fail(const std::string& message, DWORD error = ERROR_SUCCESS) {
std::cout << "{\"ok\":false,\"mode\":\"read-only\",\"error\":\""
<< jsonEscape(message) << "\"";
if (error != ERROR_SUCCESS) std::cout << ",\"win32_error\":" << error;
std::cout << "}" << std::endl;
}
FARPROC required(HMODULE module, const char* name) {
FARPROC address = GetProcAddress(module, name);
return address;
}
int run(const std::string& lmc) {
const std::string sddHome = envValue("SDD_HOME");
const std::string configured = envValue("LIBMANAGERDBPI_PATH");
const std::string dbPath = !configured.empty()
? configured
: (sddHome.empty() ? "LibManagerDBPI.dll"
: sddHome + "\\common\\win32\\lib\\LibManagerDBPI.dll");
HMODULE module = LoadLibraryW(widen(dbPath).c_str());
if (!module) {
fail("无法加载 LibManagerDBPI.dll: " + dbPath, GetLastError());
return 2;
}
const char* ctorName = "??0CLibServer@@QAE@PBD@Z";
const char* initName = "?Init@CLibServer@@QAEJXZ";
const char* loadName = "?Load@CLibServer@@QAEJPBDH@Z";
const char* closeName = "?Close@CLibServer@@QAEXXZ";
const char* dtorName = "??1CLibServer@@QAE@XZ";
Functions fn{
reinterpret_cast<CtorFn>(required(module, ctorName)),
reinterpret_cast<InitFn>(required(module, initName)),
reinterpret_cast<LoadFn>(required(module, loadName)),
reinterpret_cast<CloseFn>(required(module, closeName)),
reinterpret_cast<DtorFn>(required(module, dtorName)),
};
if (!fn.ctor || !fn.init || !fn.load || !fn.close || !fn.dtor) {
fail("CLibServer lifecycle export is incomplete");
return 3;
}
// RFSymMergeUtility.exe calls operator new(0xC) before the constructor.
void* object = VirtualAlloc(nullptr, kCLibServerObjectSize,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!object) {
fail("无法分配 CLibServer 对象缓冲区", GetLastError());
return 4;
}
LifecycleResult lifecycle{};
invokeLifecycle(&fn, object, lmc.c_str(), &lifecycle);
VirtualFree(object, 0, MEM_RELEASE);
// Deliberately do not FreeLibrary(module): Mentor's MFC/DBPI module graph
// is process-scoped and the OS reclaims it safely at process exit.
std::cout << "{\"ok\":" << (lifecycle.exceptionCode == ERROR_SUCCESS ? "true" : "false")
<< ",\"mode\":\"read-only\",\"architecture\":\"x86\""
<< ",\"module\":\"" << jsonEscape(dbPath) << "\""
<< ",\"object_size\":" << kCLibServerObjectSize
<< ",\"init_return\":" << lifecycle.initReturn
<< ",\"load_return\":" << lifecycle.loadReturn
<< ",\"load_mode\":1"
<< ",\"constructed\":" << (lifecycle.constructed ? "true" : "false")
<< ",\"closed\":" << (lifecycle.closed ? "true" : "false")
<< ",\"destroyed\":" << (lifecycle.destroyed ? "true" : "false")
<< ",\"write_call_enabled\":false";
if (lifecycle.exceptionCode != ERROR_SUCCESS) {
std::cout << ",\"exception_code\":" << lifecycle.exceptionCode;
}
std::cout << "}" << std::endl;
return lifecycle.exceptionCode == ERROR_SUCCESS && lifecycle.initReturn == 0 &&
lifecycle.loadReturn == 0
? 0
: 5;
}
std::string fullPath(const std::string& path) {
char buffer[MAX_PATH * 4] = {};
const DWORD length = GetFullPathNameA(path.c_str(), sizeof(buffer), buffer, nullptr);
return length == 0 || length >= sizeof(buffer) ? std::string() : std::string(buffer, length);
}
bool pathWithin(const std::string& root, const std::string& candidate) {
const std::string rootFull = fullPath(root);
const std::string candidateFull = fullPath(candidate);
if (rootFull.empty() || candidateFull.empty()) return false;
if (_strnicmp(rootFull.c_str(), candidateFull.c_str(), rootFull.size()) != 0) return false;
if (candidateFull.size() == rootFull.size()) return false;
return candidateFull[rootFull.size()] == '\\';
}
int runWrite(const std::string& fixtureRoot, const std::string& lmc, int verifyFlag) {
if (!pathWithin(fixtureRoot, lmc)) {
std::cout << "{\"ok\":false,\"mode\":\"write-isolated-copy\",\"error\":\"path_guard\",\"fixture_root\":\""
<< jsonEscape(fullPath(fixtureRoot)) << "\",\"lmc\":\""
<< jsonEscape(fullPath(lmc)) << "\"}" << std::endl;
return 10;
}
const std::string sddHome = envValue("SDD_HOME");
const std::string configured = envValue("LIBMANAGERDBPI_PATH");
const std::string dbPath = !configured.empty()
? configured
: (sddHome.empty() ? "LibManagerDBPI.dll"
: sddHome + "\\common\\win32\\lib\\LibManagerDBPI.dll");
HMODULE module = LoadLibraryW(widen(dbPath).c_str());
if (!module) {
fail("无法加载 LibManagerDBPI.dll: " + dbPath, GetLastError());
return 11;
}
Functions fn{
reinterpret_cast<CtorFn>(required(module, "??0CLibServer@@QAE@PBD@Z")),
reinterpret_cast<InitFn>(required(module, "?Init@CLibServer@@QAEJXZ")),
reinterpret_cast<LoadFn>(required(module, "?Load@CLibServer@@QAEJPBDH@Z")),
reinterpret_cast<CloseFn>(required(module, "?Close@CLibServer@@QAEXXZ")),
reinterpret_cast<DtorFn>(required(module, "??1CLibServer@@QAE@XZ")),
reinterpret_cast<SetVerifyFlagFn>(required(module, "?SetVerifyRCCellsFlag@CLibServer@@QAEXH@Z")),
reinterpret_cast<SaveFn>(required(module, "?Save@CLibServer@@QAEJPBDHH@Z")),
};
if (!fn.ctor || !fn.init || !fn.load || !fn.close || !fn.dtor ||
!fn.setVerifyFlag || !fn.save) {
fail("CLibServer write lifecycle export is incomplete");
return 12;
}
void* object = VirtualAlloc(nullptr, kCLibServerObjectSize,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!object) {
fail("无法分配 CLibServer 对象缓冲区", GetLastError());
return 13;
}
WriteResult result{};
invokeWriteLifecycle(&fn, object, lmc.c_str(), verifyFlag, &result);
VirtualFree(object, 0, MEM_RELEASE);
std::cout << "{\"ok\":"
<< (result.exceptionCode == ERROR_SUCCESS ? "true" : "false")
<< ",\"mode\":\"write-isolated-copy\",\"architecture\":\"x86\""
<< ",\"fixture_root\":\"" << jsonEscape(fullPath(fixtureRoot)) << "\""
<< ",\"lmc\":\"" << jsonEscape(fullPath(lmc)) << "\""
<< ",\"object_size\":" << kCLibServerObjectSize
<< ",\"load_mode\":1"
<< ",\"verify_flag\":" << verifyFlag
<< ",\"init_return\":" << result.initReturn
<< ",\"load_return\":" << result.loadReturn
<< ",\"save_return\":" << result.saveReturn
<< ",\"constructed\":" << (result.constructed ? "true" : "false")
<< ",\"flag_set\":" << (result.flagSet ? "true" : "false")
<< ",\"closed\":" << (result.closed ? "true" : "false")
<< ",\"destroyed\":" << (result.destroyed ? "true" : "false")
<< ",\"write_call_enabled\":true";
if (result.exceptionCode != ERROR_SUCCESS) {
std::cout << ",\"exception_code\":" << result.exceptionCode;
}
std::cout << "}" << std::endl;
return result.exceptionCode == ERROR_SUCCESS ? 0 : 14;
}
} // namespace
int main(int argc, char** argv) {
if (argc == 8 && std::string(argv[1]) == "--write-isolated-copy" &&
std::string(argv[2]) == "--fixture-root" &&
std::string(argv[4]) == "--lmc" &&
std::string(argv[6]) == "--set-verify-flag") {
const std::string fixtureRoot(argv[3]);
const std::string lmc(argv[5]);
const int verifyFlag = std::atoi(argv[7]);
if (verifyFlag != 1) {
fail("写 probe 只允许 verify flag=1");
return 1;
}
if (GetFileAttributesA(lmc.c_str()) == INVALID_FILE_ATTRIBUTES) {
fail("LMC 文件不存在: " + lmc, GetLastError());
return 1;
}
return runWrite(fixtureRoot, lmc, verifyFlag);
}
if (argc != 4 || std::string(argv[1]) != "--read-only" ||
std::string(argv[2]) != "--lmc" || argv[3][0] == '\0') {
fail("仅支持 --read-only --lmc <isolated-lmc>");
return 1;
}
const std::string lmc(argv[3]);
if (GetFileAttributesA(lmc.c_str()) == INVALID_FILE_ATTRIBUTES) {
fail("LMC 文件不存在: " + lmc, GetLastError());
return 1;
}
return run(lmc);
}
@@ -0,0 +1,30 @@
$ErrorActionPreference = 'Stop'
$probe = Join-Path $PSScriptRoot 'build-x86\Release\NativeVerifyProbe32.exe'
$fixture = 'F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\diagnostics\Mentor_lib_EE7.9-clean\mentor_lib.lmc'
if (-not (Test-Path -LiteralPath $probe)) {
throw "NativeVerifyProbe32.exe has not been built: $probe"
}
if (-not (Test-Path -LiteralPath $fixture)) {
throw "Fixture is missing: $fixture"
}
$before = (Get-FileHash -LiteralPath $fixture -Algorithm SHA256).Hash
$output = & $probe --read-only --lmc $fixture 2>&1
if ($LASTEXITCODE -ne 0) {
throw "Probe exited with code ${LASTEXITCODE}: $($output -join ' ')"
}
$record = $output | ConvertFrom-Json
if (-not $record.ok -or $record.mode -ne 'read-only') {
throw "Probe did not report a successful read-only lifecycle: $($output -join ' ')"
}
if ($record.load_return -ne 0 -or $record.init_return -ne 0) {
throw "Mentor lifecycle returned an error: $($output -join ' ')"
}
$after = (Get-FileHash -LiteralPath $fixture -Algorithm SHA256).Hash
if ($before -ne $after) {
throw 'Read-only probe changed the isolated LMC fixture.'
}
Write-Output ($output -join "`n")
@@ -0,0 +1,20 @@
$ErrorActionPreference = 'Stop'
$probe = Join-Path $PSScriptRoot 'build-x86\Release\NativeVerifyProbe32.exe'
$outside = 'F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\diagnostics\Mentor_lib_EE7.9-clean\mentor_lib.lmc'
$fixtureRoot = 'F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\diagnostics\native-verify-probe-20260925\fixture'
if (-not (Test-Path -LiteralPath $probe)) {
throw "NativeVerifyProbe32.exe has not been built: $probe"
}
$output = & $probe --write-isolated-copy --fixture-root $fixtureRoot --lmc $outside --set-verify-flag 1 2>&1
if ($LASTEXITCODE -eq 0) {
throw 'The write probe accepted a path outside its isolated fixture.'
}
if (($output -join ' ') -notmatch 'path_guard|fixture_root|isolated_fixture') {
throw "The guard failure was not explicit: $($output -join ' ')"
}
Write-Output ($output -join "`n")
exit 0
+56
View File
@@ -0,0 +1,56 @@
"""Complete the already opened background PCB without input-desktop interaction."""
from pathlib import Path
import json
import os
import subprocess
import sys
import time
root = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(root/'src'))
output = root/'build'/'background-probe'
if '--worker' in sys.argv:
import traceback
try:
import win32com.client
from cbb_refresh_verify.integration import refresh_integration, statuses, value
app = win32com.client.GetActiveObject('MGCPCB.Application')
doc = app.ActiveDocument
expected = r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\ReusableBlocksLP\Audio_D2128_ESD\Work\Audio_D2128_ESD.prj'
assert doc.ProjectIntegration.ProjectFile.casefold() == expected.casefold()
if '--inspect' in sys.argv:
(output/'after-save-status.json').write_text(json.dumps({'states': statuses(doc.ProjectIntegration)}), encoding='utf-8')
sys.exit(0)
with (output/'com-events.jsonl').open('w', encoding='utf-8') as stream:
def emit(**event):
stream.write(json.dumps(event)+'\n');stream.flush()
refresh_integration(doc.ProjectIntegration, emit=emit)
with (output/'save.log').open('w') as log:
p = subprocess.run([r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(root/'src'/'cbb_refresh_verify'/'save_verified_block.vbs'), expected], stdout=log, stderr=log, timeout=120)
emit(stage='save_close_result', code=p.returncode)
except Exception:
(output/'com-error.txt').write_text(traceback.format_exc(), encoding='utf-8')
raise
else:
import win32service
import win32process
import win32con
import win32gui
import win32event
from cbb_refresh_verify.mentor_adapter import handle_known_dialogs
desktop = win32service.OpenDesktop('CbbVerifyBackgroundProbe',0,False,win32con.GENERIC_ALL)
startup = win32process.STARTUPINFO()
startup.lpDesktop = r'winsta0\CbbVerifyBackgroundProbe'
args = [sys.executable, str(Path(__file__).resolve()), '--worker'] + (['--inspect'] if '--inspect' in sys.argv else [])
hp, ht, pid, tid = win32process.CreateProcess(sys.executable, subprocess.list2cmdline(args), None, None, False, win32con.CREATE_NO_WINDOW, None, str(root), startup)
ht.Close()
foreground = win32gui.GetForegroundWindow()
handled = set()
for _ in range(300):
handle_known_dialogs(26012, handled, output/'dialogs.jsonl', desktop=desktop)
if win32event.WaitForSingleObject(hp, 0) == win32con.WAIT_OBJECT_0:
break
time.sleep(.5)
print('worker exit',win32process.GetExitCodeProcess(hp),'foreground before/after',foreground,win32gui.GetForegroundWindow())
print((output/'save.log').read_text(errors='replace') if (output/'save.log').exists() else 'no save log')
+53
View File
@@ -0,0 +1,53 @@
"""Test ReusableCircuit startup on a non-input desktop, without switching it."""
import json
import subprocess
import time
import sys
from pathlib import Path
import win32con
import win32gui
import win32process
import win32service
root = Path(__file__).resolve().parents[1]/'build'/'background-probe'
root.mkdir(parents=True, exist_ok=True)
desktop = win32service.CreateDesktop('CbbVerifyBackgroundProbe', 0, win32con.GENERIC_ALL, None)
info = win32process.STARTUPINFO()
info.lpDesktop = r'winsta0\CbbVerifyBackgroundProbe'
pcb = Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\ReusableBlocksLP\Audio_D2128_ESD\Work\PCB\Audio_D2128_ESD.pcb')
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\wg\win32\bin\ExpeditionPCB.exe'
foreground = win32gui.GetForegroundWindow()
cursor = win32gui.GetCursorPos()
if '--attach' not in sys.argv:
process_handle, thread_handle, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, str(pcb), '-ReusableCircuit']), None, None, False, 0, None, None, info)
thread_handle.Close()
print('pcb', pid, 'desktop', info.lpDesktop, flush=True)
last = None
with (root/'windows.jsonl').open('a', encoding='utf-8') as log:
for _ in range(180):
try:
windows = desktop.EnumDesktopWindows()
except Exception:
windows = []
state = []
for hwnd in windows:
hwnd = int(hwnd)
if not win32gui.IsWindowVisible(hwnd): continue
children = []
win32gui.EnumChildWindows(hwnd, lambda c, _: children.append(c), None)
texts = [win32gui.GetWindowText(c) for c in children]
title = win32gui.GetWindowText(hwnd)
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
state.append({'hwnd': hwnd, 'pid': pid, 'title': title, 'texts': texts if win32gui.GetClassName(hwnd) == '#32770' else []})
if title == 'Tip of the Day' or 'Select the desired product license' in texts:
buttons = [c for c in children if win32gui.GetDlgCtrlID(c) == 1]
if buttons: win32gui.PostMessage(buttons[0], win32con.BM_CLICK, 0, 0)
if state != last:
event = {'time': time.strftime('%H:%M:%S'), 'windows': state, 'foreground': win32gui.GetForegroundWindow()}
line = json.dumps(event, ensure_ascii=False)
log.write(line+'\n');log.flush();print(line, flush=True);last=state
if any('Reusable Block - [Audio_D2128_ESD]' in x['title'] for x in state):
print('BACKGROUND_DOC_WINDOW_READY', 'foreground_before', foreground, 'foreground_now', win32gui.GetForegroundWindow(), flush=True)
break
time.sleep(.5)
print('Desktop retained by PCB process; no SwitchDesktop was called.', flush=True)
+217
View File
@@ -0,0 +1,217 @@
"""Probe keyboard/WM_COMMAND routes that need no physical cursor position.
SetCursorPos fails on a non-input desktop, so LM's cursor-based hit test always
resolves (0,0) and the posted right-click yields the docking pane menu. These
variants avoid hit testing entirely:
1. WM_CONTEXTMENU with lParam=-1 (keyboard-invoked context menu for the selection)
2. VK_APPS keydown/keyup to the focused tree
3. WM_COMMAND with the Verify command id (menu AutomationId 194) to frame/pane/tree
Command execution is judged by evidence, not by return values: a launched
ExpeditionPCB.exe or a new LM window. Results land in build/command-routes.json.
"""
import ctypes, ctypes.wintypes, json, subprocess, time
from pathlib import Path
import faulthandler
import win32con, win32gui, win32process, win32service
faulthandler.dump_traceback_later(180, exit=True)
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = ROOT/'build'/'background-fixture'/'Mentor_lib_EE7.9'/'mentor_lib.lmc'
NAME = 'Audio_D2128_ESD'
OUTPUT = ROOT/'build'/'command-routes.json'
DESKTOP = 'CbbCommandProbe'
VERIFY_COMMAND_ID = 194
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, str(LIBRARY)]), None, None, False, 0, None, None, startup)
ht.Close()
lm = None
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.window_text().startswith('Library Manager:') and w.process_id() == pid]
if len(windows) == 1:
lm = windows[0]
break
time.sleep(.5)
if lm is None:
raise SystemExit('Library Manager did not open')
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', LIBRARY.name, 'Reusable Blocks', 'Logical-Physical', NAME], exact=True)
item.ensure_visible()
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
step(f'selected={item.is_selected()} tree={tree.handle} frame={lm.handle}')
pane = next((w.handle for w in lm.descendants() if w.class_name() == 'AfxControlBar90'), None)
class GUITHREADINFO(ctypes.Structure):
_fields_ = [('cbSize', ctypes.wintypes.DWORD), ('flags', ctypes.wintypes.DWORD),
('hwndActive', ctypes.wintypes.HWND), ('hwndFocus', ctypes.wintypes.HWND),
('hwndCapture', ctypes.wintypes.HWND), ('hwndMenuOwner', ctypes.wintypes.HWND),
('hwndMoveSize', ctypes.wintypes.HWND), ('hwndCaret', ctypes.wintypes.HWND),
('rcCaret', ctypes.wintypes.RECT)]
def gui_state(label):
info = GUITHREADINFO(); info.cbSize = ctypes.sizeof(GUITHREADINFO)
ok = ctypes.windll.user32.GetGUIThreadInfo(tid, ctypes.byref(info))
step(f'{label}: ok={bool(ok)} active={info.hwndActive} focus={info.hwndFocus} '
f'capture={info.hwndCapture} menuOwner={info.hwndMenuOwner}')
return {'ok': bool(ok), 'active': int(info.hwndActive or 0), 'focus': int(info.hwndFocus or 0)}
gui_state('before focus attach')
import win32api
target_tid = win32process.GetWindowThreadProcessId(tree.handle)[0]
our_tid = win32api.GetCurrentThreadId()
attached = bool(ctypes.windll.user32.AttachThreadInput(our_tid, target_tid, True))
step(f'AttachThreadInput(ours={our_tid}, target={target_tid}) = {attached}')
focus_set = False
try:
focus_set = bool(ctypes.windll.user32.SetFocus(tree.handle))
finally:
ctypes.windll.user32.AttachThreadInput(our_tid, target_tid, False)
step(f'SetFocus(tree) = {focus_set}')
gui_state('after focus attach')
def pcb_pids():
# tasklist output uses the OEM code page on this station, not UTF-8.
out = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq ExpeditionPCB.exe', '/FO', 'CSV', '/NH'],
capture_output=True).stdout.decode('gbk', errors='replace')
return [line.split(',')[1].strip('"') for line in out.splitlines() if line.strip('"').startswith('ExpeditionPCB')]
def lm_windows():
return [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.process_id() == pid]
def menus_now():
return [m for m in Desktop(backend='uia').windows(control_type='Menu') if m.is_visible()]
def dump(menus):
out = []
for menu in menus:
items = []
for entry in menu.descendants(control_type='MenuItem'):
try:
items.append({'name': entry.window_text(),
'automation_id': str(entry.element_info.automation_id or ''),
'enabled': bool(entry.is_enabled())})
except Exception:
items.append({'name': '(stale)', 'automation_id': '', 'enabled': False})
out.append(items)
return out
def menu_hwnds():
found = []
def visit(h, _):
if win32gui.GetClassName(h) == '#32768' and win32process.GetWindowThreadProcessId(h)[1] == pid:
found.append(h)
return True
win32gui.EnumWindows(visit, None)
return found
def dismiss():
for _ in range(10):
handles = menu_hwnds()
if not handles:
return True
for h in handles:
win32gui.PostMessage(h, win32con.WM_KEYDOWN, win32con.VK_ESCAPE, 0)
win32gui.PostMessage(h, win32con.WM_KEYUP, win32con.VK_ESCAPE, 0)
time.sleep(.4)
return not menu_hwnds()
def contextmenu_keyboard(hwnd):
# lParam=-1 is the documented "invoked from the keyboard" marker.
win32gui.PostMessage(hwnd, win32con.WM_CONTEXTMENU, hwnd, -1 & 0xffffffff)
def apps_key(hwnd):
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_APPS, 0)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_APPS, 0)
def wm_command(hwnd):
win32gui.PostMessage(hwnd, win32con.WM_COMMAND, VERIFY_COMMAND_ID, 0)
def post_mouse(hwnd, xy):
lp = ((xy[1] & 0xffff) << 16) | (xy[0] & 0xffff)
win32gui.PostMessage(hwnd, win32con.WM_MOUSEMOVE, 0, lp)
win32gui.PostMessage(hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lp)
win32gui.PostMessage(hwnd, win32con.WM_RBUTTONUP, 0, lp)
ui = Desktop(backend='uia').window(handle=lm.handle)
hits = [entry for entry in ui.descendants(control_type='TreeItem') if entry.window_text() == NAME]
rect = hits[0].rectangle()
screen_xy = (rect.mid_point().x, rect.mid_point().y)
client_point = ctypes.wintypes.POINT(*screen_xy)
ctypes.windll.user32.ScreenToClient(tree.handle, ctypes.byref(client_point))
tree_client = (client_point.x, client_point.y)
step(f'screen={screen_xy} tree_client={tree_client}')
baseline_pcb = set(pcb_pids())
baseline_windows = {w.handle for w in lm_windows()}
step(f'baseline pcb={sorted(baseline_pcb)} lm_windows={len(baseline_windows)} pane={pane}')
variants = [
('post-rclick-tree-after-focus', lambda: post_mouse(tree.handle, tree_client)),
('contextmenu-key-tree', lambda: contextmenu_keyboard(tree.handle)),
('contextmenu-key-pane', lambda: contextmenu_keyboard(pane) if pane else None),
('contextmenu-key-frame', lambda: contextmenu_keyboard(lm.handle)),
('apps-key-tree', lambda: apps_key(tree.handle)),
('wm-command-frame', lambda: wm_command(lm.handle)),
('wm-command-tree', lambda: wm_command(tree.handle)),
('wm-command-pane', lambda: wm_command(pane) if pane else None),
]
results = []
for label, trigger in variants:
if not dismiss():
results.append({'variant': label, 'error': 'previous menu could not be dismissed'})
break
before_focus = gui_state(f'{label}: state')
try:
trigger()
except Exception as error:
results.append({'variant': label, 'error': f'trigger failed: {error}'})
continue
time.sleep(1.2)
new_pcb = sorted(set(pcb_pids()) - baseline_pcb)
new_windows = [w.window_text() for w in lm_windows() if w.handle not in baseline_windows]
menus = menus_now()
verdict = {'variant': label, 'menus': dump(menus), 'new_pcb': new_pcb, 'new_lm_windows': new_windows}
results.append(verdict)
step(f'{label} -> menus={json.dumps(verdict["menus"], ensure_ascii=False)[:200]} '
f'new_pcb={new_pcb} new_windows={new_windows}')
OUTPUT.write_text(json.dumps({'library': str(LIBRARY), 'block': NAME, 'pane': int(pane or 0),
'verify_command_id': VERIFY_COMMAND_ID, 'gui': before_focus,
'baseline_pcb': sorted(baseline_pcb), 'variants': results},
ensure_ascii=False, indent=2), encoding='utf-8')
dismiss()
step('written ' + str(OUTPUT))
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
+55
View File
@@ -0,0 +1,55 @@
import ctypes
import json
import time
from pathlib import Path
import win32con
import win32gui
from pywinauto import Desktop, win32defines
from pywinauto.controls.common_controls import TreeViewWrapper
library = Path(r"F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\build\background-fixture\Mentor_lib_EE7.9\mentor_lib.lmc")
output = Path(r"F:\Sync Tool Skyworth\Work Maps\cbb-refresh-verify-795\build\context-child-result.jsonl")
name = "Audio_D2128_ESD"
target = None
for _ in range(160):
windows = [w for w in Desktop(backend="win32").windows()
if w.is_visible() and w.window_text().startswith("Library Manager:")
and str(library).casefold() in w.window_text().casefold()]
if windows:
target = windows[-1]
break
time.sleep(0.25)
if target is None:
raise RuntimeError("Library Manager child window not found")
tw = [w for w in target.descendants() if "TreeView" in w.class_name()][0]
tree = TreeViewWrapper(tw.handle)
item = tree.get_item(["Central Libraries", library.name, "Reusable Blocks", "Logical-Physical", name], exact=True)
item.ensure_visible()
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
def dump(label):
time.sleep(0.5)
menus = [m for m in Desktop(backend="uia").windows(control_type="Menu") if m.is_visible()]
values = []
for menu in menus:
values.append({"menu": getattr(menu, "handle", None), "items": [
(x.window_text(), x.element_info.automation_id, x.is_enabled())
for x in menu.descendants(control_type="MenuItem")
]})
line = label + " " + json.dumps(values, ensure_ascii=False)
output.open("a", encoding="utf-8").write(line + "\n")
print(line, flush=True)
ctypes.windll.user32.EndMenu()
output.write_text(f"target {target.handle} {target.process_id()} tree {tw.handle} selected {item.is_selected()}\n", encoding="utf-8")
print("target", target.handle, target.process_id(), "tree", tw.handle, "selected", item.is_selected(), flush=True)
ctypes.windll.user32.PostMessageW(tw.handle, win32con.WM_CONTEXTMENU, tw.handle, 0xFFFFFFFF)
dump("context--1")
ctypes.windll.user32.PostMessageW(tw.handle, win32con.WM_CONTEXTMENU, tw.handle, 0)
dump("context-0")
ctypes.windll.user32.PostMessageW(tw.handle, win32con.WM_KEYDOWN, win32con.VK_APPS, 0)
ctypes.windll.user32.PostMessageW(tw.handle, win32con.WM_KEYUP, win32con.VK_APPS, 0)
dump("apps")
+167
View File
@@ -0,0 +1,167 @@
"""Probe which message path opens the real CBB context menu on a private desktop.
Production must not switch the input desktop, so the winning variant has to be a
posted/sent message, not pywinauto's click_input. Tries, in order:
1. posted WM_MOUSEMOVE/WM_RBUTTONDOWN/WM_RBUTTONUP with client coords (current production path)
2. posted WM_CONTEXTMENU with screen coords to the tree
3. sent (synchronous) WM_MOUSEMOVE/WM_RBUTTONDOWN/WM_RBUTTONUP with client coords
4. posted WM_CONTEXTMENU with screen coords to the top-level frame
Results land in build/context-menu-variants.json.
"""
import ctypes, json, subprocess, time
from pathlib import Path
import faulthandler
import win32con, win32gui, win32process, win32service
# A blocked SendMessage or a UIA call into a modal menu loop would otherwise
# hang this probe forever; dump the stack and exit instead.
faulthandler.dump_traceback_later(120, exit=True)
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = ROOT/'build'/'background-fixture'/'Mentor_lib_EE7.9'/'mentor_lib.lmc'
NAME = 'Audio_D2128_ESD'
OUTPUT = ROOT/'build'/'context-menu-variants.json'
DESKTOP = 'CbbContextMenuProbe'
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, str(LIBRARY)]), None, None, False, 0, None, None, startup)
ht.Close()
lm = None
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.window_text().startswith('Library Manager:') and w.process_id() == pid]
if len(windows) == 1:
lm = windows[0]
break
time.sleep(.5)
if lm is None:
raise SystemExit('Library Manager did not open')
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', LIBRARY.name, 'Reusable Blocks', 'Logical-Physical', NAME], exact=True)
item.ensure_visible()
ctypes.windll.user32.SetFocus(tree.handle)
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
print('selected:', item.is_selected(), 'tree:', tree.handle, flush=True)
ui = Desktop(backend='uia').window(handle=lm.handle)
hits = [entry for entry in ui.descendants(control_type='TreeItem') if entry.window_text() == NAME]
if len(hits) != 1:
raise SystemExit(f'CBB 条目定位不唯一: {len(hits)}')
rect = hits[0].rectangle()
sx, sy = rect.mid_point().x, rect.mid_point().y
client = ctypes.wintypes.POINT(sx, sy)
ctypes.windll.user32.ScreenToClient(tree.handle, ctypes.byref(client))
client_xy = (client.x, client.y)
screen_xy = (sx, sy)
print('screen:', screen_xy, 'client:', client_xy, flush=True)
def visible_menus():
return [m for m in Desktop(backend='uia').windows(control_type='Menu') if m.is_visible()]
def dump(menus):
out = []
for menu in menus:
items = []
for entry in menu.descendants(control_type='MenuItem'):
try:
items.append({'name': entry.window_text(),
'automation_id': str(entry.element_info.automation_id or ''),
'enabled': bool(entry.is_enabled())})
except Exception:
items.append({'name': '(stale)', 'automation_id': '', 'enabled': False})
try:
hwnd = int(getattr(menu, 'handle', 0) or 0)
except Exception:
hwnd = 0
out.append({'hwnd': hwnd, 'items': items})
return out
def menu_hwnds():
found = []
def visit(h, _):
if win32gui.GetClassName(h) == '#32768':
tid_ = win32process.GetWindowThreadProcessId(h)[1]
if tid_ == pid:
found.append(h)
return True
win32gui.EnumWindows(visit, None)
return found
def dismiss():
for _ in range(12):
handles = menu_hwnds()
if not handles:
return True
for h in handles:
win32gui.PostMessage(h, win32con.WM_KEYDOWN, win32con.VK_ESCAPE, 0)
win32gui.PostMessage(h, win32con.WM_KEYUP, win32con.VK_ESCAPE, 0)
win32gui.PostMessage(h, win32con.WM_CANCELMODE, 0, 0)
time.sleep(.4)
return not menu_hwnds()
def mouse_messages(send):
lp = ((client_xy[1] & 0xffff) << 16) | (client_xy[0] & 0xffff)
deliver = win32gui.SendMessage if send else win32gui.PostMessage
deliver(tree.handle, win32con.WM_MOUSEMOVE, 0, lp)
deliver(tree.handle, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lp)
deliver(tree.handle, win32con.WM_RBUTTONUP, 0, lp)
lp_screen = ((screen_xy[1] & 0xffff) << 16) | (screen_xy[0] & 0xffff)
frame = lm.handle
variants = [
('posted-mouse-client', lambda: mouse_messages(False)),
('posted-contextmenu-tree', lambda: win32gui.PostMessage(tree.handle, win32con.WM_CONTEXTMENU, tree.handle, lp_screen)),
('sent-mouse-client', lambda: mouse_messages(True)),
('posted-contextmenu-frame', lambda: win32gui.PostMessage(frame, win32con.WM_CONTEXTMENU, frame, lp_screen)),
]
results = []
for label, trigger in variants:
step(f'variant {label}: dismissing leftovers')
if not dismiss():
results.append({'variant': label, 'error': 'previous menu could not be dismissed'})
break
step(f'variant {label}: triggering')
try:
trigger()
except Exception as error:
results.append({'variant': label, 'error': f'trigger failed: {error}'})
continue
time.sleep(.8)
step(f'variant {label}: enumerating menus')
menus = visible_menus()
step(f'variant {label}: dumping {len(menus)} menu(s)')
results.append({'variant': label, 'menus': dump(menus)})
step(f'{label} -> ' + json.dumps(results[-1], ensure_ascii=False)[:300])
OUTPUT.write_text(json.dumps({'library': str(LIBRARY), 'block': NAME,
'screen': screen_xy, 'client': client_xy,
'variants': results}, ensure_ascii=False, indent=2), encoding='utf-8')
dismiss()
OUTPUT.write_text(json.dumps({'library': str(LIBRARY), 'block': NAME,
'screen': screen_xy, 'client': client_xy,
'variants': results}, ensure_ascii=False, indent=2), encoding='utf-8')
print('written', OUTPUT, flush=True)
try:
win32gui.PostMessage(frame, win32con.WM_CLOSE, 0, 0)
except Exception:
pass
time.sleep(2)
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
+162
View File
@@ -0,0 +1,162 @@
"""Probe whether LM's context hit test follows the physical cursor position.
The posted-message variants only ever produce the docking pane menu, so LM is
probably resolving the right-click target from the cursor position rather than
from the message lparam. This probe measures whether SetCursorPos actually
moves the cursor on a private (non-input) desktop and whether the real CBB menu
then appears. No desktop switching, no input injection.
Results land in build/cursor-hit-test.json.
"""
import ctypes, ctypes.wintypes, json, subprocess, time
from pathlib import Path
import faulthandler
import win32con, win32gui, win32process, win32service
faulthandler.dump_traceback_later(150, exit=True)
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = ROOT/'build'/'background-fixture'/'Mentor_lib_EE7.9'/'mentor_lib.lmc'
NAME = 'Audio_D2128_ESD'
OUTPUT = ROOT/'build'/'cursor-hit-test.json'
DESKTOP = 'CbbCursorProbe'
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, str(LIBRARY)]), None, None, False, 0, None, None, startup)
ht.Close()
lm = None
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.window_text().startswith('Library Manager:') and w.process_id() == pid]
if len(windows) == 1:
lm = windows[0]
break
time.sleep(.5)
if lm is None:
raise SystemExit('Library Manager did not open')
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', LIBRARY.name, 'Reusable Blocks', 'Logical-Physical', NAME], exact=True)
item.ensure_visible()
ctypes.windll.user32.SetFocus(tree.handle)
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
step(f'selected={item.is_selected()} tree={tree.handle} frame={lm.handle}')
ui = Desktop(backend='uia').window(handle=lm.handle)
hits = [entry for entry in ui.descendants(control_type='TreeItem') if entry.window_text() == NAME]
rect = hits[0].rectangle()
screen_xy = (rect.mid_point().x, rect.mid_point().y)
client = ctypes.wintypes.POINT(*screen_xy)
ctypes.windll.user32.ScreenToClient(tree.handle, ctypes.byref(client))
step(f'screen={screen_xy} tree_client=({client.x},{client.y})')
before = ctypes.wintypes.POINT()
ctypes.windll.user32.GetCursorPos(ctypes.byref(before))
moved = bool(ctypes.windll.user32.SetCursorPos(screen_xy[0], screen_xy[1]))
after = ctypes.wintypes.POINT()
ctypes.windll.user32.GetCursorPos(ctypes.byref(after))
step(f'cursor before=({before.x},{before.y}) SetCursorPos={moved} after=({after.x},{after.y})')
cursor_effective = (after.x, after.y) == screen_xy
def visible_menus():
return [m for m in Desktop(backend='uia').windows(control_type='Menu') if m.is_visible()]
def dump(menus):
out = []
for menu in menus:
items = []
for entry in menu.descendants(control_type='MenuItem'):
try:
items.append({'name': entry.window_text(),
'automation_id': str(entry.element_info.automation_id or ''),
'enabled': bool(entry.is_enabled())})
except Exception:
items.append({'name': '(stale)', 'automation_id': '', 'enabled': False})
out.append({'hwnd': int(getattr(menu, 'handle', 0) or 0), 'items': items})
return out
def menu_hwnds():
found = []
def visit(h, _):
if win32gui.GetClassName(h) == '#32768' and win32process.GetWindowThreadProcessId(h)[1] == pid:
found.append(h)
return True
win32gui.EnumWindows(visit, None)
return found
def dismiss():
for _ in range(10):
handles = menu_hwnds()
if not handles:
return True
for h in handles:
win32gui.PostMessage(h, win32con.WM_KEYDOWN, win32con.VK_ESCAPE, 0)
win32gui.PostMessage(h, win32con.WM_KEYUP, win32con.VK_ESCAPE, 0)
time.sleep(.4)
return not menu_hwnds()
def post_mouse(hwnd, xy):
lp = ((xy[1] & 0xffff) << 16) | (xy[0] & 0xffff)
win32gui.PostMessage(hwnd, win32con.WM_MOUSEMOVE, 0, lp)
win32gui.PostMessage(hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, lp)
win32gui.PostMessage(hwnd, win32con.WM_RBUTTONUP, 0, lp)
frame = lm.handle
pane = None
for w in lm.descendants():
if w.class_name() == 'AfxControlBar90':
pane = w.handle
break
step(f'pane={pane}')
variants = [
('cursor-moved-then-post-tree', lambda: post_mouse(tree.handle, (client.x, client.y))),
('post-pane-client', lambda: post_mouse(pane, (client.x, client.y)) if pane else None),
('post-frame-client', lambda: post_mouse(frame, (client.x, client.y))),
('contextmenu-frame-screen', lambda: win32gui.PostMessage(frame, win32con.WM_CONTEXTMENU, frame,
((screen_xy[1] & 0xffff) << 16) | (screen_xy[0] & 0xffff))),
]
results = []
for label, trigger in variants:
if not dismiss():
results.append({'variant': label, 'error': 'previous menu could not be dismissed'})
break
step(f'variant {label}: trigger')
try:
trigger()
except Exception as error:
results.append({'variant': label, 'error': f'trigger failed: {error}'})
continue
time.sleep(.8)
menus = visible_menus()
results.append({'variant': label, 'menus': dump(menus)})
step(f'{label} -> ' + json.dumps(results[-1], ensure_ascii=False)[:300])
OUTPUT.write_text(json.dumps({'library': str(LIBRARY), 'block': NAME,
'cursor_before': [before.x, before.y],
'cursor_set': moved, 'cursor_after': [after.x, after.y],
'cursor_effective': cursor_effective,
'screen': list(screen_xy), 'tree_client': [client.x, client.y],
'variants': results}, ensure_ascii=False, indent=2), encoding='utf-8')
dismiss()
step('written ' + str(OUTPUT))
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
+95
View File
@@ -0,0 +1,95 @@
"""Capture the unidentified Workbook/PCB startup dialog's pixels on a private desktop.
The dialog titled 'Expedition PCB' with Yes/No buttons has no enumerable static
text, so its message must be read from an image. Runs against the fixture copy
first; nothing is saved and the PCB is killed at the end.
Output: build/dialog-capture/dialog-*.bmp (converted to PNG by the caller).
"""
import subprocess, time
from pathlib import Path
import faulthandler
import win32con, win32gui, win32process, win32service
faulthandler.dump_traceback_later(180, exit=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc')
PCB = Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\ReusableBlocksLP\Audio_D2128_ESD\Work\PCB\Audio_D2128_ESD.pcb')
EXE = r'D:\Mentor\7.9.5EE\SDD_HOME\wg\win32\bin\ExpeditionPCB.exe'
OUT = ROOT/'build'/'dialog-capture'
OUT.mkdir(parents=True, exist_ok=True)
DESKTOP = 'CbbDialogCapture' + __import__('uuid').uuid4().hex[:8]
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
handle, thread, pid, _ = win32process.CreateProcess(
EXE, subprocess.list2cmdline([EXE, str(PCB), '-ReusableCircuit']), None, None, False, 0, None, None, startup)
thread.Close()
step(f'pcb pid={pid} (fixture library)')
captured, handled = set(), set()
deadline = time.monotonic() + 120
try:
while time.monotonic() < deadline:
windows = []
win32gui.EnumWindows(lambda h, _: windows.append(h), None)
alive = False
for hwnd in windows:
try:
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
continue
if win32gui.GetClassName(hwnd) != '#32770':
continue
alive = True
children = []
win32gui.EnumChildWindows(hwnd, lambda c, _: children.append(c), None)
texts = [win32gui.GetWindowText(c) for c in children]
title = win32gui.GetWindowText(hwnd)
ids = [win32gui.GetDlgCtrlID(c) for c in children]
if hwnd not in captured:
import win32ui
captured.add(hwnd)
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
width, height = right-left, bottom-top
window_dc = win32gui.GetWindowDC(hwnd)
source = win32ui.CreateDCFromHandle(window_dc)
memory = source.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap(); bitmap.CreateCompatibleBitmap(source, width, height)
memory.SelectObject(bitmap)
win32gui.PrintWindow(hwnd, memory.GetSafeHdc(), 0)
path = OUT/f'dialog-{len(captured):02d}.bmp'
bitmap.SaveBitmapFile(memory, str(path))
step(f'captured {path.name}: title={title!r} ids={ids} texts={[t for t in texts if t.strip()][:3]}')
identity = (hwnd, tuple(texts))
if identity in handled:
continue
if title == 'Tip of the Day' or 'Select the desired product license' in texts:
target = [c for c in children if win32gui.GetDlgCtrlID(c) == 1]
elif title == 'Expedition PCB' and 7 in ids:
target = [c for c in children if win32gui.GetDlgCtrlID(c) == 7] # 否 (probe only)
else:
target = []
if target and win32gui.IsWindowEnabled(target[0]):
win32gui.PostMessage(target[0], win32con.BM_CLICK, 0, 0)
handled.add(identity)
step(f'clicked {win32gui.GetDlgCtrlID(target[0])} on {title!r}')
except Exception:
continue
if not alive and time.monotonic() > deadline - 140:
step('no dialogs for a while')
time.sleep(1)
if time.monotonic() > deadline - 20:
break
time.sleep(.3)
finally:
for image in sorted(OUT.glob('dialog-*.bmp')):
step(f'kept {image.name}')
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
step('killed pcb')
+151
View File
@@ -0,0 +1,151 @@
"""Probe the only route proven to open LM's real CBB menu: real input while the
private desktop is the input desktop.
Message-based triggering cannot work on this LM build because the navigator
resolves the right-click target from the physical cursor, and SetCursorPos
fails on a non-input desktop. This probe measures the practical cost:
switch to the private desktop -> real right-click on the CBB -> UIA invoke of
the Verify item -> switch straight back -> confirm ExpeditionPCB launched.
Results land in build/input-switch.json. The switch window is kept as short as
possible; the desktop is restored in a finally block.
"""
import ctypes, ctypes.wintypes, json, subprocess, time
from pathlib import Path
import faulthandler
import win32api, win32con, win32gui, win32process, win32service
faulthandler.dump_traceback_later(180, exit=True)
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = ROOT/'build'/'background-fixture'/'Mentor_lib_EE7.9'/'mentor_lib.lmc'
NAME = 'Audio_D2128_ESD'
OUTPUT = ROOT/'build'/'input-switch.json'
DESKTOP = 'CbbInputSwitchProbe'
result = {'library': str(LIBRARY), 'block': NAME, 'steps': []}
def record(**entry):
entry['time'] = time.strftime('%H:%M:%S')
result['steps'].append(entry)
OUTPUT.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, str(LIBRARY)]), None, None, False, 0, None, None, startup)
ht.Close()
lm = None
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.window_text().startswith('Library Manager:') and w.process_id() == pid]
if len(windows) == 1:
lm = windows[0]
break
time.sleep(.5)
if lm is None:
raise SystemExit('Library Manager did not open')
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', LIBRARY.name, 'Reusable Blocks', 'Logical-Physical', NAME], exact=True)
item.ensure_visible()
target_tid = win32process.GetWindowThreadProcessId(tree.handle)[0]
our_tid = win32api.GetCurrentThreadId()
ctypes.windll.user32.AttachThreadInput(our_tid, target_tid, True)
try:
ctypes.windll.user32.SetFocus(tree.handle)
finally:
ctypes.windll.user32.AttachThreadInput(our_tid, target_tid, False)
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
step(f'selected={item.is_selected()} tree={tree.handle}')
record(event='selected', selected=bool(item.is_selected()))
ui = Desktop(backend='uia').window(handle=lm.handle)
hits = [entry for entry in ui.descendants(control_type='TreeItem') if entry.window_text() == NAME]
rect = hits[0].rectangle()
screen_xy = (rect.mid_point().x, rect.mid_point().y)
step(f'item screen point={screen_xy}')
record(event='item_point', screen=list(screen_xy))
def pcb_commands():
service = __import__('win32com.client').client.GetObject('winmgmts:')
return [(int(p.ProcessId), str(p.CommandLine or ''))
for p in service.ExecQuery("SELECT ProcessId, CommandLine FROM Win32_Process WHERE Name='ExpeditionPCB.exe'")]
baseline = {pid_ for pid_, _ in pcb_commands()}
record(event='baseline_pcb', pids=sorted(baseline))
input_desktop = win32service.OpenInputDesktop(0, False, win32con.GENERIC_ALL)
step(f'input desktop handle={input_desktop}')
switch_desktop = ctypes.windll.user32.SwitchDesktop
switch_desktop.restype = ctypes.wintypes.BOOL
switch_desktop.argtypes = [ctypes.wintypes.HANDLE]
switched_in = False
try:
switched_in = bool(switch_desktop(int(desktop)))
step(f'SwitchDesktop(private) = {switched_in}')
record(event='switch_in', ok=switched_in)
if switched_in:
moved = bool(ctypes.windll.user32.SetCursorPos(*screen_xy))
pos = ctypes.wintypes.POINT()
ctypes.windll.user32.GetCursorPos(ctypes.byref(pos))
step(f'SetCursorPos={moved} cursor=({pos.x},{pos.y})')
record(event='cursor', moved=moved, pos=[pos.x, pos.y])
t0 = time.monotonic()
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0)
time.sleep(.5)
menus = [m for m in Desktop(backend='uia').windows(control_type='Menu') if m.is_visible()]
items = [[{'name': e.window_text(), 'automation_id': str(e.element_info.automation_id or ''),
'enabled': bool(e.is_enabled())} for e in menu.descendants(control_type='MenuItem')]
for menu in menus]
step(f'menus after real right-click: {json.dumps(items, ensure_ascii=False)[:300]}')
record(event='menu_after_rclick', menus=items)
verify = [e for menu in menus for e in menu.descendants(control_type='MenuItem')
if str(e.element_info.automation_id or '') == '194']
if len(verify) == 1 and verify[0].is_enabled():
verify[0].invoke()
record(event='invoked', automation_id='194', elapsed_ms=int((time.monotonic()-t0)*1000))
step('invoked Verify via UIA')
else:
record(event='invoke_skipped', found=len(verify))
time.sleep(.4)
finally:
back = False
try:
back = bool(switch_desktop(int(input_desktop)))
except Exception as error:
record(event='switch_back_error', error=str(error))
step(f'SwitchDesktop(back) = {back}')
record(event='switch_back', ok=back)
for _ in range(40):
new = [(pid_, cmd) for pid_, cmd in pcb_commands() if pid_ not in baseline]
if new:
step(f'PCB launched: {new}')
record(event='pcb_launched', pcb=[[pid_, cmd] for pid_, cmd in new])
break
time.sleep(.5)
else:
record(event='pcb_launched', pcb=[])
step('cleanup')
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
for pid_, _ in pcb_commands():
subprocess.run(['taskkill', '/PID', str(pid_), '/T', '/F'], capture_output=True)
step('written ' + str(OUTPUT))
+149
View File
@@ -0,0 +1,149 @@
"""Probe keyboard-only activation of LM's CBB context menu on a private desktop.
Rationale: a keyboard-invoked menu carries no point, so it may sidestep the
cursor-based hit test that defeats the posted mouse messages. Nothing here
moves the cursor or switches desktops.
Variants (each posted, never sent synchronously — SendMessage deadlocks on this
build): VK_APPS, Shift+F10, and WM_CONTEXTMENU(-1) against the tree, its ATL
host, the navigator pane and the frame.
Results land in build/keyboard-menu.json.
"""
import ctypes, ctypes.wintypes, json, subprocess, time
from pathlib import Path
import faulthandler
import win32api, win32con, win32gui, win32process, win32service
faulthandler.dump_traceback_later(240, exit=True)
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = ROOT/'build'/'background-fixture'/'Mentor_lib_EE7.9'/'mentor_lib.lmc'
NAME = 'Audio_D2128_ESD'
OUTPUT = ROOT/'build'/'keyboard-menu.json'
DESKTOP = 'CbbKeyboardProbe' + __import__('uuid').uuid4().hex[:8]
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
exe = str(Path(r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'))
handle, thread, pid, _ = win32process.CreateProcess(
exe, subprocess.list2cmdline([exe, str(LIBRARY)]), None, None, False, 0, None, None, startup)
thread.Close()
lm = None
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.window_text().startswith('Library Manager:') and w.process_id() == pid]
if len(windows) == 1:
lm = windows[0]
break
time.sleep(.5)
if lm is None:
raise SystemExit('Library Manager did not open')
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', LIBRARY.name, 'Reusable Blocks', 'Logical-Physical', NAME], exact=True)
item.ensure_visible()
ctypes.windll.user32.AttachThreadInput(win32api.GetCurrentThreadId(), win32process.GetWindowThreadProcessId(tree.handle)[0], True)
try:
ctypes.windll.user32.SetFocus(tree.handle)
finally:
ctypes.windll.user32.AttachThreadInput(win32api.GetCurrentThreadId(), win32process.GetWindowThreadProcessId(tree.handle)[0], False)
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
step(f'selected={item.is_selected()} tree={tree.handle} frame={lm.handle}')
atl = next((w.handle for w in lm.descendants() if w.class_name().startswith('AtlAxWin')), None)
panes = [w.handle for w in lm.descendants() if w.class_name() == 'AfxControlBar90']
step(f'atl={atl} panes={[hex(p) for p in panes]}')
CONTEXT_KEY = 0x20000000 # lParam bit 29: key came from the context-menu key / Shift+F10
def apps_key(hwnd):
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_APPS, 0)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_APPS, 0)
def shift_f10(hwnd):
win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_SHIFT, 0)
win32gui.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, win32con.VK_F10, CONTEXT_KEY)
win32gui.PostMessage(hwnd, win32con.WM_SYSKEYUP, win32con.VK_F10, CONTEXT_KEY)
win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_SHIFT, 0)
def contextmenu_key(hwnd):
win32gui.PostMessage(hwnd, win32con.WM_CONTEXTMENU, hwnd, -1 & 0xffffffff)
def visible_menus():
return [m for m in Desktop(backend='uia').windows(control_type='Menu') if m.is_visible()]
def dump(menus):
return [[{'name': e.window_text(), 'automation_id': str(e.element_info.automation_id or ''),
'enabled': bool(e.is_enabled())} for e in menu.descendants(control_type='MenuItem')]
for menu in menus]
def menu_hwnds():
found = []
def visit(h, _):
if win32gui.GetClassName(h) == '#32768' and win32process.GetWindowThreadProcessId(h)[1] == pid:
found.append(h)
return True
win32gui.EnumWindows(visit, None)
return found
def dismiss():
for _ in range(10):
handles = menu_hwnds()
if not handles:
return True
for h in handles:
win32gui.PostMessage(h, win32con.WM_KEYDOWN, win32con.VK_ESCAPE, 0)
win32gui.PostMessage(h, win32con.WM_KEYUP, win32con.VK_ESCAPE, 0)
time.sleep(.4)
return not menu_hwnds()
targets = [('tree', tree.handle)]
if atl:
targets.append(('atl-host', atl))
for index, pane in enumerate(panes):
targets.append((f'pane{index}', pane))
targets.append(('frame', lm.handle))
results = []
for label, hwnd in targets:
for gesture, trigger in (('VK_APPS', apps_key), ('Shift+F10', shift_f10), ('WM_CONTEXTMENU(-1)', contextmenu_key)):
if not dismiss():
results.append({'target': label, 'gesture': gesture, 'error': 'menu stuck open'})
break
try:
trigger(hwnd)
except Exception as error:
results.append({'target': label, 'gesture': gesture, 'error': str(error)})
continue
time.sleep(1.0)
menus = visible_menus()
entry = {'target': label, 'gesture': gesture, 'menus': dump(menus)}
results.append(entry)
verify = [i for menu in entry['menus'] for i in menu if i['automation_id'] == '194']
step(f'{label:10s} {gesture:18s} -> {json.dumps(entry["menus"], ensure_ascii=False)[:150]}'
+ (' *** VERIFY FOUND ***' if verify else ''))
OUTPUT.write_text(json.dumps({'library': str(LIBRARY), 'block': NAME, 'results': results},
ensure_ascii=False, indent=2), encoding='utf-8')
dismiss()
step('written ' + str(OUTPUT))
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
+44
View File
@@ -0,0 +1,44 @@
"""Read a fresh LM tree's verification icon on a private desktop; no input events."""
import json
import subprocess
import time
import sys
from pathlib import Path
import win32con
import win32gui
import win32process
import win32service
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto.remote_memory_block import RemoteMemoryBlock
from pywinauto import win32structures, win32defines
library = str(Path(sys.argv[1]).resolve())
name = sys.argv[2]
desktop = win32service.CreateDesktop('CbbLibraryReadProbe', 0, win32con.GENERIC_ALL, None)
startup = win32process.STARTUPINFO();startup.lpDesktop = r'winsta0\CbbLibraryReadProbe'
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, library]), None, None, False, 0, None, None, startup)
ht.Close()
last_error = ''
for attempt in range(120):
try:
windows = [int(h) for h in desktop.EnumDesktopWindows()]
for hwnd in windows:
if not win32gui.GetWindowText(hwnd).startswith('Library Manager:'):continue
children = []
win32gui.EnumChildWindows(hwnd, lambda c, _: children.append(c), None)
trees = [c for c in children if 'TreeView' in win32gui.GetClassName(c)]
if not trees:continue
tree = TreeViewWrapper(trees[0])
item = tree.get_item(['Central Libraries', Path(library).name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
mem = RemoteMemoryBlock(tree)
value = win32structures.TVITEMW32();value.mask = 2|32;value.hItem=item.elem
mem.Write(value);tree.send_message(win32defines.TVM_GETITEMW,0,mem);mem.Read(value)
print(json.dumps({'library':library, 'name':item.text(), 'image':value.iImage, 'selected_image':value.iSelectedImage, 'pid':pid}),flush=True)
del mem
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
sys.exit(0)
except Exception as error:
last_error = str(error)
time.sleep(.5)
raise RuntimeError(last_error or 'LM tree was not ready')
+13
View File
@@ -0,0 +1,13 @@
from pathlib import Path
import win32com.client
import json
app = win32com.client.GetActiveObject('MGCPCB.Application')
pi = app.ActiveDocument.ProjectIntegration
info = pi._oleobj_.GetTypeInfo()
attr = info.GetTypeAttr()
members=[]
for n in range(attr.cFuncs):
desc=info.GetFuncDesc(n)
names=info.GetNames(desc.memid)
members.append({'names':names,'description':str(desc),'docs':info.GetDocumentation(desc.memid)})
Path(__file__).with_suffix('.json').write_text(json.dumps(members,ensure_ascii=False,indent=2),encoding='utf-8')
+40
View File
@@ -0,0 +1,40 @@
import ctypes, json, subprocess, time
from pathlib import Path
import win32con, win32gui, win32process, win32service
library = str(Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib_EE7.9\mentor_lib.lmc'))
library = str(Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc'))
name = 'Audio_D2128_ESD'
desktop = win32service.CreateDesktop('CbbPrivateLMProbe', 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = r'winsta0\CbbPrivateLMProbe'
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, library]), None, None, False, 0, None, None, startup)
ht.Close()
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows() if w.is_visible() and w.window_text().startswith('Library Manager:')]
if len(windows) == 1: break
time.sleep(.5)
lm = windows[0]
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', Path(library).name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
item.ensure_visible()
ctypes.windll.user32.SetFocus(tree.handle)
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
ui = Desktop(backend='uia').window(handle=lm.handle)
uitem = [x for x in ui.descendants(control_type='TreeItem') if x.window_text() == name][0]
r = uitem.rectangle(); x = (r.left+r.right)//2; y = (r.top+r.bottom)//2
print('selected', item.is_selected(), 'rect', r, 'tree', tree.handle, flush=True)
print('keyboard context', win32gui.PostMessage(tree.handle, win32con.WM_KEYDOWN, win32con.VK_APPS, 0), flush=True)
win32gui.PostMessage(tree.handle, win32con.WM_KEYUP, win32con.VK_APPS, 0)
time.sleep(.8)
menus = [m for m in Desktop(backend='uia').windows(control_type='Menu') if m.is_visible()]
print('menus',len(menus),flush=True)
for menu in menus:
print([(x.window_text(), x.element_info.automation_id, x.is_enabled()) for x in menu.descendants(control_type='MenuItem')],flush=True)
for x in menu.descendants(control_type='MenuItem'):
if x.window_text().replace('&','') == 'Verify': x.invoke(); print('INVOKED',flush=True)
time.sleep(4)
+67
View File
@@ -0,0 +1,67 @@
"""Invoke the selected, named LM Verify menu and record native window changes."""
import ctypes
ctypes.windll.user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(-4))
import json
import time
from pathlib import Path
import win32gui
import win32process
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
def snapshot():
windows = []
win32gui.EnumWindows(lambda h, _: windows.append(h), None)
result = []
for h in windows:
title = win32gui.GetWindowText(h)
if not win32gui.IsWindowVisible(h):
continue
if win32gui.GetClassName(h) != '#32770' and not any(x in title for x in ('Expedition', 'Library Manager')):
continue
children = []
win32gui.EnumChildWindows(h, lambda c, _: children.append(c), None)
result.append({'hwnd': h, 'pid': win32process.GetWindowThreadProcessId(h)[1], 'title': title,
'controls': [(c, win32gui.GetDlgCtrlID(c), win32gui.GetClassName(c), win32gui.GetWindowText(c)) for c in children]})
return result
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('name')
parser.add_argument('--seconds', type=int, default=90)
args = parser.parse_args()
output = Path(__file__).resolve().parents[1] / 'build' / 'verify-launch-probe.jsonl'
lm = [w for w in Desktop(backend='win32').windows() if w.is_visible() and w.window_text().startswith('Library Manager:')]
assert len(lm) == 1, 'Need exactly one visible Library Manager'
import ctypes
ctypes.windll.user32.EndMenu()
lm[0].set_focus()
trees = [w for w in lm[0].descendants() if 'TreeView' in w.class_name()]
assert len(trees) == 1
tree = TreeViewWrapper(trees[0].handle)
block = tree.get_item(['Central Libraries', 'mentor_lib.lmc', 'Reusable Blocks', 'Logical-Physical', args.name], exact=True)
block.ensure_visible()
block.select()
block.click_input(button='right')
time.sleep(.3)
assert block.is_selected(), 'Right click changed selected CBB; aborting'
items = [i for m in Desktop(backend='uia').windows(control_type='Menu') for i in m.descendants(control_type='MenuItem') if i.window_text() == 'Verify']
assert len(items) == 1 and items[0].is_enabled()
items[0].invoke()
print('Verify invoked for', args.name, flush=True)
last = None
with output.open('a', encoding='utf-8') as stream:
start = time.monotonic()
while time.monotonic() - start < args.seconds:
state = snapshot()
if state != last:
record = {'time': time.strftime('%Y-%m-%d %H:%M:%S'), 'block': args.name, 'windows': state}
line = json.dumps(record, ensure_ascii=False)
stream.write(line + '\n'); stream.flush()
print(line, flush=True)
last = state
time.sleep(.3)
+127
View File
@@ -0,0 +1,127 @@
"""Probe whether the Verify command can be executed by WM_COMMAND without a menu.
AutomationId 194 on the context menu item is likely the MFC command id. If any
window in the navigator's command chain accepts WM_COMMAND 194, LM starts the
Verify flow (observable as an ExpeditionPCB.exe launch) with no mouse involved.
Only command 194 is ever sent; no other command id is tested.
Results land in build/wmcommand-broadcast.json.
"""
import ctypes, ctypes.wintypes, json, subprocess, time
from pathlib import Path
import faulthandler
import win32api, win32con, win32gui, win32process, win32service
faulthandler.dump_traceback_later(180, exit=True)
def step(message):
print(f'[{time.strftime("%H:%M:%S")}] {message}', flush=True)
ROOT = Path(__file__).resolve().parents[1]
LIBRARY = ROOT/'build'/'background-fixture'/'Mentor_lib_EE7.9'/'mentor_lib.lmc'
NAME = 'Audio_D2128_ESD'
OUTPUT = ROOT/'build'/'wmcommand-broadcast.json'
DESKTOP = 'CbbCommandBroadcast'
VERIFY_COMMAND_ID = 194
desktop = win32service.CreateDesktop(DESKTOP, 0, win32con.GENERIC_ALL, None)
desktop.SetThreadDesktop()
from pywinauto import Desktop
from pywinauto.controls.common_controls import TreeViewWrapper
from pywinauto import win32defines
startup = win32process.STARTUPINFO(); startup.lpDesktop = 'winsta0\\' + DESKTOP
exe = r'D:\Mentor\7.9.5EE\SDD_HOME\lm\win32\bin\LibraryManager.exe'
hp, ht, pid, tid = win32process.CreateProcess(exe, subprocess.list2cmdline([exe, str(LIBRARY)]), None, None, False, 0, None, None, startup)
ht.Close()
lm = None
for _ in range(120):
windows = [w for w in Desktop(backend='win32').windows()
if w.is_visible() and w.window_text().startswith('Library Manager:') and w.process_id() == pid]
if len(windows) == 1:
lm = windows[0]
break
time.sleep(.5)
if lm is None:
raise SystemExit('Library Manager did not open')
tree = TreeViewWrapper([w for w in lm.descendants() if 'TreeView' in w.class_name()][0].handle)
item = tree.get_item(['Central Libraries', LIBRARY.name, 'Reusable Blocks', 'Logical-Physical', NAME], exact=True)
item.ensure_visible()
tree.send_message(win32defines.TVM_SELECTITEM, win32defines.TVGN_CARET, item.elem)
step(f'selected={item.is_selected()}')
def focus_window(hwnd):
target_tid = win32process.GetWindowThreadProcessId(hwnd)[0]
our_tid = win32api.GetCurrentThreadId()
attached = bool(ctypes.windll.user32.AttachThreadInput(our_tid, target_tid, True))
try:
return bool(ctypes.windll.user32.SetFocus(hwnd)), attached
finally:
ctypes.windll.user32.AttachThreadInput(our_tid, target_tid, False)
def all_windows(root_pid):
"""Every top-level and child window of the LM process, with its class name."""
found = []
def visit(h, _):
if win32process.GetWindowThreadProcessId(h)[1] == root_pid:
found.append((h, win32gui.GetClassName(h), win32gui.GetWindowText(h)))
def child(c, _2):
if win32process.GetWindowThreadProcessId(c)[1] == root_pid:
found.append((c, win32gui.GetClassName(c), win32gui.GetWindowText(c)))
return True
win32gui.EnumChildWindows(h, child, None)
return True
win32gui.EnumWindows(visit, None)
return found
def pcb_pids():
service = __import__('win32com.client').client.GetObject('winmgmts:')
return [int(p.ProcessId) for p in service.ExecQuery("SELECT ProcessId FROM Win32_Process WHERE Name='ExpeditionPCB.exe'")]
baseline = set(pcb_pids())
windows = all_windows(pid)
step(f'LM windows: {[(hex(h), c) for h, c, _ in windows]}')
result = {'library': str(LIBRARY), 'block': NAME, 'verify_command_id': VERIFY_COMMAND_ID,
'windows': [[int(h), c] for h, c, _ in windows], 'attempts': []}
def check(label, hwnd):
time.sleep(1.0)
new = sorted(set(pcb_pids()) - baseline)
entry = {'target': int(hwnd), 'class': win32gui.GetClassName(hwnd), 'new_pcb': new}
result['attempts'].append(entry)
OUTPUT.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
step(f'{label} hwnd={hex(hwnd)} class={entry["class"]} -> new_pcb={new}')
return bool(new)
# Focus the navigator tree (input-independent) then broadcast only command 194.
focus_ok, attached = focus_window(tree.handle)
step(f'focus tree ok={focus_ok} attached={attached}')
try:
frame_hwnd = lm.handle
for hwnd, cls, title in windows:
win32gui.PostMessage(hwnd, win32con.WM_COMMAND, VERIFY_COMMAND_ID, 0)
if check('broadcast-all-windows', frame_hwnd):
raise SystemExit(0)
# Retry with the pane/view focused explicitly.
for hwnd, cls, title in windows:
if cls.startswith('Afx') or cls.startswith('ATL'):
focus_window(hwnd)
win32gui.PostMessage(hwnd, win32con.WM_COMMAND, VERIFY_COMMAND_ID, 0)
if check(f'command-after-focus-{cls}', hwnd):
raise SystemExit(0)
finally:
step('written ' + str(OUTPUT))
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
for p in pcb_pids():
subprocess.run(['taskkill', '/PID', str(p), '/T', '/F'], capture_output=True)
+29
View File
@@ -0,0 +1,29 @@
Option Explicit
Dim app, doc, pi, licensing, token, expected
expected = WScript.Arguments(0)
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(expected) Then
WScript.Echo "IDENTITY_MISMATCH"
WScript.Quit 2
End If
If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then
WScript.Echo "NOT_SYNCHRONIZED"
WScript.Quit 3
End If
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
doc.Validate token
WScript.Echo "LICENSE_OK"
If Not doc.IsSaved() Then
If Not doc.Save() Then WScript.Quit 4
End If
WScript.Echo "SAVE_OK"
If Not doc.IsSaved() Then WScript.Quit 5
WScript.Echo "IS_SAVED"
If WScript.Arguments.Count > 1 Then
WScript.Echo "CLOSE_START"
If Not doc.Close(True) Then WScript.Quit 6
WScript.Echo "CLOSE_OK"
End If
+18
View File
@@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.20)
project(CbbStatusBridge32 LANGUAGES CXX)
set(CMAKE_MFC_FLAG 2)
add_executable(CbbStatusBridge32 CbbStatusBridge32.cpp)
target_compile_features(CbbStatusBridge32 PRIVATE cxx_std_17)
set_target_properties(CbbStatusBridge32 PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
if (MSVC)
target_compile_definitions(CbbStatusBridge32 PRIVATE _AFXDLL)
target_compile_options(CbbStatusBridge32 PRIVATE /EHsc /MD /utf-8)
endif()
add_executable(VerifyProbe32 VerifyProbe32.cpp)
target_compile_features(VerifyProbe32 PRIVATE cxx_std_17)
set_target_properties(VerifyProbe32 PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
if (MSVC)
target_compile_options(VerifyProbe32 PRIVATE /EHsc /MD /utf-8)
endif()
+243
View File
@@ -0,0 +1,243 @@
// CbbStatusBridge32 - read-only Mentor EE 7.9 Verify status probe.
//
// Build this file as a 32-bit /MD MFC application with the same toolchain
// family as Mentor EE 7.9 (mfc90). It is intentionally not built by the
// Python package on machines that only have a 64-bit compiler.
#include <windows.h>
#include <afx.h>
#include <afxstr.h>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
using MentorString = ATL::CStringT<char, StrTraitMFC_DLL<char>>;
// The decorated export encodes the first CStringT by value; the library path
// is the only const reference parameter in the signature.
using IsVerifiedReuseBlock = bool(__cdecl*)(MentorString, int, const MentorString&);
static std::string jsonEscape(const std::string& value) {
std::ostringstream out;
for (const char ch : value) {
switch (ch) {
case '\\': out << "\\\\"; break;
case '"': out << "\\\""; break;
case '\n': out << "\\n"; break;
case '\r': out << "\\r"; break;
default: out << ch; break;
}
}
return out.str();
}
static std::string field(const std::string& json, const char* key) {
const std::string needle = std::string("\"") + key + "\"";
const auto keyPos = json.find(needle);
if (keyPos == std::string::npos) return {};
const auto colon = json.find(':', keyPos + needle.size());
if (colon == std::string::npos) return {};
const auto first = json.find('"', colon + 1);
if (first == std::string::npos) return {};
std::string result;
for (size_t index = first + 1; index < json.size(); ++index) {
const char ch = json[index];
if (ch == '"') return result;
if (ch != '\\') {
result.push_back(ch);
continue;
}
if (++index >= json.size()) return {};
switch (json[index]) {
case '"': result.push_back('"'); break;
case '\\': result.push_back('\\'); break;
case '/': result.push_back('/'); break;
case 'b': result.push_back('\b'); break;
case 'f': result.push_back('\f'); break;
case 'n': result.push_back('\n'); break;
case 'r': result.push_back('\r'); break;
case 't': result.push_back('\t'); break;
default: return {};
}
}
return {};
}
static int blockType(const std::string& value) {
// Mentor's eReuseBlockType uses 0 for the logical-physical (RULP/LP)
// reusable-block partition. Keep numeric input available for probing.
if (value == "RULP" || value == "LP" || value.empty()) return 0;
if (value == "RUL") return 1;
try { return std::stoi(value); } catch (...) { return 0; }
}
static std::wstring widen(const std::string& value) {
if (value.empty()) return {};
const int size = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), nullptr, 0);
if (size <= 0) return {};
std::wstring result(static_cast<size_t>(size), L'\0');
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), result.data(), size);
return result;
}
static std::string dllPath() {
const char* configured = std::getenv("LMCDLL70_PATH");
if (configured && *configured) return configured;
const char* sddHome = std::getenv("SDD_HOME");
if (sddHome && *sddHome) return std::string(sddHome) + "\\common\\win32\\lib\\LMCDLL70.dll";
return "LMCDLL70.dll";
}
static void printError(const std::string& message) {
std::cout << "{\"ok\":false,\"error\":\"" << jsonEscape(message) << "\"}" << std::endl;
}
static void trace(const char* message) {
const char* enabled = std::getenv("CBB_STATUS_BRIDGE_TRACE");
if (enabled && std::string(enabled) == "1") {
std::cerr << "[status-bridge] " << message << std::endl;
}
}
static bool requestIsValid(const std::string& request, std::string& lmc,
std::string& name, std::string& type,
std::string& requestId) {
const std::string op = field(request, "op");
lmc = field(request, "lmc_file");
name = field(request, "block_name");
type = field(request, "block_type");
requestId = field(request, "request_id");
return op == "is_verified" && !requestId.empty() && !lmc.empty() && !name.empty();
}
static void handleRequest(const std::string& request, IsVerifiedReuseBlock fn,
bool serverMode) {
std::string lmc;
std::string name;
std::string type;
std::string requestId;
if (!requestIsValid(request, lmc, name, type, requestId)) {
printError("请求必须包含 op=is_verified、request_id、lmc_file 和 block_name");
return;
}
try {
bool verified = false;
// Keep MFC CString instances alive through the private call. In
// server mode the DLL remains loaded until process exit.
{
const MentorString block(name.c_str());
const MentorString library(lmc.c_str());
trace("calling-status-function");
verified = fn(block, blockType(type), library);
trace("status-function-returned");
}
trace("cstring-scope-ended");
std::cout << "{\"ok\":true,\"request_id\":\""
<< jsonEscape(requestId) << "\",\"block_name\":\""
<< jsonEscape(name) << "\",\"lmc_file\":\""
<< jsonEscape(lmc) << "\",\"status\":\""
<< (verified ? "READY" : "PENDING")
<< "\",\"source\":\"IsVerifiedReuseBlock\",\"raw_status\":"
<< (verified ? "1" : "0") << "}" << std::endl;
} catch (...) {
// Do not unload LMCDLL70 after entering Mentor's private MFC code.
// The server can continue with the next isolated request; the process
// owns the module lifetime and the OS reclaims it at exit.
printError("调用 Mentor 私有状态函数时发生异常");
}
}
static int runServer(HMODULE module, FARPROC address) {
(void)module;
const auto fn = reinterpret_cast<IsVerifiedReuseBlock>(address);
std::string request;
trace("server-ready");
while (std::getline(std::cin, request)) {
if (request.empty()) {
printError("空请求");
continue;
}
handleRequest(request, fn, true);
std::cout.flush();
}
trace("server-eof");
return 0;
}
int main(int argc, char** argv) {
const bool codecTest = argc > 1 && std::string(argv[1]) == "--codec-test";
if (codecTest) {
std::string request;
if (!std::getline(std::cin, request)) return 5;
const std::string requestId = field(request, "request_id");
const std::string lmc = field(request, "lmc_file");
const std::string name = field(request, "block_name");
if (requestId.empty() || lmc.empty() || name.empty()) return 6;
std::cout << "{\"request_id\":\"" << jsonEscape(requestId)
<< "\",\"lmc_file\":\"" << jsonEscape(lmc)
<< "\",\"block_name\":\"" << jsonEscape(name)
<< "\"}" << std::endl;
return 0;
}
const bool probeOnly = argc > 1 && std::string(argv[1]) == "--probe-only";
const bool serverMode = argc > 1 && std::string(argv[1]) == "--server";
const std::string path = dllPath();
trace("starting");
HMODULE module = LoadLibraryW(widen(path).c_str());
trace(module ? "dll-loaded" : "dll-load-failed");
if (!module) {
printError("无法加载 LMCDLL70.dll: " + path);
return 2;
}
const char* decorated =
"?IsVerifiedReuseBlock@reusableBlocks@@YA_NV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@W4eReuseBlockType@1@ABV23@@Z";
auto address = GetProcAddress(module, decorated);
trace(address ? "export-found" : "export-missing");
if (!address) {
FreeLibrary(module);
printError("LMCDLL70.dll 中没有 IsVerifiedReuseBlock 导出");
return 3;
}
if (probeOnly) {
FreeLibrary(module);
std::cout << "{\"ok\":true,\"probe\":true,\"export_found\":true,\"source\":\"IsVerifiedReuseBlock\"}" << std::endl;
return 0;
}
// Calling a private MFC ABI is opt-in. The default probe is harmless;
// production integration must explicitly enable this after compiling and
// validating the helper with the target Mentor installation.
const char* allow = std::getenv("CBB_STATUS_BRIDGE_ALLOW_PRIVATE");
if (!allow || std::string(allow) != "1") {
FreeLibrary(module);
printError("私有 MFC 状态调用未启用;仅完成导出探测");
return 4;
}
if (serverMode) {
return runServer(module, address);
}
std::string request;
trace("waiting-for-request");
if (!std::getline(std::cin, request)) {
FreeLibrary(module);
printError("缺少 JSON 请求");
return 5;
}
trace("request-parsed");
const auto fn = reinterpret_cast<IsVerifiedReuseBlock>(address);
std::string lmc;
std::string name;
std::string type;
std::string requestId;
if (!requestIsValid(request, lmc, name, type, requestId)) {
FreeLibrary(module);
printError("请求必须包含 op=is_verified、request_id、lmc_file 和 block_name");
return 6;
}
handleRequest(request, fn, false);
return 0;
}
+70
View File
@@ -0,0 +1,70 @@
# CBB 状态桥接试验
这是主程序使用的隔离只读状态桥。它不修改中心库,只调用
`IsVerifiedReuseBlock` 读取权威 `READY/PENDING` 状态。
## 编译前提
- 32 位 Visual C++ 工具链;
- 与 Mentor EE 7.9 兼容的 MFC/ATL ABI;
- `LMCDLL70.dll` 的 32 位运行环境。
必须使用 32 位 MSVC/MFC 构建;64 位或 MinGW 产物不能替代经过验证的 x86 MFC 版本。
在具备 x86 MSVC 的机器上,从此目录执行类似命令:
```powershell
cmake -S . -B build-x86 -A Win32
cmake --build build-x86 --config Release
```
## 只读导出探测
默认只建议运行探测模式:
```powershell
$env:SDD_HOME = 'D:\Mentor\7.9.5EE\SDD_HOME'
.\build-x86\Release\CbbStatusBridge32.exe --probe-only
```
成功只证明导出存在,不会调用状态函数。
真正调用私有函数前必须显式设置:
```powershell
$env:CBB_STATUS_BRIDGE_ALLOW_PRIVATE = '1'
```
主程序已通过 `BatchStatusSession` 接入该桥。UI 默认读取权威状态;旧图标/文件证据
仅在显式设置 `CBB_STATUS_BRIDGE_MODE=legacy` 时使用。任何现场调用仍应保留 JSONL
检查点、原始响应和 DLL 路径。
## 已验证的真实调用
桥已用本机 `D:\Mentor\7.9.5EE\SDD_HOME\common\win32\lib\LMCDLL70.dll`
对中心库副本和生产库进行只读调用。`RULP`/`LP` 对应 `eReuseBlockType = 0`;
调用 `IsVerifiedReuseBlock` 能返回 `READY` 或 `PENDING`,结果与已知人工状态一致。
桥默认是一次性进程;也支持 `--server` 常驻 JSONL 模式。常驻模式从标准输入逐行
读取 `op=is_verified`、`request_id`、`lmc_file`、`block_name`、`block_type`,每行输出
一个 JSON 响应并立即刷新。成功响应回显 `request_id`、`block_name` 和 `lmc_file`;
Python 客户端会核对三者,拒绝错序或串项响应。DLL 只加载一次,请求串行处理;单条
坏请求会返回 `ok:false` 并继续处理后续请求。
调用 Mentor 私有 MFC 函数后不主动 `FreeLibrary`,由操作系统在进程退出时回收 DLL;
主动卸载会触发 Mentor 模块级状态的堆异常或阻塞。常驻模式尤其必须遵守这一点。
## Verify 导出只读探测
`bin\\VerifyProbe32.exe --probe-exports` 只加载 `LMCDLL70.dll` 和
`LibManagerDBPI.dll`,枚举 `IsVerifiedReuseBlock`、
`GetStatusRBInContextOfCL`、`VerifyReuseBlock`、`UnVerifyReuseBlock` 与
`GetReusableCircuitVerificationStatus` 的导出地址,并输出一行 JSON。它不会调用
任何 Verify/UnVerify 写接口,响应中的 `write_call.enabled` 始终为 `false`。
探测桥也不会主动卸载 Mentor DLL。该 DLL 的 MFC/DBPI 模块状态在卸载时可能触发堆
损坏,因此由操作系统在短进程退出时统一回收。探测结果只能证明导出存在,不能证明
`CFilename` ABI 已经可以安全构造。
经过验证的可执行文件位于 `bin\\CbbStatusBridge32.exe`。主 UI 的读取和 Verify 后复查
默认使用该桥;执行结果只有在关闭 PCB 后再次读到 `READY` 才能保留为 `PASS`。
+148
View File
@@ -0,0 +1,148 @@
// VerifyProbe32 - read-only export inventory for Mentor EE 7.9.
//
// This helper intentionally does not call VerifyReuseBlock or
// UnVerifyReuseBlock. Those exports use Mentor's private CFilename MFC ABI;
// the probe records that the symbols exist so a separate isolated ABI study
// can be performed without changing a library.
#include <windows.h>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
struct ExportSpec {
const char* key;
const char* module;
const char* decorated;
};
static const ExportSpec kExports[] = {
{"IsVerifiedReuseBlock", "LMCDLL70.dll",
"?IsVerifiedReuseBlock@reusableBlocks@@YA_NV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@W4eReuseBlockType@1@ABV23@@Z"},
{"GetStatusRBInContextOfCL", "LMCDLL70.dll",
"?GetStatusRBInContextOfCL@reusableBlocks@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@W4eReuseBlockType@1@ABVDatabase@ODB@@@Z"},
{"VerifyReuseBlock", "LMCDLL70.dll",
"?VerifyReuseBlock@reusableBlocks@@YA_NABV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@W4eReuseBlockType@1@ABVCFilename@@@Z"},
{"UnVerifyReuseBlock", "LMCDLL70.dll",
"?UnVerifyReuseBlock@reusableBlocks@@YA_NABV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@W4eReuseBlockType@1@ABVCFilename@@_N@Z"},
{"GetReusableCircuitVerificationStatus", "LibManagerDBPI.dll",
"?GetReusableCircuitVerificationStatus@@YAHABV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@0HAAH@Z"},
};
static std::string jsonEscape(const std::string& value) {
std::ostringstream out;
for (const char ch : value) {
switch (ch) {
case '\\': out << "\\\\"; break;
case '"': out << "\\\""; break;
case '\n': out << "\\n"; break;
case '\r': out << "\\r"; break;
default: out << ch; break;
}
}
return out.str();
}
static std::wstring widen(const std::string& value) {
if (value.empty()) return {};
const int size = MultiByteToWideChar(CP_UTF8, 0, value.data(),
static_cast<int>(value.size()), nullptr, 0);
if (size <= 0) return {};
std::wstring result(static_cast<size_t>(size), L'\0');
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()),
result.data(), size);
return result;
}
static std::string narrow(const std::wstring& value) {
if (value.empty()) return {};
const int size = WideCharToMultiByte(CP_UTF8, 0, value.data(),
static_cast<int>(value.size()), nullptr, 0,
nullptr, nullptr);
if (size <= 0) return {};
std::string result(static_cast<size_t>(size), '\0');
WideCharToMultiByte(CP_UTF8, 0, value.data(), static_cast<int>(value.size()),
result.data(), size, nullptr, nullptr);
return result;
}
static std::string envValue(const char* name) {
const char* value = std::getenv(name);
return value && *value ? value : std::string();
}
static std::string lmPath() {
const std::string configured = envValue("LMCDLL70_PATH");
if (!configured.empty()) return configured;
const std::string sddHome = envValue("SDD_HOME");
if (!sddHome.empty()) return sddHome + "\\common\\win32\\lib\\LMCDLL70.dll";
return "LMCDLL70.dll";
}
static std::string dbPath(const std::string& lm) {
const std::string configured = envValue("LIBMANAGERDBPI_PATH");
if (!configured.empty()) return configured;
const size_t slash = lm.find_last_of("\\/");
if (slash == std::string::npos) return "LibManagerDBPI.dll";
return lm.substr(0, slash + 1) + "LibManagerDBPI.dll";
}
static std::string address(FARPROC value) {
if (!value) return {};
std::ostringstream out;
out << "0x" << std::hex << std::uppercase
<< reinterpret_cast<unsigned long>(value);
return out.str();
}
static void errorResponse(const std::string& message) {
std::cout << "{\"ok\":false,\"error\":\""
<< jsonEscape(message) << "\"}" << std::endl;
}
static int runProbe() {
const std::string lm = lmPath();
const std::string db = dbPath(lm);
HMODULE lmModule = LoadLibraryW(widen(lm).c_str());
if (!lmModule) {
errorResponse("无法加载 LMCDLL70.dll: " + lm);
return 2;
}
HMODULE dbModule = LoadLibraryW(widen(db).c_str());
std::ostringstream out;
out << "{\"ok\":true,\"probe\":\"exports\",\"dll_path\":\""
<< jsonEscape(lm) << "\",\"architecture\":\"x86\",\"modules\":{";
out << "\"LMCDLL70.dll\":{\"loaded\":true,\"path\":\""
<< jsonEscape(lm) << "\"},\"LibManagerDBPI.dll\":{\"loaded\":"
<< (dbModule ? "true" : "false") << ",\"path\":\""
<< jsonEscape(db) << "\"}},\"exports\":{";
for (size_t index = 0; index < sizeof(kExports) / sizeof(kExports[0]); ++index) {
const ExportSpec& spec = kExports[index];
HMODULE module = std::string(spec.module) == "LMCDLL70.dll" ? lmModule : dbModule;
FARPROC proc = module ? GetProcAddress(module, spec.decorated) : nullptr;
if (index) out << ',';
out << '"' << spec.key << "\":{\"module\":\"" << spec.module
<< "\",\"found\":" << (proc ? "true" : "false")
<< ",\"address\":\"" << address(proc) << "\"}";
}
out << "},\"write_call\":{\"enabled\":false,\"reason\":\"CFilename MFC ABI has not been reconstructed; this probe never calls VerifyReuseBlock or UnVerifyReuseBlock\"}}";
std::cout << out.str() << std::endl;
// Do not call FreeLibrary here. Mentor's module graph owns process-wide
// MFC/DBPI state; unloading it, even without calling a private function,
// can terminate the helper with STATUS_HEAP_CORRUPTION. The operating
// system reclaims the modules when this short-lived probe exits.
return 0;
}
int main(int argc, char** argv) {
if (argc != 2 || std::string(argv[1]) != "--probe-exports") {
errorResponse("仅支持只读参数 --probe-exports");
return 1;
}
return runProbe();
}
Binary file not shown.
Binary file not shown.