import win32gui
import ctypes
from ctypes import wintypes
import sys

sys.stdout.reconfigure(encoding='utf-8')
user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

# TCVN3 Decoder
TCVN3_MAP = {
    0xb8: 'á', 0xb5: 'à', 0xb7: 'ả', 0xb6: 'ã', 0xb9: 'ạ',
    0xca: 'ă', 0xbe: 'ắ', 0xbb: 'ằ', 0xbd: 'ẳ', 0xbc: 'ẵ', 0xc6: 'ặ',
    0xcb: 'â', 0xc1: 'ấ', 0xbf: 'ầ', 0xc0: 'ẩ', 0xc2: 'ẫ', 0xc5: 'ậ',
    0xd0: 'é', 0xcd: 'è', 0xcf: 'ẻ', 0xce: 'ẽ', 0xd1: 'ẹ',
    0xd2: 'ê', 0xd5: 'ế', 0xd3: 'ề', 0xd4: 'ể', 0xd6: 'ễ', 0xd8: 'ệ',
    0xdc: 'í', 0xd9: 'ì', 0xdb: 'ỉ', 0xda: 'ĩ', 0xdd: 'ị',
    0xf3: 'ó', 0xdf: 'ò', 0xee: 'ỏ', 0xde: 'õ', 0xf4: 'ọ',
    0xf5: 'ô', 0xf8: 'ố', 0xf6: 'ồ', 0xf7: 'ổ', 0xf9: 'ỗ', 0xfa: 'ộ',
    0xfb: 'ơ', 0xfe: 'ớ', 0xfc: 'ờ', 0xfd: 'ở', 0xff: 'ỡ', 0x82: 'ợ',
    0x87: 'ú', 0x83: 'ù', 0x85: 'ủ', 0x84: 'ũ', 0x88: 'ụ',
    0x89: 'ư', 0x8c: 'ứ', 0x8a: 'ừ', 0x8b: 'ử', 0x8d: 'ữ', 0x8e: 'ự',
    0x95: 'ý', 0x90: 'ỳ', 0x93: 'ỷ', 0x92: 'ỹ', 0x96: 'ỵ',
    0xa7: 'đ', 0xa1: 'Đ'
}

def decode_tcvn3(s_bytes):
    chars = []
    for b in s_bytes:
        if b in TCVN3_MAP:
            chars.append(TCVN3_MAP[b])
        elif 32 <= b <= 126:
            chars.append(chr(b))
        elif b == 0:
            break
        else:
            chars.append(f"\\x{b:02x}")
    return "".join(chars)

def decode_str(s):
    b = s.encode('latin1', errors='replace')
    return decode_tcvn3(b)

main_hwnd = 0x8c4c02
controls = []
def child_cb(h, _):
    txt_len = user32.GetWindowTextLengthW(h) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, txt_buf, txt_len)
    cls = win32gui.GetClassName(h)
    vis = win32gui.IsWindowVisible(h)
    rect = win32gui.GetWindowRect(h)
    decoded = decode_str(txt_buf.value) if txt_buf.value else ""
    controls.append((h, cls, decoded, vis, rect))
    return True

user32.EnumChildWindows(main_hwnd, ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(child_cb), 0)
print(f"Total controls in AutoVLBS main: {len(controls)}")
for h, cls, txt, vis, r in controls:
    if vis and txt:
        print(f"  {hex(h)} [{cls}] at {r}: '{txt}'")
