Newer
Older
TIASShot / scripts / verify / release_check_win.py
"""配る Release 版の外からの確認(run_release_check.py)の Win32 と補助スクリプトの呼び出し.

状態の読み取り(ボタンの有効/無効・表示文・ウィンドウの一覧)は ctypes の Win32 API で行う.
撮影中は Form1 の UI スレッドがメッセージを処理しないため,UI Automation で読むと戻らないことがある.
そこで,止まっていても戻る呼び方だけを使う:
  - ボタンの有効/無効: IsWindowEnabled(ウィンドウのスタイルを読むだけで,相手にメッセージを送らない)
  - 表示文: SendMessageTimeout(WM_GETTEXT)(上限つき.相手が応答しなければ None)
  - トップレベルのウィンドウのタイトル: GetWindowText(他のプロセスのウィンドウにはメッセージを送らない)
コントロールの特定(メインウィンドウの子を UI Automation で列挙し,WinForms の Control.Name → ウィンドウハンドル)と
ボタンを押す操作(UI Automation の InvokePattern.無ければ MSAA の既定の動作)は release_check_uia.ps1 で行う.
(.NET Framework の UI Automation は,WinForms のコントロールを AutomationId=ウィンドウハンドル・パターンなしの Pane として
返すことがある(2026-10-20 に .NET 4.8 向けの WinForms で確認).そのため名前は WinForms の WM_GETCONTROLNAME で読む)
新しい依存は入れない(ctypes は標準ライブラリ,UIAutomationClient は .NET Framework に含まれる).
"""

from __future__ import annotations

import ctypes
import json
import subprocess
import sys
from ctypes import wintypes
from pathlib import Path

from release_check_judge import WindowInfo

UIA_SCRIPT = Path(__file__).resolve().parent / "release_check_uia.ps1"

WM_GETTEXT = 0x000D
WM_GETTEXTLENGTH = 0x000E
WM_CLOSE = 0x0010
SMTO_ABORTIFHUNG = 0x0002
TEXT_TIMEOUT_MS = 1000
MAX_TEXT_LEN = 4096

if sys.platform == "win32":
    _user32 = ctypes.WinDLL("user32", use_last_error=True)
    _EnumProc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
    _user32.EnumWindows.argtypes = [_EnumProc, wintypes.LPARAM]
    _user32.EnumWindows.restype = wintypes.BOOL
    _user32.EnumChildWindows.argtypes = [wintypes.HWND, _EnumProc, wintypes.LPARAM]
    _user32.EnumChildWindows.restype = wintypes.BOOL
    _user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
    _user32.GetWindowThreadProcessId.restype = wintypes.DWORD
    _user32.IsWindowVisible.argtypes = [wintypes.HWND]
    _user32.IsWindowVisible.restype = wintypes.BOOL
    _user32.IsWindowEnabled.argtypes = [wintypes.HWND]
    _user32.IsWindowEnabled.restype = wintypes.BOOL
    _user32.IsWindow.argtypes = [wintypes.HWND]
    _user32.IsWindow.restype = wintypes.BOOL
    _user32.IsHungAppWindow.argtypes = [wintypes.HWND]
    _user32.IsHungAppWindow.restype = wintypes.BOOL
    _user32.GetClassNameW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
    _user32.GetClassNameW.restype = ctypes.c_int
    _user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
    _user32.GetWindowTextW.restype = ctypes.c_int
    _user32.SendMessageTimeoutW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM,
                                            wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)]
    _user32.SendMessageTimeoutW.restype = ctypes.c_ssize_t
    _user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
    _user32.PostMessageW.restype = wintypes.BOOL
else:   # pragma: no cover - Windows 専用(他の環境では前提エラーになる)
    _user32 = None


def available() -> bool:
    """Win32 API を使えるか(Windows 以外では使えない)."""
    return _user32 is not None


def _class_name(hwnd: int) -> str:
    buf = ctypes.create_unicode_buffer(256)
    _user32.GetClassNameW(hwnd, buf, len(buf))
    return buf.value


def _window_title(hwnd: int) -> str:
    buf = ctypes.create_unicode_buffer(512)
    _user32.GetWindowTextW(hwnd, buf, len(buf))
    return buf.value


def get_text(hwnd: int, timeout_ms: int = TEXT_TIMEOUT_MS) -> str | None:
    """コントロールの文字列を WM_GETTEXT で読む.相手が timeout_ms 以内に応答しなければ None."""
    if not hwnd or not _user32.IsWindow(hwnd):
        return None
    length = ctypes.c_size_t(0)
    if not _user32.SendMessageTimeoutW(hwnd, WM_GETTEXTLENGTH, 0, 0, SMTO_ABORTIFHUNG, timeout_ms, ctypes.byref(length)):
        return None
    n = min(int(length.value), MAX_TEXT_LEN) + 1
    buf = ctypes.create_unicode_buffer(n)
    copied = ctypes.c_size_t(0)
    if not _user32.SendMessageTimeoutW(hwnd, WM_GETTEXT, n, ctypes.addressof(buf), SMTO_ABORTIFHUNG, timeout_ms,
                                       ctypes.byref(copied)):
        return None
    return buf.value


def is_enabled(hwnd: int) -> bool | None:
    """ウィンドウ(ボタン等)が有効か.ハンドルが無効なら None."""
    if not hwnd or not _user32.IsWindow(hwnd):
        return None
    return bool(_user32.IsWindowEnabled(hwnd))


def is_hung(hwnd: int) -> bool:
    """ウィンドウが応答なし(約 5 秒メッセージを処理していない)か."""
    return bool(hwnd) and bool(_user32.IsHungAppWindow(hwnd))


def window_texts(hwnd: int) -> list[str]:
    """ダイアログの中の文(子ウィンドウの文字列.ボタンの文字を除く)を集める.

    ダイアログとみなしたウィンドウにだけ使う.相手が応答しなければ読めた分だけ.
    """
    texts: list[str] = []

    @_EnumProc
    def cb(child, _lparam):
        cls = _class_name(child)
        if cls.lower() != "button" and _user32.IsWindowVisible(child):
            t = get_text(child)
            if t:
                texts.append(t)
        return True

    _user32.EnumChildWindows(hwnd, cb, 0)
    return texts


def top_level_windows(pid: int) -> list[WindowInfo]:
    """プロセス pid のトップレベルのウィンドウの一覧(クラス名・タイトル・見えているか.相手にメッセージは送らない)."""
    found: list[int] = []

    @_EnumProc
    def cb(hwnd, _lparam):
        owner = wintypes.DWORD(0)
        _user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
        if owner.value == pid:
            found.append(hwnd)
        return True

    _user32.EnumWindows(cb, 0)
    windows = []
    for h in found:
        windows.append(WindowInfo(hwnd=int(h), cls=_class_name(h), title=_window_title(h),
                                  visible=bool(_user32.IsWindowVisible(h))))
    return windows


def post_close(hwnd: int) -> bool:
    """WM_CLOSE を投稿する(待たない).投稿できれば True."""
    return bool(_user32.PostMessageW(hwnd, WM_CLOSE, 0, 0))


# ---------------------------------------------------------------------------
# 補助スクリプト(release_check_uia.ps1)
# ---------------------------------------------------------------------------

def _ps_command(action: str, **kwargs: object) -> list[str]:
    cmd = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
           "-File", str(UIA_SCRIPT), "-Action", action]
    for k, v in kwargs.items():
        cmd.extend([f"-{k}", str(v)])
    return cmd


def _decode(data: bytes) -> str:
    try:
        return data.decode("utf-8")
    except UnicodeDecodeError:
        return data.decode("cp932", errors="replace")


def parse_helper_output(stdout: bytes, stderr: bytes, returncode: int | None) -> dict:
    """補助スクリプトの出力(JSON)を辞書にする.読めなければ {"ok": False, "error": ...}."""
    text = _decode(stdout or b"").strip()
    if not text:
        err = _decode(stderr or b"").strip()
        return {"ok": False, "error": f"出力がありません(exit {returncode}){(': ' + err[:500]) if err else ''}"}
    try:
        obj = json.loads(text)
    except json.JSONDecodeError:
        return {"ok": False, "error": f"出力を JSON として読めません: {text[:500]}"}
    if not isinstance(obj, dict):
        return {"ok": False, "error": f"出力の形が違います: {text[:500]}"}
    return obj


def run_helper(action: str, timeout_sec: float, **kwargs: object) -> dict:
    """補助スクリプトを実行して結果を待つ(上限つき)."""
    try:
        proc = subprocess.run(_ps_command(action, **kwargs), capture_output=True, timeout=timeout_sec, check=False)
    except subprocess.TimeoutExpired:
        return {"ok": False, "error": f"補助スクリプト({action})が {timeout_sec:.0f} 秒で終わりません"}
    except OSError as ex:
        return {"ok": False, "error": f"補助スクリプト({action})を起動できません: {ex}"}
    return parse_helper_output(proc.stdout, proc.stderr, proc.returncode)


def control_key(entry: dict) -> str | None:
    """補助スクリプトの controls の 1 要素から,コントロールを引く名前を決める.

    WinForms の Control.Name(WM_GETCONTROLNAME で読んだ control_name)を優先し,読めなければ UI Automation の AutomationId.
    (.NET Framework の UI Automation は WinForms のコントロールの AutomationId にウィンドウハンドルの値を返すことがある)
    """
    return entry.get("control_name") or entry.get("automation_id") or None


class AsyncInvoke:
    """ボタンを押す補助スクリプトを待たずに起動する(WinForms のボタンの Invoke は,撮影ループの終わりまで戻らないことがある)."""

    def __init__(self, button_hwnd: int) -> None:
        self.button_hwnd = button_hwnd
        self.proc = subprocess.Popen(_ps_command("invoke", Hwnd=button_hwnd),
                                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self._result: dict | None = None

    def done(self) -> bool:
        return self.proc.poll() is not None

    def result(self, timeout_sec: float = 0) -> dict | None:
        """終わっていれば結果を返す.timeout_sec まで待っても終わらなければ None."""
        if self._result is not None:
            return self._result
        try:
            out, err = self.proc.communicate(timeout=timeout_sec)
        except subprocess.TimeoutExpired:
            return None
        self._result = parse_helper_output(out, err, self.proc.returncode)
        return self._result

    def kill(self) -> None:
        """補助スクリプト(自分が起動した PowerShell)を止める."""
        if self.proc.poll() is None:
            self.proc.kill()
            try:
                self.proc.communicate(timeout=10)
            except subprocess.TimeoutExpired:
                pass