Files
阿白叔 11a2b2e46e 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.
2026-09-29 15:05:20 +08:00

218 lines
8.9 KiB
Python

"""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)