Files
cbb-refresh-verify-795/tools/probe_cursor_hit_test.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

163 lines
6.4 KiB
Python

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