#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GRBL 二次加工「找中心」辅助程序  v1.0

用途
----
木板已经雕过一遍轮廓，二次加工要对回原来的中心。本程序通过 GRBL 串口实时读
机床坐标 (MPos)，你手动点动让刀尖轻碰工件的四条边，程序自动算出中心与倾斜角，
并可直接写入 G54（G10 L2 P1），倾斜时还能把原刀路按角度旋转后另存新文件。

三种模式
--------
1) 正交分中：四条边各碰 1 次 -> 中心 = 两对边中点，最常用。
2) 倾斜分中：四条边各碰 2 次 -> 最小二乘拟合四条直线、求交点，得到中心 + θ。
3) 圆形：碰 3~4 个圆周点（3 点定圆 / ≥4 点最小二乘 + 圆度自检）。

用法
----
  python grbl_center.py                    # 打开图形界面
  python grbl_center.py --demo             # 图形界面 + 内置模拟机（无硬件也能试）
  python grbl_center.py --list             # 列出可用串口
  python grbl_center.py transform in.nc -o out.nc --theta 1.25 --ox 0 --oy 0
  python grbl_center.py selftest           # 内置算法自测

依赖: pip install pyserial     （图形界面需要 Python 自带 tkinter，Windows 默认有）

硬件连接
--------
USB 线接 GRBL 控制板 -> 串口（Windows 是 COM3 之类），波特率 115200。
GRBL 必须能回 <Idle|MPos:x,y,z|FS:..>，即固件正常。
"""

from __future__ import annotations

import argparse
import json
import math
import os
import queue
import re
import sys
import tempfile
import threading
import time

APP = "GRBL 分中助手"
# R1 = v3.0.2 定版；R1.1 = 防撞修订（安全 Z + 发送前预动作 + 点动续航）；
# R1.2 = 界面精简（初步定位 / 八格快移整体退出界面）。
# 以后对外就是 R1 → R1.1 → R1.2 → R2 的正式序列，不再使用 v1.x / v3.0.x 开发期版本号
# （历史版本见 NAS「历史归档」目录）。
VER = "R2.13"
# ---- 检查更新（R2.13）----
# 版本数据源：grbl.cn 上的 version.json（发版时改这一个文件）
UPDATE_URL = "https://grbl.cn/center/version.json"
DOWNLOAD_PAGE = "https://grbl.cn/center/"


def _ver_key(v):
    """把 R2.12 / v1.39.8 / 3.0.2 变成可比较的元组。R 系正式序列排在所有旧版本之前。"""
    s = str(v or "").strip().lstrip("vV")
    m = re.match(r"^([A-Za-z]+)", s)
    pre = (m.group(1).upper() if m else "")
    parts = re.split(r"[.\-_]", s[len(m.group(0)) if m else 0:])
    nums = []
    for x in parts:
        nums.append(int(x) if x.isdigit() else 0)
    while len(nums) < 4:
        nums.append(0)
    rank = 10 if pre.startswith("R") else (5 if pre else 0)
    return (rank,) + tuple(nums[:4])


def ver_cmp(a, b):
    """a 比 b 新返回 1，旧返回 -1，相同返回 0。"""
    ka, kb = _ver_key(a), _ver_key(b)
    return (ka > kb) - (ka < kb)


def update_check(timeout=6.0, url=None):
    """联网查最新版本。不抛异常，失败把原因放在 err 里。"""
    out = {"ok": False, "cur": VER, "latest": "", "newer": False,
           "url": "", "note": "", "date": "", "err": ""}
    try:
        import json as _json
        import urllib.request as _rq
        req = _rq.Request(url or UPDATE_URL, headers={
            "User-Agent": "grbl-center/%s" % VER,
            "Cache-Control": "no-cache",
        })
        with _rq.urlopen(req, timeout=timeout) as resp:
            data = _json.loads(resp.read().decode("utf-8"))
        out["ok"] = True
        out["latest"] = str(data.get("ver") or "").strip()
        out["url"] = str(data.get("zip") or data.get("py") or "").strip()
        out["note"] = str(data.get("note") or "").strip()
        out["date"] = str(data.get("date") or "").strip()
        if out["latest"]:
            out["newer"] = ver_cmp(out["latest"], VER) > 0
    except Exception as e:
        out["err"] = "%s: %s" % (type(e).__name__, e)
    return out

EPS = 1e-9

# 程序图标（内嵌 PNG，不依赖外部文件；Windows 标题栏/任务栏/Alt-Tab 都认）
LOGO_PNG64_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAIC0lEQVR4nO2bTYxUxxHHf9Xd"
    "b2dmv4bFXtsgIq8w2JIxUkykHGKTjYksIVuJY0WcArJjklus+BDLPiAtK9kHy7lFysVgYsEt"
    "iizFUWTFiskGIvkSWwpBMphgkBEEL7CfM7M787orh7ezsOzuzAPmYwn8pTm8ef26q+r16/pX"
    "dbWwFIbUMIyCKEND5uELv3qK4H+ghK0QBlBdveRz7YbIFTBnBHMEYz84uebXhxkeDqDCEMKw"
    "hEWPLOpkh1p+Lx5g4+4rL2Dty6LhW2JzaCijIQb1LdDmJiAWMQ4xHagvoWL+ife/+WL/6veA"
    "BbrNP3LtxeDgYTcy8lS8/sWvNrqO3neM6xpUP0uICwAeRRAEZLHhVgRUURRBAWtcF2IzhLgw"
    "Epcnf376d9/4oqpj9Yl5Rao3HnrhwvdspvsPYqPVfnYyFjCImLboc6tQDQrBZnqd+soVPzv9"
    "4/+8t+Zv1xohMcCQGoYlbPjp+UETdf8ZtDPEs7GIuLYq0CCoamxcxoEUQ2X6mVMH1o5UdZbq"
    "gvfwz8YHQD7DSF79rAex7Ra8sVAvNmMJOgH6+Ml9q84wxNzUVgihclCiXD7EM/H/n/IAYkM8"
    "E0uUy4dQOYjO/QuwYffoTpddfTAuXYpFzLLT3qZcCUKg2n/DIIBN8VpUwS9ydtfeD7HL3evi"
    "mSu7Tu3vPyQ7dqj9rGf0UxN1bda4GIBlh5kuadK5UFPDnpxgTeOMIEAcYKpUv0cr0NNZ00l5"
    "cZ0mVArHHp/q3yLrX7ywzUW5v2ooaz339vSWDnpyBq3T8qNPZxkvKK4BRhCg4pX+vGHnttyy"
    "7aoyjU0HDn08U6dXVTEdEldK33fG2OfFZtFQrvn2AYZ+0s19+frfwb9OVxidiIkygt6iBUQg"
    "9nBPj+HlH3bWbX9pMo0BCGKz1vjy8wZ4UrUCupgVWpNMu6e3ZPjwjT66skJIodCtKr1knynb"
    "ZCPhwzf62Lkty2RJl143FFGtADzpRBjAV0gY3mL4AKu6hPUPWFSTt3H2kq8pUDluHFdUwBgo"
    "ziqffF5Ztp0PsHnA0Z0T1ucs/XmDD0txfRJdfQURBhzIKlXPciJXF6CgYAS+uuTZvmesruCZ"
    "KN1sqQdV6HDC+cuBHW+OL9nGCEzPKB/s7eM7j0YEhUq8jPIAiMzpvCoV05O5QdoJEejKLi1E"
    "VTZjrl6nnYG3FdWtNaNudrbdnkFOA3HXAO0WoN24a4B2C9BuyMbdozXXzxAg3yX0z1Hgcgzn"
    "Lq28nKAqrL3HkOtI/N/YtHJ5MtQNyuq6QWtgvKCMTiRpNJGE5Kw0iMDZrz1hLhR2VohsfQpd"
    "1wAKOANRRuavm8H1G4FMdJXPp5UzFRFqtNJCwtqqbE21MUkU1Rvvo+VM0JokoJoqKHF1upqE"
    "5jpbO5vTDLTUANbAZFHp6RSe+XaGTQ8mwx8/G3P0eJnJotLbKS01QssMYA1MFJXvPtbB8M4u"
    "Hlm3cOgT52KGDhX4+7/L5FtohJbwgOqb37op4tCreR5Z5/CBBb9H1jkOvZpn66aIyaKmTsDe"
    "Kpo+jJB889054a2XenA2ubZm4S/24Cy89VIP3Tkh9rXi+cah6QYwJklWDG7uYOB+iw+Jotej"
    "ugAO3G8Z3NzB9IzOx/dNla/ZA4gkim160CVuqoafqt7f9GDyibRiC/aOjwWabgDV5Bs/fjZG"
    "6qSqqvePn40TDt8Cxtl0A4QA3Vlh5FiZMxf9/IJ3PaoL45mLnpFjZbqzMs/rm4nmzwCSBW66"
    "pLz27tT8an+9G6x6h9fenWK6pLgUgUwj0JI1wAfo7RSOHK+w8+0JTpyLF7nBE+didr49wZHj"
    "lZaywbr5gEbiWir85KaORVR4qg1UuKUGgKukpzBzBwZDkChoJMkyXR8Ot1p5SGkAEW440VAL"
    "SnOUXSBnytxAXQMIyT5b7JPujEn26lYiZso6/3IiJ6nqE2oaQEjeVH/e0NedKF0qK+cvhxVZ"
    "KfjQGkfHnEajE4GJQv14oqYBrIWxgvLLH2XnixM++bzCjjfHU9cKtBL7Xull/QNJpPX6gWkO"
    "/KXE6p7aXuVuLNBuAdqNuwZotwDtxh1vgJtigkZql8ysNO9QC+l2hvRqkVQISY4Pllc02yFt"
    "5QnhBnaIHOi4iFulGi9Z/6lA5OaUV3hswPHHvX0109avvTvF2a89mejWCyWNJORrwxrHO6/0"
    "LttOgHX3JqV8RqjDAlVFnKjG406VM+Kib1KJ9fpaweTYRcKqTv/Xc1/e0NMpPPFoVFPozkyS"
    "zalTUpwaSakc8yRnOQSFYlm5OBYYL9TYW1AUF4lW4jMGOCoSMXfMZAG8h96ccOjjGbbvGWOm"
    "skQ56RJoxuxP80kZScLs7XvG+OjTWXpyy7BAQUUigKMuBP++8TO/IIVH+O2fivR11y+WvjwV"
    "kpRWgwolIydcHA+8fmC6ZjsRmCqlCjON+hlC8O/fULn8VFHxKZTqyaWLxNKiGpTVLJef+96s"
    "SXahamBhuTzc2IGJNFPR++YcmEi7U3RDByYYUsNedMPu0SM2k3/Cz47XNMLtDNUQ28wq52cn"
    "/nFqf/9W9lbPDAkYE+3SSmnCuKxbuScjbwXqjcs6rZQmjIl2VVdqw7AEhpCT+/q+DL74HEhR"
    "bMaqaly7w9sHqhqLzViQYvDF507u6/uyepQ2mQHDEgYHD7tTB9aO+NnCs2Cu2EyvU9UY1Tak"
    "KhsE1aCqsc30OjBX/Gzh2VMH1o4MDh521XPEd4/OLurjTj48PY876Pj8/wBFnwJiWTQCzQAA"
    "AABJRU5ErkJggg=="
)
# 界面左上角小徽标（已贴到 #f8fafc 底色上，和 DRO 小卡同色）
LOGO_PNG26_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAADPUlEQVR4nL2Wz2tcVRTHP+e+"
    "O+9NJnFoV05UyKKNuhBEW0GKIC6E2UnRhbrUoLjQP0CpwYL+AUJBYXDpDygUdwNdCKIQNLUI"
    "VbBNFwPRVKUkxMxk3o97j4s7MzHJ+DIdpV+4m3fuPd9zvu+cc6+wrIb3xD/0Suc+Hx1/W3DP"
    "qS/uB4TpoGLsr0r0pXGbH/zyycJvLKsRgJNLt5400dznYioLmndRdVNyBIhESGUW9XnHu50X"
    "11qNFXn4tT/mnTM/mPiehku3ChGJjIjIlPmogldVVXVRcsz67K9bUeQft67gnEnqDZ9uFiLG"
    "ikA3VbKcIJ5OmkbYG1egloiAWJ9uFSY53nDp1jmLyFktdhSRyAj0MuWJxQoPPmDxqhP/KAWM"
    "CNfXC1bXcmqx4JFo4PusBRrqHUaEbqqcXqxw8Z1jGDOFboD38Pz7W6zeyJlNRLx3AI2ROxFI"
    "M3hkwWIMZAU4D4WbbDkfzhgTfKRZ8DmE3SezQJrrQAZ4/cNtbm4UVGNBNTgZntVB9CLQz5QT"
    "85aP3qyjBB8Hi8lyACJ7zm5uFPzUKZitCgps9xTngy0yUK8JAnT7exUjcIhkLNE/UY2FWlWo"
    "xkK3r7zwVJVnHo0B+OrHjPZqOgqiGpeXTSmRaoixmyrvvjzHUnNmZHvp6Sqt9i7nP9vBiAz2"
    "/jtKa8sY2O55mqcSlpozhwpgqTlD81TCds8fWaWlZgGcg2cfi/GDiG0UFoDXYHPu6ME4Zbfc"
    "OUqJFIgiuHw1wwxCHsoGoQUuX82IoqMnVSmR91CvGdpXUlrt3ZFsw9Vq79K+klKvGbwvJyqt"
    "utAPymwinP90h++u52PLezc73KB3RNTPlF4/DFZj4OI3fb74ug/sNexwTz8rF+8Qkeqe3ifm"
    "g3nSETT8Pq6n9hGpQlIJY8UrfPxW/chGHEIkDFZL8HHw3IhIFZIYrnUKvIe4VNTxiEzI8lqn"
    "IIn3ZyaLr/65ISa6V32BEZFeppw++T9dfKoqxqLe/W5RvSR27g1NNwuP2JlY+P5Gzrc/5//l"
    "Kg+TRNWJnbOabl26a4+Tu/bcMiyrWWs1ViS/fcYX6QVE1plcsLFJIbLui/SC5LfPrLUaKyyr"
    "+Ruo4cV63YXQPwAAAABJRU5ErkJggg=="
)

EDGES = ("L", "R", "F", "B")
EDGE_CN = {"L": "左壁", "R": "右壁", "F": "前壁", "B": "后壁"}

# 工件形状：矩形走「四边各碰求交」，圆形走「圆上 3 点定圆」
SHAPE_RECT = "rect"
SHAPE_CIRCLE = "circle"
SHAPES = ["矩形（四边各碰）", "圆形（圆上碰 3 点）"]
SHAPE_CN = {SHAPE_RECT: "矩形", SHAPE_CIRCLE: "圆形"}


def shape_of(label):
    """下拉文案 → 内部标识（认字不看序号，改文案不会错位）"""
    return SHAPE_CIRCLE if str(label).strip().startswith("圆") else SHAPE_RECT

# 基准补偿档位：把「碰到的线」修正到「刀路线」上要平移多少
#   + 外扩（远离中心）  - 内缩（朝中心）
COMP_MODES = [
    "不补偿（刀路就在碰到的线上）",
    "外扩一个半径（碰工件外缘）",
    "内缩一个半径（碰槽壁·刀路在内侧）",
    "内缩一个刀径",
    "外扩一个刀径",
    "自定义（按生效偏移填）",
]
# 点动发送节流：GRBL 的 RX 缓冲只有 128 字节，猛发命令会溢出/丢字符，表现出来就是"点不动"
POLL_SEC = 0.20          # 状态轮询（?）间隔。328p（Nano/Uno）只有 2KB RAM，8Hz 时点动与轮询互挤 → 用 5Hz
JOG_MIN_GAP = 0.06        # 两条 jog 命令之间最小间隔（秒）
JOG_MAX_PENDING = 3       # 允许的"已发未应答"命令数（超过就先不发）

# ---- 发送加工（把刀路流式下发给 GRBL）----
RX_BUFFER = 128           # GRBL 串口接收缓冲（v1.1 默认 128 字节，与官方 stream.py 同值）
RX_KEEP = 12              # 余量：在途字符不超过 RX_BUFFER-RX_KEEP，给状态帧/换行留余地
SEND_CHUNK = 6            # 在途最多几条行：塞太深急停刹车距离会长
ACK_TIMEOUT = 8.0         # 多久收不到 ok 就判通讯中断（v1.39.5：3→8，慢速段不再被误杀）
ACK_HARD_TIMEOUT = 150.0  # 硬超时：机床确实在动就容忍，但这么久一条 ok 都没有仍判中断
FINISH_WAIT_MAX = 1800.0  # 收尾前等「机床真的走完」的上限
EEPROM_RE = re.compile(r"G10|G28|G30|\$RST", re.I)   # 写 EEPROM 的行：必须等 ok，不能字符计数
JOG_MAX_STEP = 5.0        # 一次合并的最大位移（mm，防连点累加跑太远）
SAFE_WZ = 5.0             # 抬刀时「工作坐标 Z 至少到这个高度」（Z0=顶面时＝顶面以上 5mm；
#                            2mm 太薄，压板/毛刺/工件不平就蹭上了）
                          # 刀在深槽里（Z-6）时只抬 5mm 还在工件里 → 回中心就是横着穿工件
_AXI = {"X": 0, "Y": 1, "Z": 2}   # 取 mpos 分量的下标（以前写 0 if X else 1，Z 会错取 Y）

# 只记录到 1 个点时，该边按哪个方向当直线（正交分中用）
DEFAULT_DIR = {"L": (0.0, 1.0), "R": (0.0, 1.0), "F": (1.0, 0.0), "B": (1.0, 0.0)}


# ---------------------------------------------------------------- 几何 ----
class Line:
    """归一化直线 a*x + b*y + c = 0（(a,b) 为单位法向）"""

    __slots__ = ("a", "b", "c", "d", "p0")

    def __init__(self, a, b, c, d=None, p0=None):
        n = math.hypot(a, b)
        if n < EPS:
            raise ValueError("退化直线")
        self.a, self.b, self.c = a / n, b / n, c / n
        self.d = d
        self.p0 = p0

    @property
    def angle(self):
        """方向角（弧度）"""
        if self.d is not None:
            return math.atan2(self.d[1], self.d[0])
        return math.atan2(-self.a, self.b)

    def signed(self, p):
        return self.a * p[0] + self.b * p[1] + self.c

    def shift_outward(self, pt, dist):
        """沿法向背离 pt 平移 dist

        用途：碰到的点是刀心位置，刀心距真实壁面还有半径 r，
        真实壁面在原直线的外侧，故要背离中心方向推 r。
        """
        s = self.signed(pt)
        sign = 1.0 if s > 0 else -1.0
        return Line(self.a, self.b, self.c + sign * dist, self.d, None)


def fit_line(pts):
    """总最小二乘拟合直线（对 2 点即过两点的直线）"""
    n = len(pts)
    mx = sum(p[0] for p in pts) / n
    my = sum(p[1] for p in pts) / n
    sxx = sum((p[0] - mx) ** 2 for p in pts)
    syy = sum((p[1] - my) ** 2 for p in pts)
    sxy = sum((p[0] - mx) * (p[1] - my) for p in pts)
    if abs(sxy) < EPS and abs(sxx - syy) < EPS:
        raise ValueError("点重合，无法拟合直线")
    if abs(sxy) < EPS:
        dx, dy = (1.0, 0.0) if sxx >= syy else (0.0, 1.0)
    else:
        # 主特征向量方向
        tmp = math.hypot(sxx - syy, 2.0 * sxy)
        big = (sxx + syy + tmp) / 2.0
        dx, dy = big - syy, sxy
        if abs(dx) < EPS and abs(dy) < EPS:
            dx, dy = 1.0, 0.0
    n2 = math.hypot(dx, dy)
    dx, dy = dx / n2, dy / n2
    a, b = -dy, dx
    return Line(a, b, -(a * mx + b * my), (dx, dy), (mx, my))


def _solve3(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3):
    """3×3 线性方程组（高斯消元 + 部分主元）。退化抛 ValueError。"""
    m = [[a11, a12, a13, b1], [a21, a22, a23, b2], [a31, a32, a33, b3]]
    for c in range(3):
        piv = max(range(c, 3), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) < 1e-12:
            raise ValueError("三点几乎在一条直线上，算不出圆（换个位置再碰）")
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
        pv = m[c][c]
        for r in range(3):
            if r == c:
                continue
            f = m[r][c] / pv
            if f:
                for k in range(c, 4):
                    m[r][k] -= f * m[c][k]
    return m[0][3] / m[0][0], m[1][3] / m[1][1], m[2][3] / m[2][2]


def fit_circle(pts):
    """最小二乘拟合圆（Kåsa 代数法）→ (cx, cy, R, 最大径向偏差)

    - 3 点：唯一精确解
    - ≥4 点：最小二乘，max_err 能查出碰错的那个点（3 点时恒为 0）
    先平移到质心再解，避免大坐标下的数值病态。
    """
    ps = [(float(p[0]), float(p[1])) for p in pts]
    n = len(ps)
    if n < 3:
        raise ValueError("拟合圆至少要 3 个点")
    mx = sum(p[0] for p in ps) / n
    my = sum(p[1] for p in ps) / n
    us = [p[0] - mx for p in ps]
    vs = [p[1] - my for p in ps]
    zs = [u * u + v * v for u, v in zip(us, vs)]

    suu = sum(u * u for u in us)
    svv = sum(v * v for v in vs)
    suv = sum(u * v for u, v in zip(us, vs))
    su = sum(us)
    sv = sum(vs)
    suz = sum(u * z for u, z in zip(us, zs))
    svz = sum(v * z for v, z in zip(vs, zs))
    sz = sum(zs)

    # 解   [suu suv su][D]   [-suz]
    #      [suv svv sv][E] = [-svz]
    #      [su  sv  n ][F]   [-sz ]
    D, E, F = _solve3(suu, suv, su, suv, svv, sv, su, sv, float(n), -suz, -svz, -sz)
    cx, cy = mx - D / 2.0, my - E / 2.0
    r2 = (D * D + E * E) / 4.0 - F
    if r2 <= 0:
        raise ValueError("三点几乎在一条直线上，算不出圆（换个位置再碰）")
    R = math.sqrt(r2)
    err = max(abs(math.hypot(p[0] - cx, p[1] - cy) - R) for p in ps)
    return cx, cy, R, err


def intersect(l1, l2):
    det = l1.a * l2.b - l2.a * l1.b
    if abs(det) < 1e-12:
        return None
    x = (l1.b * l2.c - l2.b * l1.c) / det
    y = (l1.c * l2.a - l2.c * l1.a) / det
    return (x, y)


def mean_angle(angles):
    """方向角平均（按 180° 周期，避开 ±π 环绕问题）"""
    s = sum(math.sin(2.0 * a) for a in angles)
    c = sum(math.cos(2.0 * a) for a in angles)
    return math.atan2(s, c) / 2.0


def dist(p, q):
    return math.hypot(p[0] - q[0], p[1] - q[1])


class CenterFitter:
    """碰点记录 + 中心求解

    offset: 基准补偿量（mm，带符号）。把碰到的每条边沿法向平移 offset 后再求中心/宽高。
            + = 背离中心（外扩）  - = 朝中心（内缩）
            0 = 不补偿（刀路就在被碰到的那条线上）
            常用值：
              碰工件外缘、刀路是轮廓线            → +刀半径
              碰槽壁、刀路在内侧一个半径（本机）  → -刀半径
            重要：四条边同量偏移不改变中心，只改宽高。只要「对边同类型」，中心永远是对的。

    radius: 旧接口，等价于 offset=+radius。
    """

    def __init__(self, radius=0.0):
        self.radius = float(radius)
        self.offset = None      # None → 回退 +radius（向后兼容）
        self.pts = {k: [] for k in EDGES}
        self.shape = SHAPE_RECT
        self.cpts = []          # 圆形模式：圆周上的碰点（与 self.pts 互不干扰）

    # -- 记录 --
    def add(self, edge, xy):
        edge = edge.upper()
        if edge not in self.pts:
            raise ValueError("未知边 " + edge)
        self.pts[edge].append((float(xy[0]), float(xy[1])))
        if len(self.pts[edge]) > 2:          # 每边最多留最近 2 点
            self.pts[edge].pop(0)

    def pop(self):
        """撤销最近记录的一个点"""
        best, best_i = None, -1
        for k in EDGES:
            if self.pts[k]:
                if best is None or len(self.pts[k]) >= len(self.pts[best]):
                    best, best_i = k, len(self.pts[k]) - 1
        if best is None:
            return None
        p = self.pts[best].pop()
        return best, p

    def clear(self):
        for k in EDGES:
            self.pts[k] = []
        self.cpts = []

    def count(self, edge=None):
        if edge:
            return len(self.pts[edge.upper()])
        return sum(len(self.pts[k]) for k in EDGES)

    def ready(self):
        return all(self.pts[k] for k in EDGES)

    # -- 圆形模式：圆上碰点 --
    MAX_CPTS = 8

    def add_circle(self, xy):
        """记一个圆周上的点（保留最近 MAX_CPTS 个）"""
        self.cpts.append((float(xy[0]), float(xy[1])))
        if len(self.cpts) > self.MAX_CPTS:
            self.cpts.pop(0)

    def pop_circle(self):
        if not self.cpts:
            return None
        return self.cpts.pop()

    def circle_ready(self):
        return len(self.cpts) >= 3

    # -- 求解 --
    def _line(self, edge, theta=0.0):
        """单点的边：只提供「边在哪」，方向用 θ 对齐（θ 由别的边实测得出）。
        这样 1 条边点 2 次「定方向」+ 其余边各 1 点「定位置」也能算角度。"""
        ps = self.pts[edge]
        if not ps:
            return None
        if len(ps) == 1:
            if edge in ("F", "B"):
                d = (math.cos(theta), math.sin(theta))
            else:
                d = (-math.sin(theta), math.cos(theta))
            p0 = ps[0]
            return Line(-d[1], d[0], -(-d[1] * p0[0] + d[0] * p0[1]), d, p0)
        return fit_line(ps)

    def theta_from_multi(self):
        """有 2 点的边能算出这条边真实朝向 → θ（弧度）。一条都没有则返回 None"""
        cands = []
        for k in EDGES:
            if len(self.pts[k]) >= 2:
                phi = fit_line(self.pts[k]).angle
                cands.append(phi if k in ("F", "B") else phi - math.pi / 2.0)
        if not cands:
            return None
        return mean_angle(cands)

    def edges_with_dir(self):
        return [k for k in EDGES if len(self.pts[k]) >= 2]

    def solve(self):
        th0 = self.theta_from_multi()          # 有 2 点的边给出的真实 θ
        have_theta = th0 is not None
        lines = {k: self._line(k, th0 if have_theta else 0.0) for k in EDGES}
        missing = [EDGE_CN[k] for k, v in lines.items() if v is None]
        if missing:
            raise ValueError("还没碰：" + "、".join(missing))

        def corners_of(ls):
            out = {}
            for xk in ("L", "R"):
                for yk in ("F", "B"):
                    p = intersect(ls[xk], ls[yk])
                    if p is None:
                        raise ValueError(
                            "%s 与 %s 几乎平行，无法求交（碰点是否记错？）" % (EDGE_CN[xk], EDGE_CN[yk])
                        )
                    out[(xk, yk)] = p
            return out

        seg_ok = all(len(self.pts[k]) >= 2 for k in EDGES)
        c_raw = corners_of(lines)
        c0 = (
            sum(p[0] for p in c_raw.values()) / 4.0,
            sum(p[1] for p in c_raw.values()) / 4.0,
        )
        # 补偿前的原始宽高（「自动测偏移」靠它反推该内缩/外扩多少）
        raw_w = dist(c_raw[("L", "F")], c_raw[("R", "F")])
        raw_h = dist(c_raw[("L", "F")], c_raw[("L", "B")])

        d = self.offset if self.offset is not None else self.radius
        if abs(d) > 1e-9:
            lines2 = {k: l.shift_outward(c0, d) for k, l in lines.items()}
            corners = corners_of(lines2)
            lines = lines2
        else:
            corners = c_raw

        center = (
            sum(p[0] for p in corners.values()) / 4.0,
            sum(p[1] for p in corners.values()) / 4.0,
        )

        angles = [
            lines["F"].angle,
            lines["B"].angle,
            lines["L"].angle - math.pi / 2.0,
            lines["R"].angle - math.pi / 2.0,
        ]
        theta = mean_angle(angles)
        # 归一到 (-90, 90]
        while theta > math.pi / 2:
            theta -= math.pi
        while theta <= -math.pi / 2:
            theta += math.pi

        w = dist(corners[("L", "F")], corners[("R", "F")])
        h = dist(corners[("L", "F")], corners[("L", "B")])

        # 直角自检：四个顶点实测角度偏离 90° 的最大值（碰点有误会有大偏差）
        order = [("L", "F"), ("R", "F"), ("R", "B"), ("L", "B")]
        cp = [corners[o] for o in order]
        sq_err = 0.0
        for i in range(4):
            a, b, c = cp[i - 1], cp[i], cp[(i + 1) % 4]
            v1 = (a[0] - b[0], a[1] - b[1])
            v2 = (c[0] - b[0], c[1] - b[1])
            n1, n2 = math.hypot(*v1), math.hypot(*v2)
            if n1 < EPS or n2 < EPS:
                continue
            cs = max(-1.0, min(1.0, (v1[0] * v2[0] + v1[1] * v2[1]) / (n1 * n2)))
            sq_err = max(sq_err, abs(math.degrees(math.acos(cs)) - 90.0))

        if seg_ok:
            src = "edge2"
        elif have_theta:
            src = "mixed"
        else:
            src = "edge1"
        return {
            "center": center,
            "theta": theta,
            "theta_deg": math.degrees(theta),
            "width": w,
            "height": h,
            "corners": corners,
            "lines": lines,
            "radius": self.radius,
            "offset": d,
            "raw_width": raw_w,
            "raw_height": raw_h,
            "segs": seg_ok,
            "src": src,
            "theta_measured": have_theta,
            "theta_src_edges": self.edges_with_dir(),
            "square_err": sq_err,
            "theta_warn": abs(math.degrees(theta)) > 45.0,
        }

    def solve_circle(self):
        """圆形工件：圆上 3 点定圆（≥4 点最小二乘）

        补偿口径与矩形同构：碰到的点是「碰针压到的壁面」，刀心还在壁内一个半径，
        所以 offset = -r 时有效半径 = 实测半径 + offset，直径同理。
        重要：半径均匀变化不移动圆心 —— 补偿只影响直径（自检口径），不影响中心。

        圆形本身无方向性，θ 恒为 0，不做旋转。
        """
        if len(self.cpts) < 3:
            raise ValueError("圆形至少要在圆上碰 3 个点（现在 %d 个）" % len(self.cpts))
        cx, cy, R, rerr = fit_circle(self.cpts)
        d = self.offset if self.offset is not None else self.radius
        R_eff = R + d
        dia_raw = 2.0 * R
        dia = 2.0 * R_eff
        return {
            "shape": SHAPE_CIRCLE,
            "center": (cx, cy),
            "theta": 0.0,
            "theta_deg": 0.0,
            "theta_measured": False,      # 圆形无方向，界面不要报「歪了」
            "theta_warn": False,
            "theta_src_edges": [],
            "width": dia,
            "height": dia,
            "diameter": dia,
            "diameter_raw": dia_raw,
            "radius": R,
            "radius_eff": R_eff,
            "round_err": rerr,            # 各点到拟合圆的最大偏差（mm）
            "npts": len(self.cpts),
            "corners": None,
            "lines": None,
            "offset": d,
            "raw_width": dia_raw,
            "raw_height": dia_raw,
            "segs": True,
            "src": "circle",
            "square_err": None,
        }

    # -- 三点/四点定角（四角模式） --


def g10_cmd(center, p=1, z=None):
    """G10 L2 P1 直接设置 G54 偏移。⚠ GRBL 对未指定的轴按 0 处理，
    所以想保住 Z 对刀必须显式带上 Z，否则 Z 偏移会被清成 0（刀会扎下去/悬空）。"""
    s = "G10 L2 P%d X%.4f Y%.4f" % (p, center[0], center[1])
    if z is not None:
        s += " Z%.4f" % z
    return s


# ------------------------------------------------------------ G 代码变换 ----
WORD_RE = re.compile(r"([A-Za-z])\s*([-+]?(?:\d+\.\d*|\.\d+|\d+))")


def _split_comment(line):
    code, comments = [], []
    i, n = 0, len(line)
    while i < n:
        ch = line[i]
        if ch == "(":
            start, depth = i, 0
            while i < n:
                if line[i] == "(":
                    depth += 1
                elif line[i] == ")":
                    depth -= 1
                i += 1
                if depth == 0:
                    break
            comments.append(line[start:i])
            continue
        if ch == ";":
            comments.append(line[i:])
            break
        code.append(ch)
        i += 1
    return "".join(code), " ".join(comments)


def _fmt(v):
    s = "%.4f" % v
    s = s.rstrip("0").rstrip(".")
    return s if s not in ("", "-", "-0") else "0"


def spindle_directive(text):
    """从原刀路里提取主轴指令 → "S15000 M3"。没有 S 就返回 None（不瞎写，免得 S0 不转）。"""
    s_val = None
    dirn = None
    for raw in text.splitlines():
        code, _c = _split_comment(raw)
        up = code.upper()
        m = re.search(r"S\s*(\d+(?:\.\d+)?)", up)
        if m and s_val is None:
            s_val = m.group(1)
        if dirn is None:
            if re.search(r"(?:^|[^A-Z])M4(?![0-9])", up):
                dirn = "M4"
            elif re.search(r"(?:^|[^A-Z])M3(?![0-9])", up):
                dirn = "M3"
        if s_val and dirn:
            break
    if not s_val:
        return None
    return "S%s %s" % (s_val, dirn or "M3")


def insert_start_block(text, start_z, warn=None, spindle=None):
    """R2：在文件头的「抬到安全高度」之后插入两行 ——
        `G90 G0 X.. Y..`（安全高度走到加工起点）
        `G90 G0 Z<起刀>`（下到加工起始高度·工件坐标）
    这样加工前软件不需要再插任何动作：与在 Candle 里跑同一份文件行为完全一致。
    起点取变换后正文里第一处绝对 X/Y（跳过 G53 / G10 / G92 与注释）。
    找不到抬刀行 → 原样返回（说明不是本程序生成的文件）。
    """
    warn = warn or (lambda m: None)
    sep = "\r\n" if "\r\n" in text else "\n"
    lines = text.splitlines()
    lift_i = None
    for i, ln in enumerate(lines[:80]):
        if "开工前抬到安全高度" in ln:
            lift_i = i
            break
    if lift_i is None:
        return text
    x = y = None
    sx = sy = None
    first_z = None                     # 原刀路第一处「正 Z」= 它自己的抬刀高度
    for ln in lines[lift_i + 1:]:
        code, _c = _split_comment(ln)
        up = code.replace(" ", "").upper()
        if not up or "G53" in up or "G10" in up or "G92" in up:
            continue
        w = {}
        for L, v in WORD_RE.findall(code):
            w[L.upper()] = v
        if "X" in w:
            x = float(w["X"])
        if "Y" in w:
            y = float(w["Y"])
        if sx is None and x is not None and y is not None:
            sx, sy = x, y              # 第一处同时有 X/Y 的行 = 加工起点
        if first_z is None and "Z" in w:
            _z0 = float(w["Z"])
            if _z0 > 0:                # 只认抬刀高度；负的是切深，绝不能用 G0 快速下
                first_z = _z0
        if sx is not None and first_z is not None:
            break
    if sx is None and sy is None:
        warn("文件里没找到起点的 X/Y —— 只加了抬刀，没加「走到起点 / 下到起刀 Z」")
        return text
    block = ["G90 G0 X%.4f Y%.4f   (安全高度走到加工起点)" % (sx or 0.0, sy or 0.0)]
    _raw = str(start_z if start_z is not None else "").strip()
    z = None
    _auto = _raw == "" or _raw.lower() in ("auto", "自动")
    if not _auto:
        try:
            z = float(_raw)
        except Exception:
            warn("「起刀 Z」不是数字 —— 按「跟随原刀路」处理")
            _auto = True
    if _auto:
        z = first_z                   # 跟随原刀路自己的抬刀高度（如 Z5）
        if z is None:
            warn("原刀路里没找到正的 Z（抬刀高度）—— 只走到起点，下刀交给刀路自己")
    if z is not None:
        block.append("G90 G0 Z%.4f   (下到加工起始高度·工件坐标%s)"
                     % (z, "·跟随原刀路" if _auto else ""))
    if spindle:
        # 主轴在「下刀之后、第一刀之前」启动：抬刀/横移时不转更安全，
        # 同时保证无论原文件把 M3 写在哪一行，切削前一定是转的（Candle 跑同样如此）
        block.append("%s   (启动主轴)" % spindle)
        # 起转延时：主轴/变频器启动瞬间的电流冲击容易把 328p 板子搞复位
        # （用户报「无故复位、走飞」）。G4 不影响 Candle，GRBL 原生支持。
        block.append("G4 P0.8   (等主轴起转，防启动冲击复位)")
    return sep.join(lines[:lift_i + 1] + block + lines[lift_i + 1:])


def transform_gcode(text, theta=0.0, ox=0.0, oy=0.0, rotate=True,
                    translate=(0.0, 0.0), z_shift=0.0, z_override=None,
                    drop_tool_change=False, eol=None, warn=None, prelude=None):
    """刀路变换：P' = R(θ)·(P - 设计原点 O) + T

    - O = 设计原点（刀路文件里工件零点在哪，多数是 0,0）
    - T = 平移量。G54 模式填 (0,0)；无回零的机床坐标直出填实测中心 (Xc,Yc)
    - rotate=False 时只平移不旋转
    - z_shift: 所有 Z 加偏移（做空跑版就填 +5）
    - z_override: 把 Z<0（切削深度）改成该值，安全高度不动
    - drop_tool_change: 删掉 T/M6 换刀行（GRBL 可能报 error:20）
    只处理 G0/G1/G2/G3 的 X/Y 与圆弧 I/J；Z、F 原样（除非指定 z_shift/override）。
    G91 增量模式：向量只旋转，不平移。G53 行跳过并警告。
    """
    warn = warn or (lambda m: None)
    ct, st = math.cos(theta), math.sin(theta)
    if not rotate:
        ct, st = 1.0, 0.0
    tx, ty = float(translate[0]), float(translate[1])
    if eol is None:
        eol = "\r\n" if "\r\n" in text else "\n"

    # Z 覆盖 = 等比缩放到目标最深（保留分层结构，避免一刀到底断刀）
    z_scale = 1.0
    if z_override is not None:
        deepest = None
        for _raw in text.splitlines():
            _code, _c = _split_comment(_raw)
            for _L, _v in WORD_RE.findall(_code):
                if _L.upper() == "Z":
                    _z = float(_v)
                    if _z < 0 and (deepest is None or _z < deepest):
                        deepest = _z
        if deepest is None or abs(deepest) < 1e-9:
            warn("刀路里没有负 Z（切削深度），忽略「最深切到」设置")
            z_override = None
        else:
            z_scale = float(z_override) / deepest

    abs_mode = True
    _g91_warned = [False]
    cur = (0.0, 0.0)
    out = []
    if prelude:
        out.extend([str(x) for x in prelude] if not isinstance(prelude, str) else [prelude])

    for raw in text.splitlines():
        code, comment = _split_comment(raw)
        if not code.strip():
            out.append(raw.strip())      # 空行 / 纯注释行原样保留
            continue
        words = WORD_RE.findall(code)

        for L, v in words:
            if L.upper() == "G":
                g = float(v)
                if abs(g - 90.0) < 1e-9:
                    abs_mode = True
                elif abs(g - 91.0) < 1e-9:
                    abs_mode = False

        compact = code.replace(" ", "").upper()
        if "G53" in compact:
            warn("跳过 G53 行（机床坐标，不做变换）: " + raw.strip())
            out.append(raw.strip())
            continue
        # ---- v3.0：坐标系 / 回零 / 参数行一律不当刀路处理 ----
        # 「Z 补偿莫名其妙」的一大来源：源文件里若带 `G10 L2 P1 X0 Y0`（把 G54 归零），
        # 旧版把里面的 X0 Y0 当成刀路坐标去平移 → 变成 `G10 L2 P1 X<中心> Y<中心>`，
        # 跑起来 G54 被改写成中心坐标，整份刀路又偏一次；带 Z 的还会把 Z 零点改掉。
        if compact.startswith("$") or re.search(r"(?:^|[^0-9.])G(?:10|28|30|92)(?![0-9])", compact):
            if re.search(r"(?:^|[^0-9.])G10(?![0-9])", compact) and "L2" in compact:
                out.append("(v3.0 已屏蔽源文件里改写坐标系的 G10：%s)" % raw.strip())
                warn("源文件里的 G10（改写 G54）已屏蔽 —— 坐标基准只由本程序的文件头决定，"
                     "否则会和中心/Z 零点打架，表现就是「偶发整件偏 / 切深不对」")
            else:
                out.append(raw.strip())
                if any(c in compact for c in ("X", "Y", "Z")):
                    warn("坐标设置行保持原样（不旋转/不平移）: " + raw.strip())
            continue
        if drop_tool_change and ("M6" in compact or re.search(r"T\d", compact)):
            # 只删换刀词，同一行里的 S / M3 必须留着 ——
            # 用户报「生成的刀里主轴不转了」：整行删会把 T1M6 S15000 M3 的主轴指令一起删掉。
            keep = re.sub(r"T\d{1,2}", "", code, flags=re.I)
            keep = re.sub(r"M0?6", "", keep, flags=re.I)
            keep = " ".join(keep.split())
            if keep and re.search(r"[A-Za-z]", keep):
                out.append(keep + ((" " + comment) if comment else ""))
                warn("已去掉换刀词（同行其它指令保留）: %s → %s" % (raw.strip(), keep))
            else:
                warn("已移除换刀行: " + raw.strip())
            continue

        vals = {}
        for L, v in words:
            L = L.upper()
            if L in ("X", "Y", "Z", "I", "J") and L not in vals:
                vals[L] = float(v)

        newvals = {}
        if ("X" in vals) or ("Y" in vals):
            if abs_mode:
                x = vals.get("X", cur[0])
                y = vals.get("Y", cur[1])
                dx, dy = x - ox, y - oy
                newvals["X"] = ct * dx - st * dy + tx
                newvals["Y"] = st * dx + ct * dy + ty
                cur = (x, y)
            else:
                dx = vals.get("X", 0.0)
                dy = vals.get("Y", 0.0)
                newvals["X"] = ct * dx - st * dy
                newvals["Y"] = st * dx + ct * dy
                cur = (cur[0] + dx, cur[1] + dy)
        if "I" in vals or "J" in vals:
            ix, jy = vals.get("I", 0.0), vals.get("J", 0.0)
            newvals["I"] = ct * ix - st * jy
            newvals["J"] = st * ix + ct * jy
        if "Z" in vals:
            z = vals["Z"]
            if z_override is not None and z < 0:
                newvals["Z"] = z * z_scale
            elif abs_mode:
                newvals["Z"] = z + float(z_shift)
            else:
                # v3.0：G91 增量模式里 Z 是「相对上一行的增量」，
                # 加固定偏移会**每行都加一次** → 越走越高/越低。增量模式不加偏移。
                newvals["Z"] = z
                if abs(float(z_shift)) > 1e-9 and not _g91_warned[0]:
                    _g91_warned[0] = True
                    warn("刀路是 G91 增量模式：「整体偏移」会把每行都偏一次，已忽略（Z 保持原样）")

        if not newvals:
            out.append(raw.strip())
            continue

        used = set()

        def repl(m):
            L = m.group(1).upper()
            if L in newvals:
                if L in used:
                    return ""
                used.add(L)
                return L + _fmt(newvals[L])
            return m.group(0)

        new_code = WORD_RE.sub(repl, code)
        extra = ""
        for L in ("X", "Y", "I", "J", "Z"):
            if L in newvals and L not in used:
                extra += " " + L + _fmt(newvals[L])
                used.add(L)
        new_line = " ".join(new_code.split()) + extra
        if comment:
            new_line = new_line + " " + comment
        out.append(new_line)

    return eol.join(out) + eol


def z_levels(text):
    """刀路里所有负 Z（切削层），从小到大排"""
    zs = set()
    for raw in text.splitlines():
        code, _c = _split_comment(raw)
        for L, v in WORD_RE.findall(code):
            if L.upper() == "Z":
                z = float(v)
                if z < 0:
                    zs.add(round(z, 4))
    return sorted(zs)


def path_bbox(text):
    """刀路 XY 包围盒（只统计端点，圆弧外凸部分略小于实际）"""
    abs_mode = True
    cur = (0.0, 0.0)
    xs, ys = [], []
    for raw in text.splitlines():
        code, _c = _split_comment(raw)
        if not code.strip():
            continue
        up = code.upper()
        if up.lstrip().startswith("$") or "G10" in up or "G92" in up or "G28" in up or "G30" in up:
            continue          # 偏移/回零/复位类不改刀路位置，别把它们的 X0 Y0 算进包围盒
        words = WORD_RE.findall(code)
        for L, v in words:
            if L.upper() == "G":
                g = float(v)
                if abs(g - 90.0) < 1e-9:
                    abs_mode = True
                elif abs(g - 91.0) < 1e-9:
                    abs_mode = False
        vals = {}
        for L, v in words:
            L = L.upper()
            if L in ("X", "Y") and L not in vals:
                vals[L] = float(v)
        if not vals:
            continue
        if abs_mode:
            cur = (vals.get("X", cur[0]), vals.get("Y", cur[1]))
        else:
            cur = (cur[0] + vals.get("X", 0.0), cur[1] + vals.get("Y", 0.0))
        xs.append(cur[0])
        ys.append(cur[1])
    if not xs:
        return None
    return (min(xs), max(xs), min(ys), max(ys))


# ------------------------------------------------------------ 串口传输层 ----
import ctypes as _ct


class _WinDCB(_ct.Structure):
    """Win32 DCB（Windows 下 sizeof = 28）"""
    _fields_ = [
        ("DCBlength", _ct.c_uint32),
        ("BaudRate", _ct.c_uint32),
        ("flags", _ct.c_uint32),        # fBinary / fDtrControl / fRtsControl 等位域
        ("wReserved", _ct.c_uint16),
        ("XonLim", _ct.c_uint16),
        ("XoffLim", _ct.c_uint16),
        ("ByteSize", _ct.c_uint8),
        ("Parity", _ct.c_uint8),
        ("StopBits", _ct.c_uint8),
        ("XonChar", _ct.c_uint8),
        ("XoffChar", _ct.c_uint8),
        ("ErrorChar", _ct.c_uint8),
        ("EofChar", _ct.c_uint8),
        ("EvtChar", _ct.c_uint8),
        ("wReserved1", _ct.c_uint16),
    ]


class _WinCommTimeouts(_ct.Structure):
    """Win32 COMMTIMEOUTS（sizeof = 20）"""
    _fields_ = [
        ("ReadIntervalTimeout", _ct.c_uint32),
        ("ReadTotalTimeoutMultiplier", _ct.c_uint32),
        ("ReadTotalTimeoutConstant", _ct.c_uint32),
        ("WriteTotalTimeoutMultiplier", _ct.c_uint32),
        ("WriteTotalTimeoutConstant", _ct.c_uint32),
    ]


class WinSerial:
    """Windows 零依赖串口：ctypes 直接调 Win32 API

    用于装不上 pyserial 的工控机（很多精简系统 / 内网机）。接口与 pyserial 兼容：
    write(bytes) / read(n)->bytes / close() / is_open
    """

    GENERIC_READ = 0x80000000
    GENERIC_WRITE = 0x40000000
    OPEN_EXISTING = 3
    PURGE_ALL = 0x000F

    def __init__(self, port, baud=115200):
        if os.name != "nt":
            raise GrblError("内置串口只支持 Windows；其它系统请安装 pyserial")
        import ctypes

        self._ct = ctypes
        DWORD = ctypes.c_uint32
        LPVOID = ctypes.c_void_p
        k32 = ctypes.WinDLL("kernel32", use_last_error=True)
        self.k32 = k32
        k32.CreateFileW.restype = LPVOID
        k32.CreateFileW.argtypes = [ctypes.c_wchar_p, DWORD, DWORD, LPVOID, DWORD, DWORD, LPVOID]
        k32.ReadFile.argtypes = [LPVOID, LPVOID, DWORD, ctypes.POINTER(DWORD), LPVOID]
        k32.WriteFile.argtypes = [LPVOID, LPVOID, DWORD, ctypes.POINTER(DWORD), LPVOID]
        k32.CloseHandle.argtypes = [LPVOID]
        k32.GetCommState.argtypes = [LPVOID, ctypes.POINTER(_WinDCB)]
        k32.SetCommState.argtypes = [LPVOID, ctypes.POINTER(_WinDCB)]
        k32.SetCommTimeouts.argtypes = [LPVOID, ctypes.POINTER(_WinCommTimeouts)]
        k32.SetupComm.argtypes = [LPVOID, DWORD, DWORD]
        k32.PurgeComm.argtypes = [LPVOID, DWORD]

        path = "\\\\.\\" + port
        h = k32.CreateFileW(path, self.GENERIC_READ | self.GENERIC_WRITE, 0, None,
                            self.OPEN_EXISTING, 0, None)
        invalid = (None, 0, -1, 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
                   ctypes.c_void_p(-1).value)
        if h in invalid:
            err = ctypes.get_last_error()
            raise GrblError("打开 %s 失败（WinError %d）：%s"
                            % (port, err, "可能被其它程序占用（先关掉 Candle）" if err == 5 or err == 32 else "检查端口号"))
        self.h = h

        try:
            k32.SetupComm(h, 64 * 1024, 64 * 1024)
            dcb = _WinDCB()
            dcb.DCBlength = ctypes.sizeof(_WinDCB)
            if not k32.GetCommState(h, ctypes.byref(dcb)):
                raise GrblError("GetCommState 失败（WinError %d）" % ctypes.get_last_error())
            dcb.BaudRate = int(baud)
            dcb.ByteSize = 8
            dcb.Parity = 0        # NOPARITY
            dcb.StopBits = 0      # ONESTOPBIT
            # fBinary=1, fDtrControl=1, fRtsControl=1
            dcb.flags = 0x1 | (1 << 4) | (1 << 12)
            if not k32.SetCommState(h, ctypes.byref(dcb)):
                raise GrblError("SetCommState 失败（WinError %d，波特率 %s 可能不支持）"
                                % (ctypes.get_last_error(), baud))
            t = _WinCommTimeouts()
            t.ReadIntervalTimeout = 0xFFFFFFFF     # 有数据立刻返回
            t.ReadTotalTimeoutMultiplier = 0
            t.ReadTotalTimeoutConstant = 0
            t.WriteTotalTimeoutMultiplier = 0
            t.WriteTotalTimeoutConstant = 2000
            if not k32.SetCommTimeouts(h, ctypes.byref(t)):
                raise GrblError("SetCommTimeouts 失败（WinError %d）" % ctypes.get_last_error())
            k32.PurgeComm(h, self.PURGE_ALL)
        except Exception:
            self.close()
            raise
        self._open = True

    @property
    def is_open(self):
        return getattr(self, "_open", False)

    def write(self, data):
        if not self.is_open:
            raise GrblError("串口未打开")
        n = self._ct.c_uint32(0)
        buf = self._ct.create_string_buffer(bytes(data), len(data))
        ok = self.k32.WriteFile(self.h, buf, len(data), self._ct.byref(n), None)
        if not ok:
            raise GrblError("写串口失败（WinError %d）" % self._ct.get_last_error())
        return n.value

    def read(self, size=1024):
        if not self.is_open:
            return b""
        buf = self._ct.create_string_buffer(size)
        got = self._ct.c_uint32(0)
        ok = self.k32.ReadFile(self.h, buf, size, self._ct.byref(got), None)
        if not ok:
            raise GrblError("读串口失败（WinError %d）" % self._ct.get_last_error())
        return buf.raw[:got.value] if got.value else b""

    def close(self):
        if getattr(self, "_open", False):
            try:
                self.k32.CloseHandle(self.h)
            except Exception:
                pass
        self._open = False

    def reset_input_buffer(self):
        try:
            self.k32.PurgeComm(self.h, self.PURGE_ALL)
        except Exception:
            pass


class _PySerialTransport:
    """pyserial 的薄包装，接口与 WinSerial 一致"""

    def __init__(self, ser):
        self.s = ser

    @property
    def is_open(self):
        return self.s.is_open

    def write(self, data):
        return self.s.write(bytes(data))

    def read(self, size=1024):
        return self.s.read(size)

    def close(self):
        self.s.close()

    def reset_input_buffer(self):
        try:
            self.s.reset_input_buffer()
        except Exception:
            pass


def open_transport(port, baud=115200, log=None, force=None):
    """优先 pyserial；装不上时 Windows 走 ctypes 内置串口

    force="win32" 时强制用内置串口（排错用）
    """
    log = log or (lambda m: None)
    if force == "win32":
        log("强制使用内置串口（ctype/Win32，不依赖 pyserial）")
        return WinSerial(port, baud)
    try:
        import serial
    except Exception as e:
        serial = None
        log("未找到 pyserial（%s）" % e)
    if serial is not None:
        s = serial.Serial()
        s.port = port
        s.baudrate = baud
        s.timeout = 0.05
        s.write_timeout = 2
        s.open()
        return _PySerialTransport(s)
    if os.name == "nt":
        log("改用内置串口（不依赖 pyserial）")
        return WinSerial(port, baud)
    raise GrblError("缺少 pyserial，请执行： pip install pyserial")


def win_registry_ports():
    """读注册表 HARDWARE\\DEVICEMAP\\SERIALCOMM（Candle 的 .NET 也走这条路）"""
    if os.name != "nt":
        return []
    try:
        import winreg
    except Exception:
        return []
    out = []
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DEVICEMAP\SERIALCOMM")
    except OSError:
        return []
    i = 0
    while True:
        try:
            name, val, _t = winreg.EnumValue(key, i)
        except OSError:
            break
        out.append((str(val), name))
        i += 1
    try:
        winreg.CloseKey(key)
    except Exception:
        pass
    return out


def win_dos_ports():
    """QueryDosDevice 枚举所有 COM 设备名"""
    if os.name != "nt":
        return []
    try:
        import ctypes
        buf = ctypes.create_string_buffer(65536)
        n = ctypes.windll.kernel32.QueryDosDeviceA(None, buf, 65536)
        if not n:
            return []
        names = buf.raw[:n].split(b"\x00")
        out = []
        for b in names:
            sname = b.decode("ascii", "ignore").strip()
            if re.match(r"^COM\d+$", sname, re.I):
                out.append(sname.upper())
        return sorted(set(out))
    except Exception:
        return []


# ---------------------------------------------------------------- GRBL ----
STATUS_RE = re.compile(r"<([^|>]+)\|(?:MPos:([-\d.]+),([-\d.]+),([-\d.]+))?")
WCO_RE = re.compile(r"WCO:([-\d.]+),([-\d.]+),([-\d.]+)")


class GrblError(Exception):
    pass


class GrblLink:
    """真实 GRBL 串口连接"""

    def __init__(self, port, baud=115200, log=None, transport=None):
        self.log = log or (lambda m: None)
        try:
            self.ser = open_transport(port, baud, log=self.log, force=transport)
        except GrblError:
            raise
        except Exception as e:
            raise GrblError("打开串口 %s 失败：%s（是否被 Candle 占用？先把 Candle 断开）" % (port, e))

        self._port = port
        self._baud = baud
        self._transport = transport
        self._lock = threading.Lock()
        self._rx_ts = time.time()      # 最后一次收到任何串口数据的时刻（判链路死活用）
        self._need_reconnect = False   # 读线程判定链路死 → 主线程执行重连
        self.poll_sec = POLL_SEC       # R2.3：加工期间降频（0.5s）减轻 328p 负担
        self._dead_logged = False
        self._io_err_ts = 0.0          # 读/写异常日志限频
        self._state = "Unknown"
        self._mpos = None
        self._wco = None
        self._g54 = None
        self._g92 = None          # Candle「设零」写的是 G92，会叠在 G54 上
        self._buf = ""
        self._stop = threading.Event()
        self._th = threading.Thread(target=self._reader, daemon=True)
        self._msg_cb = None
        # 点动流控：只保留"最新意图"，由读线程按节拍发出去
        self._jog_req = None          # [axis, delta, feed]
        self._jog_lock = threading.RLock()
        self._jog_last = 0.0
        self._jog_sent = 0            # 实际发出去的条数（调试/诊断）
        self._jog_merged = 0          # 被合并掉的次数
        self._jog_expect = None       # 点动看门狗：[轴, 起点, 应该走多少, 最后更新时刻]
        self._cont = None            # 连续点动监控：[轴, 起点, 起始时刻, 速度mm/s, 本次行程]
        # R2.5：软限位相关已全部移除（用户机床没有限位/没设行程，按行程算余量反而会挡住点动）
        # R2.5：断线/复位后「坐标续接」——板子重启会把 MPos 归零，但刀头若没动物理位置没变，
        #       就把断开前最后一次真实坐标当作偏移补回去，碰点数据直接续用。
        self.pos_offset = [0.0, 0.0, 0.0]     # 原始 MPos + 偏移 = 真实机床坐标
        self._raw_mpos = None                 # 板子自己报的原始 MPos（没加偏移）
        self._pos_pending_resume = None       # 待验证的续接坐标（复位/断线前最后一次真实坐标）
        self._resume_notice = None            # 给界面的一次性提示（取走即清）
        self._was_jogging_at_reset = False
        self.grbl_cfg = {}                    # R2.5：$$ 里的关键项（20/21/22/130/131/132），只做诊断
        self.soft_limit_notified = False
        self._reset_cnt = 0          # R1.4：收到 Grbl 欢迎串（上电/软复位）的次数
        self.on_reset = None         # R1.4：复位回调（主界面用来停用旧坐标）
        self._mpos_ts = 0.0          # 坐标最后一次「真的变了」的时刻（判点动是否卡住）
        self._jog_req_ts = 0.0       # 最近一次点动请求的时刻（诊断用，不再当 Jog 等待基准）
        self._reader_hb = 0.0        # R2.6：读取线程心跳（界面据此判断线程是否还活着）
        self._reader_err_ts = 0.0    # R2.6：上次记录读取线程异常的时刻（限频）
        self._jog_drop_stuck = 0     # R2.6：因为「机床停在 Jog」被挡下的次数（诊断）
        self._jog_stuck_ts = 0.0     # 上次因「卡在 Jog」补发停止的时刻（限频）
        self._cancel_last = 0.0      # 上一次真正发出 0x85 的时刻
        self._cancel_pending = False # 去重窗口内被挡下的 cancel：必须补发，不能丢
        self._cancel_rep = 0         # 已发出 0x85 后还要补发几次（串口丢字节/GRBL 漏读的兜底）
        self._cancel_probe = None    # 松手后滑行诊断：[轴, 松手时的坐标, 松手时刻]
        self._ok_pending = 0          # 已发未 ack 的命令数
        self.no_jog = False           # 发送加工中置 True：禁止点动（$J 会打断正在走的刀路）
        self._no_jog_logged = False
        self.acks = queue.Queue()     # 每个 ok/error 入队：发送器靠它做字符计数
        self._pending_ts = 0.0        # 开始堆积的时间（用于超时自愈）
        self._err_cnt = 0
        time.sleep(0.25)

    # -- 生命周期 --
    def start(self):
        if not self._th.is_alive():
            self._th.start()

    def stop(self):
        self._stop.set()
        try:
            self.ser.close()
        except Exception:
            pass

    def connected(self):
        return self.ser.is_open

    # -- 读线程 --
    def _reader(self):
        next_poll = 0.0
        while not self._stop.is_set():
            self._reader_hb = time.time()
            try:
                now = time.time()
                if now >= next_poll:
                    try:
                        with self._lock:
                            self.ser.write(b"?")
                    except Exception:
                        pass
                    next_poll = now + float(getattr(self, "poll_sec", POLL_SEC) or POLL_SEC)
                    # v1.39.3：问了两秒一句都不回 → 链路死了（USB 掉线 / 板子复位）
                    # 以前这种情况下软件会一直往死链路写，界面只是「点不动」，看不出原因
                    if now - (self._rx_ts or 0.0) > 6.0:
                        if not self._dead_logged:
                            self._dead_logged = True
                            self.log("！串口 6 秒没有任何回应（USB 掉了 / 板子复位 / 被别的软件抢走）"
                                     " —— 正在自动重连，重连后会提示核对刀位")
                        self._need_reconnect = True
                try:
                    self._flush_jog(now)
                except Exception:
                    pass
                try:
                    # 去重窗口内被挡下的 cancel 要补发：0x85 是「停」的唯一手段，
                    # 吞掉一次就等于让那条长行程 jog 自己走完（点动跑飞的来源之一）
                    if self._cancel_pending and now - self._cancel_last >= 0.07:
                        self._cancel_pending = False
                        self._cancel_last = now
                        self._raw_cancel()
                    elif self._cancel_rep > 0 and now - self._cancel_last >= 0.10:
                        self._cancel_rep -= 1
                        self._cancel_last = now
                        self._raw_cancel()
                    if self._cancel_probe and self._mpos is not None:
                        pb = self._cancel_probe
                        _allow = float(pb[4]) if len(pb) > 4 else 8.0
                        if now - pb[2] >= 0.55:
                            slid = abs(self._mpos[_AXI.get(pb[0], 0)] - pb[1])
                            st_now = str(self._state).lower()
                            moving = st_now.startswith("jog") or st_now.startswith("run")
                            if moving and slid > _allow and pb[3] < 4:
                                # 超过这台机器正常的减速距离还在走 —— 才是停止信号真丢了
                                pb[3] += 1
                                pb[1] = self._mpos[_AXI.get(pb[0], 0)]
                                pb[2] = now
                                self._raw_cancel()
                                self.log("！松手后走了 %.1fmm 还在动（超过正常减速 %.1fmm）—— 已补发停止"
                                         % (slid, _allow))
                            else:
                                self._cancel_probe = None      # 正常减速停住：不刷日志
                except Exception:
                    pass
                try:
                    chunk = self.ser.read(1024)
                except Exception as e:
                    # 以前这里静默 continue —— USB 掉了以后软件照旧往死链路写，没人知道
                    _n = time.time()
                    if _n - self._io_err_ts > 3.0:
                        self._io_err_ts = _n
                        self.log("！串口读失败：%s —— 链路可能已断，正在自动重连" % e)
                    time.sleep(0.05)
                    continue
                if not chunk:
                    time.sleep(0.005)
                    continue
                self._rx_ts = time.time()
                self._dead_logged = False
                self._buf += chunk.decode("utf-8", "ignore")
                while "\n" in self._buf:
                    line, self._buf = self._buf.split("\n", 1)
                    line = line.strip()
                    if not line:
                        continue
                    if line.startswith("<"):
                        m = STATUS_RE.search(line)
                        if m:
                            self._state = m.group(1)
                            if m.group(2) is not None:
                                self._apply_mpos((float(m.group(2)), float(m.group(3)),
                                                  float(m.group(4))))
                            w = WCO_RE.search(line)
                            if w:
                                self._wco = (float(w.group(1)), float(w.group(2)), float(w.group(3)))
                    elif line.startswith("Grbl"):
                        # R1.4：上电 / 软复位（Ctrl-X）—— 机床坐标归零，G92 清空
                        # R2.5：先记下复位前的真实坐标，等第一帧 ? 回来判断能不能续接
                        try:
                            if self._mpos is not None:
                                self._pos_pending_resume = tuple(float(v) for v in self._mpos)
                                self._was_jogging_at_reset = bool(self._cont)
                        except Exception:
                            self._pos_pending_resume = None
                        self._reset_cnt += 1
                        self._mpos = None
                        self._wco = None
                        self._g54 = None
                        self._g92 = None
                        self.log("⚠ 机床复位了（%s）—— 机床坐标已归零（没回零前所有绝对坐标都不可信）"
                                 % line.strip())
                        _cb = self.on_reset
                        if _cb:
                            try:
                                _cb()
                            except Exception as e:
                                self.log("（复位回调出错：%s）" % e)
                    elif line.lower() == "ok":
                        self._ok_pending = max(0, self._ok_pending - 1)
                        self.acks.put(("ok", line))
                    elif line.lower().startswith("error") or line.lower().startswith("alarm"):
                        self._ok_pending = max(0, self._ok_pending - 1)
                        self._err_cnt += 1
                        self.acks.put(("error", line))
                        self.log(line + ("   ← 命令被拒（点动已自动降频；多次出现请点「■ 停止」再连一次）"
                                         if line.lower().startswith("error") else ""))
                    elif line.lower().startswith("[msg"):
                        self.log(line)
                    elif line.startswith("[") and "G54:" in line:
                        m54 = re.search(r"G54:([-\d.]+),([-\d.]+),([-\d.]+)", line)
                        if m54:
                            self._g54 = tuple(float(m54.group(i)) for i in (1, 2, 3))
                            self.log("核对 G54 偏移：X=%.4f Y=%.4f Z=%.4f" % self._g54)
                    elif line.startswith("[") and "G92:" in line:
                        m92 = re.search(r"G92:([-\d.]+),([-\d.]+),([-\d.]+)", line)
                        if m92:
                            self._g92 = tuple(float(m92.group(i)) for i in (1, 2, 3))
                            if max(abs(self._g92[0]), abs(self._g92[1])) > 0.001:
                                self.log("⚠ 检测到 G92 残留：X=%.4f Y=%.4f —— 它会叠在 G54 上，"
                                         "发 G92.1 或软复位清掉" % (self._g92[0], self._g92[1]))
                            else:
                                self.log("G92：无残留")
                    elif line.startswith("$") and "=" in line:
                        # R2.5：只收关键设置项（软限位/回零/行程），其余 $$ 行不刷日志
                        _ms = re.match(r"\$(\d+)=([-\d.]+)", line)
                        if _ms:
                            _k = int(_ms.group(1))
                            if _k in (20, 21, 22, 120, 121, 122, 130, 131, 132):
                                try:
                                    self.grbl_cfg[_k] = float(_ms.group(2))
                                except Exception:
                                    pass
                    elif line.startswith("["):
                        # $I（固件信息）/ $G（模态）/ $#（偏移）等原始回复，以前会被丢掉
                        self.log(line)
            except Exception as _e:
                # 读取线程绝不退出：解析异常只跳过这一轮继续跑。
                # 以前这里一抛异常线程就死了 —— 症状正是「状态不再刷新、点动怎么点都不动，只能复位」。
                _now = time.time()
                if _now - getattr(self, "_reader_err_ts", 0.0) > 3.0:
                    self._reader_err_ts = _now
                    try:
                        self.log("！读取线程异常（已跳过继续运行，点动不受影响）：%s" % _e)
                    except Exception:
                        pass
                time.sleep(0.05)
    # -- 状态 --
    def status(self):
        return {"state": self._state, "mpos": self._mpos, "wco": self._wco,
                "g54": self._g54, "g92": self._g92}

    def mpos(self):
        return self._mpos

    def mpos_mach(self):
        """**真机床坐标**（不含「设 0 点（显示清零）」的显示偏移）。

        R2.9：凡是要发 G53、或者存起来以后拿去发 G53 的值（安全 Z、靠边位置、中心），
        一律用这个口径。用显示值发 G53 会整体差一个偏移量 —— 设过 0 点以后抬刀
        会朝一个超行程的绝对坐标走，一路顶到限位（用户实测踩过）。
        """
        r = getattr(self, "_raw_mpos", None)
        if r is not None:
            return (float(r[0]), float(r[1]), float(r[2]))
        return self._mpos

    # -- 指令 --
    def _raw_send(self, text, log_it=True, expect_ok=True):
        if not self.ser.is_open:
            self._need_reconnect = True
            raise GrblError("串口连接已断开 —— 正在自动重连")
        try:
            with self._lock:
                self.ser.write(text.encode("ascii", "ignore"))
        except Exception as e:
            # USB 掉了 / 驱动卡住：写失败以前是静默的，人只看到「点不动」
            now = time.time()
            if now - self._io_err_ts > 3.0:
                self._io_err_ts = now
                self.log("！串口写失败：%s（USB 线 / 供电干扰）—— 正在自动重连" % e)
            self._need_reconnect = True
            raise GrblError("串口写失败（USB 掉线）")
        if expect_ok:
            # ⚠ `$J=`（点动）GRBL 只回状态、不回 ok —— 把它算进来会让 _ok_pending 只增不减，
            #   3 条以后点动全被流控挡住（现象：点几下就不动了，过 1.5 秒又能点）。
            self._ok_pending += 1
        if log_it:
            self.log("> " + text.rstrip("\n"))

    def send(self, cmd, log_it=True):
        self._raw_send(cmd + "\n", log_it=log_it)

    def reconnect(self, wait=0.5):
        # R2.5：重连会复位板子（DTR），先把断线时的真实坐标存起来，重连后试着续上
        try:
            if self._mpos is not None and self._pos_pending_resume is None:
                self._pos_pending_resume = tuple(float(v) for v in self._mpos)
                self._was_jogging_at_reset = bool(self._cont)
        except Exception:
            pass
        return self._reconnect_impl(wait)

    def _apply_mpos(self, raw):
        """R2.5：一帧 MPos 进来 —— 先判「板子是否刚重启过」，再加坐标续接偏移。

        为什么需要：没装限位/没开回零的机器，一软复位 MPos 就全变 0，但刀头其实没动。
        把断开前最后一次真实坐标存成偏移补回去，碰点/靠边位置全部还能用。
        """
        raw = (float(raw[0]), float(raw[1]), float(raw[2]))
        self._raw_mpos = raw
        if self._pos_pending_resume is not None:
            _before = tuple(float(v) for v in self._pos_pending_resume)
            self._pos_pending_resume = None
            if all(abs(raw[_i]) < 0.5 for _i in range(3)):
                # 坐标被清零 = 板子重启过 → 按断开前的位置接回来
                self.pos_offset = [_before[0], _before[1], _before[2]]
                self._resume_notice = {"status": "resumed", "before": _before,
                                       "jog": bool(self._was_jogging_at_reset)}
            else:
                # 板子报了真实坐标（装了回零/真的回零过）→ 以板子为准，偏移清零
                self.pos_offset = [0.0, 0.0, 0.0]
                self._resume_notice = {"status": "valid", "before": _before, "now": raw}
        _off = self.pos_offset
        new = (raw[0] + _off[0], raw[1] + _off[1], raw[2] + _off[2])
        if self._mpos is None or any(abs(new[_i] - self._mpos[_i]) > 0.0005 for _i in range(3)):
            self._mpos_ts = time.time()
        self._mpos = new
        return new

    def restart_reader(self):
        """R2.6：读取线程卡死/异常退出后重启（不重连串口、不动坐标）。"""
        try:
            self._stop.set()
        except Exception:
            pass
        time.sleep(0.08)
        self._stop = threading.Event()
        self._th = threading.Thread(target=self._reader, daemon=True)
        self._th.start()
        self._reader_hb = time.time()
        self.log("读取线程已重启（串口没断、坐标没动）—— 点动应恢复")

    def jog_diag(self):
        """R2.6：点动不动时给一句能拿去定位的话。"""
        try:
            hb = time.time() - (getattr(self, "_reader_hb", 0.0) or 0.0)
        except Exception:
            hb = -1
        try:
            thread_alive = bool(getattr(self, "_th", None) and self._th.is_alive())
        except Exception:
            thread_alive = False
        return ("已发 %d 条 / 合并 %d 次 / 被Jog挡%d次 / 状态=%s / ok待=%d / "
                "线程%s(%.1fs前)" % (
                    int(getattr(self, "_jog_sent", 0)), int(getattr(self, "_jog_merged", 0)),
                    int(getattr(self, "_jog_drop_stuck", 0)), str(self._state),
                    int(self._ok_pending or 0), "活" if thread_alive else "死", hb))

    def take_resume_notice(self):
        """R2.5：取走一次性提示（界面用）。None = 没有需要确认的事。"""
        n = self._resume_notice
        self._resume_notice = None
        return n

    def clear_pos_offset(self):
        """R2.5：刀头被推过了 —— 丢掉续接偏移，坐标回到板子自己报的（需重新对零）。"""
        self.pos_offset = [0.0, 0.0, 0.0]
        self._raw_mpos = None
        self._mpos = None
        self._mpos_ts = 0.0
        try:
            self.log("已清除坐标续接 —— 现在显示的是板子原始坐标，请重新对零后再碰点")
        except Exception:
            pass

    def _reconnect_impl(self, wait=0.5):
        """链路死掉后的自救：先尽力停住运动，再关/开串口（DTR 会把 GRBL 复位）。

        为什么敢这么做：卡在 Jog / 半截命令时，只有复位板子能救；
        G54/WCS 存在 EEPROM 里不会丢，刀位要操作员自己核。
        """
        try:
            self.feed_hold()
        except Exception:
            pass
        try:
            self.jog_cancel()
        except Exception:
            pass
        time.sleep(0.12)
        try:
            self.ser.close()
        except Exception:
            pass
        time.sleep(wait)
        self.ser = open_transport(self._port, self._baud, log=self.log, force=self._transport)
        self._buf = ""
        self._ok_pending = 0
        self._pending_ts = 0.0
        self._cont = None
        self._jog_req = None
        self._jog_expect = None
        self._state = "Unknown"
        self._rx_ts = time.time()
        self._dead_logged = False
        self._need_reconnect = False
        self.log("✓ 串口已自动重连（板子已复位：G54/WCS 不会丢，但刀位请自己核一下，"
                 "必要时重新对刀）")
        try:
            self.query_offsets()
        except Exception:
            pass

    def _flush_jog(self, now=None):
        """把"最新点动意图"按节拍发出去（限频 + 限未应答数），避免把 GRBL 缓冲塞爆"""
        with self._jog_lock:
            req = self._jog_req
            if req is None:
                return
            now = now or time.time()
            # v1.39.2 ①：小步长（0.01/0.02…）别 60ms 一条 —— 每条 $J 都会 cancel 上一条，
            # GRBL 的 cancel 风暴会把状态卡在 Jog，之后点动全部被忽略（必须断串口重连）。
            # 降到 150ms 一条，连点会被下面的合并逻辑收成一条，位移照样准。
            _gap = JOG_MIN_GAP
            try:
                if abs(float(req[1])) < 0.05:
                    _gap = 0.15
            except Exception:
                pass
            if now - self._jog_last < _gap:
                return
            # R2.6 ★点动假死真因：GRBL 还在 Jog/减速时别插队（新 $J 会取消当前这条），
            # 但**基准必须是「上次真正发出去的时刻」**，不能是「上次请求的时刻」——
            # 用请求时刻的话，手一直在点就会不停刷新它，`now - req_ts` 永远≈0，
            # 于是一条都发不出去：连点半天没反应，停手 0.8 秒才动一下，只能复位。
            try:
                if str(self._state).lower().startswith("jog"):
                    if now - (self._jog_last or 0.0) < 0.6:
                        self._jog_drop_stuck = int(getattr(self, "_jog_drop_stuck", 0)) + 1
                        return
            except Exception:
                pass
            if self._ok_pending >= JOG_MAX_PENDING:
                # 卡住自愈：GRBL 迟迟不回 ok（忙 / 半截命令 / 串口丢字节）时不能永久挡住点动
                if self._pending_ts == 0.0:
                    self._pending_ts = now
                    return
                if now - self._pending_ts <= 1.5:
                    return
                self._ok_pending = 0
                self._pending_ts = 0.0
                self._jog_last = now + 0.3      # 冷却 300ms，别一重置就猛发把缓冲塞爆
                self.log("！1.5 秒没收到 ok，已重置发送流控（若还不动：点「■ 停止」→ 断开重连；"
                         "别点软复位，会丢机床坐标）")
            else:
                self._pending_ts = 0.0
            if self.no_jog:
                # 发送加工中：$J 是实时点动，会直接打断正在走的刀路
                self._jog_req = None
                if not self._no_jog_logged:
                    self._no_jog_logged = True
                    self.log("发送加工中：点动已忽略（先「■ 停止」才能手动移动）")
                return
            if self.is_alarm():
                self._jog_req = None
                return
            self._jog_req = None
            try:
                if self._jog_expect and self._mpos is not None:
                    self._jog_expect[1] = self._mpos[_AXI.get(self._jog_expect[0], 0)]
                    self._jog_expect[3] = now
            except Exception:
                pass
            self._jog_last = now
            self._jog_sent += 1
            # v1.39.4（重要）：马上要发新的点动了 —— 「停止补发」必须作废。
            # 否则上一次松手残留的 0x85 会把这一条新 jog 取消掉（现象：按几下就不走了）
            self._cancel_rep = 0
            self._cancel_pending = False
            self._cancel_probe = None
            axis, delta, feed = req
        if abs(delta) < 1e-6:
            return
        self._raw_send("$J=G91 %s%.3f F%.0f\n" % (axis.upper(), delta, feed),
                       log_it=False, expect_ok=False)

    def jog(self, axis, delta, feed=100, cont=False):
        """点动：只提交"最新意图"，由读线程节流发出。

        快速连点会合并成一条（同向累加 / 反向抵消），既不会堵串口，也不会排队跑很久。
        """
        if self._need_reconnect or (time.time() - (self._rx_ts or 0.0) > 6.0 and not self._stop.is_set()):
            raise GrblError("串口没回应（USB 掉线）—— 正在自动重连，等 1~2 秒再点")
        if self.is_alarm():
            raise GrblError("机床处于 %s 状态 —— 先点「解锁 $X」再点动" % self._state)
        # R2.5：卡在 Hold（按过暂停/停止、或 GRBL 自己进了 hold）时 $J 发进去也不动，
        # 表现就是「点动假死、怎么点都没反应」。这里先发 ~ 把它放出来再点。
        try:
            if str(self._state).lower().startswith("hold"):
                now = time.time()
                if now - (getattr(self, "_hold_release_ts", 0.0) or 0.0) > 0.6:
                    self._hold_release_ts = now
                    with self._lock:
                        self.ser.write(b"~")
                    self.log("机床停在 Hold（暂停态）—— 已发 ~ 放出来，再点一次就能动")
        except Exception:
            pass
        axis = axis.upper()
        if cont:
            # 连续点动：直接发一条长行程 jog（靠 0x85 停），全程匀速不顿
            with self._jog_lock:
                self._jog_req = None
            # R2.5：不再按软限位余量裁剪（机床没设行程，算出来会挡点动）
            base = None if self._mpos is None else self._mpos[_AXI.get(axis, 0)]
            # 第 5 项 = 这条命令实际要走的行程：看门狗拿它当硬上限，
            # 万一把 0x85 弄丢了也只会多走这么点，不会一路跑飞
            self._cont = [axis, base, time.time(), abs(float(feed)) / 60.0,
                          abs(float(delta))]
            self._jog_expect = None
            # v1.39.4：同上 —— 松手后残留的停止补发不能杀新发的这条长 jog
            self._cancel_rep = 0
            self._cancel_pending = False
            self._cancel_probe = None
            self._raw_send("$J=G91 %s%.3f F%.0f\n" % (axis, delta, float(feed)),
                           log_it=False, expect_ok=False)
            self._jog_sent += 1
            return
        with self._jog_lock:
            cur = self._jog_req
            # 合并上限按「步长的 4 倍」算：连点合并出来的跨度不会一下跳出 4 个步长
            lim = min(JOG_MAX_STEP, max(1.0, abs(delta) * 4.0))
            if cur is not None and cur[0] == axis and abs(float(feed) - cur[2]) < 1e-6:
                total = cur[1] + delta
                total = max(-lim, min(lim, total))
                self._jog_req = [axis, total, float(feed)]
                self._jog_merged += 1
            else:
                d = max(-lim, min(lim, delta))
                self._jog_req = [axis, d, float(feed)]
            self._jog_req_ts = time.time()      # 诊断用
            self._cancel_probe = None           # R2.7：又按下了 → 之前松手留下的补停不再需要
            # 看门狗：记下「按意图应该走多少」，实际走超了就急停
            # （串口丢一个字节能把 X1.000 变成 X1000，这种只能靠实测位移兜住）
            if self._mpos is not None:
                i = _AXI.get(axis, 0)
                e = self._jog_expect
                if e is None or e[0] != axis or time.time() - e[3] > 1.5:
                    self._jog_expect = [axis, self._mpos[i], float(delta), time.time()]
                else:
                    e[2] += float(delta)
                    e[3] = time.time()
        self._flush_jog()

    def jog_watchdog(self, tol=6.0):
        """点动看门狗：实际位移比「意图」多出 tol 以上就返回 (多走了多少, 轴)，正常返回 None。

        R2.7：tol 2mm → 6mm。这台机加速度低，松手后正常减速滑行就有 4~6mm，
        2mm 会把正常滑行判成「点动失控」，反而把人吓得去复位。真丢字节是上百毫米，6mm 照样抓得住。

        为什么需要：`$J=G91 X1.000 F100` 在串口上丢一个字节就可能变成 `X1000`，
        一条命令就能把刀送出 1 米远 —— 发出去之前怎么钳制都没用，只能靠实测位移兜底。
        """
        c = self._cont
        if c and self._mpos is not None:
            # 连续点动：按「按住时长 × 速度」算允许跑多远，超 1.6 倍 + 3mm 判失控；
            # 再加一道硬上限 —— 这条 jog 只有 seg 那么长，超 seg+3mm 必是没停住
            axis, base, t0, sp = c[0], c[1], c[2], c[3]
            seg = c[4] if len(c) > 4 else None
            if time.time() - t0 > 45:
                self._cont = None
            elif base is not None:
                moved = abs(self._mpos[_AXI.get(axis, 0)] - base)
                allowed = (time.time() - t0) * sp * 1.6 + 3.0
                if seg:
                    allowed = min(allowed, seg + 3.0)
                if moved > allowed:
                    return (moved - allowed, axis)
                return None
        e = self._jog_expect
        if not e or self._mpos is None:
            return None
        if time.time() - e[3] > 1.5:       # 早就停了，别拿旧期望误报
            self._jog_expect = None
            return None
        axis, base, want = e[0], e[1], e[2]
        moved = self._mpos[_AXI.get(axis, 0)] - base
        over = abs(moved) - abs(want)
        if over > tol:
            return (over, axis)
        return None

    def jog_expect_reset(self):
        self._jog_expect = None
        self._cont = None

    def jog_cancel(self):
        """取消点动：丢掉还没发的意图 + 发 0x85。

        去重窗口（60ms）内重复请求**不丢弃**，而是记成待补发、由读线程在 70ms 后发出。
        以前这里直接 return —— 结果是「0x85 没发、_cont 已清」，机器一路把长行程走完，
        而看门狗因为 _cont 没了也不管了。这就是点动偶尔跑飞的一条真实路径。
        """
        c = self._cont
        with self._jog_lock:
            self._jog_req = None
        self._cont = None
        if c and self._mpos is not None:
            # R2.7：松手后机床要减速停住，滑多远由「速度²/(2×加速度)」决定。
            # F800 + $120=50 约滑 1.8mm，$120=10 能滑 9mm —— 以前固定 3mm 就判「停止信号丢了」，
            # 于是每次松手都误补 0x85，而补发出去的 0x85 又会把紧接着的下一次点动取消掉（点动卡掉）。
            _i = _AXI.get(c[0], 0)
            try:
                _sp = float(c[3]) if len(c) > 3 else 0.0                 # mm/s
                _acc = float((self.grbl_cfg or {}).get(120 + min(_i, 2), 0) or 0) or 50.0
                _allow = (_sp * _sp) / (2.0 * _acc) * 2.0 + 3.0          # 理论滑行 ×2 + 3mm 余量
            except Exception:
                _allow = 8.0
            self._cancel_probe = [c[0], self._mpos[_i], time.time(), 0, max(6.0, _allow)]
        if not self.ser.is_open:
            return
        now = time.time()
        if now - self._cancel_last < 0.06:
            self._cancel_pending = True      # 不能丢：交给读线程补发
            return
        self._cancel_last = now
        self._cancel_pending = False
        self._cancel_rep = 1                 # v1.39.4：补 1 发（补 2 发会越过下一次点动把它取消）
        self._raw_cancel()

    def _raw_cancel(self):
        """发 0x85。串口偶发写超时不能只发一次就算了 —— 丢了就是「刹不住」。"""
        err = None
        for i in range(4):
            try:
                with self._lock:
                    self.ser.write(b"\x85")
                return True
            except Exception as _e:
                err = _e
                time.sleep(0.03 * (i + 1))
        try:
            self.log("！点动停止信号发了 4 次都没成功（%s）—— 立刻按 Esc 或点「■ 停止」" % err)
        except Exception:
            pass
        return False

    def recover_jog(self):
        """点动通道急救（R1.5）：不动坐标、不停摆、不重连 —— 只把卡住的状态放出来。

        何时用：按住/连点后突然点不动（状态卡在 Jog，或发送流控被卡住）。
        做什么：清流控计数、清点动意图、发 0x85 放掉卡着的 jog、再问一次状态。
        """
        self._ok_pending = 0
        self._pending_ts = 0.0
        self._jog_req = None
        self._cont = None
        self._jog_expect = None
        self._cancel_pending = False
        self._cancel_rep = 0
        self._cancel_probe = None
        self._jog_last = 0.0
        self._jog_stuck_ts = 0.0
        self._no_jog_logged = False
        self._jog_sent = 0
        self._jog_merged = 0
        if not self.ser.is_open:
            raise GrblError("串口已断开 —— 请重新点「连接」")
        self._raw_cancel()              # 放掉卡住的 jog（带重试，丢了就是「刹不住」）
        try:
            with self._lock:
                self.ser.write(b"?")    # 立刻问一次状态
        except Exception:
            pass
        self.log("✓ 点动通道已恢复（发 0x85 + 状态查询；坐标没动，不需要重新对刀）")

    def feed_hold(self):
        """实时命令 !：运动中也能发，平滑停住（实时命令不带换行）"""
        with self._lock:
            self.ser.write(b"!")
        self.log("已发 feed hold（! 平滑停住）")

    def resume_run(self):
        """实时命令 ~：从 feed hold 继续"""
        with self._lock:
            self.ser.write(b"~")
        self.log("已发 resume（~ 继续）")

    def jog_z(self, dz, feed=400):
        """只动 Z 的抬刀/下刀。用 $J（jog）而不是 G91 G0：
        jog 不改 G90/G91 模态，抬完不会影响后面整份刀路。"""
        self._raw_send("$J=G21G91 Z%.3f F%.0f\n" % (float(dz), float(feed)),
                       log_it=False, expect_ok=False)
        return float(dz)

    def soft_reset(self):
        with self._lock:
            self.ser.write(b"\x18")

    def is_alarm(self):
        return str(self._state).lower().startswith("alarm")

    def running_now(self):
        """机床是否真的在动：状态 Run/Jog，且最近 0.6 秒坐标在变"""
        s = str(self._state).lower()
        if not (s.startswith("run") or s.startswith("jog")):
            return False
        return (time.time() - (self._mpos_ts or 0.0)) < 0.6

    def unlock(self):
        """解除报警锁：GRBL 上电 / 急停 / 软限位触发后都停在 Alarm，
        不解锁则点动和刀路一律不执行。发 $X 清锁（位置不变、不回零）。"""
        self.send("$X")
        self.log("已发送 $X（解锁 Alarm；位置不变，不影响当前机床坐标）")

    def home(self):
        self.send("$H")

    def goto(self, x, y, feed=None):
        """走到指定 XY（Z 不动）。feed=None 用 G0。

        ⚠ 必须用 G53（机床绝对坐标）：碰边记的是 MPos，若按工作坐标发，
        残留的 G54/G92 偏移会让刀走偏「偏多少走多远」，偏大了直接撞限位跑飞。
        """
        if self.is_alarm():
            raise GrblError("机床处于 %s 状态 —— 先点「解锁 $X」，否则不会动" % self._state)
        # 先 G90：万一机床停在 G91（相对）模式，G53 G0 会被当成相对移动，直接跑飞
        if feed:
            self.send("G90 G53 G1 X%.4f Y%.4f F%.0f" % (x, y, feed))
        else:
            self.send("G90 G53 G0 X%.4f Y%.4f" % (x, y))

    def set_g54(self, x, y):
        if self._g54 is None:                 # 先拿到当前 Z 偏移，避免被 G10 清 0
            self.query_offsets()
            t0 = time.time()
            while self._g54 is None and time.time() - t0 < 1.0:
                time.sleep(0.02)
        gz = self._g54[2] if self._g54 else None
        self.send(g10_cmd((x, y), z=gz))
        self.send("G54")          # 切换一次坐标系，让当前 WCO 立即刷新（空操作，不移动）
        if gz is None:
            self.log("已写入 G54：X=%.4f Y=%.4f（⚠ 没读到原 Z 偏移，Z 可能被清 0，请重新确认对刀 Z）" % (x, y))
        else:
            self.log("已写入 G54：X=%.4f Y=%.4f Z=%.4f（Z 保持不动，存 EEPROM）" % (x, y, gz))

    def query_offsets(self):
        self.send("$#")

    def close(self):
        self.stop()


class MockLink:
    """模拟 GRBL：没有硬件时用，坐标是虚拟的，可演示整个流程"""

    def __init__(self, pos=(0.0, 0.0, 0.0), log=None):
        self._pos = list(pos)
        self.log = log or (lambda m: None)
        self._state = "Idle"
        self._g54 = [0.0, 0.0, 0.0]
        self._g92 = [0.0, 0.0, 0.0]
        self.acks = queue.Queue()

    def start(self):
        pass

    def stop(self):
        pass

    def close(self):
        pass

    def connected(self):
        return True

    def status(self):
        wco = tuple(self._g54[i] + self._g92[i] for i in range(3))
        return {"state": self._state, "mpos": tuple(self._pos), "wco": wco,
                "g54": tuple(self._g54), "g92": tuple(self._g92)}

    def mpos(self):
        return tuple(self._pos)

    def mpos_mach(self):
        """R2.9：模拟链路默认没有显示偏移（机床坐标 = 当前坐标）；
        测试可塞 _raw_mpos 模拟「设 0 点」后的显示偏移。"""
        r = getattr(self, "_raw_mpos", None)
        if r is not None:
            return (float(r[0]), float(r[1]), float(r[2]))
        return tuple(self._pos)

    def send(self, cmd, log_it=True):
        if log_it:
            self.log("> " + cmd)
        if cmd.strip().upper().startswith("$X"):
            self._state = "Idle"
        elif cmd.strip().upper().startswith("G92.1"):
            self._g92 = [0.0, 0.0, 0.0]
        elif cmd.strip().upper().startswith("G92"):
            # G92 X0 = 「当前这点就是工作坐标 0」→ 偏移 = 机床坐标 − 设定值
            for ax, i in (("X", 0), ("Y", 1), ("Z", 2)):
                m = re.search(ax + r"(-?[\d.]+)", cmd)
                if m:
                    self._g92[i] = self._pos[i] - float(m.group(1))
        elif cmd.startswith("G10"):
            self._state = "Idle"
            up = cmd.upper().replace(" ", "").replace("P1", "")
            if "L20" in up:                 # G10 L20 P1 X0 Y0 → 当前位置即工件零点（只改写出来的轴）
                hit = False
                for _ax, _i in (("X", 0), ("Y", 1), ("Z", 2)):
                    _m = re.search(_ax + r"(-?[\d.]+)", up)
                    if _m:
                        self._g54[_i] = self._pos[_i] - float(_m.group(1))
                        hit = True
                if not hit:
                    self._g54 = list(self._pos)
        elif "G53" in cmd.upper().replace(" ", ""):
            # 机床绝对坐标：不受 G54/G92 影响（真机行为）
            # v3.0：允许 "G90 G53 G0 Z.." 这种带前导模态词的写法（抬刀用的就是它）
            _up = cmd.upper().replace(" ", "")
            for _ax, _i in (("X", 0), ("Y", 1), ("Z", 2)):
                _m = re.search(_ax + r"(-?[\d.]+)", _up)
                if _m:
                    self._pos[_i] = float(_m.group(1))
        elif re.match(r"^(G90)?G0(?![0-9])", cmd.strip().upper().replace(" ", "")):
            # 工作坐标绝对移动：MPos = 目标工作坐标 + WCO(G54+G92)
            _wco = [self._g54[i] + self._g92[i] for i in range(3)]
            _up = cmd.upper().replace(" ", "")
            for _ax, _i in (("X", 0), ("Y", 1), ("Z", 2)):
                _m = re.search(_ax + r"(-?[\d.]+)", _up)
                if _m:
                    self._pos[_i] = float(_m.group(1)) + _wco[_i]

        self.acks.put(("ok", "ok"))          # 模拟机：每条命令立刻回 ok

    def recover_jog(self):
        self._jog_expect = None
        self._cont = None
        self._state = "Idle"
        self.log("✓ 点动通道已恢复（模拟机）")

    def feed_hold(self):
        self._state = "Hold"

    def resume_run(self):
        self._state = "Idle"

    def jog_z(self, dz, feed=400):
        self._pos[2] += float(dz)
        self.acks.put(("ok", "ok"))
        return float(dz)

    def jog(self, axis, delta, feed=100, cont=False):
        if self.is_alarm():
            raise GrblError("机床处于 %s 状态 —— 先点「解锁 $X」再点动" % self._state)
        i = "XYZ".index(axis.upper())
        if cont:
            # 模拟机只在收到 jog_cancel 时才停；这里不瞬间跳 50mm，
            # 免得看门狗把"模拟的瞬移"当成真实失控
            self._cont = [axis.upper(), self._pos[i], time.time(), abs(float(feed)) / 60.0,
                          abs(float(delta))]
            self._jog_expect = None
            self._jog_sent = getattr(self, "_jog_sent", 0) + 1
            return
        e = getattr(self, "_jog_expect", None)
        if e is None or e[0] != axis.upper() or time.time() - e[3] > 1.5:
            self._jog_expect = [axis.upper(), self._pos[i], float(delta), time.time()]
        else:
            e[2] += float(delta)
            e[3] = time.time()
        self._pos[i] += delta
        self._jog_sent = getattr(self, "_jog_sent", 0) + 1

    def jog_watchdog(self, tol=2.0):
        c = getattr(self, "_cont", None)
        if c:
            axis, base, t0, sp = c[0], c[1], c[2], c[3]
            seg = c[4] if len(c) > 4 else None
            if time.time() - t0 > 45:
                self._cont = None
            elif base is not None:
                moved = abs(self._pos[_AXI.get(axis, 0)] - base)
                allowed = (time.time() - t0) * sp * 1.6 + 3.0
                if seg:
                    allowed = min(allowed, seg + 3.0)
                if moved > allowed:
                    return (moved - allowed, axis)
                return None
        e = getattr(self, "_jog_expect", None)
        if not e:
            return None
        if time.time() - e[3] > 1.5:
            self._jog_expect = None
            return None
        moved = self._pos[_AXI.get(e[0], 0)] - e[1]
        over = abs(moved) - abs(e[2])
        return (over, e[0]) if over > tol else None

    def jog_expect_reset(self):
        self._jog_expect = None
        self._cont = None

    def jog_cancel(self):
        self._cont = None
        self.cancel_cnt = getattr(self, "cancel_cnt", 0) + 1

    def soft_reset(self):
        self._pos = [0.0, 0.0, 0.0]
        self._state = "Idle"      # 真机软复位后也是回 Idle（不回零、G54 不变）

    def is_alarm(self):
        return str(self._state).lower().startswith("alarm")

    def running_now(self):
        return False

    def unlock(self):
        self.log("模拟：已发送 $X，状态 -> Idle")
        self._state = "Idle"

    def home(self):
        self._pos = [0.0, 0.0, 0.0]

    def goto(self, x, y, feed=None):
        if self.is_alarm():
            raise GrblError("机床处于 %s 状态 —— 先点「解锁 $X」，否则不会动" % self._state)
        self._pos[0], self._pos[1] = float(x), float(y)

    def set_g54(self, x, y):
        self.log("模拟：已写入 G54 X=%.4f Y=%.4f" % (x, y))

    def query_offsets(self):
        pass


# ---------------------------------------------------------------- 发送加工 ----
def _send_clean(raw):
    """剥掉括号注释 / 分号注释 / 行号 / 所有空白并转大写（与官方 stream.py 的清洗一致）。
    GRBL 本来也吃注释，但去掉后一行更短：字符计数更准、同样缓冲能塞更多条。"""
    t = re.sub(r"\([^)]*\)", "", raw)
    t = t.split(";")[0]
    t = re.sub(r"\s", "", t).upper()
    t = re.sub(r"^N\d+", "", t)
    return t


def _fmt_dur(sec):
    sec = max(0, int(sec))
    if sec < 60:
        return "%d 秒" % sec
    if sec < 3600:
        return "%d 分 %02d 秒" % (sec // 60, sec % 60)
    return "%d 时 %02d 分" % (sec // 3600, sec % 3600 // 60)


class SendError(Exception):
    pass


class GrblStreamer:
    """把刀路流式发给 GRBL：字符计数流控 + 进度 + 暂停抬刀 + 断点续切。

    安全要点（每条都是踩过的坑）：
    - 含 EEPROM 写的行（G10 / $ 设置 / $RST）强制走「发一行等 ok」：
      GRBL 写 EEPROM 时会短暂关串口中断，字符计数会误判 → 塞爆缓冲。
    - 暂停不是硬停：先 feed hold（!）让运动平滑停住，再软复位 + $X + 抬 Z。
      软复位不清 G54（存 EEPROM），所以坐标不丢；但会把主轴状态清掉，
      所以续切前要补一条 M3 S（值从文件头解析）。
    - 断线 / ACK_TIMEOUT 秒没 ok → 立即中止、抬刀、把断点写进 <刀路>.sendlog。
    - 抬刀一律 $J（jog）而不是 G91 G0：jog 不改模态，不会把后面整份刀路带成相对。
    """

    def __init__(self, link, log=None, on_tick=None):
        self.link = link
        self.log = log or (lambda m: None)
        self.on_tick = on_tick or (lambda st: None)
        self.path = ""
        self.lines = []
        self.valid = []          # 有效行（去掉空行/纯注释）在 lines 里的下标
        self.total = 0
        self.cur = 0             # 下一条要发的位置（valid 里的下标）
        self.acked = 0           # 已确认执行完的条数（valid 里的下标）
        self.c_line = []         # 在途每行的字符数（含换行）：字符计数的核心
        self.state = "idle"      # idle/running/pausing/paused/resuming/stopping/stopped/finishing/done/error
        self.msg = ""
        self.errs = []
        self.t0 = 0.0
        self.t_stop = 0.0
        self.z_lift = 5.0        # 暂停/停止时抬多高
        self.z_safe = 5.0        # 加工完成后抬到的高度
        # R1.1：安全高度（机床绝对 Z）。由界面标定后传进来；有它就优先用它抬
        self.z_safe_mz = None
        self.plunge = 300        # 续切下刀进给
        self.auto_home = True    # 加工完回工件中心
        self.home_mpos = None    # 工件中心的机床坐标（分中得到的 center）；None=用 G54 的 0,0
        self.break_line = 1      # 断点（文件行号，1 基）
        self._soft_stopped = False   # R2.1：True = 走过「停止」（软复位过，续切要回断点）；False = 纯暂停
        self.pause_line = 0          # 暂停时停在哪一行（只作显示，不用于重定位）
        self._reset_abort = False    # R2.3：机床复位（板子重启）→ 立刻停发
        self.break_wpos = None   # 断点工作坐标
        self.break_mpos = None   # v3.0 断点机床坐标（续切用它回位，不受 G54/G92 影响）
        self.break_wco = None    # v3.0 断点时的坐标系偏移（用来发现「基准被改了」）
        self.z_break = None
        self._stop = False
        self._pause = False
        self._resume = False
        self._th = None
        self._last_ack = 0.0
        self._spindle = None

    # -- 文件 --
    def load(self, path):
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            self.lines = [ln.rstrip("\r\n") for ln in f]
        self.valid = [i for i, ln in enumerate(self.lines) if _send_clean(ln)]
        self.total = len(self.valid)
        self.path = path
        self.cur = self.acked = 0
        self.c_line = []
        self.errs = []
        self.msg = ""
        self.state = "idle"
        self.break_line = 1
        self.break_wpos = None
        self._spindle = self._find_spindle()
        return self.total

    def _find_spindle(self):
        """文件头里的主轴转速（M3 Sxxxx）：软复位会清主轴状态，续切时要补回来"""
        for ln in self.lines[:40]:
            u = ln.upper().replace(" ", "")
            if "M3" in u or "M03" in u:
                m = re.search(r"S(\d{2,6})", u)
                if m:
                    return int(m.group(1))
        for ln in self.lines[:40]:
            m = re.search(r"S(\d{2,6})", ln.upper())
            if m:
                return int(m.group(1))
        return None

    def _line_no(self, k):
        if not self.valid:
            return 1
        if k < len(self.valid):
            return self.valid[k] + 1
        return len(self.lines) + 1

    def _idx_of_line(self, n):
        for k, i in enumerate(self.valid):
            if i + 1 >= int(n):
                return k
        return len(self.valid)

    # -- 断点文件 --
    def break_file(self):
        return (self.path or "") + ".sendlog"

    def _save_break(self):
        if not self.path:
            return
        try:
            d = {"file": os.path.basename(self.path), "line": int(self.break_line or 1),
                 "total": int(self.total), "done": int(self.acked),
                 "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
                 "wpos": list(self.break_wpos) if self.break_wpos else None,
                 "mpos": list(self.break_mpos) if self.break_mpos else None,
                 "wco": list(self.break_wco) if self.break_wco else None}
            with open(self.break_file(), "w", encoding="utf-8") as f:
                json.dump(d, f, ensure_ascii=False)
        except Exception:
            pass

    def _clear_break(self):
        try:
            if self.path and os.path.isfile(self.break_file()):
                os.remove(self.break_file())
        except Exception:
            pass

    def load_break(self):
        p = self.break_file()
        if not self.path or not os.path.isfile(p):
            return None
        try:
            with open(p, encoding="utf-8") as f:
                d = json.load(f)
            d["line"] = int(d.get("line") or 1)
            return d
        except Exception:
            return None

    # -- 状态 --
    def running(self):
        return self.state in ("running", "pausing", "paused", "resuming", "stopping", "finishing")

    def snapshot(self):
        el = ((self.t_stop or time.time()) - self.t0) if self.t0 else 0.0
        eta = None
        if self.acked > 0 and self.total:
            rate = self.acked / el if el > 0 else 0
            if rate > 0:
                eta = max(0.0, (self.total - self.acked) / rate)
        return {"state": self.state, "msg": self.msg, "path": self.path,
                "acked": self.acked, "cur": self.cur, "total": self.total,
                "line": self._line_no(self.acked), "elapsed": el, "eta": eta,
                "errs": len(self.errs), "break_line": self.break_line,
                "running": self.running()}

    def _tick(self):
        try:
            self.on_tick(self.snapshot())
        except Exception:
            pass

    # -- 内部工具 --
    def _drain_acks(self, now=None, count=True):
        """把读线程入队的 ok/error 消费掉：每条出队一个「在途行」计数。

        count=False 用于内部命令（G90/G0/M3/$X…）期间：这些 ok 不属于刀路行，
        算了会把 acked 污染成超过 total。"""
        n = 0
        while True:
            try:
                kind, txt = self.link.acks.get_nowait()
            except queue.Empty:
                break
            n += 1
            if not self.c_line:
                # 不属于任何刀路行的回包（点动 $J / 内部命令 / 手动发命令）：
                # 拿去计进度会让 acked 跑到 total 前面 → 提前收尾抬刀
                if kind != "ok":
                    self.errs.append((self._line_no(self.acked), txt))
                    self.log("！非刀路命令被拒：%s" % txt)
                continue
            self.c_line.pop(0)
            if kind != "ok":
                self.errs.append((self._line_no(self.acked), txt))
                self.log("！第 %d 行被拒：%s" % (self._line_no(self.acked), txt))
            if count:
                self.acked += 1
                self._last_ack = now or time.time()
        return n

    def _clear_acks(self):
        try:
            while True:
                self.link.acks.get_nowait()
        except queue.Empty:
            pass

    def _wait_state(self, key, timeout, count=False):
        t0 = time.time()
        while time.time() - t0 < timeout:
            st = str((self.link.status() or {}).get("state", "")).lower()
            if key in st:
                return True
            self._drain_acks(time.time(), count=count)
            time.sleep(0.03)
        return False

    def _wait_idle(self, timeout, count=False):
        return self._wait_state("idle", timeout, count=count)

    def _stable_mpos(self, tries=14, tol=0.005):
        """连续两次读到的机床坐标几乎不变，才算「真的停稳了」。

        feed hold 之后 planner 里还有几段在减速，立刻读会读到减速途中的位置 ——
        断点按那个位置存，续切时刀就偏了这么一截（用户看到的「暂停后继续，刀跑到别处」）。
        """
        prev = None
        for _ in range(tries):
            st = self.link.status() or {}
            mp = st.get("mpos")
            if mp and prev and max(abs(float(mp[i]) - float(prev[i])) for i in range(3)) <= tol:
                return mp
            prev = mp
            time.sleep(0.06)
        return prev

    def _wpos(self):
        st = self.link.status() or {}
        mp = st.get("mpos")
        if not mp:
            return None
        w = st.get("wco") or st.get("g54") or (0.0, 0.0, 0.0)
        return (mp[0] - w[0], mp[1] - w[1], mp[2] - w[2])

    def _guard(self):
        if not self.link.connected():
            raise SendError("串口断开了（USB 掉了 / 板子掉电）")
        st = str((self.link.status() or {}).get("state", ""))
        if st.lower().startswith("alarm"):
            raise SendError("机床报警了（%s）—— 多为撞到限位：检查工件是否超出行程、"
                            "$20=1 时软限位范围、或中途有没有手动移过刀" % (st or "Alarm"))
        if self.c_line and self._last_ack:
            gap = time.time() - self._last_ack
            if gap > ACK_TIMEOUT:
                # 机床确实还在动（Run/Jog 且坐标在变）就继续等：慢速段、密集小线段、
                # planner 满都会让 ok 变慢，这不是故障
                moving = bool(getattr(self.link, "running_now", lambda: False)())
                if moving and gap <= ACK_HARD_TIMEOUT:
                    return
                if moving:
                    raise SendError("%.0f 秒一条 ok 都没有（机床在动但通讯像断了）—— 检查 USB 线/干扰"
                                    % gap)
                raise SendError("%.0f 秒没收到 ok，机床也不动 —— 判定通讯中断（USB 掉了/丢字节）"
                                % gap)

    # -- 起停 --
    def start(self, from_line=None):
        if self._th and self._th.is_alive():
            raise SendError("正在发送中（先停止）")
        if not self.lines:
            raise SendError("先选一份刀路文件")
        if not self.total:
            raise SendError("这个文件里没有可执行的刀路行")
        if not self.link.connected():
            raise SendError("串口没连上")
        if self.link.is_alarm():
            raise SendError("机床在 Alarm —— 先点「解锁 $X」")
        k = self._idx_of_line(from_line) if from_line else 0
        self.cur = k
        self.acked = k
        self.c_line = []
        self.errs = []
        self.msg = ""
        self._stop = self._pause = self._resume = False
        self._soft_stopped = False
        self._reset_abort = False
        self._clear_acks()
        self._last_ack = time.time()
        self.z_break = None
        self.t0 = time.time()
        self.t_stop = 0.0
        self.state = "running"
        self._last_tick = 0.0
        try:
            self.link.no_jog = True
            self.link._no_jog_logged = False
        except Exception:
            pass
        try:
            self.link.poll_sec = 0.5      # R2.3：加工中状态轮询降到 2Hz（板子更稳）
        except Exception:
            pass
        # R1.1 防撞：发送前**必须先抬到安全高度**，再 G0 到第一处起点 XY。
        # 原来直接发第一行：刀还停在工件里时，第一句 G0 就是斜着穿过去（用户撞过）。
        # 从断点续切也要先抬：刀可能还停在工件里，_do_resume 第一步就是横移回断点 XY
        self._pre_start(go_start=(from_line is None))
        self._th = threading.Thread(target=self._run, daemon=True)
        self._th.start()

    def pause(self):
        if self.state == "running":
            self._pause = True

    def resume(self):
        if self.state in ("paused", "stopped"):
            self._resume = True

    def abort_on_reset(self):
        """R2.3：机床复位了（GRBL 打出 "Grbl" 横幅 = 板子重启）。

        复位后机床坐标归零、G92 清空、G54 从 EEPROM 重载 —— 继续按旧坐标发绝对移动，
        刀就会按新基准大幅横移（用户说的「走飞刹不住」）。所以**立刻停发**，不许自动续切。
        """
        self._reset_abort = True
        self._stop = False
        self._pause = False
        self._resume = False
        self.log("！检测到机床复位 —— 立即停发（复位后坐标已归零，续切会走飞）")

    def _do_reset_abort(self):
        """复位中止：不抬刀（坐标不可信，G53 也危险）、不写可续切断点、直接结束。"""
        self.state = "error"
        self.msg = ("机床复位了 —— 已停发。复位后机床坐标归零，这份刀路**不能续切**："
                    "请回零或重新对刀/分中，再从头跑。")
        self.log("✗ " + self.msg)
        self.t_stop = time.time()
        try:
            self.link.no_jog = False
        except Exception:
            pass
        try:
            self._save_break()          # 只留档「跑到哪了」，不带可续切的坐标
        except Exception:
            pass
        self._tick()

    def stop(self):
        if self.running():
            self._stop = True
            self._pause = False

    # -- 主循环 --
    def _run(self):
        try:
            self._loop()
        except Exception as e:
            # 先把断点落盘再改状态：外面看到 "error" 时断点文件必须已经在
            self.break_line = self._line_no(self.acked)
            self._save_break()
            self.msg = "发送中止：%s" % e
            self.log("✗ " + self.msg)
            if not self._reset_abort:      # R2.3：复位过就别用 G53 抬刀（坐标不可信）
                self._safe_lift()
            self.t_stop = time.time()
            self.state = "error"
            self._tick()
        finally:
            try:
                self.link.no_jog = False
                self.link._no_jog_logged = False
                self.link.poll_sec = POLL_SEC
            except Exception:
                pass

    def _loop(self):
        self.log("开始发送 %s（%d 行，起自第 %d 行）"
                 % (os.path.basename(self.path), self.total, self._line_no(self.cur)))
        while True:
            if self._reset_abort:
                self._do_reset_abort()
                return
            if self._stop:
                self._do_stop()
                self._stop = False
                continue        # R2.1：不退出循环 —— 留在 stopped 状态等「继续」（否则继续点了没反应）
            if self._pause:
                self._do_pause()
                continue
            if self._resume:
                self._do_resume()
                continue
            if self.state in ("paused", "stopped"):
                # R2.1：暂停/停止期间绝不继续发（以前这里会一路把剩余行发完）
                # 注意：不在这里 drain —— count=False 会 pop 掉在途行却不加 acked，
                # 收尾时 acked 永远追不上 total，程序会卡在收不了尾。
                self._tick()
                time.sleep(0.03)
                continue
            if self.cur >= self.total:
                # 全发完了：只剩把尾部缓冲里的 ack 收干净
                if self._drain_acks(time.time()) == 0:
                    if self.acked >= self.total:
                        break
                    self._guard()
                    self._tick()
                    time.sleep(0.01)
                continue
            payload = _send_clean(self.lines[self.valid[self.cur]])
            ln = len(payload) + 1
            if re.search(r"^T\d{1,2}|M0?6", payload):
                # 换刀行 GRBL 会回 error:20（不支持 M6），直接跳过，不占行也不等 ack
                self.cur += 1
                self.acked += 1
                continue
            eeprom = payload.startswith("$") or bool(EEPROM_RE.search(payload))
            if eeprom:
                # 写 EEPROM 必须先清空在途 + 等这一条的 ok（GRBL 官方硬规则）
                if self.c_line:
                    self._drain_acks(time.time())
                    self._guard()
                    time.sleep(0.005)
                    continue
                self.link.send(payload, log_it=False)
                self.c_line.append(ln)
                self.cur += 1
                t0 = time.time()
                while self.c_line and time.time() - t0 < ACK_TIMEOUT:
                    self._drain_acks(time.time())
                    time.sleep(0.01)
                continue
            # 缓冲还塞得下就直接发：先喂满再等 ack（这是字符计数比「发一条等一条」快的原因）
            if len(self.c_line) < SEND_CHUNK and (sum(self.c_line) + ln) <= (RX_BUFFER - RX_KEEP):
                self.link.send(payload, log_it=False)
                self.c_line.append(ln)
                self.cur += 1
                if time.time() - self._last_tick >= 0.25:
                    self._last_tick = time.time()
                    self._tick()
                continue
            # 塞不下了：读 ack 腾地方
            if self._drain_acks(time.time()) == 0:
                self._guard()
                self._tick()
                time.sleep(0.005)
        self._finish()

    # -- 暂停 / 继续 / 停止 / 完成 --
    def _do_pause(self):
        """R2.1：暂停 = 纯 GRBL feed hold（`!`）—— 不软复位、不抬刀、坐标不丢。

        用户反馈「暂停有问题 / 续切后刀重复退、加工不到工件」：旧实现是
        feed hold → 软复位 → 抬刀 → 存断点，再续切时按断点重定位。
        软复位会让 GRBL 的机床坐标归零（无回零的机器），G92 也丢，
        续切回断点的坐标全错 + 多抬一次刀 → 实际切不到工件。
        现在暂停只按 `!` 停住，刀留在原位；继续时 `~`（cycle start）接着切，
        缓冲/坐标都是 GRBL 自己维护的，不需要任何重建。
        """
        self._pause = False
        self.state = "pausing"
        self.msg = "正在停住…"
        self._tick()
        self.log("—— 暂停（feed hold，刀停在原位）——")
        try:
            self.link.feed_hold()
            self._wait_state("hold", 4.0, count=True)
        except Exception as e:
            self.log("！feed hold 没确认：%s" % e)
        self._drain_acks(time.time())          # count=True：在途行的 ok 要计入 acked
        self.pause_line = self._line_no(self.acked)
        self.state = "paused"
        self.msg = "已暂停（第 %d 行停住，刀还在工件里）" % self.pause_line
        self.log(self.msg + "　点「▶ 继续」直接接着切 —— 不重定位、不抬刀、坐标不会丢")
        self._tick()

    def _do_resume(self):
        self._resume = False
        if not self._soft_stopped:
            # 纯暂停（feed hold）：cycle start 接着切 —— 缓冲与坐标都在 GRBL 里，不重建
            self.state = "running"
            self.msg = "继续（cycle start）"
            self.log("—— 继续：cycle start，从第 %d 行接着切（不重定位、不抬刀）——"
                     % self._line_no(self.acked))
            self._tick()
            try:
                self.link.resume_run()
            except Exception as e:
                self.log("！cycle start 失败：%s" % e)
            self._last_ack = time.time()
            self._clear_acks()
            self._tick()
            return
        self.state = "resuming"
        self.msg = "正在回断点…"
        self._tick()
        try:
            self.link.no_jog = True         # 续切期间接管点动（防手误）
        except Exception:
            pass
        k = self._idx_of_line(self.break_line)
        wp = self.break_wpos
        mp = self.break_mpos
        try:
            if mp:
                # v3.0：一律用 G53（机床绝对坐标）回断点。
                # 以前发的是 `G0 X<工作坐标> Y<工作坐标>` —— 只要 G54/G92 被动过
                # （直出模式的刀路文件头就会重写 G54），这里就整体偏，而且 Z 也跟着错。
                self.log("回断点：机床坐标 (%.3f, %.3f, %.3f)" % (mp[0], mp[1], mp[2]))
                self._safe_lift()          # 横移回断点前先抬；读不到也不中止（R2：不再因读数滞后拒绝续切）
                self.link.send("G90 G53 G0 X%.3f Y%.3f" % (mp[0], mp[1]), log_it=False)
                self._wait_idle(15.0, count=False)
                self.link.send("G90 G53 G1 Z%.3f F%d" % (mp[2], int(self.plunge)), log_it=False)
                self._wait_idle(25.0, count=False)
            elif wp:
                self.log("回断点（旧断点无机床坐标，按工作坐标回）：(%.3f, %.3f, %.3f)"
                         % (wp[0], wp[1], wp[2]))
                self.link.send("G90", log_it=False)
                self.link.send("G0 X%.3f Y%.3f" % (wp[0], wp[1]), log_it=False)
                self._wait_idle(12.0, count=False)
                self.link.send("G1 Z%.3f F%d" % (wp[2], int(self.plunge)), log_it=False)
                self._wait_idle(20.0, count=False)
            # 坐标系被改过？改了后面所有工作坐标的刀路都会整体偏 —— 必须让操作员知道
            if self.break_wco:
                _st = self.link.status() or {}
                _now = _st.get("wco")
                if _now and max(abs(float(_now[i]) - float(self.break_wco[i]))
                                for i in range(3)) > 0.05:
                    self.log("！坐标系偏移和暂停时不一样了"
                             "（X %+.3f→%+.3f  Y %+.3f→%+.3f  Z %+.3f→%+.3f）："
                             "续切是照机床坐标回去的，刀的位置没错，但后面的刀路会按新基准走 —— "
                             "请先确认零点没被改过"
                             % (self.break_wco[0], _now[0], self.break_wco[1], _now[1],
                                self.break_wco[2], _now[2]))
            if self._spindle:
                self.link.send("M3 S%d" % self._spindle, log_it=False)   # 软复位把主轴清了
                time.sleep(0.2)
        except Exception as e:
            self.log("！回断点失败：%s → 直接续发（请先确认刀已对准、Z 到位）" % e)
        self._clear_acks()
        self.c_line = []
        self.cur = k
        self.acked = k
        self._last_ack = time.time()
        self.state = "running"
        self.msg = "已从第 %d 行继续" % self.break_line
        self.log(self.msg)
        self._tick()

    def _do_stop(self):
        """R2.1：停止 = 停住 → **软复位前**记断点坐标 → 软复位 → 抬刀。
        软复位会让无回零机器的机床坐标归零，所以断点必须在复位之前读稳。"""
        self.state = "stopping"
        self.msg = "正在停止…"
        self._tick()
        self.log("—— 停止（停住 → 记断点 → 软复位 → 抬刀）——")
        try:
            self.link.feed_hold()
            self._wait_state("hold", 3.0, count=True)
        except Exception:
            pass
        # ① 软复位前把断点读稳（复位后坐标归零就读不到了）
        mp_stable = self._stable_mpos()
        _st = self.link.status() or {}
        self.break_wco = _st.get("wco") or _st.get("g54")
        self.break_mpos = mp_stable
        wp = None
        if mp_stable and self.break_wco:
            wp = (float(mp_stable[0]) - float(self.break_wco[0]),
                  float(mp_stable[1]) - float(self.break_wco[1]),
                  float(mp_stable[2]) - float(self.break_wco[2]))
        self.break_wpos = wp
        self.z_break = wp[2] if wp else None
        # ok 只代表「进了缓冲」，acked 那行可能还没走完 → 往前退 3 行续切，防台阶
        self.break_line = self._line_no(max(0, self.acked - 3))
        self._save_break()                 # 先落盘：后面软复位/断电都不丢
        self.log("断点：第 %d 行%s" % (self.break_line,
                 ("，机床坐标 (%.3f, %.3f, %.3f)" % tuple(mp_stable)) if mp_stable
                 else "（没读到坐标）"))
        # ② 软复位（清缓冲）+ 抬刀
        try:
            self.link.soft_reset()
        except Exception as e:
            self.log("！软复位失败：%s" % e)
        time.sleep(1.0)
        self._clear_acks()
        self.c_line = []
        try:
            self._safe_lift(extra=5.0)
        except Exception as e:
            self.log("！抬刀失败：%s ← 请手动抬 Z！" % e)
        self._save_break()
        self.t_stop = time.time()
        self._soft_stopped = True
        try:
            self.link.no_jog = False        # R2.1：停止＝交还手动控制，可以点动/抬刀
            self.link._no_jog_logged = False
        except Exception:
            pass
        self.state = "stopped"
        self.msg = "已停止（第 %d 行前）—— 点「继续」可从断点续切" % self.break_line
        self.log(self.msg)
        self._tick()

    def _safe_lift(self, extra=0.0):
        """抬到安全高度 —— **只允许往上**（R1.4）。

        撞刀教训（2026-11-20，用户报「刀直接往下扎进工件」）：
        手动把刀降到工件上再点开始，程序按「标定过的安全 Z」发 `G53 G0 Z<z>`，
        那个值比工件还低（换刀/换件后没重标）→ 刀直接扎下去。

        现在三道保护：
          ① 目标 = max(当前 Z + 抬升量, 工作顶面 + SAFE_WZ, 标定值[仅当它更高且不超过 +50])
          ② 读不到当前坐标 → 绝不发绝对 Z，改相对抬 5mm（只往上）
          ③ 抬完再读一次坐标核对，没上去就返回 None，让上层拒绝开工

        返回：抬到的机床 Z（float）／失败返回 None（调用方自己决定要不要继续）。
        """
        try:
            if self.link.is_alarm():
                self.link.unlock()
                time.sleep(0.2)
            st = self.link.status() or {}
            mp = st.get("mpos")
            wco = st.get("wco") or st.get("g54")
            lift = max(SAFE_WZ, float(self.z_lift) + float(extra))
            cur = float(mp[2]) if mp else None

            if cur is None:
                # 读不到当前 Z：发绝对坐标 = 把刀送到未知高度，宁可只做相对抬
                self.log("！读不到当前坐标 —— 不走绝对 Z，改为相对抬 %.1fmm（只往上）" % lift)
                try:
                    self.link.jog_z(lift, 600)
                    self._wait_idle(6.0, count=False)
                    self._clear_acks()
                except Exception as e:
                    self.log("！相对抬刀也失败：%s ← 请手动抬 Z！" % e)
                    return None
                st2 = self.link.status() or {}
                mp2 = st2.get("mpos")
                return float(mp2[2]) if mp2 else None

            cands = [cur + lift]                            # ①
            if wco:
                cands.append(float(wco[2]) + SAFE_WZ)       # ② 工件顶面以上
            if self.z_safe_mz is not None:
                _sm = float(self.z_safe_mz)
                if cur + 0.5 < _sm <= cur + 50.0:
                    cands.append(_sm)                       # ③ 标定值只在合理范围采用
                elif _sm > cur + 50.0:
                    self.log("（安全 Z 标定值比当前位置高 %.0fmm —— 可能换过刀/工件，本次按 +%.0f 抬）"
                             % (_sm - cur, lift))
                else:
                    self.log("（安全 Z 标定值 %.3f 不高于当前位置 —— 忽略它，按 +%.0f 抬）"
                             % (_sm, lift))
            tz = max(cands)
            self.link.send("G90 G53 G0 Z%.4f" % tz, log_it=False)
            self._wait_idle(10.0, count=False)
            self._clear_acks()
            # R2：读状态有 5Hz 滞后，读一次就判「没抬起来」会误杀（用户报「抬刀成功却提示失败」）。
            # 多读几次；仍读不到就相信指令已执行，只提示。
            _z_after = None
            for _k in range(5):
                st3 = self.link.status() or {}
                mp3 = st3.get("mpos")
                if mp3 is not None:
                    _z_after = float(mp3[2])
                    if _z_after >= cur + 0.4:
                        break
                time.sleep(0.12)
            if _z_after is None:
                self.log("（抬刀后读不到 Z —— 指令已发，按 GRBL 执行结果继续）")
                return tz
            mp3 = [_z_after]
            if _z_after < cur + 0.4:
                self.log("！抬刀没生效（Z %.3f → %.3f）—— 请手动抬 Z" % (cur, float(mp3[2])))
                return None
            return tz
        except Exception as e:
            self.log("！抬刀失败：%s ← 请手动抬 Z！" % e)
            return None

    def _first_xy(self):
        """从文件里找第一处绝对坐标的 X/Y（用来在安全高度上先走到起点）。"""
        abs_mode = True
        for i in self.valid[:400]:
            code, _c = _split_comment(self.lines[i])
            code = code.strip()
            if not code:
                continue
            up = code.replace(" ", "").upper()
            if any(k in up for k in ("G53", "G10", "G92", "G28", "G30")):
                continue
            words = {}
            for L, v in WORD_RE.findall(code):
                L = L.upper()
                words[L] = v
                if L == "G":
                    g = float(v)
                    if abs(g - 90.0) < 1e-9:
                        abs_mode = True
                    elif abs(g - 91.0) < 1e-9:
                        abs_mode = False
            if not abs_mode:
                continue
            if "X" in words or "Y" in words:
                return (float(words["X"]) if "X" in words else None,
                        float(words["Y"]) if "Y" in words else None)
        return None, None

    def _lift_line_in_file(self, n=80):
        """文件前 n 行里有没有「抬 Z」的指令（本程序生成的是 G53 G0 Z.. / G90 G0 Z..）。
        找到就返回那一行，找不到返回 None。"""
        try:
            for ln in self.lines[:n]:
                code, _c = _split_comment(ln)
                up = code.replace(" ", "").upper()
                if not up or "Z" not in up:
                    continue
                if ("G53" in up and "G0" in up) or re.search(r"G0*0?", up) and "Z" in up:
                    return ln.strip()
        except Exception:
            pass
        return None

    def _pre_start(self, go_start=True):
        """R2：加工前软件**不再插任何动作**（用户 2026-11-20 要求）。

        「加工时抬刀和生成代码不要冲突，去掉软件加工前的抬刀，生成代码时加抬刀；
          过中心时下到加工起始高度，代码执行时按代码抬刀」——所以：
          抬刀 → 走到起点 → 下到起刀 Z 全部写在**生成的代码文件头**里
          （见 insert_start_block），软件只负责按行发送，跟 Candle 跑同一份文件一模一样。

        这里只做两件事：报警先解锁；文件头没有抬刀时提醒（不拦，由界面先问过用户）。
        """
        if self.link.is_alarm():
            try:
                self.link.unlock()
            except Exception:
                pass
            time.sleep(0.2)
        hit = self._lift_line_in_file()
        if hit:
            self.log("开始加工：按代码执行（文件头自带抬刀：%s）" % hit)
        else:
            self.log("！这份文件开头没有抬刀指令 —— 软件不再替你抬刀，请确认刀已在工件上方"
                     "（建议用「生成刀路」出来的文件，文件头自带抬刀）")
        return None

    def _wait_motion_done(self, timeout=FINISH_WAIT_MAX):
        """等机床把 planner 里剩的运动真的走完。

        ok 只代表「GRBL 收到了这一行」，最后几行可能还在走；此时若直接跳 Z
        抬刀（$J 是实时点动）会把刀从工件里提起来 → 看着就是「中途停止」。
        """
        t0 = time.time()
        logged = False
        while time.time() - t0 < timeout:
            if self._stop:
                raise SendError("已停止（收尾前）")
            st = str((self.link.status() or {}).get("state", "")).lower()
            if st.startswith("idle"):
                return True
            if st.startswith("alarm"):
                raise SendError("机床报警了（%s）—— 检查是否撞限位" % st)
            if not logged:
                logged = True
                self.msg = "刀路已发完，等机床走完最后几行…"
                self.log("刀路已全部下发，等机床走完剩余运动（最多 %d 分钟）"
                         % int(timeout / 60))
                self._tick()
            self._drain_acks(time.time(), count=False)
            time.sleep(0.05)
        self.log("！等机床走完超时（%d 分钟）—— 仍继续收尾，请目视确认刀已离开工件"
                 % int(timeout / 60))
        return False

    def _finish(self):
        self.state = "finishing"
        self.msg = "正在收尾…"
        self._tick()
        if self._reset_abort:
            # 复位过：只停主轴，绝不做 G53 抬刀/回中心（坐标已归零，会走飞）
            try:
                self.link.send("M5", log_it=False)
            except Exception:
                pass
            self.t_stop = time.time()
            self.state = "error"
            self.msg = "机床复位过 —— 已停主轴，不做回中心（请重新对零/分中）"
            self.log("✗ " + self.msg)
            self._tick()
            return
        self._wait_motion_done()
        try:
            self.link.send("M5", log_it=False)
            if self.auto_home:
                # v3.0：G53 绝对抬刀 + 保证抬到工件顶面以上（原来是相对 +5，深槽里抬不够）
                self.z_lift = max(0.5, float(self.z_safe or self.z_lift))
                self._safe_lift()
                self._wait_idle(8.0, count=False)
                if self.home_mpos:
                    # 分中的中心本身是机床坐标 → 用 G53 回，G54 被写成什么都不会回错地方
                    self.log("加工完成 → 停主轴 → 抬刀 → 回工件中心（机床坐标 %.3f, %.3f）"
                             % (self.home_mpos[0], self.home_mpos[1]))
                    self.link.send("G90 G53 G0 X%.3f Y%.3f"
                                   % (self.home_mpos[0], self.home_mpos[1]), log_it=False)
                else:
                    self.log("加工完成 → 停主轴 → 抬刀 → 回工件中心（G54 X0 Y0）")
                    self.link.send("G90 G0 X0 Y0", log_it=False)
                self._wait_idle(20.0, count=False)
        except Exception as e:
            self.log("！回中心失败：%s ← 请手动把刀移开" % e)
        self._clear_acks()
        self.t_stop = time.time()
        self.state = "done"
        self.break_line = self._line_no(self.acked)
        self.msg = "加工完成：%d 行，用时 %s" % (self.total, _fmt_dur(self.t_stop - self.t0))
        self._clear_break()
        self.log(self.msg)
        self._tick()


def wpos_dev(l):
    """刀尖当前的工作坐标 = MPos − 偏移。偏移取 GRBL 状态里的 WCO（= G54 + G92 的合成值），
    没有 WCO 时用 G54 + G92 相加。返回 (x, y) 或 None（坐标还没读到）。"""
    st = (l.status() if l else None) or {}
    mp = st.get("mpos")
    if not mp:
        return None
    w = st.get("wco")
    if w:
        return (mp[0] - w[0], mp[1] - w[1])
    g = st.get("g54")
    g92 = st.get("g92")
    if g is None and g92 is None:
        return None
    g = g or (0.0, 0.0, 0.0)
    g92 = g92 or (0.0, 0.0, 0.0)
    return (mp[0] - g[0] - g92[0], mp[1] - g[1] - g92[1])


PRESET_NAME = "grbl_center_preset.json"
PRESET_VER = 2          # v2 = 8 点存「相对标定起点的偏移」→ 不依赖回零精度
GENLOG_NAME = "grbl_center_genlog.json"   # 每次生成刀路的快照（事后对账用）
GENLOG_MAX = 30
SESSION_NAME = "grbl_center_session.json"   # 当前工件的工作状态（碰点/选项）
SESSION_VER = 2                              # R2.9：2 = 安全Z/碰点改存机床真实坐标（旧 1 版数据作废）
LIFT_TRUST_MAX = 50.0                        # R2.9：单次抬刀可信上限 5cm，超过必是目标值算错
LIFT_FALLBACK = 20.0                         # 超过上限时改为「当前 +20」，绝不硬顶限位


def preset_path():
    """预设文件：优先程序同目录，不可写就退到用户目录。
    环境变量 GRBL_CENTER_PRESET_FILE 可覆盖（自测隔离用，免得跑自检把真实标定删了）"""
    envp = os.environ.get("GRBL_CENTER_PRESET_FILE")
    if envp:
        return envp
    here = os.path.dirname(os.path.abspath(__file__))
    p1 = os.path.join(here, PRESET_NAME)
    try:
        if os.access(here, os.W_OK):
            return p1
    except Exception:
        pass
    return os.path.join(os.path.expanduser("~"), "." + PRESET_NAME)


def genlog_path():
    """生成快照文件：与预设同目录；环境变量 GRBL_CENTER_GENLOG_FILE 可覆盖（自测隔离）"""
    envp = os.environ.get("GRBL_CENTER_GENLOG_FILE")
    if envp:
        return envp
    here = os.path.dirname(os.path.abspath(__file__))
    try:
        if os.access(here, os.W_OK):
            return os.path.join(here, GENLOG_NAME)
    except Exception:
        pass
    return os.path.join(os.path.expanduser("~"), "." + GENLOG_NAME)


def genlog_load():
    try:
        with open(genlog_path(), "r", encoding="utf-8") as f:
            d = json.load(f)
        return d if isinstance(d, list) else []
    except Exception:
        return []


def genlog_add(rec):
    """追加一条生成快照（原子写，故障不影响生成流程）"""
    try:
        rows = genlog_load()
        rows.append(rec)
        rows = rows[-GENLOG_MAX:]
        p = genlog_path()
        tmp = p + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(rows, f, ensure_ascii=False, indent=1)
        os.replace(tmp, p)
        return True
    except Exception:
        return False


def preset_load():
    try:
        with open(preset_path(), "r", encoding="utf-8") as f:
            d = json.load(f)
        if not isinstance(d, dict):
            return {}
        return d
    except Exception:
        return {}


def preset_save(d):
    try:
        with open(preset_path(), "w", encoding="utf-8") as f:
            json.dump(d, f, ensure_ascii=False, indent=1)
        return True
    except Exception:
        return False

CP_VER = 8          # v8 = 定位点存机床绝对坐标 + refz（纠偏基准），设零/算中心时整体平移
CP_LIFT = 5.0       # 快速定位抬刀量（mm）：走到该点前抬到「该点的 Z + 这么多」（绝对目标，不会累加）


def cp_normalize(d):
    """规整成：

        {"ver":8, "pts":{edge:{"1":{mx,my,mz,cur?}, "2":{...}}},
         "refz":{"x","y","t"}}

    每个槽 = 这条边上记过的一个点，存的是**机床绝对坐标**，一种数据两种用途：
      · 碰点：算中心 / θ   （mx,my 就是本件实测的 MPos）
      · 快速定位：下一件点一下格子 → 抬 Z 5mm → G53 直接走到 (mx,my)，
                 然后人工 Z- 下降贴边、Enter 记点。不做中心/θ 推算，
                 误差只等于两次摆件的差异，靠手精调。
    字段：
      mx,my = 记点时的机床坐标 MPos（定位就走到这里）
      mz    = 记点时的工作坐标 Z（老字段；抬刀优先用下面的 mzm）
      mzm   = 记点时的机床坐标 Z（v3.0.2）：工作坐标会随 G54 的 Z 偏移变，机床坐标不会
      cur   = 1 → 本件碰过；换件「清空」只清这个标记，mx/my/mz 一定留着

      refz  = 纠偏基准：最近一次「设零 / 算出中心」的机床坐标。定位点相对它不动，
              基准一变就整体平移过去（第二件设完零点，点跟着走，不会停在上一件）。

    ver6/7 的点位自动升级（mx/my/mz/cur 保留；dx/dy/th 丢弃：不再按中心推算）。
    ver1~5 一律丢弃：那时存的是「离边 8~10mm 的起点」，不是碰点。
    """
    out = {"ver": CP_VER, "pts": {}, "_discarded": 0}
    if not isinstance(d, dict):
        return out
    if d.get("ver") not in (6, 7, CP_VER):
        old = d.get("pts") or d.get("pos")
        if isinstance(old, dict):
            out["_discarded"] = sum(len(v) for v in old.values() if isinstance(v, dict))
        else:
            out["_discarded"] = len(d.get("points") or [])
        return out
    for e, slots in (d.get("pts") or {}).items():
        if not isinstance(slots, dict):
            continue
        got = {}
        for k in ("1", "2"):
            q = slots.get(k) if slots.get(k) is not None else slots.get(int(k))
            if not isinstance(q, dict) or q.get("mx") is None:
                continue          # 没有机床坐标 = 用不了（老版本清空过的点）
            item = {"mx": round(float(q["mx"]), 4),
                    "my": round(float(q.get("my") or 0.0), 4)}
            if q.get("mz") is not None:
                item["mz"] = round(float(q["mz"]), 4)
            if q.get("mzm") is not None:
                item["mzm"] = round(float(q["mzm"]), 4)   # v3.0.2：别把机床 Z 弄丢（抬刀靠它）
            if q.get("cur"):
                item["cur"] = 1
            got[k] = item
        if got:
            out["pts"][e] = got
    rz = d.get("refz")
    if isinstance(rz, dict) and rz.get("x") is not None:
        out["refz"] = {"x": round(float(rz["x"]), 4),
                       "y": round(float(rz.get("y") or 0.0), 4),
                       "t": str(rz.get("t") or "")}
    return out


def wpos3(l):
    """刀尖当前工作坐标 (x, y, z) = MPos − 偏移（相对本次零点）。读不到返回 None。"""
    st = (l.status() if l else None) or {}
    mp = st.get("mpos")
    if not mp:
        return None
    w = st.get("wco")
    if w and len(w) >= 3:
        return (mp[0] - w[0], mp[1] - w[1], mp[2] - w[2])
    g = st.get("g54")
    g92 = st.get("g92")
    if g is None and g92 is None:
        # 刚连上 / 重连后 $# 还没回来：宁可显示「同步中」，也不能把机床坐标当工作坐标
        return None
    g = g or (0.0, 0.0, 0.0)
    g92 = g92 or (0.0, 0.0, 0.0)
    return (mp[0] - g[0] - g92[0], mp[1] - g[1] - g92[1], mp[2] - g[2] - g92[2])


def session_path():
    """会话快照文件。和 preset 分开存：8 点标定是长期资产，会话是一次性工作状态。
    环境变量 GRBL_CENTER_SESSION_FILE 可覆盖（自测用，避免污染真实数据）。"""
    envp = os.environ.get("GRBL_CENTER_SESSION_FILE")
    if envp:
        return envp
    here = os.path.dirname(os.path.abspath(__file__))
    try:
        if os.access(here, os.W_OK):
            return os.path.join(here, SESSION_NAME)
    except Exception:
        pass
    return os.path.join(os.path.expanduser("~"), "." + SESSION_NAME)


def session_load():
    try:
        with open(session_path(), "r", encoding="utf-8") as f:
            d = json.load(f)
        return d if isinstance(d, dict) else {}
    except Exception:
        return {}


def session_save(d):
    """原子写：先写 .tmp 再 os.replace —— 写到一半断电也不会留下坏文件"""
    p = session_path()
    tmp = p + ".tmp"
    try:
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(d, f, ensure_ascii=False, indent=1)
        os.replace(tmp, p)
        return True
    except Exception:
        try:
            if os.path.exists(tmp):
                os.remove(tmp)
        except Exception:
            pass
        return False


def session_ok(d):
    """能不能拿来恢复：版本对、且确实有内容（碰点 / 圆点 / 源刀路任一）"""
    if not isinstance(d, dict) or d.get("ver") != SESSION_VER:
        return False
    pts = d.get("pts") or {}
    n = 0
    if isinstance(pts, dict):
        n = sum(len(v or []) for v in pts.values())
    return bool(n or (d.get("cpts") or []) or (d.get("src") or "").strip())


def list_ports():
    """三路合并枚举串口：pyserial + 注册表 + QueryDosDevice（任一可用即可）"""
    found = {}          # key = 大写端口名, value = (原始端口名, 描述)

    def _add(dev, desc):
        k = dev.upper()
        if k and k not in found:
            found[k] = (dev, desc or "")

    try:
        from serial.tools import list_ports as lp
        for p in lp.comports():
            _add(p.device, p.description or "")
    except Exception:
        pass

    for dev, desc in win_registry_ports():
        _add(dev, desc or "注册表")
    for dev in win_dos_ports():
        _add(dev, "")

    def _key(item):
        dev = item[1][0]
        m = re.search(r"(\d+)$", dev)
        return (int(m.group(1)) if m else 999, dev)

    return [_v for _k, _v in sorted(found.items(), key=_key)]


def serial_env_report():
    """诊断信息：解释器、pyserial 状态、三路枚举结果"""
    lines = []
    lines.append("Python %s" % sys.version.split()[0])
    lines.append("解释器 %s" % sys.executable)
    try:
        import serial
        lines.append("pyserial %s  (%s)" % (getattr(serial, "__version__", "?"),
                                            os.path.dirname(serial.__file__)))
    except Exception as e:
        lines.append("pyserial 不可用：%s" % e)
    try:
        from serial.tools import list_ports as lp
        raw = list(lp.comports())
        lines.append("pyserial 枚举：%d 个 %s" % (
            len(raw), ", ".join("%s(%s)" % (p.device, p.description or "") for p in raw) or "无"))
    except Exception as e:
        lines.append("pyserial 枚举失败：%s" % e)
    if os.name == "nt":
        reg = win_registry_ports()
        lines.append("注册表 SERIALCOMM：%s" % (", ".join(d for d, _ in reg) or "无"))
        dos = win_dos_ports()
        lines.append("QueryDosDevice：%s" % (", ".join(dos) or "无"))
    else:
        lines.append("（非 Windows，跳过注册表枚举）")
    lines.append("最终可用：%s" % (", ".join(d for d, _ in list_ports()) or "无"))
    return lines


# ---------------------------------------------------------------- GUI ----
def _enable_dpi_awareness():
    """Windows 高分屏：先声明 DPI 感知。

    不声明时，Windows 会把整个窗口**按位图放大**再交给显示器 ——
    125%/150% 缩放下所有文字都被拉伸插值，看起来发虚、模糊、边缘毛糙。
    这是「字体难看」最常见也最容易被忽略的原因（改字号字体都治不了）。
    返回实际缩放比（96dpi = 1.0），供 tk scaling 与窗口尺寸使用。
    """
    if os.name != "nt":
        return 1.0
    try:
        import ctypes
        try:
            # 1 = system aware：Tk 8.6 下最稳；2(per-monitor) 会在拖动窗口时错位
            ctypes.windll.shcore.SetProcessDpiAwareness(1)
        except Exception:
            try:
                ctypes.windll.user32.SetProcessDPIAware()
            except Exception:
                return 1.0
        try:
            hdc = ctypes.windll.user32.GetDC(0)
            _dpi = ctypes.windll.gdi32.GetDeviceCaps(hdc, 88)   # LOGPIXELSX
            ctypes.windll.user32.ReleaseDC(0, hdc)
            if _dpi and 72 <= _dpi <= 480:
                return _dpi / 96.0
        except Exception:
            pass
        return 1.0
    except Exception:
        return 1.0


def run_gui(mock=False, port=None, baud=115200, gui_test=False, transport=None, shape=None,
            tab=None, font=None):
    try:
        import tkinter as tk
        from tkinter import ttk, filedialog, messagebox
    except ImportError:
        print("缺少 tkinter，无法打开图形界面。可以用命令行模式： python grbl_center.py transform ...")
        return

    # 高分屏先声明 DPI 感知，否则整个界面被系统位图放大 → 字全糊（详见 _enable_dpi_awareness）
    _scale = _enable_dpi_awareness()
    root = tk.Tk()
    try:
        if abs(_scale - 1.0) > 0.01:
            root.tk.call("tk", "scaling", _scale * 96.0 / 72.0)   # scaling = 每磅像素数
    except Exception:
        pass
    vlabel = VER if str(VER)[:1].isalpha() else ("v" + str(VER))

    # ---- 全局字体（R1 修订：宋体优先 + 像素字号）----
    # 实测结论：这台机器上 Microsoft YaHei UI 反而糊、难看，宋体更清楚。
    # 原因是宋体（SimSun）在 12~16px 档位带**内嵌点阵**，整数像素时笔画是「点」出来的，
    # 比矢量轮廓抗锯齿锐利得多；而用磅值(9/10/11pt)会换算成 12/13.3/14.7px 这类
    # 非整数像素 → 点阵失效退回轮廓 → 反而发虚。所以宋体模式一律用「像素字号」
    # （Tk 里负数 = 像素），并乘 DPI 缩放保证物理像素跟手。
    # 想换矢量字：--font yahei（雅黑UI）/ dengxian（等线）/ auto（自动挑）
    try:
        from tkinter import font as _tkfont
        _fams = set(_tkfont.families(root))
    except Exception:
        _tkfont = None
        _fams = set()

    def _pick_font(cands, fallback):
        for _c in cands:
            if _c in _fams:
                return _c
        # 一个候选都没有（非 Windows / 精简字体包）：跟随系统默认，别硬塞不存在的族
        try:
            return _tkfont.nametofont("TkDefaultFont").actual("family")
        except Exception:
            return fallback

    # 方案 = (族候选, 是否用像素字号)。宋体靠点阵，必须像素；矢量字用磅值即可。
    _FONT_PRESETS = {
        "simsun":   (("SimSun", "宋体", "NSimSun", "Noto Serif CJK SC"), True),
        "yahei":    (("Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC"), False),
        "dengxian": (("DengXian", "等线", "Microsoft YaHei UI"), False),
        "auto":     (("Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC"), False),
    }
    _pre = _FONT_PRESETS.get(str(font or "simsun").lower(), _FONT_PRESETS["simsun"])
    UI_FONT = _pick_font(_pre[0], "SimSun")
    UI_MONO = _pick_font(("Cascadia Mono", "Consolas", "JetBrains Mono",
                          "DejaVu Sans Mono", "Courier New"), "Consolas")
    UIFONT_NAME = str(font or "simsun").lower()
    if _pre[1]:
        def _px(n):
            """逻辑像素 → Tk 像素字号（负数）。乘 DPI 缩放，150% 屏上也是同一物理大小。"""
            return -max(11, int(round(n * _scale)))
        FS_TINY = _px(12)    # 说明/辅助（宋体 12px 点阵最锐）
        FS_SMALL = _px(13)   # 次要标签
        FS_BODY = _px(13)    # 正文（宋体 13px 点阵；比 14 更紧凑，车间屏上一行能多放几个字）
        FS_HEAD = _px(16)    # 区标题/页签
        FS_BIG = _px(20)     # 结果大字
    else:
        FS_TINY = 9
        FS_SMALL = 10
        FS_BODY = 11
        FS_HEAD = 12
        FS_BIG = 16
    root.title("%s  %s" % (APP, vlabel))
    _sw, _sh = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d" % (min(int(1060 * _scale), max(int(880 * _scale), _sw - 60)),
                             min(int(1400 * _scale), max(int(720 * _scale), _sh - 100))))
    root.minsize(int(900 * _scale), int(720 * _scale))
    try:
        _icon = tk.PhotoImage(data=LOGO_PNG64_B64)
        root.iconphoto(True, _icon)
        root._logo_img = _icon          # 留住引用，否则会被回收掉变成默认羽毛图标
    except Exception:
        pass
    # ============ v1.39.6：页面分区（顶部固定 + 三页签 + 底部固定日志）============
    # 原来所有卡片塞在一个 Canvas 里滚：滚一格要重绘整屏几十个控件 —— 这是「滚屏卡」；
    # 滚轮又是全局绑定，鼠标停在日志上滚，翻的是整页 —— 这是「样式莫名干扰」。
    # 现在：顶部只留 DRO / 流程条 / 步骤条（永不动）；
    #       中间三页签「定位 → 刀路 → 发送」，顺序就是操作顺序；
    #       每页各自一节滚动区（内容不溢出就不滚，溢出只重绘本页少量控件）；
    #       底部日志独立，滚轮按「鼠标停在哪」分发，谁也不抢。
    _top = ttk.Frame(root)
    _top.pack(side="top", fill="x")

    try:
        ttk.Style().configure("TNotebook.Tab", padding=(22, 10),
                              font=(UI_FONT, FS_HEAD, "bold"))
    except Exception:
        pass
    _nb = ttk.Notebook(root)
    _nb.pack(side="top", fill="both", expand=True, padx=10, pady=(8, 8))

    _page_cvs = []

    def _mk_page(tab_text):
        """一页 = 一个独立滚动区；内容没超出时完全不滚（零重绘）。"""
        outer = ttk.Frame(_nb)
        _nb.add(outer, text=tab_text)
        cv = tk.Canvas(outer, highlightthickness=0, bd=0, bg="#f5f6f8")
        sb = ttk.Scrollbar(outer, orient="vertical", command=cv.yview)
        cv.configure(yscrollcommand=sb.set)
        inner = ttk.Frame(cv)
        win = cv.create_window((0, 0), window=inner, anchor="nw")

        def _sync(_e=None):
            try:
                cv.configure(scrollregion=cv.bbox("all"))
                over = inner.winfo_reqheight() > cv.winfo_height() + 1
                if over and not sb.winfo_ismapped():
                    sb.pack(side="right", fill="y")
                elif (not over) and sb.winfo_ismapped():
                    sb.pack_forget()
                    cv.yview_moveto(0.0)
            except Exception:
                pass

        inner.bind("<Configure>", _sync)
        cv.bind("<Configure>", lambda e: (cv.itemconfigure(win, width=e.width), _sync()))
        cv.pack(side="left", fill="both", expand=True)
        _page_cvs.append(cv)
        return inner

    # v1.39.7：串口状态 / 连接 / 日志 独立成第一页。
    # 这一页不用滚动区 —— 日志框直接 expand 撑满，任何屏幕高度都正好，不会多一条滚动条。
    _pg_conn = ttk.Frame(_nb)
    _nb.add(_pg_conn, text="连接 · 日志")
    _pg_pos = _mk_page("定位 · 碰边 / 记点")
    _pg_cut = _mk_page("中心 · 刀路")
    _pg_snd = _mk_page("发送 · 加工")

    if tab:                                  # --tab pos / cut / send：启动即停在该页
        # 注意：_mk_page 返回的是页内滚动容器（inner），不是 notebook 的页对象，
        # 传对象给 select 会静默失败 —— 这里用页序号。
        _TABS = {"connect": 0, "pos": 1, "cut": 2, "send": 3}
        try:
            _nb.select(_TABS[str(tab)])
        except Exception:
            pass

    def _on_wheel(e):
        # v1.39.6：滚轮按归属分发 —— 停在日志上翻日志、停在页签上翻本页，互不干扰。
        _up = (getattr(e, "num", None) == 4) or getattr(e, "delta", 0) > 0
        _step = -3 if _up else 3
        try:
            _w = root.winfo_containing(e.x_root, e.y_root)
            while _w is not None:
                if _w is txt:
                    txt.yview_scroll(_step, "units")
                    return "break"
                if _w in _page_cvs:
                    _w.yview_scroll(_step, "units")
                    return "break"
                _w = getattr(_w, "master", None)
        except Exception:
            pass
        return "break"

    root.bind_all("<MouseWheel>", _on_wheel)
    root.bind_all("<Button-4>", _on_wheel)
    root.bind_all("<Button-5>", _on_wheel)
    # ================= v1.34 A 档：视觉统一（只改样式，不动布局/逻辑）=================
    # 配色令牌（改主题只改这里）
    UI_BG = "#f5f6f8"        # 窗口底（浅灰，衬托白卡片）
    UI_CARD = "#ffffff"      # 卡片/输入框底
    UI_LINE = "#e4e7ec"      # 边框
    UI_TXT = "#1f2937"       # 主文字
    UI_TXT2 = "#64748b"      # 次文字（slate-500，比旧 #888 更清）
    UI_TXT3 = "#9ca3af"      # 弱提示
    UI_PRIMARY = "#2563eb"   # 主色
    UI_PRIM_D = "#1d4ed8"    # 主色（按下/区标题）
    UI_OK = "#10b981"
    UI_WARN = "#f59e0b"
    UI_DANGER = "#ef4444"
    # UI_FONT / UI_MONO 已在 root 建好后（函数开头）探测定义

    try:
        from tkinter import font as _uifont
        # 默认字体一次统一（所有没显式指定字体的控件跟着走），顺带把混杂的 8/9 号收敛到 10
        for _fn in ("TkDefaultFont", "TkTextFont", "TkMenuFont", "TkHeadingFont"):
            try:
                _uifont.nametofont(_fn).configure(family=UI_FONT, size=FS_BODY)
            except Exception:
                pass
        try:
            _uifont.nametofont("TkFixedFont").configure(family=UI_MONO, size=FS_BODY)
        except Exception:
            pass
    except Exception:
        pass

    try:
        _st = ttk.Style()
        _st.theme_use("clam")          # 唯一支持完全自定义颜色的内置主题
        root.configure(bg=UI_BG)
        _st.configure(".", background=UI_BG, foreground=UI_TXT, font=(UI_FONT, FS_BODY))
        _st.configure("TFrame", background=UI_BG)
        _st.configure("TLabel", background=UI_BG, foreground=UI_TXT)
        # 卡片内部的容器/文字必须是白底（否则卡片里会出现一条条浅灰带）
        _st.configure("Card.TFrame", background=UI_CARD)
        _st.configure("Card.TLabel", background=UI_CARD, foreground=UI_TXT)

        # ---- 卡片：白底 + 1px 细边（取代 Windows98 凹槽 GroupBox 观感）----
        _st.configure("TLabelframe", background=UI_CARD, bordercolor=UI_LINE,
                      relief="solid", borderwidth=1, padding=6)
        _st.configure("TLabelframe.Label", background=UI_CARD, foreground=UI_PRIM_D,
                      font=(UI_FONT, FS_BODY, "bold"))
        _st.configure("Sec.TLabelframe", background=UI_CARD, bordercolor=UI_LINE,
                      relief="solid", borderwidth=1, padding=6)
        _st.configure("Sec.TLabelframe.Label", background=UI_CARD, foreground=UI_PRIM_D,
                      font=(UI_FONT, FS_HEAD, "bold"))

        # ---- 次按钮：白底细边（扁平，无 XP 渐变）----
        _st.configure("TButton", background=UI_CARD, foreground=UI_TXT,
                      bordercolor="#dbe0e7", lightcolor=UI_CARD, darkcolor=UI_CARD,
                      relief="flat", padding=(7, 4), focuscolor=UI_CARD)
        _st.map("TButton",
                background=[("pressed", "#eef2f7"), ("active", "#f3f6fb")],
                bordercolor=[("active", UI_PRIMARY)],
                foreground=[("disabled", UI_TXT3)])
        # 小号按钮（点动/微调那种密集排列用）
        _st.configure("Sm.TButton", font=(UI_FONT, FS_SMALL), padding=(7, 3))

        # ---- 主按钮：实心蓝白字 ----
        _st.configure("Go.TButton", font=(UI_FONT, FS_HEAD, "bold"), padding=(16, 9),
                      background=UI_PRIMARY, foreground="#ffffff",
                      bordercolor=UI_PRIMARY, lightcolor=UI_PRIMARY,
                      darkcolor=UI_PRIMARY, relief="flat", focuscolor=UI_PRIMARY)
        _st.map("Go.TButton",
                background=[("pressed", UI_PRIM_D), ("active", UI_PRIM_D),
                            ("disabled", "#9db8f0"), ("!disabled", UI_PRIMARY)],
                foreground=[("disabled", "#f2f6ff"), ("!disabled", "#ffffff")],
                bordercolor=[("!disabled", UI_PRIMARY)])

        # 次级按钮：白底 + 细边 + 深字。clam 的默认 TButton 是灰底方框，
        # 放在白色卡片里像「复选框」，看不出是能点的按钮（用户实机反馈过）。
        _st.configure("TButton", background=UI_CARD, foreground=UI_TXT,
                      bordercolor=UI_LINE, lightcolor=UI_CARD, darkcolor=UI_CARD,
                      relief="flat", padding=(8, 4), font=(UI_FONT, FS_BODY))
        _st.map("TButton",
                background=[("pressed", "#e9eef6"), ("active", "#f2f5f9"),
                            ("disabled", "#f7f8fa")],
                foreground=[("disabled", UI_TXT3), ("active", UI_PRIM_D)],
                bordercolor=[("active", UI_PRIMARY), ("!active", UI_LINE)],
                lightcolor=[("active", UI_PRIMARY)], darkcolor=[("active", UI_PRIMARY)])
        # 暂停（琥珀）/ 停止（红）：车间戴手套操作，这两个必须跟普通按钮一眼分开
        _st.configure("Warn.TButton", background="#FFF3E0", foreground="#A65A00",
                      bordercolor="#EBC38E", lightcolor="#FFF3E0", darkcolor="#FFF3E0",
                      relief="flat", padding=(8, 4), font=(UI_FONT, FS_BODY))
        _st.map("Warn.TButton",
                background=[("pressed", "#FFE4BC"), ("active", "#FFEFD8"),
                            ("disabled", "#f7f8fa")],
                foreground=[("disabled", UI_TXT3), ("active", "#8A4B00")],
                bordercolor=[("active", "#D9A55F"), ("!active", "#EBC38E")])
        _st.configure("Danger.TButton", background="#FDECEC", foreground="#B42318",
                      bordercolor="#F0B6AE", lightcolor="#FDECEC", darkcolor="#FDECEC",
                      relief="flat", padding=(8, 4), font=(UI_FONT, FS_BODY))
        _st.map("Danger.TButton",
                background=[("pressed", "#FBD9D6"), ("active", "#FDE4E1"),
                            ("disabled", "#f7f8fa")],
                foreground=[("disabled", UI_TXT3), ("active", "#8F1B12")],
                bordercolor=[("active", "#DE8F84"), ("!active", "#F0B6AE")])

        # 发送进度条：调粗一点，待机时那条浅槽才看得出来
        _st.configure("Send.Horizontal.TProgressbar", background=UI_PRIMARY,
                      troughcolor="#d7dde7", bordercolor="#c8d0dc",
                      lightcolor=UI_PRIMARY, darkcolor=UI_PRIMARY, thickness=18)

        # ---- 输入类：白底细边 ----
        _st.configure("TEntry", fieldbackground=UI_CARD, bordercolor=UI_LINE,
                      lightcolor=UI_LINE, darkcolor=UI_LINE, padding=4)
        _st.map("TEntry", bordercolor=[("focus", UI_PRIMARY)],
                lightcolor=[("focus", UI_PRIMARY)])
        _st.configure("TCombobox", fieldbackground=UI_CARD, background=UI_CARD,
                      bordercolor=UI_LINE, arrowcolor=UI_TXT2, padding=4)
        _st.map("TCombobox",
                fieldbackground=[("readonly", UI_CARD), ("!readonly", UI_CARD)],
                bordercolor=[("focus", UI_PRIMARY)],
                arrowcolor=[("active", UI_PRIMARY)])
        try:
            root.option_add("*TCombobox*Listbox.background", UI_CARD)
            root.option_add("*TCombobox*Listbox.foreground", UI_TXT)
            root.option_add("*TCombobox*Listbox.selectBackground", UI_PRIMARY)
            root.option_add("*TCombobox*Listbox.selectForeground", "#ffffff")
        except Exception:
            pass

        # ---- 勾选/单选/页签/滚动条/进度条 ----
        _st.configure("TCheckbutton", background=UI_BG, foreground=UI_TXT)
        _st.configure("TRadiobutton", background=UI_BG, foreground=UI_TXT)
        _st.configure("TNotebook", background=UI_BG, borderwidth=0)
        _st.configure("TNotebook.Tab", padding=(14, 6), font=(UI_FONT, FS_BODY))
        _st.map("TNotebook.Tab", background=[("selected", UI_CARD)],
                foreground=[("selected", UI_PRIM_D)])
        _st.configure("Vertical.TScrollbar", background="#dfe4ea", troughcolor=UI_BG,
                      bordercolor=UI_BG, arrowcolor=UI_TXT2, relief="flat", width=11)
        _st.configure("Horizontal.TScrollbar", background="#dfe4ea", troughcolor=UI_BG,
                      bordercolor=UI_BG, arrowcolor=UI_TXT2, relief="flat")
        _st.configure("Horizontal.TProgressbar", background=UI_PRIMARY,
                      troughcolor="#e9edf3", bordercolor=UI_LINE, lightcolor=UI_PRIMARY,
                      darkcolor=UI_PRIMARY)
        _st.configure("TSeparator", background=UI_LINE)
    except Exception:
        pass

    def _card(parent, num, title, sub="", pad=(10, 6)):
        """新式卡片：白底 + 1px 细边 + 顶栏（编号徽章 / 标题 / 右注）+ 1px 分隔线。
        返回 (外框, 内容区) —— 外框拿去 pack，内容区当父容器用（用法与 LabelFrame 一致）。"""
        wrap = tk.Frame(parent, bg=UI_CARD, bd=0, highlightthickness=1,
                        highlightbackground=UI_LINE, highlightcolor=UI_LINE)
        wrap._is_card = True          # 让 _ui_restyle 知道「这张卡里面都是白底」
        head = tk.Frame(wrap, bg=UI_CARD)
        head.pack(fill="x", padx=12, pady=(8, 7))
        if num:
            tk.Label(head, text=str(num), bg="#eef2ff", fg=UI_PRIM_D,
                     font=(UI_FONT, FS_BODY, "bold"), padx=8, pady=0).pack(side="left")
        _tlb = tk.Label(head, text=title, bg=UI_CARD, fg=UI_TXT,
                        font=(UI_FONT, FS_HEAD, "bold"))
        _tlb.pack(side="left", padx=(8, 0))
        wrap._card_title = _tlb      # 切形状时要改卡片标题（矩形/圆形）
        if sub:
            tk.Label(head, text=sub, bg=UI_CARD, fg=UI_TXT3,
                     font=(UI_FONT, FS_BODY)).pack(side="left", padx=(10, 0))
        tk.Frame(wrap, bg=UI_LINE, height=1).pack(fill="x")
        inner = tk.Frame(wrap, bg=UI_CARD)
        inner.pack(fill="both", expand=True, padx=10, pady=(7, 9))
        wrap.pack_configure = wrap.pack_configure if hasattr(wrap, "pack_configure") else None
        return wrap, inner

    def _ui_restyle(w=None, in_card=False):
        """把仍是系统灰底（#d9d9d9 / SystemButtonFace）的 tk 控件换掉。
        只动「没指定过颜色」的控件，卡片色块/模式按钮等已设色的原样保留。"""
        _w = w if w is not None else root
        for _c in _w.winfo_children():
            try:
                _card = in_card or _c.winfo_class() == "TLabelframe" or \
                    isinstance(_c, tk.LabelFrame) or getattr(_c, "_is_card", False)
                _bg = UI_CARD if _card else UI_BG
                if _c.winfo_class() in ("Label", "Frame", "Checkbutton", "Radiobutton",
                                        "Message", "Canvas", "Text", "Listbox"):
                    _cur = str(_c.cget("bg"))
                    if _cur in ("#d9d9d9", "SystemButtonFace", "#f0f0f0", "gray95"):
                        _c.configure(bg=_bg)
                elif _c.winfo_class() in ("TFrame", "TLabel"):
                    # ttk 控件不能用 configure(bg=)，只能换 style；
                    # 只动「没自定义过样式」的，避免覆盖 Go.TButton 之类
                    if _card and not str(_c.cget("style") or ""):
                        _c.configure(style="Card.TFrame" if _c.winfo_class() == "TFrame"
                                     else "Card.TLabel")
                elif _c.winfo_class() == "Button":
                    _cur = str(_c.cget("bg"))
                    if _cur in ("#d9d9d9", "SystemButtonFace", "#f0f0f0"):
                        _c.configure(bg=UI_CARD, activebackground="#f3f6fb",
                                     relief="flat", bd=0, highlightthickness=1,
                                     highlightbackground=UI_LINE,
                                     activeforeground=UI_TXT)
                _ui_restyle(_c, _card)
            except Exception:
                pass

    if gui_test:
        # 自检绝不能碰用户真实数据：会话与 8 点预设都指到临时目录
        _zzselftest = tempfile.mkdtemp(prefix="grbl_center_selftest_")
        os.environ["GRBL_CENTER_SESSION_FILE"] = os.path.join(_zzselftest, "session.json")
        os.environ["GRBL_CENTER_PRESET_FILE"] = os.path.join(_zzselftest, "preset.json")

    link_holder = {"link": MockLink() if mock else None}
    link_ref = [None]              # 延迟绑定：link() 定义在后面
    append_log_ref = [lambda m: None]
    fitter = CenterFitter(0.0)
    res_holder = {"r": None}

    v_port = tk.StringVar()
    v_baud = tk.StringVar(value=str(baud))
    v_state = tk.StringVar(value="未连接" if not mock else "模拟机 · Idle")
    v_mpos = tk.StringVar(value="-")     # 兼容保留（不再显示，逻辑侧仍写它）
    v_dro = {k: tk.StringVar(value="—") for k in ("X", "Y", "Z")}

    def _set_dro(seq=None):
        """把 X/Y/Z 三个数显块刷成 seq（None = 没数据，显示 —）"""
        for _i, _k in enumerate("XYZ"):
            try:
                _setv(v_dro[_k], "—" if seq is None else "%9.3f" % float(seq[_i]))
            except Exception:
                _setv(v_dro[_k], "—")
    v_mpos2 = tk.StringVar(value="")      # v1.28：机床坐标缩成小字（大数字显示工作坐标）
    v_radius = tk.StringVar(value="3.175")
    # R2.10：默认「不补偿」—— 分中只取中心，补偿只改宽高（四条边各偏同一个量，中心不动）
    v_comp = tk.StringVar(value="不补偿（刀路就在碰到的线上）")
    v_shape = tk.StringVar(value=(SHAPES[1] if shape == SHAPE_CIRCLE else SHAPES[0]))
    v_off = tk.StringVar(value="0.0000")
    v_step = tk.StringVar(value="0.1")
    v_feed = tk.StringVar(value="800")
    v_count = tk.StringVar(value="左 0 · 右 0 · 前 0 · 后 0")
    v_wcs = tk.StringVar(value="")
    v_result = tk.StringVar(value="—")
    v_g10 = tk.StringVar(value="")
    v_src = tk.StringVar(value="")
    v_dst = tk.StringVar(value="")
    v_ox = tk.StringVar(value="0")
    v_oy = tk.StringVar(value="0")
    v_rot = tk.BooleanVar(value=True)
    v_theta = tk.StringVar(value="")
    v_theta_src = tk.StringVar(value="")
    v_hint = tk.StringVar(value="")
    v_nextedge = tk.StringVar(value="Enter 记点（按点动方向判边；1/2/3/4 指定边）")
    v_check = tk.StringVar(value="")
    v_zero = tk.StringVar(value="读取中…")
    v_mach = tk.BooleanVar(value=False)       # False = 有回零/G54（默认）；True = 无回零直出
    v_zmode = tk.StringVar(value="none")      # none / shift / override
    v_zval = tk.StringVar(value="0")
    v_dry = tk.BooleanVar(value=False)        # v1.18 废弃（用户手动抬 Z 空走，不再出 _check 文件）
    v_droptc = tk.BooleanVar(value=False)     # 移除 T/M6
    v_start_z = tk.StringVar(value="")         # R2：起刀 Z；留空 = 跟随原刀路第一处 Z（推荐）
    v_session = tk.StringVar(value="")        # 恢复上次会话的提示条

    # 会话恢复提示条（有旧数据才显示；默认不占版面）
    lbl_session = tk.Label(_top, textvariable=v_session, anchor="w", justify="left",
                           fg="#9a3412", bg="#fff7ed", font=(UI_FONT, FS_SMALL, "bold"),
                           wraplength=980, bd=0, padx=8, pady=4,
                           highlightthickness=1, highlightbackground="#fed7aa")

    # ---- ① 连接 ----
    top_w, top = _card(_pg_conn, "1", "连接串口", "选串口 → 连接；插拔后点「刷新端口」")
    top_w.pack(fill="x", padx=10, pady=(10, 6))
    t1 = ttk.Frame(top)
    t1.pack(fill="x", padx=8, pady=(8, 2))
    ttk.Label(t1, text="串口").pack(side="left", padx=(0, 4))
    cb_port = ttk.Combobox(t1, textvariable=v_port, width=16, values=[])
    cb_port.pack(side="left", padx=4)
    ttk.Label(t1, text="（可手打 COM3 / COM10）", foreground=UI_TXT2).pack(side="left")
    ttk.Label(t1, text="波特率").pack(side="left", padx=(14, 4))
    ttk.Combobox(t1, textvariable=v_baud, width=8,
                 values=["115200", "250000", "57600"]).pack(side="left")
    ttk.Label(t1, text="机器").pack(side="left", padx=(16, 4))
    ttk.Radiobutton(t1, text="无回零 → 直出机床坐标", variable=v_mach, value=True,
                    command=lambda: apply_mode()).pack(side="left")
    ttk.Radiobutton(t1, text="有回零/有限位 → G54", variable=v_mach, value=False,
                    command=lambda: apply_mode()).pack(side="left", padx=(4, 0))

    # v1.39.7：这一页只管「连上机器 + 看日志」；
    #   设零 / 走中心 已搬到定位页顶部（那边干活要用，不能跟着跑这儿来）
    t2 = ttk.Frame(top)
    t2.pack(fill="x", padx=8, pady=(2, 8))
    btn_conn = ttk.Button(t2)
    btn_conn.pack(side="left", padx=(0, 8))
    ttk.Button(t2, text="解锁 $X", command=lambda: do(lambda: link().unlock())).pack(side="left", padx=(0, 10))
    tk.Label(t2, text="连不上？→ ③ 发送页的「高级 / 工具」里有 刷新端口 / 诊断 / 软复位",
             foreground=UI_TXT2, font=(UI_FONT, FS_TINY)).pack(side="left", padx=4)

    # ---- 状态 ----
    stf = ttk.Frame(_top)
    stf.pack(fill="x", padx=10, pady=(2, 2))
    # R1：左上角程序徽标（26px，和 DRO 小卡同色底，视觉上是一块小铭牌）
    try:
        _lg = tk.PhotoImage(data=LOGO_PNG26_B64)
        _lg_box = tk.Frame(stf, bg="#f8fafc", bd=0, highlightthickness=1,
                           highlightbackground=UI_LINE)
        _lg_box.pack(side="left", padx=(0, 8))
        tk.Label(_lg_box, image=_lg, bg="#f8fafc", bd=0).pack(padx=4, pady=4)
        _lg_box._keep = _lg
    except Exception:
        pass
    lbl_state = tk.Label(stf, textvariable=v_state, font=(UI_MONO, 13, "bold"),
                         fg="#0f9f6e", width=10, anchor="w")
    lbl_state.pack(side="left")
    # DRO：X / Y / Z 三个独立数显块（灰底小卡 + 等宽大字），一眼看清刀在哪
    for _k in ("X", "Y", "Z"):
        _b = tk.Frame(stf, bg="#f8fafc", bd=0, highlightthickness=1,
                      highlightbackground=UI_LINE, highlightcolor=UI_LINE)
        _b.pack(side="left", padx=(8, 0))
        tk.Label(_b, text=_k, bg="#f8fafc", fg=UI_TXT2,
                 font=(UI_FONT, FS_SMALL, "bold")).pack(anchor="w", padx=9, pady=(3, 0))
        tk.Label(_b, textvariable=v_dro[_k], bg="#f8fafc", fg="#111827",
                 font=(UI_MONO, 21, "bold")).pack(anchor="w", padx=9, pady=(0, 3))
    _rk = tk.Frame(stf, bg="#f8fafc", bd=0, highlightthickness=1,
                   highlightbackground=UI_LINE, highlightcolor=UI_LINE)
    _rk.pack(side="right", padx=(8, 2))
    tk.Label(_rk, text="机床 / 偏置", bg="#f8fafc", fg=UI_TXT2,
             font=(UI_FONT, FS_SMALL, "bold")).pack(anchor="w", padx=9, pady=(3, 0))
    tk.Label(_rk, textvariable=v_mpos2, bg="#f8fafc", fg=UI_TXT3,
             font=(UI_MONO, 10)).pack(anchor="w", padx=9)
    lbl_wcs = tk.Label(_rk, textvariable=v_wcs, bg="#f8fafc", fg=UI_TXT2,
                       font=(UI_FONT, FS_SMALL))
    lbl_wcs.pack(anchor="w", padx=9, pady=(0, 3))

    def _upd_done(r):
        if not r.get("ok"):
            append_log("检查更新失败：%s（可手动打开 %s 看版本）" % (r.get("err"), DOWNLOAD_PAGE))
            messagebox.showinfo(APP, "检查更新失败：\n%s\n\n当前版本 %s\n也可以直接打开 %s"
                                % (r.get("err"), VER, DOWNLOAD_PAGE))
            return
        if r.get("newer"):
            append_log("发现新版本 %s（当前 %s）：%s" % (r.get("latest"), VER, r.get("note")))
            if messagebox.askyesno(APP, "发现新版本 %s（当前 %s）\n\n%s\n\n现在打开下载页？"
                                   % (r.get("latest"), VER, r.get("note") or "")):
                try:
                    import webbrowser
                    webbrowser.open(r.get("url") or DOWNLOAD_PAGE)
                except Exception:
                    pass
        else:
            append_log("已是最新版本 %s" % VER)
            messagebox.showinfo(APP, "已是最新版本 %s" % VER)

    def _start_update_check():
        append_log("正在检查更新…（%s）" % UPDATE_URL)

        def _work():
            r = update_check()
            try:
                root.after(0, lambda: _upd_done(r))
            except Exception:
                pass

        threading.Thread(target=_work, daemon=True).start()


    # ---- 流程条：整个流程 8 格一条线（✔ 已完成 / ▶ 该做这步 / ○ 还没到）----
    # 用户要的就是「一眼看出现在走到哪、下一步点哪个按钮」，所以这里是全程唯一入口。
    # 顺序就是用户口述的：开机 → 联机 → 手动移到初步中心+设零 → 碰边(定位点) → 走中心 → 设零点 → 加载 → 生成
    FLOW_STEPS = [("boot", "开机"), ("conn", "连接"), ("zero", "设零（起点）"),
                  ("edge", "碰边"), ("center", "走中心"),
                  ("zero2", "设零（中心）"), ("src", "加载刀路"),
                  ("gen", "生成刀路")]
    flow_ok = {"zero": False, "gen": False}   # 本次会话的「设过零 / 生成过」
    last_gen = {"p": ""}                      # 最近一次生成的刀路（⑤ 发送加工默认用它）
    flow_lbl = {}
    F_FLOW = (UI_FONT, FS_SMALL)
    F_FLOW_CUR = (UI_FONT, FS_SMALL, "bold")
    flowf = tk.Frame(_top)
    flowf.pack(fill="x", padx=12, pady=(6, 0))
    for _fi, (_fk, _ft) in enumerate(FLOW_STEPS):
        if _fi:
            tk.Label(flowf, text="→", fg="#cbd5e1",
                     font=(UI_FONT, FS_SMALL)).pack(side="left", padx=3)
        _flb = tk.Label(flowf, text="○ " + _ft, fg="#94a3b8", font=F_FLOW)
        _flb.pack(side="left")
        flow_lbl[_fk] = (_flb, _ft)

    v_stepbar = tk.StringVar(value="▶  先在 ① 点「连接」")
    sbf = ttk.Frame(_top)
    sbf.pack(fill="x", padx=12, pady=(2, 0))
    lbl_step = tk.Label(sbf, textvariable=v_stepbar, font=(UI_FONT, FS_BODY),
                        fg="#1d4ed8", anchor="w", justify="left")
    lbl_step.pack(fill="x")

    # ---- v1.39.8：最近一条日志 ----
    # 日志搬到「连接 · 日志」页以后，在定位/刀路/发送页就看不见了。
    # 这里留一行只显示「最后发生了什么」（出错变红加粗），点一下跳到日志页。
    v_lastlog = tk.StringVar(value="")
    lbl_last = tk.Label(_top, textvariable=v_lastlog, font=(UI_FONT, FS_SMALL),
                        fg="#64748b", anchor="w", justify="left", cursor="hand2")
    lbl_last.pack(fill="x", padx=14, pady=(0, 3))
    lbl_last.bind("<Button-1>", lambda _e: _nb.select(0))

    # ---- v1.39.7：设零 / 走中心 常驻定位页顶部（v1.28 起它们一直是「一眼能找到」的高频键）----
    _ztop = ttk.Frame(_pg_pos)
    _ztop.pack(fill="x", padx=10, pady=(10, 2))
    btn_top_zero = ttk.Button(_ztop, text="② 就在此处设零", style="Go.TButton",
                              command=lambda: set_xy_zero())
    btn_top_zero.pack(side="left", padx=(0, 8))
    btn_top_center = ttk.Button(_ztop, text="▶ ① 走到中心", style="Go.TButton",
                                command=lambda: goto_center())
    btn_top_center.pack(side="left", padx=(0, 8))
    btn_disp_zero = ttk.Button(_ztop, text="设 0 点（显示清零）",
                               command=lambda: set_disp_zero())
    btn_disp_zero.pack(side="left", padx=(0, 8))
    tk.Label(_pg_pos, text="「设 0 点」= 把当前位置显示成 0,0,0（摇到中心后点一下，靠边碰点就以它为原点；"
                          "负方向点动不会再被当成超行程）     "
                          "「② 设零」= 把当前位置登记成工件 0,0（给加工用，写进板子 G54）",
             foreground=UI_TXT2, font=(UI_FONT, FS_TINY), justify="left",
             anchor="w").pack(fill="x", padx=14, pady=(0, 2))

    # ---- ② 碰边定位 ----
    sec2_w, sec2 = _card(_pg_pos, "2", "碰边定位", "点动 → 碰到边 → 按 Enter 记一个点")
    sec2_w.pack(fill="x", padx=10, pady=6)

    # ---- 工件形状：矩形 / 圆形 ----
    sf = ttk.Frame(sec2)
    sf.pack(fill="x", padx=8, pady=(8, 0))
    ttk.Label(sf, text="工件形状", font=(UI_FONT, FS_SMALL, "bold")).pack(side="left")
    cb_shape = ttk.Combobox(sf, textvariable=v_shape, width=24, state="readonly",
                            values=SHAPES)
    cb_shape.pack(side="left", padx=(6, 10))
    lbl_shape_tip = ttk.Label(sf, foreground=UI_TXT2)
    lbl_shape_tip.pack(side="left")

    # R2.10：刀具 / 基准补偿整块移进「高级 / 工具」—— 分中只取中心，
    # 补偿只改算出来的宽高（四条边各偏同一个量，中心不动），主界面上不需要它。

    pf2 = ttk.LabelFrame(sec2, text="步长 / 速度")
    pf2.pack(fill="x", padx=6, pady=(2, 2))
    ttk.Label(pf2, text="点动步长(mm)").pack(side="left", padx=(8, 2), pady=8)
    cb_step = ttk.Combobox(pf2, textvariable=v_step, width=7,
                           values=["0.01", "0.05", "0.1", "0.5", "1", "5"])
    cb_step.pack(side="left")
    ttk.Label(pf2, text="速度 F").pack(side="left", padx=(14, 2))
    cb_feed = ttk.Combobox(pf2, textvariable=v_feed, width=7,
                           values=["30", "50", "100", "200", "500", "800", "1000"])
    cb_feed.pack(side="left")
    tk.Label(pf2, text="轻点走一步 · 按住 0.3 秒连续 · 改完值可直接按方向键（不用点鼠标）",
             fg=UI_TXT2, font=(UI_FONT, FS_TINY)).pack(side="left", padx=10)

    def _radius_mm():
        try:
            return max(0.0, float(v_radius.get() or 0.0))
        except ValueError:
            return 0.0

    def calc_offset():
        """按当前档位算「生效偏移」：+ 外扩 / − 内缩 / 0 不补偿"""
        D = _radius_mm()
        r = D / 2.0
        m = v_comp.get()
        if m.startswith("不补偿"):
            return 0.0
        if m.startswith("外扩一个半径"):
            return r
        if m.startswith("内缩一个半径"):
            return -r
        if m.startswith("内缩一个刀径"):
            return -D
        if m.startswith("外扩一个刀径"):
            return D
        try:
            return float(v_off.get() or 0.0)
        except ValueError:
            return 0.0

    def sync_off(*_a):
        """档位或刀径变了 → 把生效偏移回显出来（自定义档不回显，免得覆盖手填值）"""
        if not v_comp.get().startswith("自定义"):
            try:
                v_off.set("%.4f" % calc_offset())
            except Exception:
                pass

    def apply_offset():
        """把当前档位应用到 fitter（每次记录/解算前都调一次）"""
        fitter.offset = calc_offset()
        try:
            v_off.set("%.4f" % fitter.offset)
        except Exception:
            pass
        return fitter.offset

    cb_shape.bind("<<ComboboxSelected>>", lambda _e=None: apply_shape())
    try:
        v_radius.trace_add("write", lambda *a: sync_off())
    except Exception:
        pass
    sync_off()

    def _safe_do(fn):
        """点动/记录用：未连接时只写日志，不弹窗骚扰"""
        try:
            return fn()
        except Exception as e:
            append_log_ref[0]("!" + str(e))
            return None

    # ---- 点动控制：防误触 / 防堆积 / 松手即停 ----
    jog_live = []          # 正在按住的点动块（全局兜底停止用）
    JOG_HOLD = 0.26        # 按住超过这个时长才开始连续走
    JOG_MAX_CONT = 45.0    # R2.4：按住上限 90→45 秒。靠边点动用不到 45 秒，超了必是没停住
    JOG_SEG_MAX = 60.0     # R2.4：单条 jog 上限 600→60mm。
                           # 不做任何分段/续发 —— Candle 就是这么干的：一条 `$J=` + jog cancel。
                           # 600mm 在 F600 下要走 60 秒，短于按住上限 90 秒，正常操作走不完。
    #   原来按「进给 × 8 秒」算：F500 就是 66mm —— 松手信号一丢，刀就冲出去 66mm，
    #   这就是「X+/Y+ 一按就失控」。现在无论进给多快，单条最多 25mm。

    def jog_seg_for(feed):
        """R2.4：单条 jog 走多远 = 约 3 秒的量，夹在 15~60mm。
        为什么改：R1.6 一条走 600mm（F800 要 45 秒），松手 0x85 一旦丢/没送到，
        机器就会把这一条走完 —— 这就是「靠边点动一松手刀就飞出去、刹不住」。
        现在最坏情况只多走 60mm（不到 2 秒），看门狗和补停都有时间拦住。"""
        try:
            return max(15.0, min(JOG_SEG_MAX, float(feed) / 60.0 * 3.0))
        except Exception:
            return 30.0

    def _kill_block_timers(blk):
        """取消一个点动块的两个定时器：按住判定(hold) + 连续走超时(timer)

        ⚠ 以前只存了 timer、没存 hold，导致松手后 cancel 不掉「按住判定」那一发：
          它 285ms 后醒来发现 blk 还在 jog_live 就判定成「按住」→ 发一条长行程 jog
          → 没人停 → 一路跑到 15 秒兜底。这就是「连点几下突然跑老远」的根因。
        """
        for k in ("hold", "timer", "seg_timer"):
            tid = blk.get(k)
            if tid:
                try:
                    root.after_cancel(tid)
                except Exception:
                    pass
                blk[k] = None

    def clear_jogs_only():
        """清 GUI 侧的按住状态/定时器。

        ⚠ 如果清掉的块**已经在连续走**（cont=True，长行程 jog 已经发给机器了），
        必须补一发 0x85 —— 否则机器会一直走那条长行程，而 GUI 已经把它忘掉了。
        场景：点着 X+ 长走 → 那一下 release 丢了 → 改点 X−/Y+ 想停 → 结果 X 继续跑。
        """
        was_moving = False
        for blk in list(jog_live):
            if blk.get("cont"):
                was_moving = True
            blk["cont"] = False
            blk["down"] = False
            _kill_block_timers(blk)
        jog_live.clear()
        if was_moving:
            _safe_do(lambda: link_ref[0]().jog_cancel())

    def stop_all_jogs(send_cancel=True, quiet=True):
        """停掉所有点动：清掉定时器 + 发 0x85 让机器减速停"""
        for blk in list(jog_live):
            blk["cont"] = False
            blk["down"] = False
            _kill_block_timers(blk)
        jog_live.clear()
        if send_cancel:
            _safe_do(lambda: link_ref[0]().jog_cancel())   # 链接层已做 60ms 去重
            if not quiet:
                append_log_ref[0]("已停止点动（0x85 jog cancel）")

    def _do_recover_jog():
        """点不死人：点不动时点一下，只放掉卡住的 jog / 清流控，不动坐标、不重连。"""
        try:
            l = link_ref[0]()
        except Exception:
            l = None
        if l is None:
            append_log_ref[0]("还没连接 —— 先点「连接」")
            return
        try:
            l.recover_jog()
            append_log_ref[0]("✓ 点动已恢复（坐标没动、不用重新对刀）—— 现在可以试点动")
        except Exception as e:
            append_log_ref[0]("！恢复点动失败：%s" % e)

    def bind_jog(widget, axis, sign):
        # down=还按着吗 / hold=按住判定定时器 / timer=连续走超时定时器
        # 三个状态都必须在 blk 里存，松手时才能一次清干净
        blk = {"cont": False, "down": False, "t": 0.0, "t0": 0.0,
               "hold": None, "timer": None, "seg_timer": None}

        def _fire(step, feed):
            try:
                note_dir(axis, sign)
            except Exception:
                pass
            _safe_do(lambda: link_ref[0]().jog(axis, sign * step, feed))

        def on_press(_e):
            # 只清 GUI 侧的定时器，不发 0x85（猛发 0x85 会堵串口，导致"点不动"）
            clear_jogs_only()
            blk["down"] = True
            blk["t"] = time.time()
            blk["cont"] = False
            if blk not in jog_live:
                jog_live.append(blk)
            blk["hold"] = root.after(int(JOG_HOLD * 1000) + 20, _go_cont)

        def _go_cont():
            blk["hold"] = None
            # 第一道判据：还按着吗？（松手后定时器才醒来的情况，直接作废）
            if not blk.get("down") or blk not in jog_live or blk["cont"]:
                return
            if time.time() - blk["t"] < JOG_HOLD - 0.02:
                return
            blk["cont"] = True
            blk["t0"] = time.time()
            feed = max(float(v_feed.get() or 800.0), 1.0)
            try:
                note_dir(axis, sign)
            except Exception:
                pass
            # 连续点动：发**一条长行程** jog，让它一直匀速走，松手用 0x85 停。
            # 旧做法每 150ms 发一条 0.25mm 的短 jog，每条都要"加速→走→减速"，所以一顿一顿；
            # 一条长行程只有开头一次加速、结尾一次减速，中间全程匀速。
            # 行程按 2.5 秒算（F100≈4mm / F600≈25mm）：万一 0x85 丢了，也只多走这么点。
            # 走完前 250ms 自动续一条 → 长按照样一直走，但每段都很短。
            _send_seg()
            blk["timer"] = root.after(int(JOG_MAX_CONT * 1000), _over_cont)
            blk["seg_timer"] = None   # R1.6（学 Candle）：按住 = 一条 jog，不做任何续发


        def _send_seg():
            """R1.5：按住 = 发一条够长的 jog，让 GRBL 全程连续匀速走。
            续航只在「这条真的走完（Idle）」时才补一条 —— 绝不在 Jog 中插队。
            （旧版每 180ms 无条件补发一次、且定时器越注册越多 → GRBL 收到 jog-in-jog
             就是 cancel 风暴 → 卡在 Jog 状态、之后点动全废、只能断串口重连。这就是
             「按住移动中随机丢点动、只能返工」的根子。）"""
            if not blk.get("down"):
                return                      # 已经松手：排队里醒来的这一发作废
            feed = max(float(v_feed.get() or 800.0), 1.0)
            seg = jog_seg_for(feed)         # R2.4：约 3 秒量，15~60mm（丢信号也只多走这么多）
            blk["last_send"] = time.time()
            blk["seg_t"] = max(0.4, seg / (feed / 60.0))    # 这条按当前速度要走几秒
            blk["seg_fn"] = _send_seg                       # R2.4：交给统一 ticker 续接
            _safe_do(lambda: link_ref[0]().jog(axis, sign * seg, feed, cont=True))

        def _over_cont():
            if blk["cont"] or blk in jog_live:
                stop_all_jogs(quiet=False)
                append_log_ref[0]("按住超过 %.0f 秒，已自动停止（防跑飞）" % JOG_MAX_CONT)

        def on_release(_e):
            was_cont = blk["cont"]
            blk["cont"] = False
            blk["down"] = False
            _kill_block_timers(blk)          # 连「按住判定」那一发一起取消
            if blk in jog_live:
                jog_live.remove(blk)
            if was_cont:
                _safe_do(lambda: link_ref[0]().jog_cancel())
            else:
                step = float(v_step.get() or 0.1)
                feed = float(v_feed.get() or 800.0)
                _fire(step, feed)      # 不发 cancel：新的 jog 本身就会覆盖上一段

        widget.bind("<ButtonPress-1>", on_press)
        widget.bind("<ButtonRelease-1>", on_release)

    def _jog_ticker():
        """R2.4：按住时的续接，全局只有这一个定时器。

        老版按住发一条 600mm（F800 走 45 秒），松手信号一丢就是「走飞刹不住」。
        现在每条只走 15~60mm（约 3 秒），走完（机床回 Idle/非 Jog）才补下一条 ——
        长按照样一直走，但任何时刻在途行程都只有几十毫米。
        """
        try:
            now = time.time()
            try:
                _l = link_ref[0]()
                _st = str(getattr(_l, "state", "")).lower()
            except Exception:
                _st = ""
            busy = _st.startswith("jog") or _st.startswith("run")
            for _blk in list(jog_live):
                if not (_blk.get("down") and _blk.get("cont")):
                    continue
                fn = _blk.get("seg_fn")
                if not fn:
                    continue
                if busy:
                    continue                     # 还在走 —— 绝不 jog-in-jog（会 cancel 风暴）
                if now - float(_blk.get("last_send") or 0) >= float(_blk.get("seg_t") or 3.0) + 0.20:
                    fn()
        except Exception:
            pass
        try:
            root.after(200, _jog_ticker)
        except Exception:
            pass

    try:
        root.after(240, _jog_ticker)
    except Exception:
        pass

    # 兜底：鼠标拖出按钮 / 切到别的窗口松手，release 事件会丢 → 全局再兜一层
    root.bind_all("<ButtonRelease-1>", lambda _e: stop_all_jogs() if jog_live else None, add="+")
    # 键盘同理：切到别的窗口后 KeyRelease 会丢 → 失焦就把所有连续点动停掉
    root.bind("<FocusOut>", lambda _e: stop_all_jogs(quiet=True) if jog_live else None, add="+")

    def _hotkey_stop(_e=None):
        w = root.focus_get()
        try:
            if w is not None and w.winfo_class() in ("Entry", "TEntry", "TCombobox", "Text"):
                return None            # 正在输入框里打字，不抢空格
        except Exception:
            pass
        stop_all_jogs(quiet=False)
        return "break"

    root.bind("<Escape>", _hotkey_stop)

    # ---------- 全键盘操作 ----------
    _ty_keys = ("Entry", "TEntry", "TCombobox", "Text", "Spinbox", "TSpinbox")

    def _typing():
        """正在输入框里打字：不抢按键"""
        try:
            w = root.focus_get()
            return w is not None and w.winfo_class() in _ty_keys
        except Exception:
            return False

    # R1.7：焦点还在「步长 / 速度」输入框里时，方向键照样要能点动（用户改完值直接按方向键）
    _DIR_KEYS = ("<Left>", "<Right>", "<Up>", "<Down>", "<Prior>", "<Next>")
    _EDGE_OF_DIR = {("X", -1): "L", ("X", 1): "R", ("Y", -1): "F", ("Y", 1): "B"}
    _last = {"axis": "X", "sign": -1, "edge": "L"}

    def note_dir(axis, sign):
        """记下最后一次点动方向，用来推测刚碰的是哪条边"""
        if axis in ("X", "Y"):
            sgn = 1 if sign > 0 else -1
            _last["axis"], _last["sign"] = axis, sgn
            e = _EDGE_OF_DIR[(axis, sgn)]
            _last["edge"] = e
            if shape_of(v_shape.get()) == SHAPE_CIRCLE:
                v_nextedge.set("Enter → 记一个圆点（朝 %s%s 碰到圆即可，圆形不分边）"
                               % (axis, "+" if sgn > 0 else "−"))
            else:
                v_nextedge.set("Enter → 记 %s（按点动方向 %s%s 推测，不对按 1/2/3/4）"
                               % (EDGE_CN[e], axis, "+" if sgn > 0 else "−"))

    def make_key_jog(axis, sign, key=""):
        """键盘方向键 = 和鼠标按钮同一套：按一下走一步，按住转「一条长行程匀速走」，松手急停。

        v1.20 之前的实现每收到一次 KeyPress 只发一步 jog，全靠系统键盘自动重复来"连续"
        （首延迟 ~0.5s、每 30ms 一条要加速减速的短 jog）→ 起手迟、命令积压、松手还在走。
        """
        kb = {"cont": False, "down": False, "t0": 0.0,
              "hold": None, "timer": None, "seg_timer": None,
              "last": 0.0, "key": key}   # v3.0：last=心跳时间，key=keysym（看门狗查物理键）

        def _kill_timers():
            for k in ("hold", "timer", "seg_timer"):
                if kb.get(k):
                    try:
                        root.after_cancel(kb[k])
                    except Exception:
                        pass
                    kb[k] = None

        def _stop(quiet=True):
            was_cont = kb["cont"]
            kb["cont"] = False
            kb["down"] = False
            _kill_timers()
            if kb in jog_live:
                jog_live.remove(kb)
            if was_cont:
                _safe_do(lambda: link_ref[0]().jog_cancel())

        def _seg_of(feed):
            return max(4.0, feed / 60.0 * 2.5)

        def _send_seg():
            if not kb.get("down"):
                return                      # 已经松手：排队里醒来的这一发必须作废
            feed = max(float(v_feed.get() or 800.0), 1.0)
            seg = jog_seg_for(feed)         # R2.4：15~60mm，走完由统一 ticker 续接
            kb["last_send"] = time.time()
            kb["seg_t"] = max(0.4, seg / (feed / 60.0))
            kb["seg_fn"] = _send_seg
            _safe_do(lambda: link_ref[0]().jog(axis, sign * seg, feed, cont=True))


        def _start_cont():
            kb["hold"] = None
            kb["last"] = time.time()
            if not kb["down"] or kb["cont"]:
                return
            kb["cont"] = True
            kb["t0"] = time.time()
            try:
                note_dir(axis, sign)
            except Exception:
                pass
            _send_seg()
            kb["seg_timer"] = None   # R1.6（学 Candle）：按住 = 一条 jog，不续发
            kb["timer"] = root.after(int(JOG_MAX_CONT * 1000), lambda: (
                _stop(), append_log_ref[0](
                    "按住超过 %.0f 秒，已自动停止（防跑飞）" % JOG_MAX_CONT)))

        def _on_press(_e=None):
            if _typing() and str(kb.get("key")) not in _DIR_KEYS:
                return None
            # v3.0：按住时系统每 30~50ms 会重复发 KeyPress —— 拿它当「心跳」。
            # 什么时候超过 0.45s 心跳停了却还在走，就说明 KeyRelease 丢了（焦点被抢 /
            # 系统吞键），_kb_watchdog 会替你把刀停住。以前没有这道兜底：
            # 按 X+ 一直走 → 松手信号丢了 → 刀一路走到 8 秒上限（F500 能冲 66mm）。
            kb["last"] = time.time()
            if kb["down"]:
                return "break"
            clear_jogs_only()
            kb["down"] = True
            if kb not in jog_live:
                jog_live.append(kb)
            try:
                note_dir(axis, sign)
            except Exception:
                pass
            step = float(v_step.get() or 0.1)
            feed = float(v_feed.get() or 800.0)
            _safe_do(lambda: link_ref[0]().jog(axis, sign * step, feed))
            kb["hold"] = root.after(int(JOG_HOLD * 1000), _start_cont)
            return "break"

        def _on_release(_e=None):
            if not kb["down"]:
                return None
            _stop()
            return "break"

        return {"press": _on_press, "release": _on_release,
                "blk": kb, "stop": _stop, "key": key, "axis": axis, "sign": sign}

    KEY_JOGS = []
    # v1.23：Z 除了 PgUp/PgDn，再加 `-` / `=`（车间键盘没有小键盘，PgUp/PgDn 又和方向键共用）
    for _k, (_ax, _sg) in (("<Left>", ("X", -1)), ("<Right>", ("X", 1)),
                           ("<Up>", ("Y", 1)), ("<Down>", ("Y", -1)),
                           ("<Prior>", ("Z", 1)), ("<Next>", ("Z", -1)),
                           ("<equal>", ("Z", 1)), ("<minus>", ("Z", -1))):
        _kj = make_key_jog(_ax, _sg, _k)
        KEY_JOGS.append(_kj)
        root.bind(_k, _kj["press"])
        # keysym 形态两种：<Left>（带尖括号）与 equal / minus（裸 keysym）都要能绑 KeyRelease
        if _k.startswith("<"):
            root.bind(_k.replace("<", "<KeyRelease-"), _kj["release"])
        else:
            root.bind("<KeyRelease-%s>" % _k, _kj["release"])

    # R1.7：焦点还在「步长 / 速度」框里时，方向键直接点动 —— 改完数值不用先点一下鼠标。
    # 另外按 Enter / 选完下拉 / Esc 都把焦点交还主窗口，后续方向键就是常规键盘点动。
    def _bind_dirs_on(w):
        for _j in KEY_JOGS:
            _k = _j.get("key") or ""
            if _k not in _DIR_KEYS:
                continue
            w.bind(_k, lambda e, j=_j: j["press"](e), add="+")
            w.bind(_k.replace("<", "<KeyRelease-"),
                   lambda e, j=_j: j["release"](e), add="+")
        w.bind("<Return>", lambda _e: (root.focus_set(), "break")[1])
        w.bind("<Escape>", lambda _e: (root.focus_set(), "break")[1])
        w.bind("<<ComboboxSelected>>", lambda _e: root.focus_set())

    for _w in (cb_step, cb_feed):
        try:
            _bind_dirs_on(_w)
        except Exception:
            pass

    # v3.0：松手信号丢失的兜底。
    # 为什么不能只看「多久没收到 KeyPress」：Windows 的键盘重复延迟默认就有约 0.5s，
    # 用户按住 X+ 时前一秒只有一个 KeyPress —— 按心跳判断会把「正常按住」误判成丢键。
    # 所以在 Windows 下直接问系统：这个键现在还按着吗（GetAsyncKeyState）。
    # 只有拿不到系统接口（非 Windows）才退回「心跳停 1.5s」的保守判据。
    _VK = {"<Left>": 0x25, "<Up>": 0x26, "<Right>": 0x27, "<Down>": 0x28,
           "<Prior>": 0x21, "<Next>": 0x22, "<equal>": 0xBB, "<minus>": 0xBD}
    _kb_vk_down = None
    try:
        import ctypes as _ct
        _gas = _ct.windll.user32.GetAsyncKeyState      # 只有 Windows 有

        def _kb_vk_down(vk):
            try:
                return bool(_gas(vk) & 0x8000)
            except Exception:
                return None
    except Exception:
        _kb_vk_down = None

    _lost_log = {"t": 0.0}     # v3.0.1：看门狗日志限流（同一原因 5s 内只记一条）

    def _kb_watchdog():
        """键盘/鼠标「松手了但信号没送到」的兜底停。

        Windows：直接读物理键状态。系统说已经松手、我们还标着「在走」= Release 丢了
        （焦点被抢 / 系统吞键 / 远程桌面切换）→ 立刻 0x85 停住。
        非 Windows：退回心跳判据（1.5s 收不到 KeyPress 才认），宁可慢一点也不误停。
        """
        _now = time.time()
        for _kj in KEY_JOGS:
            _kb = _kj.get("blk") or {}
            if not _kb.get("down"):
                continue
            _vk = _VK.get(_kb.get("key"))
            _st = _kb_vk_down(_vk) if (_kb_vk_down and _vk) else None
            if _st is False:
                # v3.0.1：连续两次（~0.4s）都读到「松开」才认，防 API 单次抖动误停
                _miss = int(_kb.get("miss") or 0) + 1
                _kb["miss"] = _miss
                _lost = _miss >= 2
            elif _st is None:
                _kb["miss"] = 0
                _lost = (_now - float(_kb.get("last") or 0.0)) > 1.5
            else:
                _kb["miss"] = 0
                _lost = False
            if _lost:
                _was = _kb.get("cont")
                _kj["stop"]()
                _kb["miss"] = 0
                if _now - _lost_log["t"] > 5.0:   # v3.0.1：同一原因 5 秒内只记一条，不刷屏
                    _lost_log["t"] = _now
                    append_log_ref[0]("键盘松手信号丢了（焦点被抢/系统吞键）→ 已自动停止"
                                      + ("（刚才在连续走）" if _was else ""))
        # ---- v3.0.1：鼠标这里不再用 GetAsyncKeyState 判「左键还按着吗」----
        # 实测（2026-11-19 车间工控机）：触摸屏 / 触摸板 / 远程桌面 / 部分安全软件下，
        # GetAsyncKeyState(VK_LBUTTON) 读不到「按住」，会把正常按住误判成
        # 「鼠标松开信号丢了」—— 每 200ms 停一次点动并打一条日志，点动根本没法用。
        # 鼠标这边本来就有三重兜底，少这一条不降低安全性：
        #   ① 全局 <ButtonRelease-1>：窗口里任何位置松手都停
        #   ② <FocusOut>：切走窗口就停
        #   ③ 连续走到 JOG_MAX_CONT 秒的定时器（_over_cont）自动停
        # 唯一剩下的缺口「Release 真丢了还在连续走」，最多多走一段 ≤ JOG_SEG_MAX（25mm）的行程。
        try:
            root.after(200, _kb_watchdog)
        except Exception:
            pass

    root.after(400, _kb_watchdog)

    _STEPS = ["0.01", "0.05", "0.1", "0.5", "1", "5"]

    def key_step(sign):
        def _h(_e=None):
            if _typing():
                return None
            try:
                cur = "%.2f" % float(v_step.get() or 0.1)
            except ValueError:
                cur = "0.10"
            try:
                i = _STEPS.index(cur)
            except ValueError:
                i = 2
            i = max(0, min(len(_STEPS) - 1, i + sign))
            v_step.set(_STEPS[i])
            append_log_ref[0]("步长 = %s mm" % _STEPS[i])
            return "break"
        return _h

    root.bind("<bracketleft>", key_step(-1))
    root.bind("<bracketright>", key_step(1))

    _last_edge = {"e": "L"}

    def _record_edge(edge):
        _last_edge["e"] = edge
        record(edge)

    def key_record_auto(_e=None):
        """Enter / 空格：按最后一次点动方向记一个点。

        v3.0.2：**点动进行中，空格 = 先停下**（状态栏一直写着「点动中，点停止或空格可停」，
        而这里原来会记一个点 —— 用户按提示按空格，结果记了个假碰点，中心就偏了）。
        """
        if _typing():
            return None
        if jog_live:
            stop_all_jogs(quiet=False)
            return "break"
        if link_holder["link"] is None:
            append_log_ref[0]("!请先连接串口")
            return "break"
        if shape_of(v_shape.get()) == SHAPE_CIRCLE:
            record_circle()
        else:
            _record_edge(_last["edge"])
        return "break"

    root.bind("<Return>", key_record_auto)
    root.bind("<space>", key_record_auto)

    def _key_record(edge):
        def _h(_e=None):
            if _typing():
                return None
            if shape_of(v_shape.get()) == SHAPE_CIRCLE:
                record_circle()      # 圆形不分边，四个数字键都当「记一个圆点」
            else:
                _record_edge(edge)
            return "break"
        return _h

    for _i, _e in enumerate(EDGES, start=1):
        root.bind(str(_i), _key_record(_e))

    def _key_undo(_e=None):
        if _typing():
            return None
        undo()
        return "break"

    root.bind("<BackSpace>", _key_undo)

    def _key_unlock(_e=None):
        if _typing():
            return None
        do(lambda: link_ref[0]().unlock())
        return "break"

    def _key_conn(_e=None):
        if _typing():
            return None
        toggle_conn()
        return "break"

    def _key_gen(_e=None):
        if _typing():
            return None
        do_transform()
        return "break"

    def _key_help(_e=None):
        show_hotkeys()
        return "break"

    root.bind("x", _key_unlock)
    root.bind("X", _key_unlock)
    root.bind("c", _key_conn)
    root.bind("C", _key_conn)
    root.bind("g", _key_gen)
    root.bind("G", _key_gen)
    root.bind("<F1>", _key_help)

    # ---- 点动 ----
    jog_btns = {}          # (轴, 方向) → 按钮，自检时用来模拟真实鼠标事件
    jf = ttk.LabelFrame(sec2, text="点动（方向键 = X± Y±；Z 用 `-` / `=`，或 PgUp/PgDn）")
    jf.pack(fill="x", padx=6, pady=2)
    for axis in ("X", "Y", "Z"):
        box = ttk.Frame(jf)
        box.pack(side="left", padx=8, pady=8)
        ttk.Label(box, text=axis, font=(UI_MONO, 13, "bold")).pack(side="left", padx=4)
        for sign, label in ((-1, "−"), (1, "+")):
            b = ttk.Button(box, text="%s%s" % (axis, label), width=4)
            b.pack(side="left", padx=2)
            bind_jog(b, axis, sign)
            jog_btns[(axis, sign)] = b      # 自检要拿它 event_generate

    stop_box = ttk.Frame(jf)
    stop_box.pack(side="left", padx=(14, 8), pady=8)
    btn_stop = tk.Button(stop_box, text="■ 停止", font=(UI_FONT, FS_BODY, "bold"),
                         fg="#fff", bg="#dc2626", activebackground="#b91c1c",
                         activeforeground="#fff", relief="flat", padx=16, pady=5,
                         command=lambda: stop_all_jogs(quiet=False))
    btn_stop.pack(side="left")
    ttk.Button(stop_box, text="恢复点动", style="Sm.TButton",
               command=lambda: _do_recover_jog()).pack(side="left", padx=(8, 0))
    ttk.Label(jf, text="（Esc = 停；Enter/空格 = 记点；- / = = Z↓/Z↑；F1 = 快捷键表）",
              foreground=UI_TXT2).pack(side="left")

    # ---- 记录 ----
    rf = ttk.LabelFrame(sec2, text="记录碰点（Enter = 记点；1/2/3/4 = 指定 左/右/前/后；Backspace = 撤销）")
    rf.pack(fill="x", padx=6, pady=(2, 6))

    # ---- v1.36：没有「点动/巡航」两种模式了 —— 格子点一下就抬 Z 走过去，Z 一直由人控制 ----

    # ---- R2.8：上次中心（取代 v3.0 的「初步定位」）----
    # 用户原话：去掉初步定位，把上一次的靠边坐标记下来；先设 Z 高，再按坐标跑过去。
    # 存的是「算出来的中心」的机床坐标（MPOS），不是手动抓的点 —— 碰边算出中心即自动记录。
    last_c = {"x": None, "y": None, "at": "", "shape": ""}

    # ---- 安全高度（R1.1 防撞刀）----
    # 语义：Z0 = 工件对边后的加工起始高度（顶面）；刀路切削前自己会抬 Z，不用管。
    # 但「走到中心 / 初步定位 / 快速定位 / 发送前 / 回中心」是程序发起的横移，
    # 必须先在顶面以上抬起来 —— 抬多少由这里定，用**机床绝对 Z**（G53）存。
    safe_z = {"mz": None}                  # 用户标定的安全机床 Z（None = 未标定）
    v_safe_z = tk.StringVar(value="")      # 输入框
    v_safe_tip = tk.StringVar(value="")
    # R1.4：机床坐标是否可信 —— 软复位/上电后 GRBL 把机床坐标归零，之前记的绝对坐标全部作废
    coord_ok = [True]

    def safe_tip():
        """刷新「当前生效的安全高度」提示"""
        try:
            tz = safe_target_mz()
        except Exception:
            tz = None
        if tz is not None:
            v_safe_tip.set("横移前抬到机床 Z %.3f" % float(tz))
        else:
            v_safe_tip.set("先把刀摇到工件上方点「取当前」，或手填一个机床 Z")

    def safe_target_mz():
        """要抬到的机床绝对 Z。优先级：输入框里填的 > 标定值 > 记点里最高的机床 Z + 15"""
        _t = (v_safe_z.get() or "").strip()
        if _t:
            try:
                return float(_t)
            except ValueError:
                pass
        if safe_z["mz"] is not None:
            return float(safe_z["mz"])
        cands = []
        try:
            for _e in EDGES:
                for _sl in (1, 2):
                    _q = cp_get(_e, _sl) or {}
                    if _q.get("mzm") is not None:
                        cands.append(float(_q["mzm"]))
        except Exception:
            pass
        if cands:
            # 记点最高 + 15：固定值，点几次都是同一个目标（绝不「当前 +N」，那会越点越高）
            return max(cands) + 15.0
        # 一个基准都没有 → None（不抬），由 lift_safe 提示标定。
        # 曾经的「当前 +15」会让同一个格子每点一次往上爬 15mm（v1.37 修过的老病，别回退）
        return None

    def safe_calibrate():
        """把当前位置的机床 Z 记成安全高度（先把刀移到工件上方再点）"""
        try:
            mp = (link_ref[0]().status() or {}).get("mpos")
        except Exception:
            mp = None
        if not mp:
            messagebox.showwarning(APP, "读不到坐标 —— 先连串口，等顶部出现 MPos")
            return
        _mm = getattr(link_holder["link"], "mpos_mach", None) if link_holder["link"] else None
        _m = _mm() if callable(_mm) else None
        safe_z["mz"] = round(float((_m or mp)[2]), 4)
        v_safe_z.set("%.3f" % safe_z["mz"])
        safe_tip()
        append_log("✓ 安全 Z 已标定：机床 Z = %.3f（以后走到中心/定位/发送前都先抬到这里）"
                   % safe_z["mz"])
        try:
            session_autosave(200)
        except Exception:
            pass

    def safe_clear():
        safe_z["mz"] = None
        v_safe_z.set("")
        safe_tip()
        append_log("安全 Z 已清除（改为兜底：记点最高 +8mm / 当前 +10mm）")
        try:
            session_autosave(200)
        except Exception:
            pass

    def safe_apply_entry():
        t = (v_safe_z.get() or "").strip()
        if not t:
            safe_clear()
            return
        try:
            safe_z["mz"] = round(float(t), 4)
        except ValueError:
            messagebox.showwarning(APP, "安全 Z 要填数字（机床坐标，mm）")
            return
        safe_tip()
        append_log("安全 Z 设为：机床 Z = %.3f" % safe_z["mz"])
        try:
            session_autosave(200)
        except Exception:
            pass

    def wait_idle_gui(l, timeout=10.0):
        """等机床回到 Idle（横移/抬刀之间必须确认上一段走完）"""
        t0 = time.time()
        while time.time() - t0 < timeout:
            try:
                st = str((l.status() or {}).get("state", "")).lower()
            except Exception:
                st = ""
            if st.startswith("idle"):
                return True
            time.sleep(0.05)
        return False

    def lift_safe(l=None, why=""):
        """抬到安全 Z（机床绝对）—— 所有横移前必须先调它。返回目标 Z。"""
        l = l or link()
        tz = safe_target_mz()
        if tz is None:
            # 没有基准：不抬、不阻塞，但必须让人知道 —— 硬抬「当前+N」会越点越高
            append_log("⚠ 还没有安全高度基准：先把刀移到工件上方点「用当前位置标定」，"
                       "或手动把 Z 抬离工件再横移（这次没有自动抬刀）")
            return None
        # R2.9：一律用机床真实坐标。安全 Z / 记点 Z 现在都存这个口径，
        # 用「显示坐标」发 G53 会差一个「设 0 点」的偏移（实测把刀一路顶到限位）。
        _mm = getattr(l, "mpos_mach", None)
        mp = _mm() if callable(_mm) else (l.status() or {}).get("mpos")
        if not mp:
            raise GrblError("读不到机床坐标（等顶部出现 MPos 再试）")
        cur = float(mp[2])
        if tz is None or tz - cur <= 0.05:
            return tz
        _dz = float(tz) - cur
        if _dz > LIFT_TRUST_MAX:
            # 目标比当前高 5cm 以上 —— 一定是安全 Z 标错 / 换过工件 / 坐标口径不对。
            # 宁可少抬，也不能朝一个超行程的绝对坐标走（撞限位就丢步）。
            append_log("⚠ 安全 Z %.3f 比当前机床 Z %.3f 高 %.0fmm（超过 %.0fmm 上限）"
                       "—— 本次不采用，改抬 %.0fmm；请重新标定安全 Z"
                       % (tz, cur, _dz, LIFT_TRUST_MAX, LIFT_FALLBACK))
            tz = cur + LIFT_FALLBACK
        l.send("G90 G53 G0 Z%.4f" % tz, log_it=False)
        wait_idle_gui(l, 12.0)
        append_log("→ 抬到安全 Z：机床 Z %.3f%s" % (tz, ("（" + why + "）") if why else ""))
        return tz


    # ---- 靠边位置（R1.3，极简版）----
    # 用户原话：就是为了下次定位方便，把靠边坐标记录下来；二次定位时 Z 抬高即可。
    # 这里只有一排按钮：碰过哪条边就亮，点一下 = 抬到安全 Z → 走过去；Z 保持抬起，
    # 人自己点 Z− 贴边。没有「记下当前位置」这种额外步骤 —— 碰点即记录。
    # ---- R2.8：上次中心（换同款工件时一键抬 Z 走过去）----
    lc_row = tk.Frame(rf)
    lc_row.pack(fill="x", padx=8, pady=(8, 0))
    btn_last_c = tk.Button(lc_row, text="\u21ba 上次中心（还没有记录）", font=(UI_FONT, FS_SMALL),
                           relief="flat", bd=0, padx=10, pady=4,
                           bg="#eef2f7", fg="#94a3b8", state="disabled",
                           command=lambda: go_last_center())
    btn_last_c.pack(side="left")

    def refresh_last_btn():
        """按钮文案 = 上次中心的机床坐标 + 时间；没有记录就禁用。"""
        try:
            if last_c["x"] is None:
                btn_last_c.configure(text="\u21ba 上次中心（还没有记录）",
                                     bg="#eef2f7", fg="#94a3b8", state="disabled")
            else:
                btn_last_c.configure(
                    text="\u21ba 上次中心 X %.3f  Y %.3f（%s）"
                         % (last_c["x"], last_c["y"], last_c["at"] or "上次"),
                    bg="#e7f6ee", fg="#15803d", state="normal")
        except Exception:
            pass

    def remember_center(x, y, why=""):
        """记下这次算出的中心（机床坐标）。不干扰碰点，只供下次一键回去。"""
        try:
            last_c["x"] = float(x)
            last_c["y"] = float(y)
            last_c["at"] = time.strftime("%m-%d %H:%M")
            last_c["shape"] = v_shape.get()
            refresh_last_btn()
            append_log("已记下中心 X %.3f Y %.3f（%s）—— 下次点「\u21ba 上次中心」先抬 Z 再走过去"
                       % (last_c["x"], last_c["y"], why or "本次"))
            session_autosave(5)
        except Exception as e:
            append_log("（记中心失败：%s）" % e)

    def go_last_center():
        if last_c["x"] is None:
            messagebox.showinfo(APP, "还没有记录过中心",
                                detail="碰边算出一次中心后会自动记住，之后就能一键回去。")
            return
        if link_holder["link"] is None:
            messagebox.showwarning(APP, "先在「连接 · 日志」页连上串口")
            return
        if not coord_ok[0]:
            if not messagebox.askokcancel(
                    APP, "机床坐标动过（软复位 / 上电），上次记的坐标可能已经不准。\n\n还按它过去吗？",
                    detail="如果不是每次开机刀都停在同一个位置，建议直接靠边重新产生一次坐标。"):
                return
        tx, ty = float(last_c["x"]), float(last_c["y"])

        def _go():
            l = link()
            lift_safe(l, "回上次中心前")                     # ① 先抬安全 Z（绝不低位横移）
            l.send("G90 G53 G0 X%.4f Y%.4f" % (tx, ty), log_it=False)
            wait_idle_gui(l, 12.0)
            _mm = getattr(l, "mpos_mach", None)
            p1 = (_mm() if callable(_mm) else None) or l.mpos()
            append_log("→ 已到上次中心 X %.3f Y %.3f —— Z 停在安全高度（不自动下降），点 Z− 贴边"
                       % (tx, ty))
            if p1 is not None:
                d = math.hypot(p1[0] - tx, p1[1] - ty)
                if d > 0.2:
                    append_log("   ⚠ 到位差 %.3f mm（丢步或限位挡了一下，建议靠边重算）" % d)
            try:
                v_nextedge.set("已到上次中心 · 点 Z− 降到碰边高度，碰到边按 Enter 记点")
            except Exception:
                pass

        do(_go)

    pv_row = tk.Frame(rf)
    pv_row.pack(fill="x", padx=8, pady=(8, 0))
    tk.Label(pv_row, text="靠边位置", font=(UI_FONT, FS_BODY, "bold"),
             fg=UI_PRIM_D).pack(side="left", padx=(2, 10))
    pv_btns = {}
    for _e0 in EDGES:
        for _sl0 in (1, 2):
            # R1.8：按钮自己就是状态灯 —— 未碰=灰底「左壁 未碰」；已碰=绿底「↩ 左壁 ✓2」。
            # 车间反馈 R1.7 把状态藏了，「不知道哪条边做完了，全靠瞎摸」。
            _b0 = tk.Button(pv_row, text="%s%s 未碰" % (EDGE_CN[_e0], ("①" if _sl0 == 1 else "②")),
                            font=(UI_FONT, FS_SMALL), relief="flat", bd=0,
                            padx=9, pady=3, bg="#eef2f7", fg="#94a3b8",
                            activebackground="#dbeafe", cursor="hand2",
                            command=lambda x=_e0, s2=_sl0: cp_goto(x, s2))
            if _sl0 == 1:                      # 每条边的 ① 常驻；② 只在真有第二个点时出现
                _b0.pack(side="left", padx=(0, 6))
            pv_btns[(_e0, _sl0)] = _b0
    pv_sum = tk.Label(pv_row, text="", font=(UI_FONT, FS_TINY, "bold"),
                      fg="#b45309", anchor="e")
    pv_sum.pack(side="right", padx=(12, 2))
    tk.Label(rf, text="碰完一条边就变绿（后面的数字=碰了几个点）· 点绿块 = 抬到安全 Z 走过去（Z 保持抬起，自己点 Z− 贴边）",
             fg=UI_TXT2, font=(UI_FONT, FS_TINY), anchor="w").pack(fill="x", padx=8, pady=(1, 6))

    # ---- 记点 / 撤销 / 清空 ----
    row1 = tk.Frame(rf)
    row1.pack(fill="x")
    edge_btns = {}
    for e in EDGES:
        # R1.9：这一排按钮也带状态（车间说「记录的状态看不到」—— 靠边位置那排在页面下方，
        # 记完点眼睛还在这儿，所以这里也标：灰=还没碰，绿「左壁 ✓1」=本件已碰几个点。
        _b = tk.Button(row1, text="记 " + EDGE_CN[e], width=9,
                       font=(UI_FONT, FS_SMALL), relief="flat", bd=0,
                       padx=6, pady=4, bg="#f1f5f9", fg="#334155",
                       activebackground="#e2e8f0", cursor="hand2",
                       command=lambda x=e: record(x))
        _b.pack(side="left", padx=6, pady=(6, 4))
        edge_btns[e] = _b

    def paint_edge_btns():
        """「记 X」按钮 = 状态灯：灰底「记 左壁」= 未碰；绿底「左壁 ✓2」= 本件已碰 2 点。
        ② 区标题同时显示「已碰 N/4 边」。记点/撤销/清空/切形状后刷新。"""
        try:
            if shape_of(v_shape.get()) == SHAPE_CIRCLE:
                for e in EDGES:
                    edge_btns[e].configure(bg="#f1f5f9", fg="#94a3b8",
                                           activebackground="#e2e8f0",
                                           text="记 " + EDGE_CN[e])
                return
            n_ok = 0
            for e in EDGES:
                n = len(fitter.pts.get(e) or [])
                if n:
                    n_ok += 1
                    edge_btns[e].configure(bg="#059669", fg="#ffffff",
                                           activebackground="#047857",
                                           text="%s ✓%d" % (EDGE_CN[e], n))
                else:
                    edge_btns[e].configure(bg="#f1f5f9", fg="#334155",
                                           activebackground="#e2e8f0",
                                           text="记 " + EDGE_CN[e])
            try:
                if n_ok >= 4:
                    _t2, _c2 = "碰边定位 · 已碰 4/4 边（可以算中心了）", "#15803d"
                elif n_ok:
                    _t2 = "碰边定位 · 已碰 %d/4 边（还差 %s）" % (
                        n_ok, "、".join(EDGE_CN[e] for e in EDGES
                                        if not (fitter.pts.get(e) or [])))
                    _c2 = "#b45309"
                else:
                    _t2, _c2 = "碰边定位 · 还没碰任何边", "#64748b"
                sec2_w._card_title.configure(text=_t2, foreground=_c2)
            except Exception:
                pass
        except Exception:
            pass
    btn_rec_circle = ttk.Button(row1, text="记圆点（Enter）", width=16,
                                command=lambda: record_circle())
    btn_undo = ttk.Button(row1, text="撤销上一点", command=lambda: undo())
    btn_undo.pack(side="left", padx=6, pady=(6, 4))
    ttk.Button(row1, text="清空", command=lambda: clear_all()).pack(side="left", padx=6, pady=(6, 4))
    tk.Label(row1, textvariable=v_nextedge, foreground="#1d4ed8",
             font=(UI_FONT, FS_SMALL, "bold")).pack(side="left", padx=10, pady=(6, 4))

    tk.Label(rf, textvariable=v_hint, fg="#d97706", anchor="w", justify="left",
             font=(UI_FONT, FS_SMALL)).pack(fill="x", padx=10, pady=(2, 8))

    # ---- 结果 ----
    gf_w, gf = _card(_pg_cut, "3", "走中心并设零",
                     "流程 ④⑤：先走到中心，到位后再在此处设零")
    gf_w.pack(fill="x", padx=10, pady=6)

    # 安全 Z：所有「程序发起的横移」都先抬到这里（走中心 / 定位 / 发送前 / 回中心）
    snf = ttk.Frame(gf)
    snf.pack(fill="x", padx=8, pady=(8, 0))
    ttk.Label(snf, text="安全 Z（机床）", font=(UI_FONT, FS_SMALL, "bold")).pack(side="left")
    ttk.Entry(snf, textvariable=v_safe_z, width=9,
              font=(UI_MONO, 12)).pack(side="left", padx=(4, 4))
    ttk.Button(snf, text="取当前", style="Sm.TButton",
               command=lambda: safe_calibrate()).pack(side="left")
    tk.Label(gf, textvariable=v_safe_tip, fg=UI_TXT2, anchor="w",
             font=(UI_FONT, FS_TINY)).pack(fill="x", padx=8, pady=(1, 0))
    safe_tip()                                 # 一进来就把「当前生效的安全高度」显示出来
    tk.Label(gf, textvariable=v_result, font=(UI_FONT, FS_BIG, "bold"), justify="left",
             anchor="w").pack(fill="x", padx=8, pady=(8, 2))
    rt = ttk.Frame(gf)
    rt.pack(fill="x", padx=8)
    ttk.Label(rt, text="θ =").pack(side="left")
    ent_theta = ttk.Entry(rt, textvariable=v_theta, width=9, font=(UI_MONO, 12),
                          state="readonly")
    ent_theta.pack(side="left", padx=(2, 4))
    ttk.Label(rt, text="度（碰边实测，刀路按这个角度转）").pack(side="left")
    ttk.Label(rt, textvariable=v_theta_src, foreground="#777").pack(side="left", padx=10)
    tk.Label(gf, textvariable=v_check, fg="#15803d", anchor="w",
             font=(UI_FONT, FS_SMALL)).pack(fill="x", padx=8, pady=(2, 0))
    tk.Label(gf, textvariable=v_g10, font=(UI_MONO, 12), fg="#b91c1c", anchor="w").pack(fill="x", padx=8, pady=(4, 0))
    # 零点状态灯（实时）
    zf = tk.Frame(gf, bg="#f8fafc", highlightthickness=0)
    zf.pack(fill="x", padx=8, pady=(8, 0))
    tk.Label(zf, text="零点", bg="#f8fafc", fg="#475569",
             font=(UI_FONT, FS_SMALL)).pack(side="left", padx=(8, 6), pady=5)
    lbl_zero = tk.Label(zf, textvariable=v_zero, bg="#f8fafc", fg="#64748b",
                        font=(UI_FONT, FS_SMALL, "bold"), anchor="w", justify="left")
    lbl_zero.pack(side="left", padx=(0, 8), pady=5)

    # 主操作：故意拆成两步（不再一键）：真机出现过「刀还没到位就把零设了」→ 整件偏。
    # 逐步点：先走中心，看日志里的偏差，确认刀尖对准了再设零。
    bf0 = ttk.Frame(gf)
    bf0.pack(fill="x", padx=8, pady=(8, 0))
    btn_center = ttk.Button(bf0, text="▶  ① 走到中心", style="Go.TButton",
                            command=lambda: goto_center())
    btn_center.pack(side="left")
    btn_zero2 = ttk.Button(bf0, text="② 就在此处设零", style="Go.TButton",
                           command=lambda: set_xy_zero())
    btn_zero2.pack(side="left", padx=(8, 0))
    tk.Label(bf0, text="① G53 走中心（绝对坐标，不被残留偏移带偏）→ 看日志里的偏差\n"
                      "② 确认刀尖对准了，再点设零（写 G54 存盘，Candle 连上就是 0,0）",
             fg="#64748b", font=(UI_FONT, FS_TINY), justify="left",
             anchor="w").pack(side="left", padx=10)

    # 诊断 / 特殊用途按钮全部收进「高级 / 工具」（v1.18）：
    # 它们不是流程步骤，摆主界面只会让人以为每次都要点。
    tk.Label(gf, text="设零 = 写 G54（生成刀路时文件头还会再写一次当保险）；出问题才用「高级 / 工具」里的「核对坐标」。",
             fg=UI_TXT2, font=(UI_FONT, FS_TINY), justify="left",
             anchor="w").pack(fill="x", padx=10, pady=(0, 8))

    # ---- 刀路 ----
    tf_w, tf = _card(_pg_cut, "4", "生成刀路", "选源刀路 → 生成（自动套用中心与 θ）")
    tf_w.pack(fill="x", padx=10, pady=6)
    r1 = ttk.Frame(tf)
    r1.pack(fill="x", padx=8, pady=(8, 2))
    ttk.Label(r1, text="源刀路").pack(side="left")
    ttk.Entry(r1, textvariable=v_src).pack(side="left", fill="x", expand=True, padx=6)

    def pick_src():
        """选原始刀路（要套中心/θ 的那一份）。v3.0.2：这个函数以前漏了定义，
        点「选择」会 NameError —— 只能手打路径，等于这步等于废了。"""
        p = filedialog.askopenfilename(
            title="选择原始刀路文件（要套用中心与 θ 的那一份）",
            filetypes=[("刀路文件", "*.tap *.nc *.gcode *.ngc *.txt"), ("全部文件", "*.*")])
        if not p:
            return
        v_src.set(p)
        try:
            with open(p, "r", encoding="utf-8", errors="replace") as f:
                n = sum(1 for ln in f if _send_clean(ln))
            append_log("已选源刀路：%s（%d 行）" % (os.path.basename(p), n))
        except Exception:
            append_log("已选源刀路：%s" % os.path.basename(p))

    ttk.Button(r1, text="选择", command=lambda: pick_src()).pack(side="left")
    r2b = ttk.Frame(tf)
    r2b.pack(fill="x", padx=8, pady=2)
    ttk.Label(r2b, text="设计原点 X").pack(side="left")
    ttk.Entry(r2b, textvariable=v_ox, width=9).pack(side="left", padx=(2, 8))
    ttk.Label(r2b, text="Y").pack(side="left")
    ttk.Entry(r2b, textvariable=v_oy, width=9).pack(side="left", padx=(2, 8))
    ttk.Checkbutton(r2b, text="按 θ 旋转", variable=v_rot).pack(side="left", padx=6)
    ttk.Label(r2b, text="（原点一般填 0,0；若刀路以工件左下角为原点，就填那个坐标）",
              foreground=UI_TXT2).pack(side="left", padx=4)
    r4 = ttk.Frame(tf)
    r4.pack(fill="x", padx=8, pady=2)
    ttk.Label(r4, text="Z 处理").pack(side="left")
    ttk.Radiobutton(r4, text="原样", value="none", variable=v_zmode).pack(side="left", padx=(6, 4))
    ttk.Radiobutton(r4, text="整体偏移", value="shift", variable=v_zmode).pack(side="left")
    ttk.Radiobutton(r4, text="最深切到", value="override", variable=v_zmode).pack(side="left")
    ttk.Entry(r4, textvariable=v_zval, width=8).pack(side="left", padx=4)
    ttk.Label(r4, text="mm（按比例缩放，保留分层）", foreground=UI_TXT2).pack(side="left")
    r4b = ttk.Frame(tf)
    r4b.pack(fill="x", padx=8, pady=2)
    ttk.Label(r4b, text="起刀 Z").pack(side="left")
    ttk.Entry(r4b, textvariable=v_start_z, width=8).pack(side="left", padx=(2, 6))
    ttk.Label(r4b, text="mm（留空 = 跟随原刀路第一个 Z，最稳；填 0 = 工件顶面）",
              foreground=UI_TXT2).pack(side="left")
    tk.Label(r4b, text="文件头顺序：抬到安全 Z → 走到起点 → G0 下到这里 → 按你的刀路切",
             fg="#1d4ed8", font=(UI_FONT, FS_TINY)).pack(side="left", padx=(10, 0))
    r5 = ttk.Frame(tf)
    r5.pack(fill="x", padx=8, pady=(2, 8))
    ttk.Checkbutton(r5, text="移除 T/M6 换刀行", variable=v_droptc).pack(side="left", padx=10)
    btn_gen = ttk.Button(r5, text="生成刀路", command=lambda: do_transform())
    btn_gen.pack(side="left", padx=8)
    ttk.Label(r5, text="（自动存到源文件旁边：xxx_run / xxx_rot）",
              foreground=UI_TXT2).pack(side="left", padx=4)

    # ---- 发送加工（v1.36）----
    v_send = tk.StringVar(value="")
    v_send_home = tk.BooleanVar(value=True)
    v_send_lift = tk.StringVar(value="5")
    v_send_plunge = tk.StringVar(value="300")
    v_send_msg = tk.StringVar(value="待机 —— 选一份刀路，点「▶ 开始」")
    v_send_info = tk.StringVar(value="")
    send_holder = {"s": None}

    sf_w, sf = _card(_pg_snd, "5", "发送加工", "刀路直接发给机床，不用再切到别的软件")
    sf_w.pack(fill="x", padx=10, pady=6)

    s0 = ttk.Frame(sf)
    s0.pack(fill="x", padx=10, pady=(8, 2))
    ttk.Label(s0, text="刀路").pack(side="left")
    ttk.Entry(s0, textvariable=v_send).pack(side="left", fill="x", expand=True, padx=6)
    ttk.Button(s0, text="选择", command=lambda: send_pick()).pack(side="left")
    ttk.Button(s0, text="用刚生成的", command=lambda: send_use_last()).pack(side="left", padx=(6, 0))

    pb = ttk.Progressbar(sf, mode="determinate", maximum=100,
                         style="Send.Horizontal.TProgressbar")
    pb.pack(fill="x", padx=10, pady=(7, 5))
    tk.Label(sf, textvariable=v_send_msg, anchor="w", justify="left",
             font=(UI_FONT, FS_BODY, "bold"), fg=UI_TXT).pack(fill="x", padx=10)
    tk.Label(sf, textvariable=v_send_info, anchor="w", justify="left",
             font=(UI_FONT, FS_SMALL), fg=UI_TXT2).pack(fill="x", padx=10, pady=(0, 5))

    sb = ttk.Frame(sf)
    sb.pack(fill="x", padx=10, pady=(2, 4))
    btn_send = ttk.Button(sb, text="▶ 开始", style="Go.TButton", command=lambda: send_go())
    btn_send.pack(side="left")
    btn_spause = ttk.Button(sb, text="⏸ 暂停抬刀", style="Warn.TButton",
                            command=lambda: send_pause())
    btn_spause.pack(side="left", padx=(8, 0))
    btn_sstop = ttk.Button(sb, text="■ 停止", style="Danger.TButton",
                           command=lambda: send_stop())
    btn_sstop.pack(side="left", padx=(8, 0))

    so = tk.Frame(sf)
    so.pack(fill="x", padx=10, pady=(0, 9))
    ttk.Checkbutton(so, text="加工完回工件中心", variable=v_send_home).pack(side="left")
    ttk.Label(so, text="抬刀").pack(side="left", padx=(12, 2))
    ttk.Entry(so, textvariable=v_send_lift, width=4).pack(side="left")
    ttk.Label(so, text="mm　续切下刀 F").pack(side="left", padx=(4, 3))
    ttk.Entry(so, textvariable=v_send_plunge, width=5).pack(side="left")
    tk.Label(so, text="（T/M6 换刀行自动跳过）", fg=UI_TXT3,
             font=(UI_FONT, FS_TINY)).pack(side="left", padx=8)

    def send_preview(p):
        """选完文件先报行数，顺便把上次断点提示出来"""
        try:
            with open(p, "r", encoding="utf-8", errors="replace") as f:
                total = sum(1 for ln in f if _send_clean(ln))
        except Exception as e:
            v_send_info.set("读不了这个文件：%s" % e)
            return
        br = None
        try:
            _tmp = GrblStreamer(None)
            _tmp.path = p
            br = _tmp.load_break()
        except Exception:
            br = None
        txt = "共 %d 行（空行/注释不计）" % total
        if br and br.get("done"):
            txt += "　⚠ 上次停在第 %d 行（%s），点「开始」会问要不要从断点续切" % (
                br.get("line"), br.get("time", br.get("ts", "")))
        v_send_info.set(txt)

    def send_pick():
        p = filedialog.askopenfilename(
            title="选择刀路文件",
            filetypes=[("刀路文件", "*.tap *.nc *.gcode *.ngc *.txt"), ("全部文件", "*.*")])
        if p:
            v_send.set(p)
            send_preview(p)

    def send_use_last():
        p = (last_gen.get("p") or "").strip()
        if not p or not os.path.isfile(p):
            messagebox.showinfo(APP, "还没生成刀路 —— 先在上面「④ 生成刀路」点一次生成")
            return
        v_send.set(p)
        send_preview(p)

    def send_go():
        p = (v_send.get() or "").strip()
        if not p or not os.path.isfile(p):
            messagebox.showwarning(APP, "先选一份刀路文件（生成刀路后会自动带过来）")
            return
        s = send_holder["s"]
        if s is not None and s.state in ("paused", "stopped"):
            do(lambda: s.resume())
            return
        if s is not None and s.running():
            append_log("正在发送中（要中断请点「■ 停止」）")
            return
        l = link()
        if not coord_ok[0]:
            if not messagebox.askokcancel(
                    APP, "机床刚复位过：坐标已经归零。\n\n"
                         "只有已经「回零」、或已经把刀移到固定角点重新对零，才可以继续。\n"
                         "否则先停下重新对刀 —— 不然刀会按错误的坐标跑。\n\n继续发送？"):
                return
            coord_ok[0] = True
        if not flow_ok["zero"]:
            if not messagebox.askokcancel(
                    APP, "还没设零（G54 不是工件中心）。\n\n"
                         "现在发送，刀会按机床里现有的零点跑 —— 可能整件偏。\n\n继续？"):
                return
        try:
            with open(p, "r", encoding="utf-8", errors="replace") as f:
                nline = sum(1 for ln in f if _send_clean(ln))
        except Exception as e:
            do(lambda: (_ for _ in ()).throw(GrblError("读不了刀路文件：%s" % e)))
            return
        if not messagebox.askokcancel(
                APP, "确认开始加工？\n\n文件：%s\n共 %d 行\n\n"
                     "刀会真的动 —— 确认已对刀（Z 正确）、工件已夹紧。\n"
                     "中途「⏸ 暂停」＝刀就地停住，「▶ 继续」接着切（不重定位）。\n"
                     "要抬刀停下检查就用「■ 停止」，之后再「继续」会回断点。" % (os.path.basename(p), nline)):
            return

        def _go():
            s = GrblStreamer(l, log=append_log)
            send_holder["s"] = s
            try:
                s.z_lift = max(0.5, float(v_send_lift.get() or 5))
            except ValueError:
                s.z_lift = 5.0
            s.z_safe = s.z_lift
            try:
                s.plunge = max(10.0, float(v_send_plunge.get() or 300))
            except ValueError:
                s.plunge = 300.0
            s.auto_home = bool(v_send_home.get())
            try:                                # R1.1：把界面标定的安全 Z 交给发送器
                s.z_safe_mz = safe_target_mz()
            except Exception:
                s.z_safe_mz = None
            rr = res_holder["r"]
            s.home_mpos = (rr["center"][0], rr["center"][1]) if rr else None
            n = s.load(p)
            if not n:
                raise GrblError("这份文件里没有可执行的行（全是注释/空行？）")
            br = s.load_break()
            from_line = None
            if br and br.get("done") and int(br.get("done")) < n:
                if messagebox.askyesno(
                        APP, "发现上次没跑完的记录：\n\n文件　%s\n停在第 %d 行（共 %d 行，已完成 %d）\n时间　%s\n\n"
                             "从第 %d 行继续？（选「否」＝从第 1 行重新开始）"
                             % (br.get("file"), br.get("line"), br.get("total", n),
                                br.get("done"), br.get("ts"), br.get("line"))):
                    from_line = br.get("line")
            # R2：软件不再自动抬刀 —— 文件头没有抬刀就先问一句（问过再跑，责任清楚）
            if from_line is None and not s._lift_line_in_file():
                if not messagebox.askokcancel(
                        APP,
                        "这份刀路开头没有抬刀指令。\n\n"
                        "按你的要求，软件已经不自动抬刀了（避免和代码里的动作打架）。\n"
                        "如果刀现在低于工件顶面，第一条 G0 会横着穿过去。\n\n"
                        "刀已经在工件上方 → 点「确定」直接跑\n"
                        "否则：先用「生成刀路」出来的文件（文件头自带抬刀），或手动抬刀后再来"):
                    append_log("已取消发送（文件没有抬刀，刀可能还在工件里）")
                    return
            s.start(from_line)
            append_log("已开始发送：%s（%d 行）" % (os.path.basename(p), n))

        do(_go)

    def send_pause():
        s = send_holder["s"]
        if s is None or s.state != "running":
            append_log("现在没在发送 —— 暂停只对发送中的刀路有效")
            return
        append_log("暂停：feed hold 就地停住（不抬刀、不软复位、坐标不丢）…")
        s.pause()

    def send_stop():
        s = send_holder["s"]
        if s is None or not s.running():
            append_log("没有正在发送的刀路")
            return
        if not messagebox.askokcancel(
                APP, "确认停止？\n\n会 feed hold → 软复位 → 抬刀。\n"
                     "加工会中断；之后点「▶ 继续」可以从断点续切。"):
            return
        s.stop()

    def send_tick():
        """每 250ms 刷一次进度（不阻塞界面）"""
        try:
            s = send_holder["s"]
            if s is not None:
                st = s.snapshot()
                tot = st["total"] or 1
                pb.configure(value=max(0.0, min(100.0, 100.0 * st["acked"] / tot)))
                info = "第 %d / %d 行 · 用时 %s" % (st["acked"], st["total"], _fmt_dur(st["elapsed"]))
                if st.get("eta") and st["state"] in ("running", "paused"):
                    info += " · 预计还要 %s" % _fmt_dur(st["eta"])
                if st["errs"]:
                    info += " · %d 条被拒（看日志）" % st["errs"]
                if st["state"] == "idle" and not st["acked"]:
                    info = ""
                _setv(v_send_info, info)
                _setv(v_send_msg, st["msg"] or "待机")
                if st["state"] in ("paused", "stopped"):
                    btn_send.configure(text="▶ 继续")
                    btn_spause.state(["disabled"])
                elif st["state"] in ("running", "resuming", "stopping", "finishing"):
                    btn_send.configure(text="▶ 开始")
                    btn_spause.state(["!disabled"])
                else:
                    btn_send.configure(text="▶ 开始")
                    btn_spause.state(["disabled"])
        except Exception:
            pass
        root.after(250, send_tick)

    root.after(400, send_tick)

    # ---- 高级 / 工具（默认收起，不占主流程版面）----
    adv_w, adv = _card(_pg_snd, "", "高级 / 工具", "平时不用：刷新端口、诊断、软复位、发送命令")
    adv_w.pack(fill="x", padx=10, pady=6)
    a0 = ttk.Frame(adv)
    a0.pack(fill="x", padx=8, pady=6)
    adv_state = [False]

    def toggle_adv():
        adv_state[0] = not adv_state[0]
        if adv_state[0]:
            adv_inner.pack(fill="x", after=a0)
            btn_adv.configure(text="▾ 收起")
        else:
            adv_inner.pack_forget()
            btn_adv.configure(text="▸ 展开　刷新端口 / 串口诊断 / 发命令 / 软复位 / 回零·G54 / 检查更新 / 快捷键表")

    btn_adv = ttk.Button(a0, command=toggle_adv,
                         text="▸ 展开　刷新端口 / 串口诊断 / 发命令 / 软复位 / 回零·G54 / 检查更新 / 快捷键表")
    btn_adv.pack(side="left")
    adv_inner = ttk.Frame(adv)
    a1 = ttk.Frame(adv_inner)
    a1.pack(fill="x", padx=8, pady=(2, 2))
    ttk.Label(a1, text="串口：", foreground=UI_TXT2).pack(side="left")
    ttk.Button(a1, text="刷新端口", command=lambda: refresh_ports()).pack(side="left", padx=4)
    ttk.Button(a1, text="串口诊断", command=lambda: do_diagnose()).pack(side="left", padx=4)
    ttk.Button(a1, text="软复位（会丢机床坐标）",
               command=lambda: do(lambda: link().soft_reset())).pack(side="left", padx=(12, 4))
    ttk.Button(a1, text="检查更新",
               command=lambda: _start_update_check()).pack(side="left", padx=(12, 4))
    a2 = ttk.Frame(adv_inner)
    a2.pack(fill="x", padx=8, pady=(2, 8))
    hg = ttk.Frame(a2)                      # 有回零机器才有意义
    hg.pack(side="left")
    ttk.Label(hg, text="有回零机器：", foreground=UI_TXT2).pack(side="left")
    ttk.Button(hg, text="回零 $H", command=lambda: do(lambda: link().home())).pack(side="left", padx=4)
    ttk.Button(hg, text="复制 G10", command=lambda: copy_g10()).pack(side="left", padx=4)
    btn_hot = ttk.Button(a2, text="快捷键表 (F1)", command=lambda: show_hotkeys())
    btn_hot.pack(side="left", padx=(16, 4))

    # v1.13：发命令（自查固件/偏移用）。回零、解锁、软复位这类会改变状态的先确认
    a3 = ttk.Frame(adv_inner)
    a3.pack(fill="x", padx=8, pady=(2, 8))
    ttk.Label(a3, text="发命令：", foreground=UI_TXT2).pack(side="left")
    v_cmd = tk.StringVar(value="")
    ent_cmd = ttk.Entry(a3, textvariable=v_cmd, width=24, font=(UI_MONO, 11))
    ent_cmd.pack(side="left", padx=4)
    ttk.Button(a3, text="发送", command=lambda: send_cmd()).pack(side="left", padx=4)
    ttk.Label(a3, text="$I 固件信息 · $$ 全部设置 · $# 当前偏移 · $G 模态（回复会显示在日志里）",
              foreground=UI_TXT2).pack(side="left", padx=6)

    # v1.16：生成记录（排查「偶发整件偏移」时对账用）
    a4 = ttk.Frame(adv_inner)
    a4.pack(fill="x", padx=8, pady=(0, 8))
    ttk.Button(a4, text="清空定位点（8 个点，连碰点一起清）",
               command=lambda: cp_clear()).pack(side="left", padx=(0, 6))
    ttk.Button(a4, text="生成记录（最近 3 次）",
               command=lambda: dump_genlog()).pack(side="left", padx=(0, 6))
    ttk.Label(a4, text="每次生成都会记下：中心 / θ / 宽高 / 当时的 G54 与 G92 → 真跑偏了先看这里",
              foreground=UI_TXT2).pack(side="left", padx=6)

    # v1.18：③ 区原来并列的那排「手动」按钮搬到这里 —— 都不是流程步骤
    a5 = ttk.Frame(adv_inner)
    a5.pack(fill="x", padx=8, pady=(0, 4))
    ttk.Label(a5, text="坐标诊断 / 特殊用途：", foreground=UI_TXT2).pack(side="left")
    ttk.Button(a5, text="核对坐标（只读）",
               command=lambda: check_coords()).pack(side="left", padx=4)
    ttk.Button(a5, text="按数值写零（刀不必在位）",
               command=lambda: write_g54()).pack(side="left", padx=4)
    ttk.Button(a5, text="清成机床坐标（不碰边直接跑才用）",
               command=lambda: zero_wcs()).pack(side="left", padx=4)
    ttk.Button(a5, text="自动测偏移（反推补偿）",
               command=lambda: auto_offset()).pack(side="left", padx=4)
    a6 = ttk.Frame(adv_inner)
    a6.pack(fill="x", padx=8, pady=(0, 8))
    ttk.Label(a6, text="手动指定 θ：", foreground=UI_TXT2).pack(side="left")
    ttk.Entry(a6, textvariable=v_theta, width=9,
              font=(UI_MONO, 11)).pack(side="left", padx=4)
    ttk.Label(a6, text="度　只在「只碰 1 点 / 不纠角度、但你知道真实倾角」时填；"
                       "正常靠碰边测出来，别手填（手填会盖住碰点记错的问题）",
              foreground=UI_TXT2).pack(side="left", padx=6)

    # ---- R2.10：刀具 / 基准补偿（从定位页搬来）----
    # 中心 = 四条边中线交点；四条边各偏同一个量 → 中心不动，只有宽高变。
    # 所以默认「不补偿」，只在你需要拿「实测宽高」当工件尺寸时才填刀径。
    a7 = ttk.Frame(adv_inner)
    a7.pack(fill="x", padx=8, pady=(0, 8))
    pf = ttk.LabelFrame(a7, text="刀具 / 基准补偿（只改「宽高 / 直径」，中心不受影响 —— 分中一般不用填）")
    pf.pack(fill="x")
    ttk.Label(pf, text="刀直径(mm)").pack(side="left", padx=(8, 2), pady=8)
    ttk.Entry(pf, textvariable=v_radius, width=7).pack(side="left")
    ttk.Label(pf, text="基准补偿").pack(side="left", padx=(12, 2))
    cb_comp = ttk.Combobox(pf, textvariable=v_comp, width=30, state="readonly",
                           values=COMP_MODES)
    cb_comp.pack(side="left")
    cb_comp.bind("<<ComboboxSelected>>", sync_off)
    ttk.Label(pf, text="生效偏移(mm)").pack(side="left", padx=(12, 2))
    ttk.Entry(pf, textvariable=v_off, width=9).pack(side="left")
    ttk.Label(pf, text="+ 外扩 / − 内缩　只影响宽高", foreground=UI_TXT2).pack(side="left", padx=6)

    def send_cmd():
        c = (v_cmd.get() or "").strip()
        if not c:
            return
        low = c.lower()
        risky = low in ("$h", "$x", "x", "$21", "$20")
        if risky and not messagebox.askokcancel(
                APP,
                "「%s」会改变机床状态：\n\n"
                "  $H = 回零（三轴会真的移动 → 先确认限位开关与方向对）\n"
                "  $X = 解锁 Alarm（不改位置，但会清掉报警原因）\n\n"
                "确定发送？" % c):
            return
        if low in ("ctrl-x", "reset"):
            if not messagebox.askokcancel(APP, "软复位会丢机床坐标（MPos 归零、位置基准变乱），确定？"):
                return
            c = "\x18"
        do(lambda: (link().send(c), append_log("→ " + repr(c) + "（GRBL 的回复会跟在后面）")))

    # ---- 日志 ----
    # 钉在窗口底部（不跟 body 一起滚）：v1.14 顶部加了流程条，日志若还在滚动区里
    # 就会被挤出可视范围 —— 而日志是「发命令」框的回复出口，必须一直看得见。
    lf_w, lf = _card(_pg_conn, "", "日志", "发命令、报警、断线都打在这里")
    lf_w.pack(fill="both", expand=True, padx=10, pady=(0, 10))
    # 日志原来用 Consolas：它没有中文字形，中文会被系统回退成宋体 ——
    # 中英混排一个字重一个发虚，整块看着很脏；wrap="none" 又让长中文行被切掉。
    # 现在改用同一个 UI 字体 + 字号抬一档 + 1px 行距 + 自动换行。
    txt = tk.Text(lf, height=7, font=(UI_FONT, FS_BODY), wrap="word",
                  spacing1=2, spacing3=3, padx=9, pady=7,
                  relief="flat", bd=0, highlightthickness=1,
                  highlightbackground=UI_LINE, highlightcolor=UI_PRIMARY)
    sb = ttk.Scrollbar(lf, command=txt.yview)
    txt.configure(yscrollcommand=sb.set)
    sb.pack(side="right", fill="y")
    txt.pack(side="left", fill="both", expand=True)

    # ---- 界面刷新的两条铁律（v1.39.5）----
    # ① 串口读线程 / 发送线程都会调 append_log，而 tkinter 不是线程安全的：
    #    非主线程 insert Text 会让界面随机僵住几秒（发送加工时日志最密，最明显）。
    #    所以 append_log 只入队，真正的 insert 由主线程 _flush_log 批量做。
    # ② tkinter 的 set()/configure() 即使值没变也会触发重排重绘。
    #    每 120ms 无条件刷十几个变量 + 7 个步骤条 Label，是界面发涩的直接原因。
    _log_q = queue.Queue()

    def _setv(var, val):
        try:
            if var.get() == val:
                return
        except Exception:
            pass
        try:
            var.set(val)
        except Exception:
            pass

    def _cfg_once(w, **kw):
        d = getattr(w, "_cfgd", None)
        if d is None:
            d = {}
            try:
                w._cfgd = d
            except Exception:
                pass
        ch = {}
        for k, v in kw.items():
            if d.get(k) != v:
                ch[k] = v
        if not ch:
            return
        d.update(ch)
        try:
            w.configure(**ch)
        except Exception:
            pass

    def append_log(msg):
        # 任何线程都可以调；真正的控件操作在主线程 _flush_log 里
        try:
            _log_q.put_nowait(str(msg))
        except Exception:
            pass

    _last_log = [""]

    def _flush_log():
        n = 0
        while n < 300:
            try:
                m = _log_q.get_nowait()
            except queue.Empty:
                break
            try:
                txt.insert("end", m + "\n")
            except Exception:
                pass
            _last_log[0] = m
            n += 1
        if n:
            try:
                txt.see("end")
                if int(txt.index("end-1c").split(".")[0]) > 600:
                    txt.delete("1.0", "200.0")
            except Exception:
                pass
            # 顶部摘要：一句太长就截断，出错那类变红加粗（一眼能看到）
            try:
                _m = _last_log[0]
                _setv(v_lastlog, "最近：" + (_m if len(_m) <= 76 else _m[:74] + "…"))
                _bad = any(k in _m for k in ("！", "错", "报警", "失败", "断开", "超时", "掉线", "重连"))
                _cfg_once(lbl_last,
                          fg=("#b91c1c" if _bad else "#64748b"),
                          font=(UI_FONT, FS_SMALL, "bold") if _bad else (UI_FONT, FS_SMALL))
            except Exception:
                pass
        try:
            root.after(90, _flush_log)
        except Exception:
            pass

    root.after(200, _flush_log)

    # ---- 机器类型切换 ----
    def apply_mode():
        """直出模式：藏掉 G54/回零相关；有回零模式：显示它们"""
        mach = bool(v_mach.get())
        try:
            if mach:
                hg.pack_forget()
            else:
                hg.pack(side="left", before=btn_hot)     # 放回原位，别跑到最后
        except Exception:
            pass

    def show_hotkeys():
        messagebox.showinfo(
            APP + " · 快捷键",
            "点动（按住 = 连续走）\n"
            "  ← → ↑ ↓   =  X− / X+ / Y− / Y+\n"
            "  =   /  -  =  Z+ / Z−      ← 不用小键盘（数字键那排右侧）\n"
            "  PgUp/PgDn =  Z+ / Z−      （键盘有独立 Page 键时可用）\n"
            "  [ ]       =  步长 降 / 升 一档\n"
            "\n记点 / 停\n"
            "  Enter        = 记一个点（按最后一次点动方向自动判边）\n"
            "  空格         = 点动中：先停下；没在点动：记一个点\n"
            "  1 2 3 4      = 指定记 左壁 / 右壁 / 前壁 / 后壁（圆形模式都记圆点）\n"
            "  Backspace    = 撤销上一点\n"
            "\n其它\n"
            "  Esc       = 停止点动\n"
            "  X         = 解锁 $X\n"
            "  C         = 连接 / 断开\n"
            "  G         = 生成刀路\n"
            "  F1        = 这个表\n"
            "\n（在输入框里打字时，以上快捷键不生效）")

    # ---- 帮助函数 ----
    def link():
        l = link_holder["link"]
        if l is None:
            raise GrblError("请先连接串口")
        return l

    append_log_ref[0] = append_log
    link_ref[0] = link

    def do(fn):
        try:
            return fn()
        except Exception as e:
            messagebox.showerror(APP, str(e))
            append_log("错误：" + str(e))
            return None

    def refresh_ports():
        ports = list_ports()
        cb_port["values"] = [p[0] for p in ports]
        if ports and not v_port.get():
            v_port.set(ports[0][0])
        if ports:
            append_log("找到 %d 个串口：%s" % (
                len(ports), "、".join("%s%s" % (d, " (%s)" % desc if desc else "") for d, desc in ports)))
            append_log("  端口框也可以直接手打（COM3 / COM10），改完点「连接」")
        else:
            append_log("没找到串口 —— 点「诊断」看原因；也可以直接在端口框手打 COM3 再点连接")

    def do_diagnose():
        append_log("---- 串口诊断 ----")
        for line in serial_env_report():
            append_log("  " + line)
        append_log("------------------")
        append_log("提示：pyserial 不可用时，本程序会自动改用内置串口（Windows 免安装）")
        try:
            messagebox.showinfo(APP, "诊断结果已写进下方日志。\n\n"
                                     "如果「最终可用」是空的：\n"
                                     "1) 试着手打端口号（如 COM3）再连接\n"
                                     "2) 关掉 Candle（它可能占着串口）\n"
                                     "3) 把日志内容发我")
        except Exception:
            pass

    def toggle_conn():
        if link_holder["link"] is not None:
            link_holder["link"].close()
            link_holder["link"] = None
            btn_conn.configure(text="连接")
            v_state.set("未连接")
            v_mpos2.set("")
            alarm_seen[0] = False
            flow_ok["zero"] = False      # 断开＝新会话，② 要重新设零
            flow_ok["gen"] = False
            try:
                lbl_state.configure(fg="#059669")
            except Exception:
                pass
            append_log("已断开")
            return

        def _go():
            if mock:
                l = MockLink()
            else:
                l = GrblLink(v_port.get().strip(), int(v_baud.get()), log=append_log,
                             transport=transport)
            l.start()
            link_holder["link"] = l
            try:
                l.on_reset = _on_machine_reset      # R1.4：复位就停用旧坐标
            except Exception:
                pass
            flow_ok["zero"] = False       # 刚连上：别拿上一次的零点充数
            flow_ok["gen"] = False
            btn_conn.configure(text="断开")
            append_log("已连接 " + ("模拟机" if mock else v_port.get()))
            try:
                l.send("$$", log_it=False)      # R2.5：读一次关键设置，查固件软限位有没有开着
                l.soft_limit_notified = False
            except Exception:
                pass
            try:
                l.query_offsets()      # 读一次 G54，看有没有残留偏移
            except Exception:
                pass
            try:
                if l.is_alarm():
                    append_log("！当前是 %s —— 先点「解锁 $X」再操作" % l.status()["state"])
            except Exception:
                pass

            # R2.7：没装回零的机器（$22=0）上电一定是 Alarm —— 自动解一次，省得每次点
            def _auto_unlock():
                try:
                    _c = getattr(l, "grbl_cfg", {}) or {}
                    if _c and _c.get(22, 0) >= 1:
                        return        # 装了回零：Alarm 多半是真没回零/撞了，不替你解
                    if l.is_alarm():
                        l.send("$X", log_it=True)
                        append_log("✓ 已自动解锁（没装回零的机器上电就是 Alarm；坐标不动、不影响对刀）")
                except Exception:
                    pass
            try:
                root.after(1800, _auto_unlock)
            except Exception:
                pass

        do(_go)

    btn_conn.configure(text="断开" if mock else "连接", command=toggle_conn)

    def paint_cards():
        """靠边位置 = 状态灯（R1.8）：未碰灰底「XXX 未碰」；已碰绿底「↩ XXX ✓N」。
        右侧一行汇总「已碰 3/4 · 还差 后壁」，做完显示可以走中心。"""
        if shape_of(v_shape.get()) == SHAPE_CIRCLE:   # 圆形：没有四边之分
            for _e in EDGES:
                for _sl in (1, 2):
                    _b = pv_btns.get((_e, _sl))
                    if _b is None:
                        continue
                    if _sl == 1:
                        _b.configure(bg="#eef2f7", fg="#cbd5e1", text="%s 不用" % EDGE_CN[_e])
                    elif _b.winfo_manager():
                        _b.pack_forget()
            try:
                pv_sum.configure(text="圆形模式 · 用上面的「记圆点」", fg="#64748b")
            except Exception:
                pass
            return
        done = []
        for _e in EDGES:
            _n = len(fitter.pts.get(_e) or [])
            for _sl in (1, 2):
                _b = pv_btns.get((_e, _sl))
                if _b is None:
                    continue
                _q = (cp["pts"].get(_e) or {}).get(str(_sl)) or {}
                _has = (_q.get("mx") is not None) and coord_ok[0]
                _mk = "①" if _sl == 1 else "②"
                if _sl == 2:                    # ②：有才显示
                    if _has and not _b.winfo_manager():
                        _b.pack(side="left", padx=(0, 6))
                    elif not _has and _b.winfo_manager():
                        _b.pack_forget()
                if _has and _n:
                    _b.configure(bg="#059669", fg="#ffffff", activebackground="#047857",
                                 text="↩ %s%s ✓%d" % (EDGE_CN[_e], _mk, _n))
                elif _has:
                    # 上一件留下的位置：能走过去，但本件还没碰过 —— 用淡蓝、标「上件」，不冒充已完成
                    _b.configure(bg="#dbeafe", fg="#1d4ed8", activebackground="#bfdbfe",
                                 text="↩ %s%s · 上件" % (EDGE_CN[_e], _mk))
                else:
                    _b.configure(bg="#eef2f7", fg="#94a3b8", activebackground="#dbeafe",
                                 text="%s%s 未碰" % (EDGE_CN[_e], _mk))
            if _n:
                done.append(EDGE_CN[_e])
        _miss = [EDGE_CN[_e] for _e in EDGES if not (fitter.pts.get(_e) or [])]
        try:
            if not coord_ok[0]:
                pv_sum.configure(text="机床刚复位 · 要重新碰点", fg="#b91c1c")
            elif not done:
                pv_sum.configure(text="还没碰任何边", fg="#b45309")
            elif _miss:
                pv_sum.configure(text="已碰 %d/4 · 还差 %s" % (len(done), "、".join(_miss)),
                                 fg="#b45309")
            else:
                pv_sum.configure(text="4 条边都碰完了 ✓ 下一步：走到中心", fg="#15803d")
        except Exception:
            pass

    def _on_machine_reset():
        """机床复位 / 上电：GRBL 机床坐标归零（没装限位回零的机器就是这样），
        之前记的「机床绝对坐标」（靠边位置、安全 Z）全部不再对应实际位置 → 立刻停用。"""
        def _apply():
            coord_ok[0] = False
            try:
                _s = send_holder["s"]
                if _s is not None and _s.state in ("running", "pausing", "paused",
                                                   "resuming", "stopping", "finishing"):
                    _s.abort_on_reset()
            except Exception:
                pass
            try:
                stop_all_jogs(quiet=True)      # R2.4：复位后坐标归零，别再让按住的长 jog 按新基准跑
            except Exception:
                pass
            try:
                safe_z["mz"] = None
                v_safe_z.set("")
                safe_tip()
            except Exception:
                pass
            try:
                paint_cards()
            except Exception:
                pass
            append_log("⚠ 机床复位：坐标已归零 —— 靠边位置和安全 Z 已停用。"
                       "先回零，或把刀移到固定角点重新对零，再重新碰点 / 标定。")
            try:
                v_nextedge.set("机床刚复位 · 靠边位置已停用（先回零 / 重新对零）")
            except Exception:
                pass
        try:
            root.after(0, _apply)      # 复位回调来自串口线程，必须回主线程改界面
        except Exception:
            _apply()

    def fitter_can_solve():
        """当前形状模式下「点够了没」"""
        if shape_of(v_shape.get()) == SHAPE_CIRCLE:
            return fitter.circle_ready()
        return fitter.ready()

    # ---- 会话快照：重开软件恢复上次的碰点/选项（只恢复数据，绝不动机床）----
    sess = {"restored": False, "saved_at": None, "guard": False,
            "loading": False, "after": None}

    def snapshot():
        """当前工作状态（碰点 + 所有影响刀路的选项）。不含 8 点预设 —— 那是另一个文件。"""
        return {
            "ver": SESSION_VER,
            "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "shape": v_shape.get(),
            "pts": {e: [[round(float(p[0]), 4), round(float(p[1]), 4)] for p in fitter.pts[e]]
                    for e in EDGES},
            "cpts": [[round(float(p[0]), 4), round(float(p[1]), 4)] for p in fitter.cpts],
            "theta": v_theta.get(),
            "comp": v_comp.get(), "off": v_off.get(), "radius": v_radius.get(),
            "mach": bool(v_mach.get()),
            "src": (v_src.get() or "").strip(),
            "ox": v_ox.get(), "oy": v_oy.get(), "rot": bool(v_rot.get()),
            "zmode": v_zmode.get(), "zval": v_zval.get(),
            "start_z": v_start_z.get(),
            "dry": False, "droptc": bool(v_droptc.get()),   # v1.18：空跑文件已废弃
            # R2.8：上次中心（机床坐标）—— 换同款工件时一键抬 Z 走过去
            "last_center": ({"x": round(last_c["x"], 4), "y": round(last_c["y"], 4),
                             "at": last_c["at"], "shape": last_c["shape"]}
                            if last_c["x"] is not None else None),
            # R1.1：安全高度（机床绝对 Z）。存它才能在下次开机继续防撞
            "safe_mz": (round(float(safe_z["mz"]), 4) if safe_z["mz"] is not None else None),
        }

    def session_flush():
        sess["after"] = None
        try:
            return snapshot() if session_save(snapshot()) else None
        except Exception:
            return None

    def session_autosave(delay=600):
        """变更后延迟落盘（防抖），避免频繁写盘卡界面"""
        if sess["loading"]:
            return
        try:
            if sess["after"]:
                root.after_cancel(sess["after"])
        except Exception:
            pass
        try:
            sess["after"] = root.after(delay, session_flush)
        except Exception:
            session_flush()

    def show_session_note(text=""):
        try:
            v_session.set(text or "")
            if text:
                lbl_session.pack(fill="x", padx=10, pady=(6, 0), before=top)
            else:
                lbl_session.pack_forget()
        except Exception:
            pass

    def apply_session_snapshot(d):
        """把快照写回界面。只改界面/内存，不发任何 G 命令（机床一动不动）。"""
        sess["loading"] = True
        try:
            sh = d.get("shape")
            if sh in SHAPES:
                v_shape.set(sh)
            if d.get("comp"):
                v_comp.set(d["comp"])
            if d.get("off") is not None:
                v_off.set(str(d["off"]))
            if d.get("radius") is not None:
                v_radius.set(str(d["radius"]))
            v_mach.set(bool(d.get("mach")))
            _src = (d.get("src") or "").strip()
            if _src and not os.path.exists(_src):
                append_log("上次的源刀路已不在原位（%s）→ 留空，请重新选择" % _src)
                _src = ""
            v_src.set(_src)
            v_ox.set(str(d.get("ox") or "0"))
            v_oy.set(str(d.get("oy") or "0"))
            v_rot.set(bool(d.get("rot", True)))
            v_zmode.set(d.get("zmode") or "none")
            v_zval.set(str(d.get("zval") or "0"))
            v_dry.set(bool(d.get("dry", True)))
            v_droptc.set(bool(d.get("droptc", False)))
            v_start_z.set(str(d.get("start_z", "") or ""))
            try:                          # R2.8：恢复上次中心（旧的 "pre" 字段直接忽略）
                _lc = d.get("last_center") or {}
                if _lc.get("x") is not None:
                    last_c["x"] = float(_lc["x"])
                    last_c["y"] = float(_lc["y"])
                    last_c["at"] = str(_lc.get("at") or "")
                    last_c["shape"] = str(_lc.get("shape") or "")
                    refresh_last_btn()
            except Exception:
                pass
            try:                              # R1.1：恢复安全 Z
                _smz = d.get("safe_mz")
                if _smz is not None:
                    safe_z["mz"] = round(float(_smz), 4)
                    v_safe_z.set("%.3f" % safe_z["mz"])
                safe_tip()
            except Exception:
                pass
            apply_shape()                     # 先按形状摆好按钮/文案
            fitter.clear()
            for e in EDGES:
                for p in ((d.get("pts") or {}).get(e) or []):
                    fitter.add(e, (float(p[0]), float(p[1])))
            for p in (d.get("cpts") or []):
                fitter.add_circle((float(p[0]), float(p[1])))
            apply_offset()
            refresh_count()
            if fitter_can_solve():
                try_solve()
            if d.get("theta"):
                v_theta.set(str(d["theta"]))   # θ 可能被手改过，重算后盖回原值
            sess["restored"] = True
            sess["saved_at"] = d.get("saved_at")
            sess["guard"] = False
        finally:
            sess["loading"] = False

    def restore_session():
        d = session_load()
        if not session_ok(d):
            return False
        try:
            apply_session_snapshot(d)
            n = sum(len(fitter.pts[e]) for e in EDGES) + len(fitter.cpts)
            c = ("中心 %.3f / %.3f" % res_holder["r"]["center"]) if res_holder["r"] else "还没算中心"
            show_session_note(
                "⚠ 已恢复 %s 的会话：%d 个碰点（%s） —— 这是上次的数据，"
                "新工件请先点 ② 区「清空」" % (d.get("saved_at") or "上次", n, c))
            append_log("已恢复上次会话（%s）：%d 个碰点，%s。这是旧数据，换新工件请点「清空」。"
                       % (d.get("saved_at") or "—", n, c))
            try:
                paint_edge_btns()
                paint_cards()
            except Exception:
                pass
            return True
        except Exception as e:
            sess["restored"] = False
            append_log("恢复上次会话失败，按空白开始：%s" % e)
            return False

    def session_guard():
        """在「恢复来的旧点」上第一次动手前问一次：继续 or 先清空（防旧点污染新工件）"""
        if not sess["restored"] or sess["guard"]:
            return True
        sess["guard"] = True
        n = sum(len(fitter.pts[e]) for e in EDGES) + len(fitter.cpts)
        if n <= 0:
            return True
        if messagebox.askokcancel(
                APP,
                "界面里还是上次会话的 %d 个碰点。\n\n"
                "· 确定 = 接着用这些点（同一件工件没做完）\n"
                "· 取消 = 先清空，再碰新工件\n\n"
                "若是新工件，请点「取消」，然后点 ② 区的「清空」。" % n):
            return True
        sess["restored"] = False
        append_log("提示：还留着上次的 %d 个碰点 —— 点 ② 区「清空」后再碰新工件" % n)
        return False

    def apply_shape(*_a):
        """切换矩形 / 圆形：换按钮、换文案、重算"""
        sh = shape_of(v_shape.get())
        fitter.shape = sh
        is_circle = (sh == SHAPE_CIRCLE)
        try:
            sec2_w._card_title.configure(
                text="碰圆点定位" if is_circle else "碰边定位")
        except Exception:
            pass
        lbl_shape_tip.configure(
            text="圆形：圆上碰 3 点定圆心，不用对准轴线；无方向不旋转" if is_circle
            else "矩形：四边各碰 1 点求中心；要角度就挑一条边再碰 1 点")
        for e in EDGES:
            if is_circle:
                edge_btns[e].pack_forget()
            else:
                edge_btns[e].pack(side="left", padx=6, pady=(8, 4))
        if is_circle:
            btn_rec_circle.pack(side="left", padx=6, pady=(8, 4), before=btn_undo)
        else:
            btn_rec_circle.pack_forget()
        try:
            # θ 是碰边测出来的：主界面只读，圆形也保持只读（手改在高级区）
            ent_theta.configure(state="disabled" if is_circle else "readonly")
        except Exception:
            pass
        try:
            paint_edge_btns()            # 标题里带「已碰 N/4 边」，切形状后要重算
        except Exception:
            pass
        v_nextedge.set("圆形：在圆的周围碰 3 点（位置随意，尽量分散）" if is_circle
                       else "Enter 记点（按点动方向判边；1/2/3/4 指定边）")
        refresh_count()
        if fitter_can_solve():
            try_solve()
        else:
            res_holder["r"] = None
            v_result.set("—")
            v_g10.set("")
            v_check.set("")
            v_theta_src.set("")

    def refresh_count():
        if shape_of(v_shape.get()) == SHAPE_CIRCLE:
            v_count.set("圆点 %d" % len(fitter.cpts))
            paint_cards()
            paint_edge_btns()
            n = len(fitter.cpts)
            if n < 3:
                v_hint.set("下一步：在圆的周围碰 %d 个点（还差 %d 个）。位置随意，但尽量分散——"
                           "三个点越接近一条直线，圆心越算不准。" % (3, 3 - n))
            elif res_holder["r"] is None:
                v_hint.set("点数够了但没算出来（三个点是不是几乎在一条直线上？换个位置再碰一个）")
            else:
                v_hint.set("✓ 圆心已算出 → 核对 ③ 的直径与圆度；想更稳就再碰 1 个点（自动改最小二乘）")
            session_autosave()
            return
        v_count.set("　".join("%s%d" % (EDGE_CN[e][0], fitter.count(e)) for e in EDGES))
        paint_cards()
        paint_edge_btns()
        dir_edges = [e for e in EDGES if fitter.count(e) >= 2]
        missing = [e for e in EDGES if not fitter.pts[e]]
        if missing:
            v_hint.set("下一步：去碰%s（点动到位 → 点「记 %s」）。四边都碰过才知道中心。"
                       % ("、".join(EDGE_CN[e] for e in missing), EDGE_CN[missing[0]]))
        elif not dir_edges:
            v_hint.set("下一步：四条边都碰过了，但角度还定不了（每边只有 1 点）→ 挑最好碰的一条边再碰一次，"
                       "两点拉开 80mm 以上（每边 2 点最稳）。")
        else:
            v_hint.set("✓ 中心 + 角度都能算了（%s有 2 点）→ 核对下面结果，然后生成刀路"
                       % "、".join(EDGE_CN[e] for e in dir_edges)
                       + ("" if len(dir_edges) == 4 else "；四边各 2 点最稳"))
        session_autosave()

    SRC_CN = {
        "edge2": "θ 来源：四条边各 2 点（最准）",
        "edge1": "θ 未测：每边仅 1 点 → 只平移，θ 按 0 处理",
    }

    def g10_text(c):
        """界面里「复制到 Candle」的那条 G10。

        v3.0.2：必须带上 G54 当前的 Z。GRBL 的 G10 L2 会把**没写到的轴按 0 处理**，
        以前这里只写 X/Y —— 复制到 Candle 一执行，Z 对刀零点就被清成 0（刀扎下去或悬空）。
        """
        z = None
        try:
            _l = link_holder["link"]
            if _l is not None:
                _g = (_l.status() or {}).get("g54")
                if _g and len(_g) >= 3:
                    z = round(float(_g[2]), 4)
        except Exception:
            z = None
        if z is not None:
            return g10_cmd(c, z=z)
        return ("G10 L2 P1 X%.4f Y%.4f Z____    ← 先连机床读 Z 或自己补（空着会把 Z 零点清成 0）"
                % (c[0], c[1]))

    def update_result(r):
        res_holder["r"] = r
        c = r["center"]
        if r.get("shape") == SHAPE_CIRCLE:
            v_result.set("中心  X = %.4f    Y = %.4f        直径 ≈ %.3f（R = %.3f）"
                         % (c[0], c[1], r["diameter"], r["radius"]))
            v_theta.set("0.000")
            v_theta_src.set("圆形无方向：θ 固定 0，不做旋转（%d 个圆点%s）"
                            % (r["npts"], "，最小二乘" if r["npts"] >= 4 else ""))
            v_g10.set(g10_text(c))
            re_ = r.get("round_err", 0.0)
            if r["npts"] < 4:
                v_check.set("圆度：3 点定圆没法自查（碰错一个点看不出来）→ 想验证就再碰 1 个点")
            elif re_ <= 0.05:
                v_check.set("圆度：各点到拟合圆偏差 ≤ %.3f mm（好，碰点确实在同一个圆上）" % re_)
            elif re_ <= 0.2:
                v_check.set("圆度：最大偏差 %.3f mm（可接受；手抖或工件本身略不圆）" % re_)
            else:
                v_check.set("圆度：最大偏差 %.3f mm（偏大！可能有一个点碰错了，或工件不是正圆）" % re_)
            return
        v_result.set("中心  X = %.4f    Y = %.4f        宽 ≈ %.3f   高 ≈ %.3f"
                     % (c[0], c[1], r["width"], r["height"]))
        v_theta.set("%.3f" % r["theta_deg"])
        src = r.get("src", "")
        if src == "mixed":
            v_theta_src.set("θ 来源：%s的 2 点实测（其余边按此角度对齐）"
                            % "、".join(EDGE_CN[e] for e in r.get("theta_src_edges", [])))
        else:
            v_theta_src.set(SRC_CN.get(src, ""))
        if not r.get("theta_measured", src != "edge1"):
            v_theta_src.set("θ 未测：每边仅 1 点 → 只平移，θ 按 0 处理（工件歪了就对不上！）")
        elif r.get("theta_warn"):
            v_theta_src.set("⚠ 角度 %.1f° 超出 ±45°：八成是把点记到别的边了（或边不是矩形）"
                            % r["theta_deg"])
        v_g10.set(g10_text(c))
        sq = r.get("square_err")
        if sq is None:
            v_check.set("")
        elif sq <= 0.15:
            v_check.set("直角自检：四角偏差 ≤ %.2f°（好，碰点可信）" % sq)
        elif sq <= 1.0:
            v_check.set("直角自检：四角偏差 %.2f°（可接受；工件本身有误差或碰点略偏）" % sq)
        else:
            v_check.set("直角自检：四角偏差 %.2f°（偏大！可能碰错边 / 工件不是矩形 / 有倒角）" % sq)
        try:
            cp_note_center(r)      # 中心一出来就补齐还没进定位表的点（定位点本身不改）
        except Exception:
            pass

    def try_solve():
        if not fitter_can_solve():
            return
        apply_offset()
        is_circle = shape_of(v_shape.get()) == SHAPE_CIRCLE

        def _go():
            if is_circle:
                r = fitter.solve_circle()
                update_result(r)
                append_log("解算（圆形）：中心 (%.4f, %.4f)  直径 %.3f（实测 %.3f）  圆度 ±%.3f"
                           "  （基准偏移 %+.4f，%d 点）"
                           % (r["center"][0], r["center"][1], r["diameter"], r["diameter_raw"],
                              r["round_err"], r.get("offset", 0.0), r["npts"]))
                _ofc = float(r.get("offset") or 0.0)
                if abs(_ofc) > 1e-9:
                    append_log("      基准补偿 %+.4f mm —— 只改「宽高 / 直径」，中心不受影响" % _ofc)
                refresh_count()      # 算出结果后刷一次状态卡/提示（否则还停在「没算出来」）
                try:
                    cp_rebase(r["center"][0], r["center"][1], "算出中心")
                except Exception as _ex:
                    append_log("定位点纠偏失败：%s" % _ex)
                return
            r = fitter.solve()
            update_result(r)
            append_log("解算：中心 (%.4f, %.4f)  θ=%.3f°  宽 %.3f  高 %.3f  "
                       "（基准偏移 %+.4f，补偿前 %.3f×%.3f）"
                       % (r["center"][0], r["center"][1], r["theta_deg"],
                          r["width"], r["height"], r.get("offset", 0.0),
                          r.get("raw_width", r["width"]), r.get("raw_height", r["height"])))
            _ofr = float(r.get("offset") or 0.0)
            if abs(_ofr) > 1e-9:
                append_log("      基准补偿 %+.4f mm —— 只改「宽高 / 直径」，中心不受影响" % _ofr)
            refresh_count()          # 同上：先刷新显示，再落盘
            try:
                cp_rebase(r["center"][0], r["center"][1], "算出中心")
            except Exception as _ex:
                append_log("定位点纠偏失败：%s" % _ex)

        do(_go)

    def auto_offset():
        """用「刀路设计尺寸 − 实测原始尺寸」反推基准偏移：off = (W刀路 − W实测)/2"""
        r = res_holder["r"]
        if r is None:
            messagebox.showinfo(APP, "先把四条边都碰完、算出中心，再来算这个")
            return
        src = (v_src.get() or "").strip()
        if not src or not os.path.isfile(src):
            messagebox.showinfo(APP, "先在 ④ 选好源刀路，才能跟它比尺寸")
            return
        with open(src, "r", encoding="utf-8", errors="ignore") as f:
            bb = path_bbox(f.read())
        if not bb:
            messagebox.showinfo(APP, "刀路文件里没读到 X/Y 坐标")
            return
        Wp, Hp = bb[1] - bb[0], bb[3] - bb[2]
        rawW = float(r.get("raw_width", r["width"]))
        rawH = float(r.get("raw_height", r["height"]))
        offW = (Wp - rawW) / 2.0
        offH = (Hp - rawH) / 2.0
        if abs(offW - offH) > 0.3:
            messagebox.showwarning(
                APP,
                "两个方向反推出来的偏移不一致：\n\n"
                "  X 方向 %+.3f mm\n  Y 方向 %+.3f mm\n\n"
                "刀路 %.3f × %.3f，实测（未补偿）%.3f × %.3f\n\n"
                "说明四条边的基准不一样（比如两条碰槽壁、两条碰外缘），\n"
                "这样中心是会偏的 —— 先让四条边都碰同一种基准再算。"
                % (offW, offH, Wp, Hp, rawW, rawH))
            append_log("自动测偏移：两向不一致 X %+.3f / Y %+.3f（基准不统一，中心会偏）"
                       % (offW, offH))
            return
        off = (offW + offH) / 2.0
        v_comp.set(COMP_MODES[5])
        v_off.set("%.4f" % off)
        apply_offset()
        try_solve()
        append_log("自动测偏移：刀路 %.3f×%.3f  实测(未补偿) %.3f×%.3f → 偏移 %+.4f mm（已切自定义档）"
                   % (Wp, Hp, rawW, rawH, off))

    # ---- 定位点 = 靠边点（v1.36）：每边 2 格，格子里就是上次碰到的那个点 ----
    # 一种数据两种用途：算中心/角度用 mx,my；下一件点一下格子 = 抬 Z 5mm 直接走到 (mx,my)。
    # 不推算（不按中心、不按 θ）：误差只等于两次摆件的差异，剩下的靠手 Z- 精调。
    cp = cp_normalize(preset_load())
    cp_used = set()          # 本件摆过哪些格（显示 ▸）

    def cp_max_mz():
        """所有定位点里最高的那个「记点时的 Z」。一个都没有 → None。

        用途：某格没记 Z（老数据/手改过）时拿它当抬刀基准 ——
        保证抬刀高度是个**固定值**，点几次都到同一个高度，不会一次比一次高。
        """
        best = None
        for _slots in (cp.get("pts") or {}).values():
            if not isinstance(_slots, dict):
                continue
            for _k in ("1", "2"):
                q = _slots.get(_k)
                if isinstance(q, dict) and q.get("mz") is not None:
                    v = float(q["mz"])
                    best = v if best is None else max(best, v)
        return best

    def cp_get(edge, slot=1):
        """取某一格的定位点（机床坐标）"""
        return (cp["pts"].get(edge) or {}).get(str(slot))

    def cp_theta():
        """当前 θ（度）+ 是否实测"""
        r = res_holder.get("r")
        if r and r.get("theta_deg") is not None and not r.get("theta_warn"):
            return float(r["theta_deg"]), True
        try:
            return float(v_theta.get() or 0.0), False
        except ValueError:
            return 0.0, False

    def _cp_write():
        try:
            preset_save(cp)
            return True
        except Exception as ex:
            append_log("定位点保存失败：%s" % ex)
            return False

    def cp_note_center(r=None):
        """本件中心算出来 → 只把「本件碰过、但还没进定位表」的点补齐（重开软件从 session 恢复走这条）。
        定位点存的是机床绝对坐标，中心变了也不用改它。"""
        r = r if r is not None else res_holder.get("r")
        if not r or not r.get("center"):
            return
        n = 0
        for _e in EDGES:
            for _i, _xy in enumerate(fitter.pts[_e][:2]):
                if str(_i + 1) not in (cp["pts"].get(_e) or {}):
                    cp["pts"].setdefault(_e, {})[str(_i + 1)] = {
                        "mx": round(_xy[0], 4), "my": round(_xy[1], 4),
                        "mz": None, "cur": 1}
                    n += 1
        if n:
            _cp_write()
            cp_refresh_text()

    def cp_rebase(nx, ny, why=""):
        """基准变了（设零 / 算出中心）→ 把「上一件留下的」定位点整体平移同样的量。

        只平移 cur != 1 的点：本件实测的点就是真位置，动它就错了。
        这是**唯一**会让定位点自己动的地方 —— 点格子走位时永远直接走绝对坐标，不做任何推算。
        """
        rz = cp.get("refz")
        if not isinstance(rz, dict) or rz.get("x") is None:
            cp["refz"] = {"x": round(nx, 4), "y": round(ny, 4),
                          "t": time.strftime("%Y-%m-%d %H:%M")}
            _cp_write()
            return 0
        dx, dy = nx - float(rz["x"]), ny - float(rz["y"])
        if abs(dx) < 0.2 and abs(dy) < 0.2:
            return 0
        n = 0
        for e in list(cp["pts"].keys()):
            for q in cp["pts"][e].values():
                if q.get("cur"):
                    continue                  # 本件实测点：真实位置，绝不动
                q["mx"] = round(q["mx"] + dx, 4)
                q["my"] = round(q["my"] + dy, 4)
                n += 1
        cp["refz"] = {"x": round(nx, 4), "y": round(ny, 4),
                      "t": time.strftime("%Y-%m-%d %H:%M")}
        _cp_write()
        if n:
            append_log("✓ %s：定位点整体跟着挪 ΔX%+.2f ΔY%+.2f（%d 个）—— 下一件点格子就按新位置走"
                       % (why or "基准变化", dx, dy, n))
            try:
                cp_refresh_text()
            except Exception:
                pass
        else:
            append_log("基准 %s 挪了 ΔX%+.2f ΔY%+.2f（本件已碰的点不动，下一件按新基准）"
                       % (why or "变化", dx, dy))
        return n

    def cp_refresh_text():
        """重画面上的 8 个格子（实际渲染在 paint_cards 里，这里只做转发）"""
        try:
            paint_cards()
        except Exception:
            pass

    def cp_add_point(edge, mx, my, mz, th, mzm=None):
        """记一个点：落到这条边的下一个空槽（①→②，已满则覆盖 ②）

        mz  = 记点时的**工作坐标** Z（老字段，老数据只有它）
        mzm = 记点时的**机床坐标** Z（v3.0.2 起）。一键定位用它抬刀：
              工作坐标会随 G54 的 Z 偏移变（重新对刀、在别处设零都会变），
              机床坐标永远不变 —— 拿它抬刀才不会「抬了等于没抬」直接横着穿工件。
        """
        ps = fitter.pts[edge]
        if len(ps) >= 2:
            ps.pop()
            slot = 2
        else:
            slot = len(ps) + 1
        ps.append((float(mx), float(my)))
        q = {"mx": round(float(mx), 4), "my": round(float(my), 4),
             "mz": (round(float(mz), 4) if mz is not None else None),
             "mzm": (round(float(mzm), 4) if mzm is not None else None), "cur": 1}
        cp["pts"].setdefault(edge, {})[str(slot)] = q
        cp["ver"] = CP_VER
        _cp_write()
        return slot

    def cp_drop_point(edge, slot):
        """撤销一个点（与 fitter 同步由调用方负责）"""
        if str(slot) in (cp["pts"].get(edge) or {}):
            cp["pts"][edge].pop(str(slot), None)
            if not cp["pts"][edge]:
                cp["pts"].pop(edge, None)
            _cp_write()

    def cp_clear():
        if not cp["pts"]:
            append_log("还没有定位点（碰过的点会自动记下来）")
            return
        if not messagebox.askokcancel(
                APP, "清空全部定位点？",
                detail="8 个格子一起忘掉（碰点、设零不受影响）。\n"
                       "以后要从头碰一遍才会有定位点。"):
            return
        cp["pts"] = {}
        cp.pop("last", None)
        cp["ver"] = CP_VER
        cp_used.clear()
        fitter.clear()
        _cp_write()
        refresh_count()
        append_log("已清空全部定位点（连碰点一起清了，从头碰）")

    def cp_goto(edge, slot=1):
        """靠边位置（R1.3）：抬到安全 Z → G53 走到该点记住的机床坐标 → 停住，Z 保持抬起。
        不降 Z、不推算、不报偏差 —— 到位后人工点 Z− 贴边、Enter 记点。"""
        mark = "①" if slot == 1 else "②"
        q = cp_get(edge, slot)
        if not q or q.get("mx") is None:
            messagebox.showinfo(
                APP, "%s %s 还没有可用的位置" % (EDGE_CN[edge], mark),
                detail="这一格还没记过点。\n\n"
                       "靠过去碰到边、按 Enter 记点，它以后就能一键定位。")
            return
        if link_holder["link"] is None:
            messagebox.showwarning(APP, "先在 ① 连接串口")
            return
        tx, ty = float(q["mx"]), float(q["my"])

        def _go():
            l = link()
            if wpos3(l) is None:
                raise GrblError("读不到坐标（等状态栏出现 MPos 再试）")
            # ① 先抬到安全 Z（R1.3：固定高度，绝不在低位平移）
            lift_safe(l, "二次定位前")
            # ② G53 机床绝对坐标走 XY（不受 G54 / G92 影响）
            l.send("G53 G0 X%.4f Y%.4f" % (tx, ty))
            wait_idle_gui(l, 12.0)
            # ③ 到此为止：Z 保持抬起，人自己点 Z− 慢慢降下来贴边
            cp_used.add((edge, slot))
            cp_refresh_text()
            try:
                v_nextedge.set("%s%s 已到位 · Z- 降下来贴边" % (EDGE_CN[edge], mark))
                v_hint.set("已到 %s%s —— Z 还抬着，点 Z- 慢慢降，碰到边按 Enter 记点"
                           % (EDGE_CN[edge], mark))
            except Exception:
                pass
            append_log("→ 已到 %s %s（X%.3f Y%.3f）· Z 保持抬起，点 Z− 降下来贴边"
                       % (EDGE_CN[edge], mark, tx, ty))

        do(_go)

    def cp_dbg_cells():
        """自检/排查用：把 8 格的当前文字拼成一行"""
        out = []
        for e in EDGES:
            for i in (1, 2):
                _b = pv_btns.get((e, i))
                out.append(_b.cget("text") if _b is not None else "-")
        return " | ".join(out)

    def cp_startup_hint():
        n = cp.pop("_discarded", 0) or 0
        if n:
            append_log("定位点：旧的 %d 个位置已作废（老数据不是「碰点」坐标，无法沿用）——"
                       "以后碰过的点会自动变成下次的一键定位目标" % n)

    def need_zero(what):
        """v1.20：联机后必须先设零，才能往下走（用户要求）。

        点动**不受限**（不然没法把刀移到初步中心去设零，会死锁）。
        """
        if flow_ok["zero"]:
            return True
        if link_holder["link"] is None:
            append_log_ref[0]("⚠ 先在 ① 连接串口")
            return False
        # v1.28：不弹窗（连着按会一直被弹框打断）—— 只在日志说一句
        append_log_ref[0]("⚠ 还没设零 —— 先点顶部「② 就在此处设零」，再%s" % what)
        return False

    def record(edge):
        if not session_guard():
            return
        if not need_zero("碰边记点"):
            return

        def _go():
            l = link()
            p = l.mpos()
            if p is None:
                raise GrblError("还没读到坐标，稍等一下或检查连接（状态栏应出现 MPos）")
            # R2.9：存机床真实坐标（G53 走回去要用它）；界面仍打印显示坐标，方便对数字
            _mm = getattr(l, "mpos_mach", None)
            pm = _mm() if callable(_mm) else None
            pm = pm or p
            w = wpos3(l)
            apply_offset()
            th, _thok = cp_theta()
            slot = cp_add_point(edge, pm[0], pm[1], (w[2] if w else None), th, pm[2])
            append_log("记录 %s %s：(%.4f, %.4f)  基准偏移 %+.4f → 同时作为定位点"
                       % (EDGE_CN[edge], "①" if slot == 1 else "②", p[0], p[1],
                          fitter.offset if fitter.offset is not None else 0.0))
            _last_edge["e"] = edge
            refresh_count()
            try_solve()

        do(_go)

    def record_circle():
        """记一个圆周上的点（圆形模式）"""
        if not session_guard():
            return
        if not need_zero("碰边记圆点"):
            return

        def _go():
            l = link()
            p = l.mpos()
            if p is None:
                raise GrblError("还没读到坐标，稍等一下或检查连接（状态栏应出现 MPos）")
            apply_offset()
            fitter.add_circle((p[0], p[1]))
            append_log("记录圆点第 %d 个：(%.4f, %.4f)" % (len(fitter.cpts), p[0], p[1]))
            refresh_count()
            try_solve()

        do(_go)

    def undo():
        if shape_of(v_shape.get()) == SHAPE_CIRCLE:
            p = fitter.pop_circle()
            if p:
                append_log("撤销圆点 (%.4f, %.4f)" % (p[0], p[1]))
            refresh_count()
            if fitter_can_solve():
                try_solve()
            else:
                res_holder["r"] = None
                v_result.set("—")
                v_g10.set("")
            return
        n_before = {k: len(fitter.pts[k]) for k in EDGES}
        r = fitter.pop()
        if r:
            cp_drop_point(r[0], n_before.get(r[0], 1))     # pop 掉的是最后一个 → 槽 = 原长度
            append_log("撤销 %s 的 (%.4f, %.4f)（定位点也一起撤）"
                       % (EDGE_CN[r[0]], r[1][0], r[1][1]))
        refresh_count()
        if fitter_can_solve():
            try_solve()
        else:
            res_holder["r"] = None
            v_result.set("—")
            v_g10.set("")

    def dump_genlog():
        """把最近几次生成快照打到日志（事后排查「那一次为什么偏」）"""
        rows = genlog_load()
        if not rows:
            append_log("还没有生成记录（生成一次刀路后就会有）")
            return
        append_log("———— 最近 %d 次生成（共存 %d 条，文件 %s）————"
                   % (min(3, len(rows)), len(rows), genlog_path()))
        for rec in rows[-3:]:
            c = rec.get("center") or [0, 0]
            append_log("  %s  %s  θ=%.3f°  中心 %.4f, %.4f  宽高 %.2f×%.2f  G54=%s G92=%s"
                       % (rec.get("t", "?"), "直出" if rec.get("mode") == "mach" else "G54",
                          float(rec.get("theta") or 0.0), c[0], c[1],
                          float(rec.get("width") or 0.0), float(rec.get("height") or 0.0),
                          rec.get("g54_at_gen"), rec.get("g92_at_gen")))
            append_log("       → %s" % os.path.basename(rec.get("dst") or ""))

    def clear_all():
        flow_ok["gen"] = False
        cp_used.clear()
        # v1.36：换件只清「本件已碰」标记 —— mx/my/mz 一定留着，它们就是下一件的定位目标
        # refz（纠偏基准）也不清：它记的是「点的参照系」，不是本件的状态
        for _e in list(cp["pts"].keys()):
            for _q in cp["pts"][_e].values():
                _q.pop("cur", None)
        _cp_write()
        try:
            cp_refresh_text()
        except Exception:
            pass
        fitter.clear()
        apply_offset()
        refresh_count()
        res_holder["r"] = None
        v_result.set("—")
        v_g10.set("")
        v_check.set("")
        v_theta_src.set("")
        refresh_count()
        # 清空是「换新工件」的起点：立即落盘，否则重开软件又会把旧点复活
        sess["restored"] = False
        sess["guard"] = False
        show_session_note("")
        session_flush()
        append_log("已清空碰点（8 点预设不受影响）")

    def write_g54():
        r = res_holder["r"]
        if not r:
            messagebox.showwarning(APP, "先记录碰点并算出中心")
            return
        c = r["center"]
        if not messagebox.askokcancel(APP, "确认把工件原点（G54）设为：\n\nX = %.4f\nY = %.4f\n\nθ = %.3f°" % (c[0], c[1], r["theta_deg"])):
            return
        do(lambda: (link().set_g54(c[0], c[1]), link().query_offsets()))
        flow_ok["zero"] = True          # 按数值写零也是设过零（否则会被「未设零」门禁拦下）
        remember_center(c[0], c[1], "写 G54")
        append_log("提示：写完后用 $# 核对 G54；若有回零开关，复位后依然有效。")

    def _zero_core(l):
        """置零 + 按这次零点位置纠偏定位点（可被「XY 置零」和「走到中心并设零点」共用）。"""
        p0 = None
        try:
            p0 = l.mpos()
        except Exception:
            p0 = None
        _zero_core_body(l)
        if p0 is not None:
            try:
                cp_rebase(p0[0], p0[1], "设零")
            except Exception as ex:
                append_log("定位点纠偏失败（不影响设零）：%s" % ex)

    def _zero_core_body(l):
        """置零核心（可被「XY 置零」和「走到中心并设零点」共用）：
        G10 L20 P1 X0 Y0 写 G54（存 EEPROM）→ G92.1 清 Candle 设零的残留 → 校验工作坐标是否真到 0。"""
        l.send("G10 L20 P1 X0 Y0")
        time.sleep(0.15)
        l.send("G92.1")                       # 不清的话，G92 会叠在 G54 上，坐标永远差那一点
        # v1.28：$# 偶尔回得慢或丢一帧 —— 以前读不到就判「没定住」，于是反复提醒「还没设零」。
        # 现在最多等 1.8 秒、中途补发一次 $#；确实读不到就按「已发出」放行（别再卡流程）。
        st = {}
        for _try in range(2):
            l.query_offsets()
            t0 = time.time()
            while time.time() - t0 < 0.9:
                st = l.status() or {}
                if st.get("g54") is not None and st.get("mpos"):
                    break
                time.sleep(0.05)
            if st.get("g54") is not None and st.get("mpos"):
                break
        if not st.get("mpos") or st.get("g54") is None:
            flow_ok["zero"] = True
            append_log("✓ 设零命令已发出（读不到 $# 偏移，没法复核）—— 状态栏大数字变 0.000 就是成功")
            try:
                update_stepbar()
            except Exception:
                pass
            return
        dev = (st["mpos"][0] - st["g54"][0], st["mpos"][1] - st["g54"][1])
        if max(abs(dev[0]), abs(dev[1])) <= 0.05:
            flow_ok["zero"] = True
            append_log("✓ 零点已生效：刀尖工作坐标 = (%.4f, %.4f)" % (dev[0], dev[1]))
            append_log("  G54 已存 EEPROM（关机 / 复位 / 回零都不丢）→ Candle 连上就是 0,0")
            append_log("  状态栏那个大数字现在应该是 0.000")
            try:
                update_stepbar()
            except Exception:
                pass
            return
        append_log("✗ 零点没定住：刀尖工作坐标 = (%.4f, %.4f) —— G10 L20 似乎没生效"
                   % (dev[0], dev[1]))
        append_log("   → 自动退回 G92 X0 Y0 兜底（只本次有效，断电 / 复位要重设）")
        l.send("G92 X0 Y0")
        time.sleep(0.35)
        _st2 = l.status() or {}
        d2 = None
        if _st2.get("mpos") and _st2.get("g54") is not None:
            d2 = (_st2["mpos"][0] - _st2["g54"][0], _st2["mpos"][1] - _st2["g54"][1])
        if d2 and max(abs(d2[0]), abs(d2[1])) <= 0.05:
            flow_ok["zero"] = True
            append_log("✓ 已用 G92 兜底：工作坐标 = 0,0（⚠ 断电 / 复位后需重设）")
            try:
                update_stepbar()
            except Exception:
                pass
        else:
            append_log("✗ 还是没定住 —— 请在 Candle 里手动设零，或先发 G92.1 / 软复位再试")

    def set_xy_zero(quiet=False):
        """把刀尖当前所在的 XY 设为工件零点。

        等价于 Candle 的「设零」，但三点更好：
        1. 用 L20 而不是 L2 —— L20 只改**指定**的轴，Z 偏移原样保留（L2 会把未指定轴清 0）
        2. G54 存 EEPROM —— 关机、软复位、回零之后依然有效（Candle 的设零走 G92，复位即丢）
        3. 写完自动校验工作坐标，没生效会自己退回 G92 兜底，不再默默出错
        """
        def _go():
            l = link()
            p = l.mpos()
            if p is None:
                raise GrblError("还没读到坐标，稍等一下或检查连接（状态栏应出现 MPos）")
            # v1.28：不再弹确认框（车间里每点一次都弹窗＝没法用）。
            # 设零不动刀，只把这个位置登记成 0,0 —— 点错再点一次就好，没有任何破坏性。
            append_log("设零：把当前位置 X %.3f  Y %.3f 登记为工件 0,0" % (p[0], p[1]))
            _zero_core(l)

        do(_go)

    def set_disp_zero():
        """R2.5：把刀现在的位置设成显示 0,0,0（不动刀、不写 G54）。

        用户的实际流程：开机 → 手动摇到大致中心 → 连机 → 设 0 点 → 靠边算中心。
        跟「② 就在此处设零」（写 G54＝工件零点，给加工用）是两件事：
        这个只挪显示基准，让碰点坐标以中心为原点、都是小数字，看着直观；
        板子复位 / 串口断开后也能靠这个基准把坐标接回去。
        """
        l = link()
        raw = getattr(l, "_raw_mpos", None)
        if raw is None:
            raise GrblError("还没读到坐标，稍等一下或检查连接（状态栏应出现 MPos）")
        n_pts = sum(len(fitter.pts[e]) for e in EDGES) + len(getattr(fitter, "cpts", []) or [])
        if n_pts and not messagebox.askokcancel(
                APP, "已经碰了 %d 个点。\n\n重新设 0 点会让这些点对不上（它们按旧基准记的），"
                     "要一起清掉重新碰吗？" % n_pts):
            return

        def _go():
            l.pos_offset = [-float(raw[0]), -float(raw[1]), -float(raw[2])]
            if l._mpos is not None:
                l._mpos = (0.0, 0.0, 0.0)
            append_log("✓ 已把当前位置设为 0,0,0（显示基准；机床原始坐标 %.3f, %.3f）"
                       % (raw[0], raw[1]))
            append_log("   接下来直接靠边：负方向点动不会再被当成「超行程」。")
        do(_go)
        if n_pts:
            try:
                fitter.clear()
                paint_cards()
                paint_edge_btns()
                refresh_count()
            except Exception:
                pass

    def check_coords():
        """坐标核对：G54 偏移、MPos、工作坐标三者关系（直出前必看）"""
        def _go():
            l = link()
            l.query_offsets()
            t0 = time.time()
            while time.time() - t0 < 0.6:
                if l.status().get("g54") is not None:
                    break
                time.sleep(0.03)
            st = l.status()
            g, mp = st.get("g54"), st.get("mpos")
            append_log("---- 坐标核对 ----")
            append_log("状态：%s" % st.get("state"))
            append_log("机床坐标 MPos：%s" % ("（还没读到）" if not mp else
                                              "X %.4f  Y %.4f  Z %.4f" % mp))
            if g:
                append_log("G54 偏移：X %.4f  Y %.4f  Z %.4f" % g)
                if mp:
                    append_log("工作坐标 = MPos − G54：X %.4f  Y %.4f" % (mp[0] - g[0], mp[1] - g[1]))
                if abs(g[0]) > 1e-4 or abs(g[1]) > 1e-4:
                    append_log("！G54 的 XY 不是 0：手发绝对坐标会整体偏 X %.3f / Y %.3f"
                               % (g[0], g[1]))
                    append_log("   → 点「清零坐标系」；或直接用本程序生成的刀路（文件头已自动清零）")
                else:
                    append_log("✓ G54 的 XY = 0：工作坐标 = 机床坐标，直出刀路可用")
            append_log("------------------")

        do(_go)

    def goto_center():
        if not need_zero("走中心"):
            return
        r = res_holder["r"]
        if not r:
            messagebox.showwarning(APP, "先算出中心")
            return
        p = link().mpos()
        zz = p[2] if p else 0.0
        _tz_safe = None
        try:
            _tz_safe = safe_target_mz()
        except Exception:
            pass
        travel = math.hypot(r["center"][0] - p[0], r["center"][1] - p[1]) if p else None
        far = ""
        if travel is not None:
            far = "\n\n这次要走 %.0f mm。" % travel
            if travel > 400:
                far += "\n⚠ 距离过大 —— 先回 ③ 核对中心，八成是碰点记错。"
        if not messagebox.askokcancel(
                APP, "刀会走到计算出的中心：\n\nX = %.4f\nY = %.4f\n\n"
                     "动作：先抬到安全 Z（机床 %s）→ 走 XY → 再落回当前 Z %.3f%s"
                     % (r["center"][0], r["center"][1],
                        ("%.3f" % _tz_safe) if _tz_safe is not None else "未标定",
                        zz, far),
                detail=("横移前一定会先抬 Z —— 不会再横着穿工件。\n"
                        "抬到安全高度后走 XY，到位再落回现在这个高度（设零只看 XY，Z 高低不影响）。")):
            return

        def _go():
            l = link()
            cx, cy = r["center"]
            keep_z = None
            try:
                _mm = getattr(l, "mpos_mach", None)
                _mp = (_mm() if callable(_mm) else None) or (l.status() or {}).get("mpos")
                keep_z = float(_mp[2]) if _mp else None
            except Exception:
                keep_z = None
            lift_safe(l, "走中心前")            # ① 先抬（绝不在低位横移）
            l.goto(cx, cy)
            time.sleep(0.9)
            if keep_z is not None:
                l.send("G90 G53 G0 Z%.4f" % keep_z, log_it=False)   # ② 落回原高度
                wait_idle_gui(l, 8.0)
            _mm = getattr(l, "mpos_mach", None)
            p1 = (_mm() if callable(_mm) else None) or l.mpos()
            if p1 is None:
                append_log("已发送：走到中心（Z 不动），但读不到坐标，无法校验")
                return
            d = math.hypot(p1[0] - cx, p1[1] - cy)
            append_log("走到中心：目标 (%.4f, %.4f) → 实际 (%.4f, %.4f)，差 %.3f mm"
                       % (cx, cy, p1[0], p1[1], d))
            if d <= 0.2:
                append_log("   ✓ 到位 → 看一眼刀尖是不是真在中心，然后点「② 就在此处设零」")
                # 用「实际到达点」记，比计算值更贴近真实（偏差 >2mm 才更新，避免反复刷盘）
                if (last_c["x"] is None
                        or math.hypot(last_c["x"] - p1[0], last_c["y"] - p1[1]) > 2.0):
                    remember_center(p1[0], p1[1], "走中心到位")
            else:
                append_log("   ⚠ 偏得多（> 0.2mm）—— 先别设零：点「核对坐标」看 G54 / G92，"
                           "位置确实不对就软复位重新碰边")
        do(_go)

    def copy_g10():
        g = v_g10.get()
        if not g:
            return
        root.clipboard_clear()
        root.clipboard_append(g)
        append_log("已复制：" + g)


    def zero_wcs():
        if not messagebox.askokcancel(
                APP,
                "把工作坐标系清零？\n\n发：G10 L2 P1 X0 Y0 + G54\n\n"
                "清零后「绝对坐标 = 机床坐标 MPos」，\n这是无回零开关的机器跑直出刀路前必须做的一步。\n"
                "（刀不会移动，只是重新解释当前位置）"):
            return
        do(lambda: (link().set_g54(0.0, 0.0), link().query_offsets()))
        append_log("已清零：现在发的绝对坐标就是机床坐标")

    def do_transform():
        def _go():
            src = (v_src.get() or "").strip()
            if not src or not os.path.isfile(src):
                raise GrblError("请选择原始刀路文件")
            # v3.0.2：文本先读进来。原来的「最深切到」分支在 z_levels(text) 里用它，
            # 而 text = f.read() 却写在后面几十行 → 选这个模式点生成必崩（UnboundLocalError）。
            with open(src, "r", encoding="utf-8", errors="ignore") as f:
                text = f.read()
            r = res_holder["r"]
            if r is None:
                raise GrblError("先算出中心与 θ")
            try:
                theta_deg = float(v_theta.get() or 0.0)
            except ValueError:
                raise GrblError("θ 要填数字（单位：度）")
            if not v_rot.get():
                theta_deg = 0.0
            elif r.get("src") == "edge1" and not r.get("theta_measured"):
                if not messagebox.askokcancel(
                        APP,
                        "角度还没测出来（四条边都只碰了 1 个点）\n\n"
                        "现在会按 θ=0 只做平移。工件只要歪一点，刀路就会偏。\n\n"
                        "想纠角度：挑最好碰的一条边再点一次（共 5 点，两点拉开 80mm 以上）。\n\n"
                        "确定按 θ=0 继续？"):
                    return
            if abs(theta_deg) > 15:
                if not messagebox.askokcancel(
                        APP, "θ = %.2f°，偏得比较多。\n正常只歪零点几到几度，\n"
                             "先确认碰点没记到别的特征上。\n\n仍然继续？" % theta_deg):
                    return

            mach = bool(v_mach.get())
            T = r["center"] if mach else (0.0, 0.0)
            oz = float(v_ox.get() or 0.0)
            oy = float(v_oy.get() or 0.0)

            z_shift, z_override = 0.0, None
            if v_zmode.get() == "shift":
                try:
                    z_shift = float(v_zval.get() or 0.0)
                except ValueError:
                    raise GrblError("Z 偏移要填数字（mm）")
            elif v_zmode.get() == "override":
                try:
                    z_override = float(v_zval.get() or 0.0)
                except ValueError:
                    raise GrblError("目标深度要填数字（mm）")
                if z_override >= 0:
                    raise GrblError("目标深度填负数（如 -0.2），0 或正数没有切削意义")
                _lv = z_levels(text)
                if not _lv:
                    raise GrblError("这个刀路里没有负 Z，用不上「最深切到」")
                if z_override < _lv[0] - 1e-6:
                    raise GrblError("目标深度 %.3f 比原刀路最深 %.3f 还深（会过切）。\n"
                                    "想切得更深请用「整体偏移」填负值。" % (z_override, _lv[0]))

            base, ext = os.path.splitext(src)
            dst = (v_dst.get() or "").strip() or (base + ("_run" if mach else "_rot") + (ext or ".nc"))

            _bbf = path_bbox(text)
            if not _bbf:
                raise GrblError("这个文件里没找到 X/Y 坐标，可能不是刀路文件")

            warns = []

            # 直出模式：把"G54 的 XY 必须为 0"这条硬要求直接写进文件头，
            # 这样不管 GRBL 里原来存着什么偏移（Candle「当前位置归零」会写 G54），
            # 跑这个文件时都会先归零 → 直出坐标永远等于机床坐标。
            # ---- 读一下当前的 G54 / G92：文件头必须把基准「钉死」 ----
            # 为什么：G92 的偏移是**叠在 G54 之上**的。Candle 里点过「归零」、或之前用过
            # 别的程序，G92 只要有残留，跑这个文件就整件偏一个 G92 量。
            # 平时 G92=0 所以一直没事，某次误点一次就偏 —— 这就是「多次正常、偶发偏」的来源。
            _st = {}
            try:
                _st = link_holder["link"].status() if link_holder["link"] else {}
            except Exception:
                _st = {}
            _g54v = (_st or {}).get("g54")
            _g92v = (_st or {}).get("g92")
            gz = None if not _g54v else _g54v[2]
            g92xy = bool(_g92v) and (abs(_g92v[0]) > 0.005 or abs(_g92v[1]) > 0.005)
            g92z = bool(_g92v) and abs(_g92v[2]) > 0.005
            clear_g92 = g92xy and not g92z     # Z 有残留就不清，否则丢掉 Z 零点会扎刀

            _stamp = time.strftime("%Y-%m-%d %H:%M:%S")
            prelude = ["(生成 %s · %s · 由 GRBL 分中助手 %s)"
                       % (_stamp, "机床坐标直出" if mach else "G54=中心", vlabel),
                       "(中心 %.4f, %.4f  θ=%.3f°  实测宽高 %.2f×%.2f)"
                       % (r["center"][0], r["center"][1], theta_deg, r["width"], r["height"]),
                       "G21 G90"]
            if clear_g92:
                prelude.append("G92.1            ; 清掉 G92 残留（它整体叠在 G54 上 → 整件跑偏）")
            elif g92xy and g92z:
                prelude.append("(注意：检测到 G92 残留 X%.3f Y%.3f Z%.3f，Z 也在里面，本次不清)"
                               % (_g92v[0], _g92v[1], _g92v[2]))
            # G10 L2 显式重申 G54：直出模式把 XY 归零（工作坐标=机床坐标）；
            # G54 模式把 XY 写回算出来的中心（这样 Candle 里误点归零也盖不掉）
            _tx, _ty = (0.0, 0.0) if mach else (r["center"][0], r["center"][1])
            prelude.append(("G10 L2 P1 X%.4f Y%.4f Z%.4f" % (_tx, _ty, gz)) if gz is not None
                           else ("G10 L2 P1 X%.4f Y%.4f" % (_tx, _ty)))
            prelude.append("G54")
            # R1.4：文件头自带抬刀 —— 第一句运动之前先把 Z 抬起来
            # 起因：刀路第一句是横移到中心（G0 X.. Y..），文件自己不带抬刀；
            #      在 Candle 里直接跑、或刀被手动降到工件上时就会横着/往下撞。
            try:
                _lift_line = None
                if mach:                       # 机床坐标直出：用 G53 绝对，最稳
                    _tz = safe_target_mz()
                    if _tz is None:
                        _mp = (_st or {}).get("mpos")
                        _tz = (float(_mp[2]) + SAFE_WZ) if _mp else None
                    if _tz is not None:
                        _lift_line = "G53 G0 Z%.4f  (开工前抬到安全高度·机床绝对)" % float(_tz)
                else:                          # G54 模式：工作坐标，Z0=顶面
                    _lift_line = "G90 G0 Z%.4f  (开工前抬到工件顶面以上)" % SAFE_WZ
                if _lift_line:
                    prelude.append(_lift_line)
                else:
                    warns.append("没读到当前坐标，文件头没加抬刀行 —— 开始前请手动把刀抬到工件上方")
            except Exception:
                pass
            if gz is None:
                warns.append("没读到 G54 的 Z 偏移（可能没连机床）：文件头只重申了 XY，"
                             "若 Z 对零存在 G54 里请自己确认 Z 零点")
            if clear_g92:
                warns.append("检测到 G92 残留（X=%+.3f Y=%+.3f）—— 这就是「平时好的、偶尔整件偏」"
                             "最典型的原因。文件头已加 G92.1 清掉，本次会是干净的基准。"
                             % (_g92v[0], _g92v[1]))
            elif g92xy and g92z:
                warns.append("检测到 G92 残留 X=%+.3f Y=%+.3f Z=%+.3f —— XY 会让整件偏，"
                             "但 Z 零点也在 G92 里，清掉会扎刀。请先在 Candle 里把 Z 重新对零、"
                             "再发一次 G92.1，然后重新生成本文件。" % (_g92v[0], _g92v[1], _g92v[2]))

            # 自检：实测宽高（已按基准补偿修正）应当≈刀路尺寸
            _bw, _bh = _bbf[1] - _bbf[0], _bbf[3] - _bbf[2]
            _dw, _dh = r["width"] - _bw, r["height"] - _bh
            if max(abs(_dw), abs(_dh)) > 0.3:
                # 差得正好是刀径的整数倍 → 说明「基准补偿」档位选错了，直接告诉他改哪档
                _D = _radius_mm()
                _need = -(_dw + _dh) / 4.0        # 平均每边还需要内缩(<0) / 外扩(>0) 多少
                _hint = ""
                if _D > 0.01:
                    if abs(abs(_need) - _D / 2.0) < 0.3:
                        _hint = "这正好是刀半径的量 → 「基准补偿」选「%s」。" % (
                            "内缩一个半径" if _need < 0 else "外扩一个半径")
                    elif abs(abs(_need) - _D) < 0.3:
                        _hint = "这正好是刀直径的量 → 「基准补偿」选「%s」。" % (
                            "内缩一个刀径" if _need < 0 else "外扩一个刀径")
                warns.append("实测宽高 %.2f×%.2f 与刀路设计 %.2f×%.2f 差 %+.2f/%+.2f mm。%s"
                             "若差得没有规律，则可能是碰的边不是「上次雕出来的轮廓」。"
                             % (r["width"], r["height"], _bw, _bh, _dw, _dh,
                                (_hint + "\n") if _hint else ""))

            def build(zh, zo):
                return transform_gcode(
                    text, math.radians(theta_deg), oz, oy, rotate=bool(v_rot.get()),
                    translate=T, z_shift=zh, z_override=zo,
                    drop_tool_change=bool(v_droptc.get()), warn=warns.append,
                    prelude=prelude)

            new = build(z_shift, z_override)
            # R2：文件头补「安全高度走到起点 → G0 下到起刀 Z」，加工前软件不再插动作
            new = insert_start_block(new, v_start_z.get(), warns.append,
                                     spindle=spindle_directive(text))
            with open(dst, "w", encoding="utf-8", newline="") as f:
                f.write(new)

            bb0, bb1 = path_bbox(text), path_bbox(new)
            append_log("—— 生成 %s ——" % dst)
            append_log("θ=%.3f°  %s  Z:%s%s" % (
                theta_deg,
                "机床坐标直出" if mach else "G54 模式（需写 G54=中心）",
                "原样" if v_zmode.get() == "none" else
                ("偏移 %+.3f mm" % z_shift if v_zmode.get() == "shift" else "切削深度改为 %.3f" % z_override),
                "，已移除换刀行" if v_droptc.get() else ""))
            append_log("原刀路 X %.3f~%.3f  Y %.3f~%.3f" % (bb0[0], bb0[1], bb0[2], bb0[3]))
            _lv = z_levels(text)
            if _lv:
                append_log("原刀路切削层 %d 层：%s" % (len(_lv), "、".join("%.3f" % z for z in _lv)))
            append_log("新刀路 X %.3f~%.3f  Y %.3f~%.3f  中心 (%.3f, %.3f)" % (
                bb1[0], bb1[1], bb1[2], bb1[3], (bb1[0] + bb1[1]) / 2, (bb1[2] + bb1[3]) / 2))
            for w in warns[:10]:
                append_log("  ! " + w)

            # v1.18：不再生成空跑校验副本（用户习惯手动把 Z 抬高走一遍看位置，多一份文件反而多一步）
            dry_dst = None

            if mach:
                steps = ("1. 点「清成机床坐标」——确保绝对坐标 = 机床坐标\n"
                         "2. 在下面「⑤ 发送加工」里直接发 %s\n"
                         "   第一次跑建议先把 Z 对刀零位抬 5mm 试，确认刀尖压槽后再按真实深度跑\n\n"
                         "本次开机内做完，中途别软复位/断电，否则要重新分中。" % os.path.basename(dst))
            else:
                _z = ("已在零点" if _zero_ok() else
                      "⚠ 还没设零 —— 会偏，先点「▶ ① 走到中心」再点「② 就在此处设零」")
                steps = ("1. 零点：%s\n"
                         "   （本程序写的是 G54，存 EEPROM；别再手工在别的软件里点「归零」，\n"
                         "     否则 G92 会叠上去，又偏一次）\n"
                         "2. 在下面「⑤ 发送加工」里直接发 %s\n"
                         "3. 加工完会自动停主轴、抬刀、回工件中心" % (_z, os.path.basename(dst)))
            last_gen["p"] = dst
            try:
                v_send.set(dst)
                send_preview(dst)
            except Exception:
                pass
            flow_ok["gen"] = True
            # ---- 生成快照：下次再「偶发偏移」，可以直接对账这一次软件算的东西 ----
            try:
                genlog_add({
                    "t": _stamp, "ver": VER,
                    "mode": "mach" if mach else "g54",
                    "src": os.path.abspath(src), "dst": os.path.abspath(dst),
                    "dry": os.path.abspath(dry_dst) if dry_dst else "",
                    "center": [r["center"][0], r["center"][1]],
                    "theta": theta_deg, "width": r["width"], "height": r["height"],
                    "g54_at_gen": list(_g54v) if _g54v else None,
                    "g92_at_gen": list(_g92v) if _g92v else None,
                    "mpos_at_gen": list(_st.get("mpos")) if _st.get("mpos") else None,
                    "clear_g92": clear_g92,
                    "comp": v_comp.get(), "shape": v_shape.get(),
                    "pts": {k: [list(p) for p in v] for k, v in fitter.pts.items()},
                    "cpts": [list(p) for p in fitter.cpts],
                    "bbox_out": [bb1[0], bb1[1], bb1[2], bb1[3]] if bb1 else None,
                    "warns": list(warns),
                })
            except Exception:
                pass
            messagebox.showinfo(
                APP,
                "已生成：\n%s%s\n\n刀路范围  X %.2f ~ %.2f（%.2f）\n"
                "          Y %.2f ~ %.2f（%.2f）\n"
                "（无硬限位，先核对这个范围在机器行程内！）\n\n操作顺序：\n%s"
                % (dst, "\n" + dry_dst if dry_dst else "",
                   bb1[0], bb1[1], bb1[1] - bb1[0], bb1[2], bb1[3], bb1[3] - bb1[2], steps))

        do(_go)

    # ---- 状态轮询 ----
    alarm_seen = [False]

    _step_cache = [""]

    def _zero_ok(tol=0.02):
        """刀尖是否已经在工件零点上（决定步骤条该提示「设零」还是「选刀路」）"""
        l = link_holder["link"]
        if l is None:
            return False
        try:
            d = wpos_dev(l)
        except Exception:
            return False
        return bool(d) and max(abs(d[0]), abs(d[1])) <= tol

    def flow_state():
        """8 格各自完成没有。第一个 False 就是「当前该做的这步」。"""
        l = link_holder["link"]
        # ⓿ 开机：上电 / 装夹 / Z 对刀 都在软件外，软件判不了 —— 用「已连上」当它做完
        #（连上了说明人已经把机器准备好；没连上时第一步就该是「开机准备 + 连接」）
        st = {"boot": l is not None,
              "conn": l is not None,
              "zero": bool(flow_ok["zero"])}
        if shape_of(v_shape.get()) == SHAPE_CIRCLE:
            st["edge"] = len(fitter.cpts) >= 3
        else:
            st["edge"] = all(fitter.pts[e] for e in EDGES)
        # ④ 走中心：刀（MPos）已经站在算出来的中心上（±0.05）
        # ⑤ 设零（中心）：G54 等于算出来的中心（±0.02）—— 「在别处设零」不会误判
        st["center"] = False
        st["zero2"] = False
        r = res_holder["r"]
        if st["edge"] and r is not None and l is not None:
            try:
                _s = l.status()
                mp, g = _s.get("mpos"), _s.get("g54")
            except Exception:
                mp, g = None, None
            c = r["center"]
            if mp:
                st["center"] = (abs(mp[0] - c[0]) <= 0.05 and abs(mp[1] - c[1]) <= 0.05)
            if g:
                st["zero2"] = (abs(g[0] - c[0]) <= 0.02 and abs(g[1] - c[1]) <= 0.02)
        st["src"] = bool((v_src.get() or "").strip())
        st["gen"] = bool(flow_ok["gen"]) and st["src"] and st["zero2"]
        return st

    def paint_flow(st):
        cur = None
        for k, _t in FLOW_STEPS:
            if not st.get(k):
                cur = k
                break
        for k, t in FLOW_STEPS:
            lb = flow_lbl[k][0]
            if cur is None or st.get(k):
                _cfg_once(lb, text="✔ " + t, fg="#15803d", font=F_FLOW)
            elif k == cur:
                _cfg_once(lb, text="▶ " + t, fg="#1d4ed8", font=F_FLOW_CUR)
            else:
                _cfg_once(lb, text="○ " + t, fg="#94a3b8", font=F_FLOW)
        return cur

    def update_stepbar():
        st = flow_state()
        cur = paint_flow(st)
        P = "▶  "
        if cur is None:
            t = P + "全流程已就绪 → Candle 里把 Z 抬高走一遍，压准旧槽再把 Z 降下来真切"
        elif cur == "boot":
            t = P + ("⓿ 开机准备：上电 → 装夹工件 → Z 对刀到工件表面 → 装刀；"
                     "好了去 ① 点「连接」（「机器」：不能回零 → 左；能回零 → 右）")
        elif cur == "conn":
            t = P + "① 在 ① 点「连接」（「机器」：不能回零 → 左；能回零 → 右）"
        elif cur == "zero":
            # 提示压成一行：多一行文字就会把底下的「日志」挤出窗口（要靠滚动才看得到）
            t = P + ("② 刀尖移到工件大致中心（毛坯上画个十字就行）→ 点「② 就在此处设零」"
                     "（不设零不让碰边 / 走中心）")
        elif cur == "edge":
            if shape_of(v_shape.get()) == SHAPE_CIRCLE:
                t = P + ("③ 圆形还差 %d 个圆点 —— 点动碰到圆后按 Enter（位置分散开）"
                         % max(0, 3 - len(fitter.cpts)))
            else:
                miss = [e for e in EDGES if not fitter.pts[e]]
                if miss:
                    t = P + ("③ 还差 %s —— 点动碰到边按 Enter（想少点动就先用「摆 X 壁」）"
                             % "、".join(EDGE_CN[e] for e in miss))
                else:
                    t = P + "③ 四边都碰过了（只够算中心）→ 想定角度就挑一条边再碰一次"
        elif cur == "center":
            t = P + ("④ 核对 ③ 的中心 / 角度（看直角自检）→ 点「▶ ① 走到中心」，"
                     "看日志里的偏差（应 < 0.2mm）")
        elif cur == "zero2":
            t = P + ("⑤ 确认刀尖真对准中心了 → 点「② 就在此处设零」"
                     "（没到位就设零，整件都会偏；偏差 >0.2mm 才去「高级」点「核对坐标」）")
        elif cur == "src":
            t = P + "⑥ 在 ④ 区「源刀路」选文件（上次跑过的那个）"
        else:
            t = P + "⑦ 点 ④ 的「生成刀路」→ Candle 里 Z 抬高空走一遍对槽，再降 Z 真切"
        if t != _step_cache[0]:
            _step_cache[0] = t
            v_stepbar.set(t)

    _sync = {"n": 0, "last": 0.0}

    def tick():
        l = link_holder["link"]
        if l is not None:
            s = l.status()
            # 偏移自愈：连上/重连后 $# 偶尔丢帧 → 界面会一直卡在「同步中」
            if s.get("g54") or s.get("wco"):
                _sync["n"] = 0
            else:
                _now = time.time()
                if _sync["n"] < 5 and _now - _sync["last"] > 2.5:
                    _sync["n"] += 1
                    _sync["last"] = _now
                    _safe_do(lambda: l.query_offsets())
                    if _sync["n"] == 1:
                        append_log("坐标偏移还没读到 —— 已自动补发 $#（重连后偶发丢帧，补一次就好）")
            _st = str(s["state"])
            _alarm = _st.lower().startswith("alarm")
            _jog = "jog" in _st.lower()
            _setv(v_state, "状态 " + _st + ("   ← 先点「解锁 $X」" if _alarm else
                                        ("   （点动中，点「■ 停止」或空格可停）" if _jog else "")))
            try:
                _cfg_once(lbl_state, fg="#dc2626" if _alarm else ("#c60" if _jog else "#1a6"))
            except Exception:
                pass
            try:
                # 发送加工时流程状态不会变，别再每 180ms 重排 7 个 Label
                _ss0 = send_holder["s"]
                if _ss0 is None or not _ss0.running():
                    update_stepbar()
            except Exception:
                pass
            if _alarm and not alarm_seen[0]:
                alarm_seen[0] = True
                append_log("！机床处于 %s —— 点动/刀路都不会执行，先点「解锁 $X」（位置不变，不影响机床坐标）" % _st)
            elif not _alarm:
                alarm_seen[0] = False
            # ---- R2.5：断线/复位后「坐标续接」确认（只问一次，刀没动就能直接接着靠边）----
            try:
                _rn = l.take_resume_notice() if l is not None else None
            except Exception:
                _rn = None
            if _rn:
                try:
                    _bx, _by, _bz = (_rn.get("before") or (0.0, 0.0, 0.0))[:3]
                except Exception:
                    _bx = _by = _bz = 0.0
                if _rn.get("status") == "resumed":
                    _ok = messagebox.askyesno(
                        APP,
                        "机床重启过（串口断过 / 复位过），板子把坐标清零了。\n\n"
                        "断开前刀停在：  X = %.3f    Y = %.3f    Z = %.3f\n"
                        "已按这个位置把坐标接回来，状态栏大数字就是那个位置。\n\n"
                        "刀头现在还是停在原处吗？\n"
                        "  【是】→ 刚才碰过的边继续用，接着靠边/算中心\n"
                        "  【否】→ 刀被动过了，清掉坐标和碰点重新来\n\n"
                        "（注意：刚才是点动中断的，刀可能惯性滑了几丝，宁可重碰那一面）"
                        % (_bx, _by, _bz))
                    if _ok:
                        append_log("✓ 坐标已续上（按断开前的位置）。继续靠边即可 —— 若偏差大就重碰这一面。")
                        try:
                            paint_cards()
                            cp_refresh_text()
                        except Exception:
                            pass
                    else:
                        try:
                            l.clear_pos_offset()
                        except Exception:
                            pass
                        try:
                            coord_ok[0] = False
                            safe_z["mz"] = None
                            _setv(v_safe_z, "")
                            fitter.clear()
                            paint_cards()
                            paint_edge_btns()
                            refresh_count()
                            safe_tip()
                        except Exception:
                            pass
                        append_log("已清掉旧坐标和碰点 —— 请重新对零后再碰边。")
                else:
                    append_log("⚠ 机床已重新归零：坐标是新的基准 —— 之前的碰点作废，请重新碰。")
                    try:
                        coord_ok[0] = False
                        fitter.clear()
                        paint_cards()
                        paint_edge_btns()
                        refresh_count()
                    except Exception:
                        pass
            # ---- R2.6：读取线程还活着吗（线程死了 = 状态不刷新、点动像假死）----
            try:
                if l is not None and getattr(l, "ser", None) is not None and l.ser.is_open:
                    _hb = float(getattr(l, "_reader_hb", 0.0) or 0.0)
                    if _hb and (time.time() - _hb) > 3.0:
                        append_log("！串口读取线程 3 秒没动静（点动会没反应）—— 正在自动重启")
                        try:
                            l.restart_reader()
                        except Exception as _e:
                            append_log("！重启读取线程失败：%s —— 请断开后重连接一次" % _e)
            except Exception:
                pass
            # ---- R2.5：固件「软限位」诊断（机床没有限位开关，$20=1 会让负坐标点动被拒）----
            try:
                if l is not None and not getattr(l, "soft_limit_notified", False):
                    _cfg = getattr(l, "grbl_cfg", {}) or {}
                    if 20 in _cfg:
                        l.soft_limit_notified = True
                        if _cfg.get(20, 0) >= 1:
                            if messagebox.askyesno(
                                    APP,
                                    "板子里的「软限位」是开着的（$20=1）。\n\n"
                                    "你的机床没有限位开关（硬限位就是急停），软限位开着会这样：\n"
                                    "开机坐标是 0，一往负方向点动就被判「超行程」，"
                                    "得缩回来再点几次才挪得动。\n\n"
                                    "要关掉吗？（发 $20=0 写进板子，以后开机也保持关闭）\n"
                                    "关掉不影响急停。"):
                                _safe_do(lambda: l.send("$20=0"))
                                append_log("✓ 已关闭固件软限位（$20=0）—— 负方向点动不会再被挡。")
                                try:
                                    l.grbl_cfg[20] = 0.0
                                except Exception:
                                    pass
            except Exception:
                pass
            # 点动看门狗：实际位移远超意图就立刻急停
            # （串口丢一个字节能把 $J=G91 X1.000 变成 X1000，一条命令送出一米）
            if l is not None:
                try:
                    _wd = l.jog_watchdog()
                except Exception:
                    _wd = None
                if _wd:
                    try:
                        l.jog_expect_reset()
                    except Exception:
                        pass
                    _safe_do(lambda: l.jog_cancel())
                    stop_all_jogs(send_cancel=False)
                    append_log("✗ 点动失控：比预期多走了 %.1f mm（%s 轴）—— 已急停！" % (_wd[0], _wd[1]))
                    append_log("   多半是串口丢字节（USB 线太长/松动/干扰）。换根短线，别用延长线或 USB Hub。")
                    append_log("   先点「核对坐标」确认位置，再重新点动。")
                    _setv(v_state, "⚠ 点动失控已急停 —— 先核对坐标")
            # 自愈：机器还在连续点动，但 GUI 侧没有任何「按住且cont」的块
            # → 松手信号丢了（或 cancel 被吞）。补一发 0x85，最多多走一个 tick（120ms）。
            # v1.39.3：读线程判定链路死 → 在这里（主线程）执行重连，避免抢串口
            try:
                if getattr(l, "_need_reconnect", False):
                    l._need_reconnect = False
                    try:
                        _ss1 = send_holder["s"]
                        if _ss1 is not None and _ss1.state in ("running", "pausing", "paused",
                                                               "resuming", "stopping", "finishing"):
                            _ss1.abort_on_reset()
                            append_log("！加工中串口断了 —— 已停发（重连会复位板子，不能续切）")
                    except Exception:
                        pass
                    append_log("正在自动重连串口…（会复位板子：刀位请自己核）")
                    l.reconnect()
            except Exception as _e:
                append_log("！自动重连失败：%s —— 请插好 USB 线，再点顶部「连接」" % _e)
            # v1.39.2：不管有没有按住，只要「状态是 Jog 但坐标 1.5 秒没动」就是卡住了，
            # 补一发 0x85 把它放出来（限频 1.5 秒一次，避免自己刷成 cancel 风暴）。
            try:
                if str(_st).lower().startswith("jog") and s.get("mpos"):
                    _mt2 = getattr(l, "_mpos_ts", 0.0) or 0.0
                    _st2 = getattr(l, "_jog_stuck_ts", 0.0) or 0.0
                    if _mt2 and time.time() - _mt2 > 1.5 and time.time() - _st2 > 1.5:
                        l._jog_stuck_ts = time.time()
                        _safe_do(lambda: l.jog_cancel())
                        append_log("！机床卡在「点动中」状态：已补发停止（0x85）。"
                                   "若是步长很小连点出来的，松手等一下就会恢复")
            except Exception:
                pass
            # v1.39.1：按住不放、但坐标 2 秒没动 → GRBL 端 jog 卡住（或 0x85 丢了）。
            # 补发停止；连补 3 次还不动就明确告诉人该怎么办（不然只能干瞪眼断串口）。
            try:
                if any(b.get("cont") and b.get("down") for b in jog_live) and s.get("mpos"):
                    _mt = getattr(l, "_mpos_ts", 0.0) or 0.0
                    if _mt and time.time() - _mt > 2.0:
                        _sk = getattr(l, "_jog_stuck", None)
                        _n = (int(_sk[1]) + 1) if _sk else 1
                        l._jog_stuck = (time.time(), _n)
                        _safe_do(lambda: l.jog_cancel())
                        if _n == 1:
                            try:
                                append_log("· 点动诊断：" + l.jog_diag())
                            except Exception:
                                pass
                        if _n >= 3:
                            append_log("！点动按着但机床没动：已补发 3 次停止仍无响应。"
                                       "请松手 → 点「高级 / 工具」里的「软复位」——"
                                       "复位后坐标会自动接回断开前的位置，碰过的边不用重碰；"
                                       "软件会弹一次确认，刀没动就点「是」。")
                            l._jog_stuck = (time.time(), 0)
                    else:
                        if getattr(l, "_jog_stuck", None):
                            l._jog_stuck = None
            except Exception:
                pass
            if getattr(l, "_cont", None) is not None:
                if not any(b.get("cont") and b.get("down") for b in jog_live):
                    _safe_do(lambda: l.jog_cancel())
                    stop_all_jogs(send_cancel=False)
                    append_log("！检测到「没人按住但机器还在连续点动」—— 已补发停止（0x85）")
            if s["mpos"]:
                _wp = wpos3(l) if l is not None else None
                if _wp:
                    _setv(v_mpos, "X %9.3f   Y %9.3f   Z %9.3f" % _wp)
                    _set_dro(_wp)
                    _setv(v_mpos2, "机床 MPos  X %.2f  Y %.2f  Z %.2f" % tuple(s["mpos"]))
                else:
                    _setv(v_mpos, "X %9.3f   Y %9.3f   Z %9.3f" % tuple(s["mpos"]))
                    _set_dro(tuple(s["mpos"]))
                    _setv(v_mpos2, "偏移未读到 —— 正在同步（自动补发 $#），稍等 1~2 秒")
            else:
                _setv(v_mpos, "读取中…")
                _set_dro(None)
                _setv(v_mpos2, "")
            # 零点灯：刀尖工作坐标离 0,0 多远（这是「到 Candle 里差多少」的直接答案）
            try:
                dev = wpos_dev(l) if l is not None else None
            except Exception:
                dev = None
            if dev and (abs(dev[0]) > 900 or abs(dev[1]) > 900):
                dev = None            # -999 之类是「无有效坐标」占位，别当真实偏差
            g92 = s.get("g92") or (0.0, 0.0, 0.0)
            g92_bad = max(abs(g92[0]), abs(g92[1])) > 0.001
            if dev is None:
                _setv(v_zero, "读取中…（① 先连接；坐标 -999 是无效占位，回零/解锁后才有值）")
                _cfg_once(lbl_zero, fg=UI_TXT2)
            elif max(abs(dev[0]), abs(dev[1])) <= 0.02:
                _setv(v_zero, "✓ 刀尖就在零点 (0.000, 0.000)%s"
                           % ("　⚠ 但有 G92 残留 %.3f/%.3f" % (g92[0], g92[1]) if g92_bad else "　· Candle 直接开跑"))
                _cfg_once(lbl_zero, fg="#c2410c" if g92_bad else "#059669")
            else:
                _setv(v_zero, "⚠ 偏 X %+.3f  Y %+.3f（点顶部「② 就在此处设零」）%s"
                           % (dev[0], dev[1],
                              ("　（另有 G92 残留 %.3f/%.3f）" % (g92[0], g92[1])) if g92_bad else ""))
                _cfg_once(lbl_zero, fg="#c2410c")
            g = s.get("g54")
            if g is None:
                _setv(v_wcs, "")
            elif abs(g[0]) > 1e-6 or abs(g[1]) > 1e-6:
                # 设零之后 G54 必然不是 0（它就是零点相对机床的偏移），属正常 —— 只报数、不引导
                _setv(v_wcs, "G54 偏移 X%.2f Y%.2f" % (g[0], g[1]))
                _cfg_once(lbl_wcs, fg=UI_TXT2)
            else:
                _setv(v_wcs, "G54 偏移 0,0")
                _cfg_once(lbl_wcs, fg=UI_TXT2)
        root.after(180, tick)

    try:
        cp_startup_hint()
    except Exception:
        pass
    refresh_ports()
    try:
        update_stepbar()
        apply_shape()
        apply_mode()
    except Exception:
        pass
    append_log("%s %s 已启动%s" % (APP, vlabel, "（模拟机模式，坐标是虚拟的）" if mock else ""))
    append_log("流程：⓿ 开机（上电/装夹/Z 对刀）→ ① 连接 → ② 移到工件大致中心就地设零 → "
               "③ 碰四边"
               " → ④ 走到中心 → ⑤ 确认到位后再设零 → ⑥ 选源刀路 → ⑦ 生成刀路"
               "（顶部流程条会实时告诉你下一步点哪）")
    tick()

    if gui_test:
        # v1.39.6/1.39.7：分区自检 —— 各页内容高度 vs 可视高度，顺带测常见屏幕会不会又裁切
        try:
            _orig_geo = root.geometry()
            for _wh in (None, (1060, 1020), (980, 760), (900, 720)):
                if _wh:
                    root.geometry("%dx%d" % _wh)
                    root.update()
                root.update_idletasks()
                print("GUI_LAYOUT: 窗口 %dx%d  顶部 %d  页签区 %d" % (
                    root.winfo_width(), root.winfo_height(),
                    _top.winfo_height(), _nb.winfo_height()))
                if _wh is None:
                    print("GUI_TABS: %d 个 → %s" % (
                        len(_nb.tabs()), " | ".join(_nb.tab(_t, "text") for _t in _nb.tabs())))
                for _i, _nm in enumerate(("定位", "刀路", "发送")):
                    _nb.select(_i + 1)          # 第 0 页是 ⓪ 连接 / 日志
                    root.update_idletasks()
                    _inner = (_pg_pos, _pg_cut, _pg_snd)[_i]
                    _need, _have = _inner.winfo_reqheight(), _page_cvs[_i].winfo_height()
                    print("GUI_PAGE %s: 需 %d / 有 %d → %s" % (
                        _nm, _need, _have,
                        ("需页内滚动 %d%%" % (100 * _need // max(1, _have))) if _need > _have + 1 else "一屏放下"))
                _nb.select(0)
                root.update_idletasks()
            root.geometry(_orig_geo.split("+")[0])
            root.update_idletasks()
        except Exception as _e:
            print("GUI_LAYOUT_ERR:", _e)

        def _find_btn(w, text):
            for ch in w.winfo_children():
                try:
                    if ch.winfo_class() in ("TButton", "Button") and str(ch.cget("text")) == text:
                        return ch
                except Exception:
                    pass
                r = _find_btn(ch, text)
                if r is not None:
                    return r
            return None

        def _jog_auto():
            """点动防误触自检：连点是否堆积 / 松手是否停 / release 丢失是否兜底"""
            l = link_holder["link"]
            rec = {"jog": [], "cancel": 0}
            _oj, _oc = l.jog, l.jog_cancel

            def _j(x, d, f=100):
                rec["jog"].append((x, round(d, 4)))
                return _oj(x, d, f)

            def _c():
                rec["cancel"] += 1
                return _oc()

            l.jog, l.jog_cancel = _j, _c
            btn = _find_btn(root, "X+")
            if btn is None:
                print("JOG_RESULT: 找不到 X+ 按钮")
                l.jog, l.jog_cancel = _oj, _oc
                root.after(60, _auto)
                return
            m = {}

            def tap(i, n):
                if i >= n:
                    root.after(90, after_taps)
                    return
                btn.event_generate("<ButtonPress-1>", x=6, y=6)
                root.after(35, lambda: btn.event_generate("<ButtonRelease-1>", x=6, y=6))
                root.after(70, lambda: tap(i + 1, n))

            def after_taps():
                m["taps_jog"] = len(rec["jog"])
                m["taps_cancel"] = rec["cancel"]
                m["taps_steps"] = sorted(set(d for _, d in rec["jog"]))
                n0 = len(rec["jog"])
                btn.event_generate("<ButtonPress-1>", x=6, y=6)
                root.after(900, lambda: release_hold(n0))

            def release_hold(n0):
                m["hold_jog"] = len(rec["jog"]) - n0        # 按住 0.9s 连发了几段
                c0 = rec["cancel"]
                btn.event_generate("<ButtonRelease-1>", x=6, y=6)
                root.after(120, lambda: after_hold(c0))

            def after_hold(c0):
                m["hold_cancel"] = rec["cancel"] - c0        # 松手是否发了 cancel
                cnt = [len(rec["jog"])]
                btn.event_generate("<ButtonPress-1>", x=6, y=6)

                def outside_release():
                    root.event_generate("<ButtonRelease-1>", x=2, y=2)   # 在按钮外松手
                    root.after(160, lambda: after_out(cnt))
                root.after(700, outside_release)

            def after_out(cnt):
                m["lost_release_burst"] = len(rec["jog"]) - cnt[0]
                base = len(rec["jog"])

                def check():
                    m["lost_release_after"] = len(rec["jog"]) - base   # 兜底后应再没新增
                    m["alive"] = len(jog_live)
                    l.jog, l.jog_cancel = _oj, _oc
                    l._pos = [0.0, 0.0, 0.0]
                    print("JOG_RESULT:", m)
                    root.after(80, _auto)
                root.after(500, check)

            tap(0, 5)

        def _auto():
            try:
                import tempfile as _tf
                from tkinter import messagebox as _mb
                _mb.showinfo = lambda *a, **k: None
                _mb.showwarning = lambda *a, **k: None
                _mb.showerror = lambda *a, **k: print("GUI_ERRBOX:", a[1] if len(a) > 1 else a)
                _mb.askokcancel = lambda *a, **k: True

                l = link_holder["link"]

                # ---- v1.15：点动防跑飞（真实鼠标事件，不是源码断言）----
                # 用例 1：长按 X+ 进了连续走 → release 事件「丢失」→ 用户改按 Y+ 想停
                #         期望：一按 Y+ 就把 X 那条长行程取消掉（0x85 发出去）
                _c0 = getattr(l, "cancel_cnt", 0)
                b_xp = jog_btns[("X", 1)]
                b_yp = jog_btns[("Y", 1)]
                b_xp.event_generate("<ButtonPress-1>")
                root.update()
                time.sleep(0.45)                     # 超过 JOG_HOLD(0.26) → 进入连续走
                root.update()
                _cont_on = getattr(l, "_cont", None) is not None
                b_yp.event_generate("<ButtonPress-1>")   # 注意：X+ 一直没松手
                root.update()
                _stopped = getattr(l, "_cont", None) is None
                _canceled = getattr(l, "cancel_cnt", 0) > _c0
                b_yp.event_generate("<ButtonRelease-1>")
                root.update()
                print("GUI_JOG_LOSTRELEASE: cont=%d stopped=%d cancel=%d"
                      % (1 if _cont_on else 0, 1 if _stopped else 0, 1 if _canceled else 0))

                # 用例 2（回归）：正常松手要能停
                _c1 = getattr(l, "cancel_cnt", 0)
                b_xp.event_generate("<ButtonPress-1>")
                root.update()
                time.sleep(0.45)
                root.update()
                b_xp.event_generate("<ButtonRelease-1>")
                root.update()
                print("GUI_JOG_NORMALRELEASE: cont=%s cancel=%d"
                      % ("None" if getattr(l, "_cont", None) is None else "alive",
                         getattr(l, "cancel_cnt", 0) - _c1))

                # 用例 3：普通轻点（不越过 JOG_HOLD）不该发 cancel、也不该进连续走
                _c2 = getattr(l, "cancel_cnt", 0)
                b_xp.event_generate("<ButtonPress-1>")
                root.update()
                time.sleep(0.05)
                b_xp.event_generate("<ButtonRelease-1>")
                root.update()
                print("GUI_JOG_TAP: cont=%s cancel=%d"
                      % ("None" if getattr(l, "_cont", None) is None else "alive",
                         getattr(l, "cancel_cnt", 0) - _c2))
                # R1.7：焦点还在「步长/速度」框里时，方向键必须能直接点动
                try:
                    cb_feed.focus_set()
                    root.update()
                    _pb = (l.status() or {}).get("mpos")
                    cb_feed.event_generate("<Left>")
                    root.update()
                    time.sleep(0.15)
                    cb_feed.event_generate("<KeyRelease-Left>")
                    root.update()
                    _pa = (l.status() or {}).get("mpos")
                    _moved = bool(_pb and _pa and abs(float(_pa[0]) - float(_pb[0])) > 1e-9)
                    _dx = (float(_pa[0]) - float(_pb[0])) if (_pb and _pa) else 0.0
                    print("GUI_DIRKEY_IN_FEEDBOX: 焦点在速度框时方向键点动=%s dx=%.4f（应=步长 0.1，不是 0.2）"
                          % ("yes" if _moved else "NO", _dx))
                    print("GUI_DIRKEY_STEP_FEED: step=%s feed=%s" % (v_step.get(), v_feed.get()))
                    root.focus_set()
                    root.update()
                except Exception as _e:
                    print("GUI_DIRKEY_IN_FEEDBOX: ERR %s" % _e)
                # v1.20 门禁：还没设零时碰边记点必须被拦下
                _saved0 = flow_ok["zero"]
                flow_ok["zero"] = False
                _n_L0 = len(fitter.pts.get("L") or [])
                record("L")
                root.update()
                print("GUI_GATE_BLOCK: 拦住了=%s"
                      % ("yes" if len(fitter.pts.get("L") or []) == _n_L0 else "no"))
                flow_ok["zero"] = _saved0
                # v1.20：门禁要求先设零才能碰边 —— 自检照真实顺序来
                set_xy_zero(quiet=True)
                root.update()
                # v1.28：状态栏大数字必须变成工作坐标（设零后归零），MPos 退到小字
                print("GUI_POS_WORK:", v_mpos.get().strip(), "| 小字：", v_mpos2.get())
                print("GUI_WCS_TEXT:", v_wcs.get())
                print("GUI_GATE_ZERO:", bool(flow_ok["zero"]))
                # ---- v1.20：键盘方向键 = 按下走一步 → 按住转连续 → 松手停 ----
                _rec = {"jog": [], "cont": 0, "cancel": 0}
                _oj, _oc = l.jog, l.jog_cancel

                def _rj(x, d, f=100, cont=False):
                    _rec["jog"].append(round(float(d), 4))
                    if cont:
                        _rec["cont"] += 1
                    return _oj(x, d, f, cont)

                def _rc():
                    _rec["cancel"] += 1
                    return _oc()

                l.jog, l.jog_cancel = _rj, _rc
                try:
                    root.focus_force()
                    root.update()
                    # 轻点：按一下立刻松（< JOG_HOLD）
                    _n0 = len(_rec["jog"])
                    root.event_generate("<KeyPress-Left>")
                    root.update()
                    time.sleep(0.05)
                    root.event_generate("<KeyRelease-Left>")
                    root.update()
                    print("GUI_KB_TAP: jog=%d cont=%d cancel=%d"
                          % (len(_rec["jog"]) - _n0, _rec["cont"], _rec["cancel"]))
                    # v1.23：Z 用 - / = （车间键盘没有小键盘）
                    for _kk, _want in (("equal", "+Z"), ("minus", "-Z")):
                        _n = len(_rec["jog"])
                        root.event_generate("<KeyPress-%s>" % _kk)
                        root.update()
                        time.sleep(0.04)
                        root.event_generate("<KeyRelease-%s>" % _kk)
                        root.update()
                        print("GUI_KB_Z_%s: jog=%d" % (_want.replace("+", "P").replace("-", "M"),
                                                       len(_rec["jog"]) - _n))
                    # 按住：连发 8 次 KeyPress（模拟系统自动重复）→ 应只走一步 + 转连续
                    _n1, _c1 = len(_rec["jog"]), _rec["cont"]
                    for _i in range(8):
                        root.event_generate("<KeyPress-Left>")
                        root.update()
                        time.sleep(0.04)
                    time.sleep(0.35)                  # 越过 JOG_HOLD(0.26) → 进连续
                    root.update()
                    _cont_on = _rec["cont"] > _c1
                    root.event_generate("<KeyRelease-Left>")
                    root.update()
                    print("GUI_KB_HOLD: jog=%d cont=%d cancel=%d 只走一步=%s"
                          % (len(_rec["jog"]) - _n1, _rec["cont"] - _c1,
                             _rec["cancel"],
                             "yes" if len(_rec["jog"]) - _n1 <= 2 else "no"))
                finally:
                    l.jog, l.jog_cancel = _oj, _oc
                    l._pos = [0.0, 0.0, 0.0]
                    l._cont = None

                l.jog("X", 52.3)
                l.jog("Y", 43.2)
                record("L")
                record("F")
                l.jog("X", 100.0)
                record("R")
                l.jog("Y", 60.0)
                record("B")
                append_log("自检：" + v_result.get())
                print("GUI_RESULT:", v_result.get())
                print("GUI_THETA:", v_theta.get())
                print("GUI_SRC:", v_theta_src.get())
                print("GUI_HINT:", v_hint.get().replace("\n", " / "))
                print("GUI_CHECK:", v_check.get())

                # 混合模式：同一条边再点一次 → 应该能测出角度
                l.jog("X", 5.0)
                record("B")
                # 机器类型切换自检
                v_mach.set(False)
                apply_mode()
                print("GUI_MODE_G54_SHOW_HOME:", bool(hg.winfo_manager()))
                v_mach.set(True)
                apply_mode()
                print("GUI_MODE_DIRECT_SHOW_HOME:", bool(hg.winfo_manager()))
                update_stepbar()
                print("GUI_FLOWBAR:", " | ".join(
                    flow_lbl[_k][0].cget("text") for _k, _t in FLOW_STEPS))
                print("GUI_STEPBAR:", v_stepbar.get())
                _fs = flow_state()
                print("GUI_FLOW:", " ".join(("%s=%d" % (k, 1 if _fs[k] else 0))
                                           for k, _t in FLOW_STEPS))
                print("GUI_NEXTEDGE:", v_nextedge.get())
                print("GUI_SRC2:", v_theta_src.get())
                print("GUI_THETA2:", v_theta.get())
                print("GUI_HINT2:", v_hint.get().replace("\n", " / "))
                print("GUI_CARDS:", cp_dbg_cells())
                print("GUI_G10:", v_g10.get())
                print("GUI_COUNT:", v_count.get())

                # ---- 圆形模式自检（圆心 102.3/73.2，R=40）----
                v_shape.set(SHAPES[1])
                apply_shape()
                clear_all()
                l._pos = [142.3, 73.2, 0.0]                 # 圆上 0°
                record_circle()
                l._pos = [82.3, 107.841, 0.0]               # 120°
                record_circle()
                l._pos = [82.3, 38.559, 0.0]                # 240°
                record_circle()
                rc = res_holder["r"]
                print("GUI_CIRCLE_RESULT:", v_result.get())
                print("GUI_CIRCLE_CENTER:", ("%.4f %.4f" % rc["center"]) if rc else "NONE")
                print("GUI_CIRCLE_DIA:", ("%.4f raw %.4f" % (rc["diameter"], rc["diameter_raw"])) if rc else "NONE")
                print("GUI_CIRCLE_THETA:", v_theta.get())
                print("GUI_CIRCLE_THETA_STATE:", str(ent_theta.cget("state")))
                print("GUI_CIRCLE_CHECK:", v_check.get())
                print("GUI_CIRCLE_HINT:", v_hint.get().replace("\n", " / "))
                print("GUI_CIRCLE_COUNT:", v_count.get())
                print("GUI_CIRCLE_CARDS:", " | ".join(
                    pv_btns[(e, 1)].cget("text") for e in EDGES))
                print("GUI_CIRCLE_BTN:", bool(btn_rec_circle.winfo_manager()),
                      bool(edge_btns["L"].winfo_manager()))
                update_stepbar()
                print("GUI_CIRCLE_STEPBAR:", v_stepbar.get())
                # 第 4 点 → 最小二乘 + 圆度自检
                l._pos = [102.3, 113.2, 0.0]                # 90°
                record_circle()
                r4 = res_holder["r"]
                print("GUI_CIRCLE4_NPTS:", r4["npts"] if r4 else 0)
                print("GUI_CIRCLE4_CHECK:", v_check.get())
                print("GUI_CIRCLE4_DIA:", ("%.4f" % r4["diameter"]) if r4 else "NONE")
                # 切回矩形：θ 恢复可编辑、边按钮恢复
                v_shape.set(SHAPES[0])
                apply_shape()
                print("GUI_BACK_THETA_STATE:", str(ent_theta.cget("state")))
                print("GUI_BACK_BTN:", bool(edge_btns["L"].winfo_manager()),
                      bool(btn_rec_circle.winfo_manager()))
                l._pos = [0.0, 0.0, 0.0]
                # 切回矩形后必须重新记点：圆形自检时 clear_all() 把矩形点清掉了，
                # 不补回来 do_transform() 会以为「还没算出中心」（自检脚本的历史问题）
                clear_all()
                for _e, _p in (("L", (52.3, 43.2)), ("R", (152.3, 43.2)),
                               ("F", (52.3, 43.2)), ("B", (157.3, 103.2))):
                    l._pos = [_p[0], _p[1], 0.0]
                    record(_e)
                print("GUI_REPOINTS:", ("中心 %.3f %.3f" % res_holder["r"]["center"])
                      if res_holder["r"] else "NONE")

                # v1.17：一键拆成两步 —— 故意造 G54/G92 残留，验证 G53 不被带偏
                # ① 走中心 → ② 到位后再设零（和人工操作顺序一致）
                l._g54 = [10.0, 20.0, 0.0]
                l._g92 = [5.0, 5.0, 0.0]
                goto_center()
                time.sleep(1.1)
                _fs_after_center = flow_state()
                print("GUI_STEP_CENTER_ONLY:", _fs_after_center["center"],
                      _fs_after_center["zero2"])
                set_xy_zero(quiet=True)
                _gp = l.mpos()
                print("GUI_GOTOZERO_POS: %.4f %.4f" % (_gp[0], _gp[1]))
                _gd = wpos_dev(l)
                print("GUI_GOTOZERO_DEV:", ("%.4f %.4f" % _gd) if _gd else "NONE")
                print("GUI_GOTOZERO_G54:", "%.4f %.4f" % (l.status()["g54"][0], l.status()["g54"][1]))
                print("GUI_GOTOZERO_G92:", "%.4f %.4f" % (l.status()["g92"][0], l.status()["g92"][1]))
                _fs_after_zero = flow_state()
                print("GUI_STEP_ZERO2:", _fs_after_zero["zero2"])

                # ---- v1.36：定位点（每边一个碰到的点，存机床绝对坐标，点一下抬 Z 走过去）----
                _cmds = []
                _os2 = l.send

                def _s2(c, log_it=True, **kw):
                    _cmds.append(str(c))
                    return _os2(c, log_it=log_it)

                _bakpts = {k: dict(v) for k, v in cp["pts"].items()}
                _bakres = res_holder.get("r")
                _bakptsfit = {k: list(fitter.pts[k]) for k in EDGES}
                l.send = _s2
                try:
                    cp["pts"] = {}
                    res_holder["r"] = None
                    fitter.clear()
                    cp_refresh_text()
                    l._pos = [62.0, -8.0, -3.0]
                    l._g54 = [0.0, 0.0, 0.0]
                    l._g92 = [0.0, 0.0, 0.0]
                    _s1 = cp_add_point("L", 62.0, -8.0, -3.0, 0.0)
                    _s2nd = cp_add_point("L", 70.0, -9.0, -5.0, 0.0)
                    cp_refresh_text()
                    print("GUI_CP8_SLOTS:", "L 槽 %d / %d" % (_s1, _s2nd),
                          "| fitter 点数 %d" % len(fitter.pts["L"]))
                    print("GUI_CP8_CELL_BEFORE:", cp_dbg_cells())
                    _q1 = cp["pts"]["L"]["1"]
                    print("GUI_CP8_STORE: mx=%.1f my=%.1f mz=%.1f 无dx/dy/th=%s"
                          % (_q1["mx"], _q1["my"], _q1["mz"],
                             ("dx" not in _q1 and "dy" not in _q1 and "th" not in _q1)))
                    _bakask = messagebox.askokcancel
                    _bakwarn = messagebox.showwarning
                    messagebox.askokcancel = lambda *a, **k: True
                    messagebox.showwarning = lambda *a, **k: None
                    flow_ok["zero"] = True
                    _cmds[:] = []
                    cp_goto("L", 1)
                    print("GUI_CP8_GOTO:", " | ".join(_cmds[:4]))
                    _g1z = _cmds[0] if _cmds else ""
                    # v1.38：重复点同一个格子，Z 目标必须还是那个值（以前是每次再 +5，越点越高）
                    _cmds[:] = []
                    cp_goto("L", 1)
                    print("GUI_CP8_GOTO2_AGAIN:", " | ".join(_cmds[:4]),
                          "| Z目标不变（已在就不动）=%s"
                          % ((not any(c.startswith("G90 G0 Z") for c in _cmds))
                             or _cmds[0] == _g1z))
                    flow_ok["zero"] = False
                    _cmds[:] = []
                    cp_goto("L", 1)
                    print("GUI_CP8_GOTO3_NOZERO:", " | ".join(_cmds[:4]),
                          "| 没设零也不发相对抬升=%s"
                          % (not any(c.startswith("G91") for c in _cmds)))
                    flow_ok["zero"] = True
                    # 某格没记 Z：拿同批点里最高的 Z 当基准（固定值，不是相对累加）
                    l._pos[2] = -10.0        # 把 Z 压回去，看它抬到哪儿
                    _cmds[:] = []
                    cp["pts"]["R"] = {"1": {"mx": -62.0, "my": -8.0, "cur": 0}}
                    cp_goto("R", 1)
                    print("GUI_CP8_GOTO4_NOZ:", " | ".join(_cmds[:4]),
                          "| 无 mzm 基准 → 不自动抬、只提示标定=%s"
                          % (not any("Z" in c for c in _cmds)))
                    # 一个 Z 基准都没有：不发 Z 指令，只提示
                    cp["pts"] = {"R": {"1": {"mx": -62.0, "my": -8.0, "cur": 0}}}
                    _cmds[:] = []
                    cp_goto("R", 1)
                    print("GUI_CP8_GOTO5_NOBASE:", " | ".join(_cmds[:4]),
                          "| 不发Z=%s"
                          % (not any("Z" in c for c in _cmds)))
                    print("GUI_CP8_STATE:", v_nextedge.get(), " || ", v_hint.get())
                    print("GUI_CP8_NODEV: 提示不带偏差数值=%s" % ("mm" not in v_hint.get()))
                    # 换件「清空」：cur 清掉，mx/my/mz 必须留着（下一件的定位目标）
                    res_holder["r"] = {"center": (60.0, -6.0), "theta_deg": 0.0}
                    clear_all()
                    _q1b = (cp["pts"].get("L") or {}).get("1") or {}
                    print("GUI_CP8_CLEARALL: cur=%s mx=%s my=%s 留着=%s fitter点=%d"
                          % (_q1b.get("cur"), _q1b.get("mx"), _q1b.get("my"),
                             (_q1b.get("mx") is not None and _q1b.get("my") is not None),
                             len(fitter.pts["L"])))
                    cp_refresh_text()
                    print("GUI_CP8_CELL_AFTER:", cp_dbg_cells())
                    # 旧版丢弃 / ver6 自动升级
                    _mig = cp_normalize({"ver": 5, "pos": {"L": {"1": {"dx": 1.0, "dy": 2.0}}}})
                    print("GUI_CP8_MIGRATE:", "pts=%s 丢弃=%d" % (_mig["pts"], _mig["_discarded"]))
                    _m6 = cp_normalize({"ver": 6, "pts": {"L": {"2": {
                        "mx": 70.0, "my": -9.0, "mz": -5.0, "dx": 10.0, "dy": -3.0,
                        "th": 0.0, "cur": 1}}}})
                    _m6q = _m6["pts"]["L"]["2"]
                    print("GUI_CP8_UPGRADE6: ver=%s mx=%.1f my=%.1f mz=%.1f cur=%s 无dx=%s"
                          % (_m6["ver"], _m6q["mx"], _m6q["my"], _m6q["mz"],
                             _m6q.get("cur"), "dx" not in _m6q))
                    # 基准纠偏（v1.37）：设零/算出中心 → 只挪历史点，本件实测点不动
                    cp["refz"] = {"x": 60.0, "y": -6.0, "t": "t"}
                    cp["pts"] = {"L": {"1": {"mx": 62.0, "my": -8.0, "mz": -3.0, "cur": 1},
                                       "2": {"mx": 70.0, "my": -9.0, "mz": -5.0}},
                                 "R": {"1": {"mx": -62.0, "my": -8.0, "mz": -3.0}}}
                    _n = cp_rebase(70.0, -6.0, "算出中心")
                    print("GUI_REBASE:", "平移%d个" % _n,
                          "本件点不动=%s" % (cp["pts"]["L"]["1"]["mx"] == 62.0),
                          "历史点跟着=%s" % (cp["pts"]["L"]["2"]["mx"] == 80.0),
                          "另一个也跟=%s" % (cp["pts"]["R"]["1"]["mx"] == -52.0),
                          "refz=%.1f cur仍在=%s"
                          % (cp["refz"]["x"], cp["pts"]["L"]["1"].get("cur") == 1))
                    _n0 = cp_rebase(70.0, -6.0, "原地再算一次")
                    print("GUI_REBASE_IDEM: 再算一次平移%d个（应为0，不重复挪）" % _n0)
                except Exception as _ex:
                    import traceback as _tb
                    print("GUI_CP_ERR:", _ex, "|", _tb.format_exc().replace("\n", " ~ "))
                finally:
                    l.send = _os2
                    cp["pts"] = _bakpts
                    res_holder["r"] = _bakres
                    for _k in EDGES:
                        fitter.pts[_k] = list(_bakptsfit[_k])
                    cp_refresh_text()

                # 刀路生成全链路
                tmp = _tf.mkdtemp()
                src = os.path.join(tmp, "t.tap")
                with open(src, "w", encoding="utf-8", newline="\r\n") as f:
                    f.write("G90\nG0 X0 Y0\nG1 Z-1 F300\nG1 X50 Y0 F600\n"
                            "G1 X50 Y30\nG1 X0 Y30\nG1 X0 Y0\nG0 Z5\nM30\n")
                v_src.set(src)
                v_dst.set("")                       # v1.11：不再选输出，按源文件自动命名
                _ib, _ie = os.path.splitext(src)
                dst = _ib + "_run" + _ie
                v_theta.set("2.5")
                do_transform()
                print("GUI_NC_AUTO:", os.path.basename(dst))
                print("GUI_NC:", os.path.exists(dst),
                      os.path.exists(os.path.splitext(dst)[0] + "_check" + (_ie or ".nc")),
                      "(第二个 False = 已不生成空跑文件)")
                print("GUI_NC_PATH:", dst)
                if os.path.exists(dst):
                    print("GUI_NC_HEAD:", " | ".join(open(dst, encoding="utf-8").read().splitlines()[:6]))

                # ---- v1.16：文件头必须把基准钉死（G92 残留 = 「偶发整件偏移」的头号原因）----
                _zzgl = os.path.join(_tf.mkdtemp(), "genlog.json")
                os.environ["GRBL_CENTER_GENLOG_FILE"] = _zzgl
                l._g54 = [0.0, 0.0, 0.0]
                l._g92 = [12.5, -8.0, 0.0]          # 模拟 Candle 里误点过「归零」
                v_mach.set(True)
                do_transform()
                _h1 = open(dst, encoding="utf-8").read().splitlines()
                print("GUI_NC_G92CLEAR:", any("G92.1" in x for x in _h1))
                print("GUI_NC_G10:", next((x for x in _h1 if x.strip().startswith("G10")), "NONE"))
                # G54 模式：文件头要把「中心」重申进 G54（Candle 归零盖不掉）
                v_mach.set(False)
                _d2 = _ib + "_rot" + _ie
                do_transform()
                _h2 = open(_d2, encoding="utf-8").read().splitlines() if os.path.exists(_d2) else []
                print("GUI_NC_G54MODE_G10:", next((x for x in _h2 if x.strip().startswith("G10")), "NONE"))
                print("GUI_NC_CENTER:", "%.4f %.4f" % res_holder["r"]["center"])
                # Z 也残留在 G92 里 → 绝不能清（否则 Z 零点丢掉会扎刀）
                v_mach.set(True)
                l._g92 = [12.5, -8.0, 25.0]
                do_transform()
                _h3 = open(dst, encoding="utf-8").read().splitlines()
                print("GUI_NC_G92Z_KEEP:", not any("G92.1" in x for x in _h3))
                # 生成快照要落盘（事后对账用）
                print("GUI_GENLOG_N:", len(genlog_load()))
                _lg = genlog_load()
                if _lg:
                    print("GUI_GENLOG_LAST:", _lg[-1].get("mode"), _lg[-1].get("clear_g92"),
                          _lg[-1].get("g92_at_gen"))
                l._g92 = [0.0, 0.0, 0.0]
                v_mach.set(True)
                if os.path.exists(dst):
                    print("GUI_NC_BODY:", open(dst, encoding="utf-8").read().replace("\r\n", "|").replace("\n", "|"))
                    print("GUI_NC_BBOX:", path_bbox(open(dst, encoding="utf-8").read()))
                # v1.12：会话快照 —— 重开能恢复，但绝不污染新数据、绝不动机床
                _zzd = _tf.mkdtemp()
                os.environ["GRBL_CENTER_SESSION_FILE"] = os.path.join(_zzd, "session.json")
                _zzpos = l.mpos()
                session_flush()
                _zz1 = session_load()
                print("GUI_SESS_FILE:", os.path.exists(session_path()))
                print("GUI_SESS_OK:", session_ok(_zz1))
                print("GUI_SESS_PTS:", sum(len(v) for v in (_zz1.get("pts") or {}).values()))
                print("GUI_SESS_SHAPE:", _zz1.get("shape"))
                print("GUI_SESS_SRC:", bool(_zz1.get("src")))
                clear_all()
                print("GUI_SESS_AFTER_CLEAR:",
                      sum(len(v) for v in ((session_load().get("pts")) or {}).values()))
                print("GUI_SESS_CLEAR_NOTE:", repr(v_session.get()))
                session_save(_zz1)                 # 把刚才的会话写回，模拟「重开软件」
                print("GUI_SESS_RELOAD:", restore_session())
                print("GUI_SESS_RESTORED:", sess["restored"],
                      ("%.4f %.4f" % res_holder["r"]["center"]) if res_holder["r"] else "NONE")
                print("GUI_SESS_MACH_UNMOVED: %.4f %.4f (before %.4f %.4f)"
                      % (l.mpos()[0], l.mpos()[1], _zzpos[0], _zzpos[1]))
                print("GUI_SESS_GUARD:", session_guard(), sess["guard"])
                print("GUI_SESS_NOTE:", v_session.get()[:36])
                print("GUI_SESS_SEP:", preset_path() != session_path())

                # v1.13：发命令框（328p 自查用）
                v_cmd.set("$I")
                send_cmd()
                _logtail = txt.get("end-6l", "end").strip().replace("\n", " | ")
                print("GUI_CMD_TAIL:", _logtail[-120:])

                # v1.25：操作条已撤 —— 主区按钮必须全部在场（用户要求「按钮都在、别藏」）
                print("GUI_MAIN_BTNS:", " ".join(
                    "%s=%s" % (_k, "on" if _b.winfo_manager() else "off")
                    for _k, _b in (("记左", edge_btns["L"]), ("记右", edge_btns["R"]),
                                   ("记前", edge_btns["F"]), ("记后", edge_btns["B"]),
                                   ("圆点", btn_rec_circle), ("撤销", btn_undo))))
                print("GUI_MAIN_TEXT:", " | ".join(
                    b.cget("text") for b in (edge_btns["L"], btn_undo,
                                             btn_center, btn_zero2, btn_gen)))
                try:
                    print("GUI_SEC2_TITLE:", sec2_w._card_title.cget("text"))
                except Exception as _e:
                    print("GUI_SEC2_TITLE: ERR", _e)
                print("GUI_CP_CELLS:", cp_dbg_cells())
                print("GUI_LAST_C_BTN:", btn_last_c.cget("text"), "|",
                      "on" if btn_last_c.winfo_manager() else "off", "|",
                      btn_last_c.cget("state"))
                # R2.9：抬刀上限自检 —— 安全 Z 设成离谱值时必须被拦（改抬 +20），不许硬顶限位
                try:
                    _lk = link_holder["link"]
                    _c0 = float(_lk.mpos_mach()[2])
                    _bak = v_safe_z.get()
                    v_safe_z.set("%.4f" % (_c0 + 15.0))
                    _tz_ok = lift_safe(_lk, "自检·正常")
                    _c1 = float(_lk.mpos_mach()[2])          # 第一次抬完后的真实位置
                    v_safe_z.set("%.4f" % (_c0 + 200.0))
                    _tz_cl = lift_safe(_lk, "自检·超限")
                    v_safe_z.set(_bak)
                    safe_tip()
                    print("GUI_LIFT_CLAMP: cur=%.3f normal=%.3f clamp=%.3f ok=%s"
                          % (_c0, float(_tz_ok), float(_tz_cl),
                             abs(float(_tz_ok) - (_c0 + 15.0)) < 0.01
                             and abs(float(_tz_cl) - (_c1 + 20.0)) < 0.01))
                except Exception as _e:
                    print("GUI_LIFT_CLAMP_ERR:", _e)
                print("GUI_CP_GEO:", " ".join(
                    "%s:%d+%d" % (e, pv_btns[(e, 1)].winfo_x(), pv_btns[(e, 1)].winfo_width())
                    for e in EDGES))
                print("GUI_TOP_BTNS:", btn_top_zero.cget("text"), "|",
                      btn_top_center.cget("text"), "|", btn_disp_zero.cget("text"))
                print("GUI_ZTOP_GEO:", "win=%d" % root.winfo_width(),
                      "disp_zero x=%d w=%d" % (btn_disp_zero.winfo_x(), btn_disp_zero.winfo_width()),
                      "center right=%d" % (btn_top_center.winfo_x()
                                           + btn_top_center.winfo_width()))
                update_stepbar()
            except Exception as e:
                import traceback
                print("GUI_TEST_ERROR:", e)
                traceback.print_exc()
            _shot = int(os.environ.get("GRBL_CENTER_SHOT_DELAY", "300") or 300)
            if _shot > 300:                  # 截图用：切回定位页 → 刷新状态灯 → 自拍
                try:
                    import subprocess as _sp
                    _nb.select(int(os.environ.get("GRBL_CENTER_SHOT_TAB", "1") or 1))
                    paint_cards()
                    root.update()
                    _sp.run(["import", "-window", "root",
                             os.environ.get("GRBL_CENTER_SHOT_PATH", "/tmp/grbl_shot.png")],
                            timeout=25)
                except Exception:
                    pass
            root.after(_shot, root.destroy)


        root.after(200, _jog_auto)

    # 选项/θ 改动也要落盘（防抖 600ms）
    def _hook_session(*_a):
        session_autosave()

    for _v in (v_theta, v_ox, v_oy, v_zval, v_comp, v_off, v_zmode, v_src,
               v_mach, v_rot, v_dry, v_droptc):
        try:
            _v.trace_add("write", _hook_session)
        except Exception:
            pass

    def on_close():
        try:
            session_flush()
        except Exception:
            pass
        try:
            root.destroy()
        except Exception:
            pass

    try:
        root.protocol("WM_DELETE_WINDOW", on_close)
    except Exception:
        pass

    # v1.34：把系统灰底的 tk 控件统一成「卡片白 / 窗口浅灰」（只改颜色，不动布局）
    try:
        _ui_restyle()
    except Exception:
        pass

    if not gui_test:
        root.after(250, restore_session)
        root.after(320, lambda: paint_edge_btns())      # 启动即把「记 X」按钮画成状态

    try:
        root.after(60, paint_edge_btns)
    except Exception:
        pass

    root.mainloop()


# ---------------------------------------------------------------- CLI ----
def cmd_transform(args):
    with open(args.src, "r", encoding="utf-8", errors="ignore") as f:
        text = f.read()
    warns = []
    trans = (args.cx, args.cy) if (args.cx or args.cy) else (0.0, 0.0)
    prelude = None
    if getattr(args, "wcs_zero", False):
        zline = ("G10 L2 P1 X0 Y0 Z%.4f" % args.g54z) if args.g54z is not None else "G10 L2 P1 X0 Y0"
        prelude = ["(直出模式：G54 的 XY 归零 = 工作坐标变成机床坐标；Z 保持)",
                   "G21 G90", zline, "G54"]
        if args.g54z is None:
            warns.append("未给 --g54z：G10 会把 G54 的 Z 偏移清 0，Z 需重新确认")
    new = transform_gcode(text, math.radians(args.theta), args.ox, args.oy,
                          rotate=not args.no_rotate, translate=trans,
                          z_shift=args.z_shift, z_override=args.z_override,
                          drop_tool_change=args.drop_tc, warn=warns.append,
                          prelude=prelude)
    suffix = "_run" if trans != (0.0, 0.0) else "_rot"
    out = args.out or (os.path.splitext(args.src)[0] + suffix + ".nc")
    with open(out, "w", encoding="utf-8", newline="") as f:
        f.write(new)
    bb = path_bbox(new)
    print("已生成:", out, " θ=%.4f°" % args.theta,
          "" if not trans[0] and not trans[1] else "  平移(%.3f, %.3f)" % trans)
    if bb:
        print("刀路范围 X %.3f~%.3f (%.3f)  Y %.3f~%.3f (%.3f)"
              % (bb[0], bb[1], bb[1] - bb[0], bb[2], bb[3], bb[3] - bb[2]))
    for w in warns:
        print("  !", w)


def cmd_selftest(args):
    ok, fail = self_test()
    print("自测：%d 通过 / %d 失败" % (ok, fail))
    return 0 if fail == 0 else 1


def self_test():
    """内置算法自测：造一个倾斜矩形，模拟碰壁点，看求解精度"""
    ok = fail = 0

    def chk(name, cond, info=""):
        nonlocal ok, fail
        if cond:
            ok += 1
        else:
            fail += 1
            print("  FAIL", name, info)

    def make_case(cx, cy, w, h, theta_deg, r, per_edge):
        f = CenterFitter(r)
        th = math.radians(theta_deg)
        ct, st = math.cos(th), math.sin(th)

        def to_machine(p):
            return (cx + ct * p[0] - st * p[1], cy + st * p[0] + ct * p[1])

        # 本地坐标下的刀心线（壁面向内偏 r）
        edges = {
            "L": [(-w / 2 + r, -h / 4), (-w / 2 + r, h / 4)],
            "R": [(w / 2 - r, -h / 4), (w / 2 - r, h / 4)],
            "F": [(-w / 4, -h / 2 + r), (w / 4, -h / 2 + r)],
            "B": [(-w / 4, h / 2 - r), (w / 4, h / 2 - r)],
        }
        for k, pts in edges.items():
            for p in pts[:per_edge]:
                f.add(k, to_machine(p))
        return f

    for theta in (0.0, 1.5, -3.7, 8.0):
        for (w, h) in ((120.0, 80.0), (300.0, 200.0)):
            f = make_case(152.3, 96.7, w, h, theta, 3.175, 2)
            r = f.solve()
            chk("倾斜分中 θ=%.1f" % theta, abs(r["theta_deg"] - theta) < 1e-3, r["theta_deg"])
            chk("倾斜分中 中心 θ=%.1f" % theta,
                dist(r["center"], (152.3, 96.7)) < 1e-3, r["center"])
            chk("倾斜分中 尺寸 θ=%.1f" % theta,
                abs(r["width"] - w) < 1e-3 and abs(r["height"] - h) < 1e-3,
                (r["width"], r["height"]))

    # 正交：每边 1 点
    f = make_case(50.0, 60.0, 100.0, 70.0, 0.0, 3.175, 1)
    r = f.solve()
    chk("正交单点 中心", dist(r["center"], (50.0, 60.0)) < 1e-3, r["center"])
    chk("正交单点 尺寸", abs(r["width"] - 100.0) < 1e-3 and abs(r["height"] - 70.0) < 1e-3,
        (r["width"], r["height"]))

    # G 代码变换
    src = "G90\nG0 X0 Y0\nG1 X10 Y0 F100\nG1 X10 Y10\nG1 X0 Y10\nG1 X0 Y0\n"
    out = transform_gcode(src, math.pi / 2, 0, 0)
    chk("变换 X10Y0 -> 0,10", "X0 Y10" in out.replace("  ", " "), out)
    chk("变换 X10Y10 -> -10,10", "-10 Y10" in out.replace("  ", " "), out)

    # 增量模式
    out = transform_gcode("G91\nG1 X10 Y0\n", math.pi / 2)
    chk("增量模式旋转", "X0 Y10" in out.replace("  ", " "), out)

    return ok, fail


def main():
    ap = argparse.ArgumentParser(description="GRBL 二次加工找中心（分中）辅助程序")
    ap.add_argument("--port", help="串口，如 COM3 / /dev/ttyUSB0")
    ap.add_argument("--baud", type=int, default=115200)
    ap.add_argument("--list", action="store_true", help="列出可用串口")
    ap.add_argument("--diag", action="store_true", help="打印串口诊断信息")
    ap.add_argument("--unlock", action="store_true", help="连上后发 $X 解锁 Alarm（配合 --port）")
    ap.add_argument("--transport", choices=["auto", "win32"], default="auto",
                    help="auto=pyserial 优先；win32=强制内置串口（Windows 排错用）")
    ap.add_argument("--check-update", action="store_true",
                    help="联网检查是否是新版本（读 grbl.cn 上的 version.json）")
    ap.add_argument("--demo", action="store_true", help="用模拟机打开界面（无硬件演示）")
    ap.add_argument("--gui-test", action="store_true", help="界面自检（配合 --demo，执行完自动退出）")
    ap.add_argument("--tab", choices=["connect", "pos", "cut", "send"], default=None,
                    help="启动后直接停在某页（connect / pos / cut / send）")
    ap.add_argument("--font", choices=["simsun", "yahei", "dengxian", "auto"], default="simsun",
                    help="界面字体：simsun 宋体（默认，小字最锐）/ yahei 雅黑UI / "
                         "dengxian 等线 / auto 自动挑")
    ap.add_argument("--shape", choices=["rect", "circle"], default="rect",
                    help="启动时的工件形状（默认 rect 矩形；circle 圆形）")
    ap.add_argument("cmd", nargs="?", choices=["transform", "selftest"], help="子命令")
    ap.add_argument("--src", help="transform: 源刀路文件")
    ap.add_argument("-o", "--out", help="transform: 输出文件")
    ap.add_argument("--theta", type=float, default=0.0, help="transform: 旋转角（度）")
    ap.add_argument("--ox", type=float, default=0.0, help="transform: 设计原点 X")
    ap.add_argument("--oy", type=float, default=0.0, help="transform: 设计原点 Y")
    ap.add_argument("--no-rotate", action="store_true", help="transform: 只平移不旋转")
    ap.add_argument("--cx", type=float, default=0.0, help="transform: 实测中心 X（机床坐标，直出模式）")
    ap.add_argument("--cy", type=float, default=0.0, help="transform: 实测中心 Y")
    ap.add_argument("--z-shift", type=float, default=0.0, help="transform: 所有 Z 加该偏移")
    ap.add_argument("--z-override", type=float, default=None, help="transform: 最深切到该深度（按比例缩放保留分层）")
    ap.add_argument("--drop-tc", action="store_true", help="transform: 移除 T/M6 换刀行")
    ap.add_argument("--wcs-zero", action="store_true",
                    help="transform: 文件头写入 G54 的 XY 归零（直出模式必加）")
    ap.add_argument("--g54z", type=float, default=None,
                    help="transform: 配合 --wcs-zero，保留 G54 原 Z 偏移（不清 0）")
    args, extra = ap.parse_known_args()

    if args.diag:
        for line in serial_env_report():
            print(line)
        return 0

    if args.list:
        ports = list_ports()
        if not ports:
            print("没有找到串口。运行 python grbl_center.py --diag 看详细原因。")
        for dev, desc in ports:
            print("%-16s %s" % (dev, desc))
        return 0

    if args.unlock:
        port = args.port or (extra[0] if extra else None)
        if not port:
            print("用法：python grbl_center.py --unlock --port COM3")
            return 2
        link = GrblLink(port, args.baud, log=lambda m: print(m),
                        transport=(None if args.transport == "auto" else "win32"))
        link.start()
        try:
            time.sleep(0.8)
            print("解锁前状态：%s" % link.status()["state"])
            link.unlock()
            time.sleep(1.0)
            print("解锁后状态：%s" % link.status()["state"])
        finally:
            link.stop()
        return 0

    if args.cmd == "selftest":
        return cmd_selftest(args)

    if args.check_update:
        _r = update_check()
        if not _r["ok"]:
            print("检查更新失败：%s" % _r["err"])
            print("手动查看：%s" % DOWNLOAD_PAGE)
            return 2
        if _r["newer"]:
            print("发现新版本 %s（当前 %s，%s）" % (_r["latest"], VER, _r["date"]))
            print("  %s" % (_r["note"] or ""))
            print("  下载：%s" % (_r["url"] or DOWNLOAD_PAGE))
        else:
            print("已是最新版本 %s" % VER)
        return 0

    if args.cmd == "transform":
        src = args.src or (extra[0] if extra else None)
        if not src:
            print("用法：python grbl_center.py transform 刀路文件 --theta 1.25 -o 输出.nc")
            return 2
        args.src = src
        cmd_transform(args)
        return 0

    run_gui(mock=args.demo, port=args.port, baud=args.baud, gui_test=args.gui_test,
            transport=(None if args.transport == "auto" else "win32"),
            shape=args.shape, tab=args.tab, font=args.font)
    return 0


if __name__ == "__main__":
    sys.exit(main())
