Files
cbb-refresh-verify-795/tools/probe_keyboard_menu.py
T
阿白叔 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

150 lines
5.9 KiB
Python

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