# -*- coding: utf-8 -*-
# =============================================================================
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH: code, comments, UI text, Help.
# (Lars's rule, 01_CORE item 1.)
# THIS IS THE SOURCE.  SightTest.py is made from it by build_program.py, which copies Lars's standard blocks
# (home, UI helpers, icon, About, open, popups) in verbatim at the block marker lines.  Edit THIS file, then run build_program.py.
# =============================================================================
"""Sight Test 1.1 - an eye chart on your phone, run from the PC.

The PHONE shows the chart: letters (Sloan) or Landolt rings, drawn exactly as tall in millimetres as the distance needs
(a "1.0" letter is 5 arc-minutes high: 4.4 mm at 3 m).  The PC is the examiner: it keeps the answers, asks for the next
size, and works out the result.  They talk through a small relay on the Webdock server (WebdockTool > Jobs > "Sight test
relay"): the PC shows a QR code, the phone scans it, a bank card tells the page how big its screen really is, then the
phone is put at a measured distance and the person types (or clicks) what they see on the PC.

The test is a Bayesian staircase: every answer moves the estimate of the person's threshold (logMAR); the next letter
is shown a little above the estimate; the test stops when the estimate is steady (about 12-20 letters per eye).
The result is an INDICATION (decimal / logMAR / Snellen), not a measurement of glasses strength and not a diagnosis.
"""

# ToDo (2026-11-22, v1.0): built and tested against a local copy of the relay (real HTTP, a fake phone and simulated
# observers); NOT yet tried on a real phone at a real distance, and the relay is not on the real server until the job
# "Sight test relay" has been run.  Possible later: astigmatism fan, Amsler grid, contrast chart, near test (40 cm),
# red/green duochrome, a card-less calibration for phones with a known screen size, sound feedback.

import os
import sys
import re
import json
import math
import time
import queue
import random
import shutil
import ctypes
import platform
import datetime
import threading
import subprocess
import webbrowser
import urllib.request
import urllib.error
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, messagebox

PROGRAM_VERSION = "1.1"
PROGRAM_TITLE = "Sight Test"

# *************** DEL 01 - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico


# *************** DEL 02 - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL 03 - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL 04 - ABOUT DIALOG (TEMPLATE) ****************************
# A TEMPLATE, not verbatim: adapt look / colours / emoji / name to the program,
# but KEEP THE MESSAGE (creator, documentation link, small gift).
# NOT for games - games never carry anything tied to me (see 40_games.md; they
# name the designers instead).
#
# Rules: About closes with ESC; Toplevel order grab_set(), focus_force(), <Escape>
# (make_modal does it).  Links open through open_url(), never webbrowser directly.
# The program NAME shown here has no "Issu" part (Issus, Issu's ...); only the
# creator line keeps Lars "Issu" Olsson.
#
# Needs:  import tkinter as tk
#         block_ui_helpers.py (make_modal)   block_open.py (open_url)
#
# Call:   show_about(root, "MyProgram", "What it is, in one line", "🏢")
# Change the colours by passing colors={...} that match the program's palette.

DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"

ABOUT_COLORS = dict(bg="#1e1e2e", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
                    sep="#3a3a4e", box="#252535", hover="#b4d4ff")


def show_about(root, app_name, tagline, emoji="🏢", colors=None):
    """Stylish About dialog with documentation link and donation info."""
    c = {**ABOUT_COLORS, **(colors or {})}

    top = tk.Toplevel(root)
    top.title("About " + app_name)
    top.configure(bg=c["bg"])
    top.resizable(False, False)
    top.transient(root)
    make_modal(top)                              # grab_set, focus_force, Escape

    # Header
    hdr = tk.Frame(top, bg=c["bg"])
    hdr.pack(fill="x")
    tk.Label(hdr, text=emoji, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 36)).pack(pady=(18, 0))
    tk.Label(hdr, text=app_name, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 20, "bold")).pack()
    tk.Label(hdr, text=tagline, bg=c["bg"], fg=c["dim"],
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20)

    # Creator
    tk.Label(top, text='Created by  Lars "Issu" Olsson', bg=c["bg"], fg=c["fg"],
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    def link(parent, text, url, size=9, **pack):
        lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=c["accent"],
                       font=("Segoe UI", size, "underline"), cursor="hand2")
        lbl.pack(**pack)
        lbl.bind("<Button-1>", lambda e: open_url(url))
        lbl.bind("<Enter>",    lambda e: lbl.configure(fg=c["hover"]))
        lbl.bind("<Leave>",    lambda e: lbl.configure(fg=c["accent"]))
        return lbl

    link(top, "📄  View documentation", DOC_URL, pady=(6, 2))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20, pady=(14, 0))

    # Donation
    tk.Label(top, text="☕  If you enjoy " + app_name +
                       ", a small gift is always welcome!",
             bg=c["bg"], fg=c["dim"], font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=c["box"], padx=16, pady=10)
    box.pack(fill="x", padx=20, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        link(box, text, url, pady=1)

    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(8, 16))
    return top


# *************** DEL 05 - OPEN THINGS WITH MY OWN PROGRAMS *******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL 06 - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL **********
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()



# *************** DEL 07 - CONSTANTS, FILES AND SETTINGS *****************
SETTINGS_PATH = os.path.join(PROGRAM_HF_DIR, "settings.json")
RELAY_PATH = os.path.join(PROGRAM_HF_DIR, "sight_relay.json")      # {"url": "https://host/sight/", "key": "..."} made by make_installer.py
HISTORY_PATH = os.path.join(PROGRAM_HF_DIR, "history.json")
REFS_PATH = os.path.join(PROGRAM_HF_DIR, "references.json")        # optician values + events (surgery ...), typed in by the user
MAX_HISTORY = 1000

SLOAN = "CDHKNORSVZ"
EYES = ("Right eye", "Left eye", "Both eyes")
GLASSES = ("Without glasses", "With glasses", "With contact lenses")
KINDS = (("sloan", "Sloan letters"), ("landolt", "Landolt C (gap direction)"))
DISTANCES = ("1.5", "2", "3", "4", "5", "6")

THEME = dict(bg="#1e1e2e", panel="#2a2a3c", fg="#e0e0e0", dim="#9090a8",
             accent="#89b4fa", btn="#3a3a4e", btnfg="#e0e0e0",
             field="#252535", field_fg="#e0e0e0")

DEFAULT_SETTINGS = {"person": "", "eye": EYES[0], "glasses": GLASSES[0], "kind": "sloan", "distance": "3",
                    "geometry": ""}


def read_json(path, default):
    try:
        with open(path, "r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return default


def write_json(path, data):
    """Atomic: a cut-off write can never leave a half file."""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8", newline="\n") as fh:
        json.dump(data, fh, indent=1, ensure_ascii=False)
        fh.write("\n")
    os.replace(tmp, path)


def load_settings():
    s = dict(DEFAULT_SETTINGS)
    s.update(read_json(SETTINGS_PATH, {}) or {})
    return s


def save_settings(s):
    try:
        write_json(SETTINGS_PATH, s)
    except Exception:
        pass


def load_history():
    h = read_json(HISTORY_PATH, [])
    return h if isinstance(h, list) else []


def save_history(items):
    write_json(HISTORY_PATH, items[-MAX_HISTORY:])


def load_refs():
    h = read_json(REFS_PATH, [])
    return [x for x in h if isinstance(x, dict)] if isinstance(h, list) else []


def save_refs(items):
    write_json(REFS_PATH, items)


# *************** DEL 08 - OPTOTYPE GEOMETRY (THE PHYSICS) *****************
# A letter of acuity 1.0 (logMAR 0.0) is 5 arc-minutes high; every +0.1 logMAR makes it 25.9 % bigger.
ARCMIN = math.radians(1.0 / 60.0)
LOGMAR_MIN_CHART = -0.3          # decimal 2.0
LOGMAR_MAX_CHART = 1.5           # decimal 0.03
MIN_DEVICE_PIXELS = 25           # a letter must be at least this many DEVICE pixels tall (5 px per stroke)
FIT_FRACTION = 0.85              # the biggest letter fills this much of the phone's shorter side

FEET_LINES = (10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 100, 125, 160, 200, 250, 320, 400, 630, 800)


def height_mm(logmar, dist_mm):
    """Height in mm of an optotype of this logMAR seen from dist_mm."""
    return 2.0 * dist_mm * math.tan(5.0 * ARCMIN * (10.0 ** logmar) / 2.0)


def logmar_for_height(h_mm, dist_mm):
    """The logMAR of an optotype that is h_mm tall at dist_mm (the inverse of height_mm)."""
    ang = 2.0 * math.atan(h_mm / (2.0 * dist_mm))
    return math.log10(ang / (5.0 * ARCMIN))


def decimal_of(logmar):
    return 10.0 ** (-logmar)


def snellen_feet(logmar):
    """'20/25' - the nearest standard line (log scale)."""
    want = 20.0 * (10.0 ** logmar)
    best = min(FEET_LINES, key=lambda f: abs(math.log10(f) - math.log10(want)))
    return "20/%d" % best, best


def snellen_metric(logmar):
    """'6/7.5' - the metric twin of the nearest standard line."""
    _txt, ft = snellen_feet(logmar)
    m = ft * 0.3
    return "6/%s" % (("%d" % round(m)) if abs(m - round(m)) < 0.05 else ("%.1f" % m))


def feasible_range(dist_mm, status):
    """(logMAR smallest, logMAR biggest) this phone can show at this distance.  status = what the phone reported."""
    w, h, px = status.get("w_mm") or 0, status.get("h_mm") or 0, status.get("pxmm") or 0
    side = min(w, h) * FIT_FRACTION
    hi = logmar_for_height(side, dist_mm) if side > 0 else LOGMAR_MIN_CHART
    lo = LOGMAR_MIN_CHART
    if px > 0:
        lo = max(lo, logmar_for_height(MIN_DEVICE_PIXELS * px, dist_mm))
    return round(lo, 2), round(min(hi, LOGMAR_MAX_CHART), 2)


# *************** DEL 09 - THE ESTIMATOR (BAYESIAN STAIRCASE) *****************
class AcuityEstimator(object):
    """Keeps a probability for every possible threshold (logMAR -0.5 ... 1.7, step 0.01).

    The chance of a right answer at size x for a person with threshold t is
        guess + (1 - guess - lapse) * logistic((x - t) / slope)
    (guess = 1/10 for ten Sloan letters, 1/8 for the eight Landolt directions).  Each answer multiplies the probabilities by
    that chance (or 1 minus it); the estimate is the mean of what is left, its spread is the +/-.
    The next size is the estimate plus a small step (a little easier than the threshold keeps the person encouraged and
    gives the curve a better fit), kept inside what the phone can show."""
    GRID_LO, GRID_HI, GRID_STEP = -0.5, 1.7, 0.01

    def __init__(self, kind, lo, hi, start=0.3, max_trials=22, min_trials=8, stop_sd=0.04,
                 slope=0.05, lapse=0.02, prior_mean=0.2, prior_sd=0.45, ease=0.03):
        self.kind = kind
        self.guess = 0.1 if kind == "sloan" else 0.125
        self.lo, self.hi = lo, hi
        self.start, self.max_trials, self.min_trials, self.stop_sd = start, max_trials, min_trials, stop_sd
        self.slope, self.lapse, self.ease = slope, lapse, ease
        n = int(round((self.GRID_HI - self.GRID_LO) / self.GRID_STEP)) + 1
        self.grid = [round(self.GRID_LO + i * self.GRID_STEP, 2) for i in range(n)]
        self.prior = [-0.5 * ((t - prior_mean) / prior_sd) ** 2 for t in self.grid]
        self.logp = list(self.prior)
        self.trials = []                 # dicts: x, correct, shown, answered

    def p_correct(self, x, t):
        z = (x - t) / self.slope
        if z > 60:
            core = 1.0
        elif z < -60:
            core = 0.0
        else:
            core = 1.0 / (1.0 + math.exp(-z))
        return self.guess + (1.0 - self.guess - self.lapse) * core

    def _add(self, x, correct):
        for i, t in enumerate(self.grid):
            p = self.p_correct(x, t)
            self.logp[i] += math.log(p if correct else 1.0 - p)

    def record(self, x, correct, shown=None, answered=None):
        self.trials.append({"x": x, "correct": bool(correct), "shown": shown, "answered": answered})
        self._add(x, correct)

    def undo(self):
        """Takes the last answer back (a mistyped key) and rebuilds the estimate."""
        if not self.trials:
            return None
        last = self.trials.pop()
        self.logp = list(self.prior)
        for tr in self.trials:
            self._add(tr["x"], tr["correct"])
        return last

    def posterior(self):
        m = max(self.logp)
        w = [math.exp(v - m) for v in self.logp]
        s = sum(w)
        return [v / s for v in w]

    def mean_sd(self):
        post = self.posterior()
        mean = sum(p * t for p, t in zip(post, self.grid))
        var = sum(p * (t - mean) ** 2 for p, t in zip(post, self.grid))
        return mean, math.sqrt(var)

    def next_level(self):
        if not self.trials:
            x = self.start
        else:
            x = self.mean_sd()[0] + self.ease
        return round(min(self.hi, max(self.lo, x)), 2)

    def range_flag(self):
        """'worse' / 'better' when the last four answers were all at the end of the range and all wrong / all right."""
        if len(self.trials) < 4:
            return None
        last = self.trials[-4:]
        if all(abs(t["x"] - self.hi) < 0.011 and not t["correct"] for t in last):
            return "worse"
        if all(abs(t["x"] - self.lo) < 0.011 and t["correct"] for t in last):
            return "better"
        return None

    def finished(self):
        n = len(self.trials)
        if self.range_flag():
            return True
        if n >= self.max_trials:
            return True
        return n >= self.min_trials and self.mean_sd()[1] <= self.stop_sd

    def expected_total(self):
        """For the 'trial n of about m' text."""
        n = len(self.trials)
        if n < self.min_trials:
            return max(self.min_trials, 12)
        return min(self.max_trials, max(n + 1, 14 if self.mean_sd()[1] > 0.06 else n + 2))


# *************** DEL 10 - ONE TEST (THE STATE MACHINE BEHIND THE SCREEN) *****************
class TestRun(object):
    """One test of one eye.  No screen code in here: the window gives it send(cmd) (to the phone) and later(ms, fn)."""

    def __init__(self, kind, dist_mm, status, send, later, rng=None, gap_ms=350):
        lo, hi = feasible_range(dist_mm, status)
        self.status = dict(status or {})
        self.kind, self.dist_mm, self.lo, self.hi = kind, dist_mm, lo, hi
        self.est = AcuityEstimator(kind, lo, hi)
        self.send, self.later, self.gap_ms = send, later, gap_ms
        self.rng = rng or random.Random()
        self.current = None              # {"x", "mm", "shown"} - what is on the phone now
        self.prev_shown = None
        self.token = 0                   # ignores a late 'show' that was overtaken by a newer one
        self.done = False

    def _pick(self):
        if self.kind == "sloan":
            opts = [c for c in SLOAN if c != self.prev_shown]
        else:
            opts = [d for d in range(8) if d != self.prev_shown]
        return self.rng.choice(opts)

    def show_next(self, same=None):
        x = self.est.next_level()
        shown = same if same is not None else self._pick()
        self.current = {"x": x, "mm": round(height_mm(x, self.dist_mm), 3), "shown": shown}
        cmd = {"t": "opt", "k": "s", "ch": shown, "mm": self.current["mm"]} if self.kind == "sloan" \
            else {"t": "opt", "k": "c", "dir": shown, "mm": self.current["mm"]}
        self.token += 1
        tok = self.token
        self.send({"t": "blank"})

        def go():
            if tok == self.token and not self.done:
                self.send(cmd)
        if self.gap_ms > 0:
            self.later(self.gap_ms, go)
        else:
            go()

    def answer(self, ans):
        """ans = a letter, a direction 0-7, or None for 'cannot see'.  Returns True when the test is over."""
        if self.done or self.current is None:
            return self.done
        shown = self.current["shown"]
        if self.kind == "sloan" and isinstance(ans, str):
            ans = ans.upper()
        ok = ans is not None and ans == shown
        self.est.record(self.current["x"], ok, shown, ans)
        self.prev_shown = shown
        if self.est.finished():
            self.finish()
            return True
        self.show_next()
        return False

    def undo(self):
        """Takes the last answer back and shows the SAME optotype again."""
        if self.done:
            return False
        last = self.est.undo()
        if last is None:
            return False
        self.prev_shown = None
        self.show_next(same=last["shown"])
        return True

    def finish(self):
        self.done = True
        self.token += 1
        self.current = None
        self.send({"t": "text", "msg": "Test finished"})

    def result(self, meta):
        """The result as a plain dict (saved in the history, shown in the window)."""
        mean, sd = self.est.mean_sd()
        tr = self.est.trials
        good = sum(1 for t in tr if t["correct"])
        mix = {}
        for t in tr:
            if not t["correct"]:
                key = "%s>%s" % (t["shown"], "?" if t["answered"] is None else t["answered"])
                mix[key] = mix.get(key, 0) + 1
        ft, _n = snellen_feet(mean)
        r = dict(meta)
        r.update({"when": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), "kind": self.kind,
                  "distance_m": round(self.dist_mm / 1000.0, 2), "logmar": round(mean, 3), "sd": round(sd, 3),
                  "decimal": round(decimal_of(mean), 2), "snellen_ft": ft, "snellen_m": snellen_metric(mean),
                  "right": good, "total": len(tr), "flag": self.est.range_flag(), "lo": self.lo, "hi": self.hi,
                  "mix": sorted(mix.items(), key=lambda kv: -kv[1])[:6],
                  "trials": [[t["x"], 1 if t["correct"] else 0, t["shown"], t["answered"]] for t in tr],
                  # what was really on the phone: letter heights in mm (a parallel list to "trials") and the phone's screen,
                  # so a strange result can be checked afterwards against the calibration and the distance
                  "mm": [round(height_mm(t["x"], self.dist_mm), 2) for t in tr],
                  "dist_mm": round(self.dist_mm),
                  "phone": {k: status_val for k, status_val in (self.status or {}).items() if k in ("w_mm", "h_mm", "mmpx", "pxmm")},
                  "version": PROGRAM_VERSION})
        return r


def in_words(decimal):
    """One plain sentence about a decimal acuity (1.0 = the standard line).  The limits are rules of thumb, not medical limits."""
    if decimal >= 1.25:
        w = "better than the standard line."
    elif decimal >= 1.0:
        w = "normal."
    elif decimal >= 0.7:
        w = "close to normal (a little under 1.0)."
    elif decimal >= 0.5:
        w = "somewhat reduced. Glasses may help."
    elif decimal >= 0.3:
        w = "clearly reduced. See an optician."
    else:
        w = "strongly reduced. See an optician soon."
    return "In words:  " + w


def result_text(r, refs=None, before=None):
    """The result as readable text.  refs = the optician values / events, before = the older history: both give extra lines."""
    lines = ["Sight test result - %s" % r.get("when", "")]
    who = r.get("person") or "(no name)"
    lines.append("%s   %s   %s" % (who, r.get("eye", ""), r.get("glasses", "")))
    chart = "Sloan letters" if r.get("kind") == "sloan" else "Landolt C"
    lines.append("%s at %.2f m   (Chart #%s)" % (chart, r.get("distance_m", 0), r.get("label", "-")))
    lines.append("")
    flag = r.get("flag")
    pm = u"±"
    if flag == "worse":
        lines.append("Could not read even the biggest letter (logMAR %.2f) at this distance." % r.get("hi", 0))
        lines.append("Move the phone CLOSER (for example 1.5 m or 1 m) and test again.")
    elif flag == "better":
        lines.append("Read every letter down to the smallest the phone can show (logMAR %.2f)." % r.get("lo", 0))
        lines.append("Acuity is at least %.2f (%s). Move FURTHER away to measure more." % (decimal_of(r.get("lo", 0)), snellen_feet(r.get("lo", 0))[0]))
    else:
        lines.append("Acuity (estimate):  decimal %.2f    logMAR %.2f  (%s %.2f)" % (r["decimal"], r["logmar"], pm, r["sd"]))
        lines.append("Snellen:  %s   (%s)" % (r["snellen_ft"], r["snellen_m"]))
        lines.append(in_words(r["decimal"]))
    lines.append("Optotypes right:  %d of %d" % (r.get("right", 0), r.get("total", 0)))
    if r.get("mix"):
        lines.append("Most common mix-ups (shown > answered):  " + ",  ".join("%s x%d" % (k.replace(">", " > "), n) for k, n in r["mix"]))
    if r.get("mm"):
        ph = r.get("phone") or {}
        lines.append("Letters shown: %.1f - %.1f mm tall%s" % (min(r["mm"]), max(r["mm"]),
                     ("   (phone screen %.0f x %.0f mm, 1 px = %.3f mm)" % (ph.get("w_mm", 0), ph.get("h_mm", 0), ph.get("mmpx", 0))) if ph else ""))
    extra = compare_lines(r, refs or [], before or [])
    if extra:
        lines.append("")
        lines.extend(extra)
    lines.append("")
    lines.append("An indication only - not a measurement of glasses strength and not a diagnosis.")
    return "\n".join(lines)


# *************** DEL 10B - OPTICIAN VALUES, COMPARISON, PLAUSIBILITY AND TREND DATA (no screen code) *****************
def parse_acuity(text):
    """'0.8', '0,8', '0.8+', '1.0-1', '20/25', '6/7.5' -> decimal acuity (float), or None when it is not a value."""
    t = str(text or "").strip().replace(",", ".").replace(" ", "")
    if not t:
        return None
    m = re.match(r"^(\d+(?:\.\d+)?)/(\d+(?:\.\d+)?)$", t)
    if m:
        den = float(m.group(2))
        v = float(m.group(1)) / den if den > 0 else 0.0
    else:
        m = re.match(r"^(\d+(?:\.\d+)?)(?:[+-]\d*)?$", t)
        if not m:
            return None
        v = float(m.group(1))
    return round(v, 3) if 0.01 <= v <= 3.0 else None


def parse_date(text):
    """'2024-10-05', '2024-10', '2024-10-05 14:30' -> datetime, or None."""
    t = str(text or "").strip()
    for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d", "%Y-%m"):
        try:
            return datetime.datetime.strptime(t, fmt)
        except ValueError:
            pass
    return None


def same_person(a, b):
    """Two names count as the same person when equal ignoring case, or when one of them is empty."""
    a, b = (a or "").strip().lower(), (b or "").strip().lower()
    return not a or not b or a == b


def _lm_of_dec(dec):
    return -math.log10(dec)


def _events_between(refs, person, eye, d0, d1):
    out = []
    for x in refs:
        if not x.get("event") or not same_person(x.get("person"), person):
            continue
        if x.get("eye") not in ("", None, eye, EYES[2]):
            continue
        d = parse_date(x.get("date"))
        if d is not None and d0 < d <= d1:
            out.append((d, x))
    return sorted(out, key=lambda p: p[0])


def compare_lines(r, refs, before):
    """Plain lines: how this result fits the optician's values, the previous test, and what is plausible.  [] when nothing to say."""
    out = []
    if "logmar" not in r:
        return out
    when = parse_date(r.get("when")) or datetime.datetime.now()
    eye, person = r.get("eye"), r.get("person")
    with_g = r.get("glasses") != GLASSES[0]
    flagged = r.get("flag") in ("worse", "better")
    # --- the optician ---
    mine = []
    for x in refs:
        d = parse_date(x.get("date"))
        if not x.get("event") and x.get("eye") == eye and same_person(x.get("person"), person) and d is not None and d <= when:
            mine.append((d, x))
    mine.sort(key=lambda p: p[0])
    if not flagged:
        use = [(d, x, parse_acuity(x.get("corrected" if with_g else "free"))) for d, x in mine]
        use = [u for u in use if u[2]]
        said_better = False
        if use:
            d, x, dec = use[-1]
            diff = r["logmar"] - _lm_of_dec(dec)
            lines_off = abs(diff) / 0.1
            what = "with glasses" if with_g else "without glasses"
            head = "Optician %s (%s, %s): %.2f   this test: %.2f." % (x.get("date", ""), eye, what, dec, r["decimal"])
            if abs(diff) <= 0.10:
                out.append(head + "  Agrees (within one chart line).")
            else:
                out.append(head + "  %.1f lines %s." % (lines_off, "BETTER" if diff < 0 else "WORSE"))
                ev = _events_between(refs, person, eye, d, when)
                if ev:
                    out.append("Recorded since then: " + "; ".join("%s %s" % (e[1].get("date", ""), e[1].get("note", "")) for e in ev[-2:]) + ". Whether that matters is for you and your optician to judge.")
                elif diff < 0:
                    out.append("Nothing recorded since then. If your sight has not changed, check the distance, the Ruler check and that the other eye is fully covered.")
                else:
                    out.append("If your sight has not changed, repeat in good light with the phone at full brightness.")
                said_better = diff < 0
        if not with_g and not said_better:
            best = [(d, x, parse_acuity(x.get("corrected"))) for d, x in mine]
            best = [u for u in best if u[2]]
            if best:
                d, x, dec = best[-1]
                if r["logmar"] < _lm_of_dec(dec) - 0.10:
                    out.append("Better than the best the optician reached WITH glasses on %s (%.2f). Rare unless the eye has improved; check the setup." % (x.get("date", ""), dec))
        if r["decimal"] > 1.6:
            out.append("Unusually sharp (better than 1.6): check the measured distance, the Ruler check and that the other eye is covered.")
        if r.get("sd", 0) > 0.09:
            out.append("The estimate is uncertain (+/- %.2f): run it again." % r["sd"])
    # --- the previous test of the same kind ---
    if not flagged:
        prev = None
        for p in before:
            if (p.get("eye") == eye and p.get("glasses") == r.get("glasses") and same_person(p.get("person"), person)
                    and not p.get("flag") and "logmar" in p and parse_date(p.get("when")) is not None
                    and 0 <= (when - parse_date(p.get("when"))).days <= 60 and p.get("when") != r.get("when")):
                prev = p
        if prev:
            diff = r["logmar"] - prev["logmar"]
            tail = "repeatable (within one line)" if abs(diff) <= 0.10 else \
                "%.1f lines %s - one line of difference is normal noise; more means conditions or sight changed" % (abs(diff) / 0.1, "better" if diff < 0 else "worse")
            out.append("Previous test (%s): %.2f -> %s." % (prev.get("when", ""), prev["decimal"], tail))
    return out


def trend_data(items, refs, person, corr):
    """What the Trend window draws.  person '' / '(all)' = everyone;  corr = None (all), 'without' or 'with'.
    Returns (points, ref_points, events): points[eye] = [(datetime, logmar, sd, record)], ref_points = [(datetime, eye, 'free'/'corrected', logmar)],
    events = [(datetime, text)]."""
    every = person in ("", "(all)", None)
    pts = dict((e, []) for e in EYES)
    for r in items:
        if r.get("flag") or "logmar" not in r or r.get("eye") not in pts:
            continue
        if not every and (r.get("person") or "").strip().lower() != person.strip().lower():
            continue
        with_g = r.get("glasses") != GLASSES[0]
        if (corr == "without" and with_g) or (corr == "with" and not with_g):
            continue
        d = parse_date(r.get("when"))
        if d is not None:
            pts[r["eye"]].append((d, r["logmar"], r.get("sd", 0), r))
    for e in EYES:
        pts[e].sort(key=lambda p: p[0])
    rp, ev = [], []
    for x in refs:
        if not every and not same_person(person, x.get("person")):
            continue
        d = parse_date(x.get("date"))
        if d is None:
            continue
        if x.get("event"):
            ev.append((d, x.get("note", "")))
            continue
        if x.get("eye") not in pts:
            continue
        for key in ("free", "corrected"):
            if (key == "free" and corr == "with") or (key == "corrected" and corr == "without"):
                continue
            dec = parse_acuity(x.get(key))
            if dec:
                rp.append((d, x["eye"], key, _lm_of_dec(dec)))
    rp.sort(key=lambda p: p[0])
    ev.sort(key=lambda p: p[0])
    return pts, rp, ev


def trend_summary(pts):
    """A few plain sentences about the newest results."""
    out = []
    last = {}
    for e in EYES:
        if pts.get(e):
            d, lm, sd, _r = pts[e][-1]
            last[e] = lm
            line = "%s:  decimal %.2f (logMAR %.2f) on %s   - %d test%s" % (e, decimal_of(lm), lm, d.strftime("%Y-%m-%d"), len(pts[e]), "" if len(pts[e]) == 1 else "s")
            if len(pts[e]) >= 2:
                ch = (pts[e][-1][1] - pts[e][0][1]) / 0.1
                line += "; since the first: %.1f lines %s" % (abs(ch), "better" if ch < 0 else "worse" if ch > 0 else "same")
            out.append(line)
    if EYES[0] in last and EYES[1] in last:
        diff = last[EYES[1]] - last[EYES[0]]
        if abs(diff) < 0.05:
            out.append("The two eyes are about equal.")
        else:
            out.append("The %s eye is better by %.1f lines (decimal %.2f against %.2f)." % (
                "right" if diff > 0 else "left", abs(diff) / 0.1, decimal_of(min(last[EYES[0]], last[EYES[1]])), decimal_of(max(last[EYES[0]], last[EYES[1]]))))
    return out


# *************** DEL 11 - THE LINK TO THE RELAY (HTTP, ONE THREAD LISTENING, ONE SENDING) *****************
class LinkError(Exception):
    pass


class SightLink(object):
    """Talks to the relay.  Everything that happens is put on `events` for the window to pick up:
        ("status", {...phone status..}, phone_age)   a new status, or just a heartbeat (status = None)
        ("online", True/False)                       the relay can / cannot be reached
        ("ended",)                                   the session is gone
    """

    def __init__(self, base_url, key, events):
        self.base = base_url if base_url.endswith("/") else base_url + "/"
        self.key = key
        self.events = events
        self.pc = self.phone = self.label = None
        self.stop = threading.Event()
        self.out = queue.Queue()
        self.threads = []

    def _call(self, method, path, body=None, headers=None, timeout=12):
        req = urllib.request.Request(self.base + path, method=method, headers=headers or {})
        data = None
        if body is not None:
            data = json.dumps(body).encode("utf-8")
            req.add_header("Content-Type", "application/json")
        try:
            with urllib.request.urlopen(req, data=data, timeout=timeout) as r:
                return r.status, json.loads(r.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            try:
                return e.code, json.loads(e.read().decode("utf-8"))
            except Exception:
                return e.code, {}
        except (urllib.error.URLError, OSError, ValueError) as e:
            raise LinkError(str(getattr(e, "reason", e)))

    def open(self):
        """Asks for a session.  Raises LinkError with a plain message."""
        st, j = self._call("POST", "api/new", {"hello": 1}, {"X-Sight-Key": self.key})
        if st == 401:
            raise LinkError("The relay refused the key. Is sight_relay.json the one made by make_installer.py?")
        if st == 429:
            raise LinkError("The relay has had too many wrong keys. Wait a while.")
        if st == 507:
            raise LinkError("The relay is full of sessions. Try again in a while.")
        if st != 200 or not j.get("ok"):
            raise LinkError("The relay answered %s. Has the job 'Sight test relay' been run?" % st)
        self.pc, self.phone, self.label = j["pc"], j["phone"], j["label"]
        for fn in (self._listen, self._sender):
            t = threading.Thread(target=fn, daemon=True)
            t.start()
            self.threads.append(t)

    def phone_url(self):
        return self.base + "#t=" + self.phone

    def send(self, cmd):
        self.out.put(cmd)

    def _sender(self):
        while not self.stop.is_set():
            try:
                cmd = self.out.get(timeout=0.3)
            except queue.Empty:
                continue
            for attempt in range(3):
                try:
                    st, _j = self._call("POST", "api/cmd", cmd, {"X-Sight-Token": self.pc})
                    if st == 404:
                        self.events.put(("ended",))
                        return
                    break
                except LinkError:
                    time.sleep(0.5)

    def _listen(self):
        since = 0
        was_online = True
        while not self.stop.is_set():
            try:
                st, j = self._call("GET", "api/poll?since=%d&wait=20" % since, None, {"X-Sight-Token": self.pc}, timeout=35)
            except LinkError:
                if was_online:
                    self.events.put(("online", False))
                    was_online = False
                self.stop.wait(2.0)
                continue
            if not was_online:
                self.events.put(("online", True))
                was_online = True
            if st == 404 or j.get("ended"):
                self.events.put(("ended",))
                return
            if st == 200:
                if j.get("seq", 0) > since:
                    since = j["seq"]
                    self.events.put(("status", j.get("status") or {}, j.get("phone_age")))
                else:
                    self.events.put(("status", None, j.get("phone_age")))
            else:
                self.stop.wait(2.0)

    def close(self):
        """Ends the session on the server (best effort) and stops the threads."""
        if self.stop.is_set():
            return
        self.stop.set()
        pc = self.pc

        def bye():
            try:
                self._call("POST", "api/end", {"bye": 1}, {"X-Sight-Token": pc}, timeout=5)
            except Exception:
                pass
        threading.Thread(target=bye, daemon=True).start()


def pretty_code(code):
    """'481726' -> '481 726'."""
    code = str(code or "")
    return code[:3] + " " + code[3:] if len(code) == 6 else code


def short_address(base_url):
    """'https://host/sight/' -> 'host/sight/' (what you type into the phone's address bar)."""
    return re.sub(r"^https?://", "", base_url)


# *************** DEL 12 - QR CODE (DRAWN ON A CANVAS) *****************
def qr_matrix(text):
    """A list of rows of booleans (with a quiet zone), or None when no QR module is installed."""
    try:
        import qrcode
        qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=2, box_size=1)
        qr.add_data(text)
        qr.make(fit=True)
        return [[bool(c) for c in row] for row in qr.get_matrix()]
    except Exception:
        pass
    try:
        import segno
        q = segno.make(text, error="m")
        rows = [list(r) for r in q.matrix_iter(scale=1, border=2)]
        return [[bool(c) for c in row] for row in rows]
    except Exception:
        return None


def draw_qr(canvas, size, text):
    """Draws the QR code for `text` on the canvas.  Returns False when there is no QR module."""
    canvas.delete("all")
    m = qr_matrix(text)
    if not m:
        return False
    n = len(m)
    cell = max(1, size // n)
    off = (size - cell * n) // 2
    canvas.create_rectangle(0, 0, size, size, fill="#ffffff", outline="")
    for y, row in enumerate(m):
        for x, v in enumerate(row):
            if v:
                canvas.create_rectangle(off + x * cell, off + y * cell, off + (x + 1) * cell, off + (y + 1) * cell,
                                        fill="#000000", outline="")
    return True


# *************** DEL 13 - HELP TEXT *****************
HELP_TEXT = """SIGHT TEST - HELP

WHAT IT IS
An eye chart on your phone, run from this PC. The phone shows one letter (or one ring with a gap) at a time, as big as the
distance needs. You type what you see on the PC. The program works out how well you see, as decimal acuity (1.0 = the usual
"normal"), logMAR and Snellen (20/20). It is an INDICATION - not a measurement of glasses strength and not a diagnosis. An
optician does the real test.

THE FIRST TIME
1. WebdockTool > Jobs > "Sight test relay" > Run job. Then copy sight_relay.json into Helpfiles\\SightTest on this PC.
2. Press "Start phone session". The window shows a 6-digit CODE, an ADDRESS and a QR code. On the phone EITHER scan the QR code with
   the camera, OR open the address in any browser (type it once, then bookmark it) and type the code on the keypad. The code works
   once, for 15 minutes, for one phone. "Copy link" copies the QR link, for opening it on the same PC while you test.
3. On the phone: set the brightness to maximum, tap Start, then hold a BANK CARD against the screen and drag until the blue box is
   exactly as wide as the card's edge: the LONG edge when the phone is sideways, the SHORT edge when it is upright (nothing needs to
   be turned). The size is remembered on that phone.
4. The window now says "Phone ready". Press "Ruler check": the phone draws a 50 mm line - hold a ruler to it. If it is not 50 mm,
   press "Calibrate again".

EVERY TEST
- Put the phone at a MEASURED distance (tape measure): 3 m is good. At 1.5 m the smallest letters are twice as small to the eye,
  so use it for weak sight. The program computes the letter heights for the distance you type.
- Stand or sit at that distance from the phone with this PC beside you (or have someone type). Test ONE eye at a time: cover the
  other with your palm, without pressing on it. Wear the glasses you want to test, or none (say which in the list).
- Press "Start test". Type each letter you see (Sloan letters: C D H K N O R S V Z). If you cannot see it, press the ? button, Space or
  Enter - that counts as wrong, and it is better than guessing for the estimate. Landolt C: press the arrow key (or numpad 1-9 around
  the 5) for the side where the gap is. Backspace takes the last answer back (a mistyped key) and shows the same letter again.
- The test stops by itself when the estimate is steady (about 12-20 letters). The result is saved in History.

READING THE RESULT
Decimal 1.0 (20/20) is the usual normal line; many healthy adults read 1.2-1.6. 0.5 (20/40) is about the limit for driving in many
countries. The "+/-" is how sure the estimate is. "Could not read the biggest letter" means: move the phone closer. "Read all letters
down to the smallest" means: move further away.

OPTICIAN VALUES, HISTORY AND TREND
- "Optician values..." : type in the numbers from an optician's or eye clinic's paper (sight without glasses, with the best glasses, the
  glasses numbers) and EVENTS such as "Eye surgery, left eye". One entry per eye and visit. They are only used for comparing.
- After each test the result window says how it fits the latest optician value for the same eye (same line = agrees; more than one
  chart line off = look again or something has changed), whether it beats the best the optician reached with glasses (rare), and how it
  fits your previous test (one line of difference is normal noise).
- "Trend..." : all results over time per eye, with the optician values (rings/squares) and the events (dashed lines). A good way to see
  an eye that is changing, and the difference between the two eyes.
- History keeps, for every test, the letter heights in mm and the phone's screen size, so a strange result can be checked afterwards.

WHAT THE TEST CANNOT TELL
The number is how sharp the eye sees, not WHY. "Near-sighted -2.00" or "astigmatism -1.00" are glasses strengths (dioptres); only an
optician's refraction measures them. Rule of thumb: if you see clearly better WITH glasses than without, the glasses are doing their
job; if you see about the same, the cause is not a glasses matter. The "In words" line is a rough guide, not a diagnosis.

WHAT CAN GO WRONG
- Wrong distance or wrong calibration: half a step off is easy. Check the ruler line and measure the distance.
- Screen brightness not at maximum, glare on the glass, the phone not at eye height.
- Changing the phone's "display size" or browser zoom after the calibration: the page notices and asks again.
- The phone's screen is small: at 3 m the biggest letter that fits is about logMAR 1.1 (decimal 0.08). Weaker sight: go closer.

PRIVACY
The relay only passes the letter that is on the phone's screen and the phone's screen size. The answers, the names and the results
stay on this PC (Helpfiles\\SightTest\\history.json). A session ends when you press "End session", close the program, or after 2 hours.

KEYS
Letters / arrows: answer. Space, Enter or ?: cannot see. Backspace: undo the last answer. F1: this help.
"""


# *************** DEL 14 - DIALOG HELPERS *****************
def show_text_window(parent, title, text, geometry="760x620"):
    """Read-only text window (Help, result details).  Escape closes it."""
    top = tk.Toplevel(parent)
    top.title(title)
    top.transient(parent)
    top.geometry(geometry)
    frame = tk.Frame(top)
    frame.pack(fill="both", expand=True, padx=8, pady=8)
    sb = ttk.Scrollbar(frame, orient="vertical")
    t = new_text(frame, wrap="word", font=("Segoe UI", 10), padx=10, pady=8, yscrollcommand=sb.set)
    sb.configure(command=t.yview)
    t.pack(side="left", fill="both", expand=True)
    sb.pack(side="left", fill="y")
    t.insert("1.0", text)
    t.configure(state="disabled")
    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(0, 8))
    try:
        top.wait_visibility()
    except Exception:
        pass
    make_modal(top)
    return top


# *************** DEL 15 - THE HISTORY WINDOW *****************
class HistoryWindow(object):
    COLS = (("when", "When", 125), ("person", "Person", 110), ("eye", "Eye", 80), ("glasses", "Glasses", 120),
            ("kind", "Chart", 90), ("dist", "m", 45), ("logmar", "logMAR", 60), ("dec", "Decimal", 60), ("sn", "Snellen", 70))

    def __init__(self, parent):
        self.parent = parent
        self.items = load_history()
        top = self.top = tk.Toplevel(parent)
        top.title("History - " + PROGRAM_TITLE)
        top.transient(parent)
        top.geometry("900x460")
        top.minsize(900, 460)
        frame = tk.Frame(top)
        frame.pack(fill="both", expand=True, padx=8, pady=8)
        sb = ttk.Scrollbar(frame, orient="vertical")
        self.tree = ttk.Treeview(frame, columns=[c[0] for c in self.COLS], show="headings", selectmode="browse",
                                 yscrollcommand=sb.set)
        sb.configure(command=self.tree.yview)
        for key, head, w in self.COLS:
            self.tree.heading(key, text=head)
            self.tree.column(key, width=w, anchor="w", stretch=False)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="left", fill="y")
        self.tree.bind("<Double-1>", lambda e: self.details())
        bar = tk.Frame(top)
        bar.pack(fill="x", padx=8, pady=(0, 8))
        tk.Button(bar, text="Details", width=10, command=self.details).pack(side="left")
        tk.Button(bar, text="Delete", width=10, command=self.delete).pack(side="left", padx=6)
        tk.Button(bar, text="Close", width=10, command=top.destroy).pack(side="right")
        self.fill()
        try:
            top.wait_visibility()
        except Exception:
            pass
        make_modal(top)

    def fill(self):
        self.tree.delete(*self.tree.get_children())
        for i in range(len(self.items) - 1, -1, -1):
            r = self.items[i]
            flag = {"worse": "<", "better": ">"}.get(r.get("flag"), "")
            self.tree.insert("", "end", iid=str(i), values=(
                r.get("when", ""), r.get("person", ""), r.get("eye", ""), r.get("glasses", ""),
                "Sloan" if r.get("kind") == "sloan" else "Landolt", "%.1f" % r.get("distance_m", 0),
                flag + "%.2f" % r.get("logmar", 0), flag + "%.2f" % r.get("decimal", 0), r.get("snellen_ft", "")))

    def _selected(self):
        sel = self.tree.selection()
        return int(sel[0]) if sel else None

    def details(self):
        i = self._selected()
        if i is not None:
            show_text_window(self.top, "Result", result_text(self.items[i], load_refs(), self.items[:i]), "700x440")

    def delete(self):
        i = self._selected()
        if i is None:
            return
        if not messagebox.askyesno(PROGRAM_TITLE, "Delete this result from the history? It cannot be undone.", parent=self.top):
            return
        del self.items[i]
        save_history(self.items)
        self.fill()


# *************** DEL 15B - THE OPTICIAN VALUES WINDOW (reference values and events typed in by the user) *****************
class RefWindow(object):
    COLS = (("date", "Date", 80), ("person", "Person", 80), ("source", "Where", 105), ("eye", "Eye", 75), ("free", "No glasses", 72),
            ("corrected", "Best glasses", 80), ("sph", "Sph", 50), ("cyl", "Cyl", 50), ("axis", "Axis", 45), ("add", "Add", 45),
            ("note", "Note", 240))

    def __init__(self, parent, person=""):
        self.parent = parent
        self.items = sorted(load_refs(), key=lambda x: parse_date(x.get("date")) or datetime.datetime.min)
        self.person = person
        top = self.top = tk.Toplevel(parent)
        top.title("Optician values - " + PROGRAM_TITLE)
        top.transient(parent)
        top.geometry("960x600")
        top.minsize(960, 600)
        frame = tk.Frame(top)
        frame.pack(fill="both", expand=True, padx=8, pady=(8, 4))
        sb = ttk.Scrollbar(frame, orient="vertical")
        self.tree = ttk.Treeview(frame, columns=[c[0] for c in self.COLS], show="headings", selectmode="browse", height=9,
                                 yscrollcommand=sb.set)
        sb.configure(command=self.tree.yview)
        for key, head, w in self.COLS:
            self.tree.heading(key, text=head)
            self.tree.column(key, width=w, anchor="w", stretch=False)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="left", fill="y")
        self.tree.bind("<<TreeviewSelect>>", lambda e: self.load_form())

        form = tk.LabelFrame(top, text=" One entry ", padx=8, pady=6)
        form.pack(fill="x", padx=8, pady=4)
        self.v = dict((k, tk.StringVar(value="")) for k in ("date", "person", "source", "eye", "free", "corrected", "sph", "cyl", "axis", "add", "note"))
        self.v_event = tk.IntVar(value=0)
        self.v["person"].set(person)

        def put(r, c, label, key, width, **kw):
            tk.Label(form, text=label, anchor="w").grid(row=r, column=c * 2, sticky="w", padx=(0, 4), pady=2)
            new_entry(form, textvariable=self.v[key], width=width, **kw).grid(row=r, column=c * 2 + 1, sticky="w", padx=(0, 12), pady=2)
        put(0, 0, "Date (YYYY-MM-DD or YYYY-MM):", "date", 12)
        put(0, 1, "Person:", "person", 14)
        put(0, 2, "Where / who:", "source", 18)
        tk.Label(form, text="Eye:", anchor="w").grid(row=1, column=0, sticky="w", pady=2)
        self.cb_eye = ttk.Combobox(form, textvariable=self.v["eye"], values=("",) + EYES, state="readonly", width=12)
        self.cb_eye.grid(row=1, column=1, sticky="w", pady=2)
        put(1, 1, "Without glasses:", "free", 14)
        put(1, 2, "With best glasses:", "corrected", 18)
        put(2, 0, "Sphere:", "sph", 12)
        put(2, 1, "Cylinder:", "cyl", 14)
        put(2, 2, "Axis:", "axis", 18)
        put(3, 0, "Reading add:", "add", 12)
        tk.Label(form, text="Note:", anchor="w").grid(row=3, column=2, sticky="w", padx=(0, 4), pady=2)
        new_entry(form, textvariable=self.v["note"], width=62).grid(row=3, column=3, columnspan=3, sticky="w", pady=2)
        tk.Checkbutton(form, text="Just an event (surgery, new glasses ...): no values, shown as a line in Trend",
                       variable=self.v_event, anchor="w").grid(row=4, column=0, columnspan=6, sticky="w", pady=(4, 0))
        tk.Label(top, anchor="w", justify="left", wraplength=920, fg="#555555",
                 text="Sight values can be written 0.8, 0,8, 0.8+, 20/25 or 6/7.5. One entry per eye and visit; the optician's paper says "
                      "which is right/left (R/L, OD/OS). The values are only used to compare with your own tests: a test that agrees "
                      "with them is more believable, one that does not asks for a second look (or tells that something has changed).").pack(fill="x", padx=10)
        bar = tk.Frame(top)
        bar.pack(fill="x", padx=8, pady=8)
        tk.Button(bar, text="Add as new", width=12, command=self.add).pack(side="left")
        tk.Button(bar, text="Save changes", width=12, command=self.save_changes).pack(side="left", padx=6)
        tk.Button(bar, text="Delete", width=10, command=self.delete).pack(side="left")
        tk.Button(bar, text="Clear form", width=10, command=self.clear_form).pack(side="left", padx=6)
        tk.Button(bar, text="Close", width=10, command=top.destroy).pack(side="right")
        self.fill()
        try:
            top.wait_visibility()
        except Exception:
            pass
        make_modal(top)

    def fill(self):
        self.tree.delete(*self.tree.get_children())
        for i, x in enumerate(self.items):
            ev = bool(x.get("event"))
            self.tree.insert("", "end", iid=str(i), values=(
                x.get("date", ""), x.get("person", ""), x.get("source", ""), "(event)" if ev else x.get("eye", ""),
                "" if ev else x.get("free", ""), "" if ev else x.get("corrected", ""), x.get("sph", ""), x.get("cyl", ""),
                x.get("axis", ""), x.get("add", ""), x.get("note", "")))

    def _selected(self):
        sel = self.tree.selection()
        return int(sel[0]) if sel else None

    def load_form(self):
        i = self._selected()
        if i is None or i >= len(self.items):
            return
        x = self.items[i]
        for k, var in self.v.items():
            var.set(str(x.get(k, "")))
        self.v_event.set(1 if x.get("event") else 0)

    def clear_form(self):
        for k, var in self.v.items():
            var.set(self.person if k == "person" else "")
        self.v_event.set(0)

    def _record(self):
        """Builds a record from the form.  Returns (record, None) or (None, 'what is wrong')."""
        g = dict((k, var.get().strip().replace(",", ".") if k in ("sph", "cyl", "axis", "add") else var.get().strip()) for k, var in self.v.items())
        if parse_date(g["date"]) is None:
            return None, "Date: write it like 2024-10-05 (or just 2024-10)."
        rec = {"date": g["date"], "person": g["person"], "source": g["source"], "note": g["note"]}
        if self.v_event.get():
            if not g["note"]:
                return None, "An event needs a note (for example: Eye surgery, left eye)."
            rec.update({"event": True, "eye": g["eye"]})
            return rec, None
        if g["eye"] not in EYES:
            return None, "Choose the eye."
        rec["eye"] = g["eye"]
        for k, label in (("free", "Without glasses"), ("corrected", "With best glasses")):
            if g[k] and parse_acuity(g[k]) is None:
                return None, "%s: write the value like 0.8, 0,8, 0.8+, 20/25 or 6/7.5." % label
            rec[k] = g[k]
        for k, label in (("sph", "Sphere"), ("cyl", "Cylinder"), ("add", "Reading add")):
            if g[k]:
                try:
                    float(g[k])
                except ValueError:
                    return None, "%s: write a number like -0.25 or +1.50." % label
            rec[k] = g[k]
        if g["axis"]:
            try:
                ax = int(float(g["axis"]))
            except ValueError:
                ax = -1
            if not 0 <= ax <= 180:
                return None, "Axis: a whole number from 0 to 180."
            rec["axis"] = str(ax)
        else:
            rec["axis"] = ""
        if not (rec["free"] or rec["corrected"] or rec["sph"] or rec["cyl"] or rec["add"]):
            return None, "Write at least one value (a sight value or a glasses number)."
        return rec, None

    def _store(self):
        self.items.sort(key=lambda x: parse_date(x.get("date")) or datetime.datetime.min)
        try:
            save_refs(self.items)
        except Exception as e:
            messagebox.showerror(PROGRAM_TITLE, "Could not save: %s" % e, parent=self.top)
        self.fill()

    def add(self):
        rec, err = self._record()
        if err:
            messagebox.showwarning(PROGRAM_TITLE, err, parent=self.top)
            return
        self.items.append(rec)
        self._store()
        # ready for the other eye of the same visit
        for k in ("free", "corrected", "sph", "cyl", "axis", "add", "note"):
            self.v[k].set("")
        if not rec.get("event"):
            self.v["eye"].set(EYES[1] if rec["eye"] == EYES[0] else EYES[0] if rec["eye"] == EYES[1] else "")

    def save_changes(self):
        i = self._selected()
        if i is None:
            messagebox.showinfo(PROGRAM_TITLE, "Click a row in the list first (or use 'Add as new').", parent=self.top)
            return
        rec, err = self._record()
        if err:
            messagebox.showwarning(PROGRAM_TITLE, err, parent=self.top)
            return
        self.items[i] = rec
        self._store()

    def delete(self):
        i = self._selected()
        if i is None:
            return
        if not messagebox.askyesno(PROGRAM_TITLE, "Delete this entry? It cannot be undone.", parent=self.top):
            return
        del self.items[i]
        self._store()


# *************** DEL 15C - THE TREND WINDOW (results over time, optician values and events in the same picture) *****************
EYE_COLORS = {"Right eye": "#2060d0", "Left eye": "#e07a10", "Both eyes": "#2a9d3f"}


class TrendWindow(object):
    CORR = (("All tests", None), ("Without glasses", "without"), ("With glasses / lenses", "with"))
    W, H = 860, 370

    def __init__(self, parent, person=""):
        self.items = load_history()
        self.refs = load_refs()
        names = sorted(set((r.get("person") or "").strip() for r in self.items if (r.get("person") or "").strip()))
        top = self.top = tk.Toplevel(parent)
        top.title("Trend - " + PROGRAM_TITLE)
        top.transient(parent)
        top.geometry("900x640")
        top.minsize(900, 640)
        bar = tk.Frame(top)
        bar.pack(fill="x", padx=10, pady=(8, 2))
        tk.Label(bar, text="Person:").pack(side="left")
        self.var_person = tk.StringVar(value=person if person in names else "(all)")
        cb = ttk.Combobox(bar, textvariable=self.var_person, values=["(all)"] + names, state="readonly", width=18)
        cb.pack(side="left", padx=(4, 14))
        cb.bind("<<ComboboxSelected>>", lambda e: self.redraw())
        tk.Label(bar, text="Show:").pack(side="left")
        self.var_corr = tk.StringVar(value=self.CORR[0][0])
        cb2 = ttk.Combobox(bar, textvariable=self.var_corr, values=[c[0] for c in self.CORR], state="readonly", width=22)
        cb2.pack(side="left", padx=4)
        cb2.bind("<<ComboboxSelected>>", lambda e: self.redraw())
        self.cv = tk.Canvas(top, width=self.W, height=self.H, bg="#ffffff", highlightthickness=1, highlightbackground="#bbbbbb")
        self.cv.pack(padx=10, pady=6)
        self.lbl = tk.Label(top, text="", justify="left", anchor="nw", wraplength=860, height=8)
        self.lbl.pack(fill="x", padx=12)
        tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(2, 8))
        self.redraw()
        try:
            top.wait_visibility()
        except Exception:
            pass
        make_modal(top)

    def redraw(self):
        corr = dict(self.CORR)[self.var_corr.get()]
        pts, rp, ev = trend_data(self.items, self.refs, self.var_person.get(), corr)
        cv = self.cv
        cv.delete("all")
        W, H, L, R, T, B = self.W, self.H, 56, 16, 18, 72
        have = [p for e in EYES for p in pts[e]]
        if not have:
            cv.create_text(W // 2, H // 2, text="No results for this choice yet.", font=("Segoe UI", 11), fill="#777777")
            self.lbl.configure(text="")
            return
        # the time axis follows YOUR tests (and the events between them); an optician value from long before is drawn at the left edge
        # with its date written next to it, so it does not squeeze the recent tests together
        first = min(p[0] for p in have)
        ev = [e for e in ev if e[0] >= first]                      # an event from before your first test is not drawn
        newest = {}                                                # long-ago optician values: only the latest per eye and kind is drawn
        for p in rp:
            if p[0] >= first:
                newest[(len(newest), p[1], p[2])] = p
            elif (p[1], p[2], "old") not in newest or newest[(p[1], p[2], "old")][0] < p[0]:
                newest[(p[1], p[2], "old")] = p
        rp = sorted(newest.values(), key=lambda p: p[0])
        xs = [p[0] for p in have] + [e[0] for e in ev]
        t0, t1 = min(xs), max(xs + [p[0] for p in rp if p[0] >= first])
        span = max((t1 - t0).total_seconds(), 14 * 86400.0)
        pad = span * 0.05
        t0 = t0 - datetime.timedelta(seconds=pad)
        total = span + 2 * pad
        ys = [p[1] for p in have] + [p[3] for p in rp]
        lo, hi = min(ys) - 0.1, max(ys) + 0.1
        if hi - lo < 0.6:
            mid = (hi + lo) / 2.0
            lo, hi = mid - 0.3, mid + 0.3

        def X(d):
            return max(L + 14, L + (d - t0).total_seconds() / total * (W - L - R))

        def Y(lm):
            return T + (lm - lo) / (hi - lo) * (H - T - B)
        for dec in (0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0, 1.25, 1.5, 2.0, 2.5):
            lm = _lm_of_dec(dec)
            if lo <= lm <= hi:
                cv.create_line(L, Y(lm), W - R, Y(lm), fill="#e4e4e4")
                cv.create_text(L - 6, Y(lm), text="%g" % dec, anchor="e", font=("Segoe UI", 8), fill="#555555")
        cv.create_text(4, T - 8, text="decimal", anchor="w", font=("Segoe UI", 7), fill="#777777")
        cv.create_line(L, T, L, H - B, fill="#999999")
        cv.create_line(L, H - B, W - R, H - B, fill="#999999")
        for i in range(6):
            d = t0 + datetime.timedelta(seconds=total * i / 5.0)
            cv.create_line(X(d), H - B, X(d), H - B + 4, fill="#999999")
            cv.create_text(X(d) + (14 if i == 5 else 0), H - B + 6, text=d.strftime("%Y-%m-%d"), anchor="ne" if i == 5 else "n",
                           font=("Segoe UI", 8), fill="#555555")
        for d, text in ev:
            right_side = X(d) > L + (W - L - R) * 0.6
            cv.create_line(X(d), T, X(d), H - B, fill="#777777", dash=(4, 3))
            cv.create_text(X(d) + (-3 if right_side else 3), T + 2, text=text[:34], anchor="ne" if right_side else "nw",
                           font=("Segoe UI", 8), fill="#555555")
        for e in EYES:
            col = EYE_COLORS[e]
            line = pts[e]
            if len(line) >= 2:
                cv.create_line(*[c for p in line for c in (X(p[0]), Y(p[1]))], fill=col, width=1)
            for d, lm, sd, _r in line:
                cv.create_line(X(d), Y(lm - sd), X(d), Y(lm + sd), fill=col)
                cv.create_oval(X(d) - 5, Y(lm) - 5, X(d) + 5, Y(lm) + 5, fill=col, outline="")
        for d, e, key, lm in rp:
            col = EYE_COLORS.get(e, "#444444")
            if key == "free":
                cv.create_oval(X(d) - 8, Y(lm) - 8, X(d) + 8, Y(lm) + 8, outline=col, width=2)
            else:
                cv.create_rectangle(X(d) - 7, Y(lm) - 7, X(d) + 7, Y(lm) + 7, outline=col, width=2)
            if d < t0:
                cv.create_text(X(d) + 11, Y(lm), text=d.strftime("%Y-%m"), anchor="w", font=("Segoe UI", 8), fill="#555555")
        lx = L
        for e in EYES:
            cv.create_oval(lx, H - 40, lx + 10, H - 30, fill=EYE_COLORS[e], outline="")
            cv.create_text(lx + 14, H - 35, text=e, anchor="w", font=("Segoe UI", 9), fill="#333333")
            lx += 100
        cv.create_text(L, H - 14, anchor="w", font=("Segoe UI", 9), fill="#333333",
                       text=u"dot = your test (bar = uncertainty)   ○ = optician, no glasses   □ = optician, best glasses   dashed line = event")
        cv.create_text(W - R, T - 8, text="better  ↑", anchor="e", font=("Segoe UI", 8), fill="#777777")
        self.lbl.configure(text="\n".join(trend_summary(pts)))


# *************** DEL 16 - THE MAIN WINDOW *****************
class App(object):
    def __init__(self, root):
        self.root = root
        self.S = load_settings()
        self.q = queue.Queue()
        self.link = None
        self.phone = {}                  # the last status the phone sent
        self.phone_age = None
        self.relay_online = True
        self.run = None                  # a TestRun while testing
        self.last_result = None
        self.save_job = None
        self.playertext = None
        self._build_ui()
        self.root.after(100, self._pump)
        self._refresh()

    # ---- settings -----------------------------------------------------------
    def save_now(self):
        if self.save_job:
            try:
                self.root.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        self._collect()
        save_settings(self.S)

    def save_soon(self):
        if self.save_job:
            self.root.after_cancel(self.save_job)
        self.save_job = self.root.after(700, self.save_now)

    def _collect(self):
        try:
            self.S["person"] = self.var_person.get().strip()
            self.S["eye"] = self.var_eye.get()
            self.S["glasses"] = self.var_glasses.get()
            self.S["kind"] = self.var_kind.get()
            self.S["distance"] = self.var_dist.get().strip()
        except Exception:
            pass

    # ---- building the window ---------------------------------------------------
    def _build_ui(self):
        r = self.root
        r.title(PROGRAM_TITLE + " " + PROGRAM_VERSION)
        r.geometry(self.S.get("geometry") or "1120x720")
        r.minsize(1120, 720)
        r.resizable(False, False)
        r.protocol("WM_DELETE_WINDOW", self.on_close)
        r.bind("<F1>", lambda e: self.show_help())
        r.bind("<Key>", self._on_key)

        body = tk.Frame(r)
        body.pack(fill="both", expand=True, padx=10, pady=(10, 4))
        body.grid_rowconfigure(0, weight=1)
        self._build_phone(body)
        self._build_setup(body)
        self._build_test(body)

        self.lbl_status = tk.Label(r, anchor="w", width=150, text="Ready.")
        self.lbl_status.pack(fill="x", padx=12)
        btns = tk.Frame(r)
        btns.pack(fill="x", padx=10, pady=(4, 10))
        tk.Button(btns, text="History...", width=12, command=self.show_history).pack(side="left")
        tk.Button(btns, text="Trend...", width=10, command=self.show_trend).pack(side="left", padx=6)
        tk.Button(btns, text="Optician values...", width=16, command=self.show_refs).pack(side="left")
        tk.Button(btns, text="Quit", width=8, command=self.on_close).pack(side="right")
        tk.Button(btns, text="About", width=8, command=self.show_about_dialog).pack(side="right", padx=6)
        tk.Button(btns, text="Help", width=8, command=self.show_help).pack(side="right")
        tk.Button(btns, text="Notes", width=8, command=self.toggle_notes).pack(side="right", padx=6)

    def _build_phone(self, body):
        f = tk.LabelFrame(body, text=" 1. The phone ", padx=8, pady=6, width=340)
        f.grid(row=0, column=0, sticky="ns", padx=(0, 8))
        f.grid_propagate(False)
        f.pack_propagate(False)
        self.b_session = tk.Button(f, text="Start phone session", width=24, command=self.toggle_session)
        self.b_session.pack(pady=(0, 6))
        self.cv_qr = tk.Canvas(f, width=250, height=250, bg="#f4f4f4", highlightthickness=1, highlightbackground="#bbbbbb")
        self.cv_qr.pack()
        self.lbl_label = tk.Label(f, text="", font=("Segoe UI", 18, "bold"), width=20)
        self.lbl_label.pack(pady=(4, 0))
        self.lbl_addr = tk.Label(f, text="", anchor="w", width=40, fg="#555555")
        self.lbl_addr.pack()
        self.var_addr = tk.StringVar(value="")
        self.ent_addr = new_entry(f, textvariable=self.var_addr, width=40, state="readonly", justify="center")
        self.ent_addr.pack()
        self.lbl_phone = tk.Label(f, text="", justify="left", anchor="nw", width=40, height=5, wraplength=265)
        self.lbl_phone.pack(pady=(2, 4))
        row = tk.Frame(f)
        row.pack()
        self.b_copy = tk.Button(row, text="Copy link", width=12, command=self.copy_link)
        self.b_copy.grid(row=0, column=0, padx=2, pady=2)
        self.b_recal = tk.Button(row, text="Calibrate again", width=12, command=lambda: self.send({"t": "calib"}))
        self.b_recal.grid(row=0, column=1, padx=2, pady=2)
        self.b_ruler = tk.Button(row, text="Ruler check", width=12, command=lambda: self.send({"t": "ruler"}))
        self.b_ruler.grid(row=1, column=0, padx=2, pady=2)
        self.b_sample = tk.Button(row, text="Show a 1.0 letter", width=12, command=self.show_sample)
        self.b_sample.grid(row=1, column=1, padx=2, pady=2)

    def _build_setup(self, body):
        f = tk.LabelFrame(body, text=" 2. Set up ", padx=8, pady=6, width=300)
        f.grid(row=0, column=1, sticky="ns", padx=(0, 8))
        f.grid_propagate(False)
        f.pack_propagate(False)
        tk.Label(f, text="Person (for the history):", anchor="w").pack(fill="x")
        self.var_person = tk.StringVar(value=self.S.get("person", ""))
        new_entry(f, textvariable=self.var_person, width=30).pack(fill="x", pady=(0, 6))
        self.var_eye = tk.StringVar(value=self.S.get("eye", EYES[0]))
        tk.Label(f, text="Eye tested:", anchor="w").pack(fill="x")
        self.rb_eye = []
        for e in EYES:
            rb = tk.Radiobutton(f, text=e, variable=self.var_eye, value=e, anchor="w", command=self.save_soon)
            rb.pack(fill="x")
            self.rb_eye.append(rb)
        tk.Label(f, text="Correction:", anchor="w").pack(fill="x", pady=(6, 0))
        self.var_glasses = tk.StringVar(value=self.S.get("glasses", GLASSES[0]))
        self.cb_glasses = ttk.Combobox(f, textvariable=self.var_glasses, values=GLASSES, state="readonly", width=28)
        self.cb_glasses.pack(fill="x")
        self.cb_glasses.bind("<<ComboboxSelected>>", lambda e: self.save_soon())
        tk.Label(f, text="Chart:", anchor="w").pack(fill="x", pady=(6, 0))
        self.var_kind = tk.StringVar(value=self.S.get("kind", "sloan"))
        self.rb_kind = []
        for k, label in KINDS:
            rb = tk.Radiobutton(f, text=label, variable=self.var_kind, value=k, anchor="w", command=self._kind_changed)
            rb.pack(fill="x")
            self.rb_kind.append(rb)
        tk.Label(f, text="Distance phone - eyes (metres, measured):", anchor="w").pack(fill="x", pady=(6, 0))
        self.var_dist = tk.StringVar(value=self.S.get("distance", "3"))
        self.cb_dist = ttk.Combobox(f, textvariable=self.var_dist, values=DISTANCES, width=8)
        self.cb_dist.pack(anchor="w")
        self.cb_dist.bind("<<ComboboxSelected>>", lambda e: self._refresh())
        self.cb_dist.bind("<KeyRelease>", lambda e: self._refresh())
        self.lbl_geom = tk.Label(f, text="", justify="left", anchor="nw", width=40, height=8, wraplength=270)
        self.lbl_geom.pack(fill="x", pady=(8, 0))

    def _build_test(self, body):
        f = tk.LabelFrame(body, text=" 3. The test ", padx=8, pady=6, width=420)
        f.grid(row=0, column=2, sticky="ns")
        f.grid_propagate(False)
        f.pack_propagate(False)
        self.lbl_prompt = tk.Label(f, text="", font=("Segoe UI", 12, "bold"), anchor="w", justify="left", width=44, height=2, wraplength=390)
        self.lbl_prompt.pack(fill="x")
        self.lbl_progress = tk.Label(f, text="", anchor="w", width=44)
        self.lbl_progress.pack(fill="x")

        pad = tk.Frame(f, height=124)
        pad.pack(fill="x", pady=4)
        pad.pack_propagate(False)
        self.pad_sloan = tk.Frame(pad)
        self.btn_ans = []
        for i, ch in enumerate(SLOAN):
            b = tk.Button(self.pad_sloan, text=ch, width=4, height=1, font=("Segoe UI", 14, "bold"),
                          command=lambda c=ch: self.answer(c))
            b.grid(row=i // 5, column=i % 5, padx=2, pady=2)
            self.btn_ans.append(b)
        b = tk.Button(self.pad_sloan, text="? cannot see", width=26, command=lambda: self.answer(None))
        b.grid(row=2, column=0, columnspan=5, pady=2)
        self.btn_ans.append(b)
        self.pad_landolt = tk.Frame(pad)
        # directions on a 3 x 3 pad: 0 right, 1 up-right, 2 up, 3 up-left, 4 left, 5 down-left, 6 down, 7 down-right
        cells = {(0, 0): (3, u"↖"), (0, 1): (2, u"↑"), (0, 2): (1, u"↗"),
                 (1, 0): (4, u"←"), (1, 2): (0, u"→"),
                 (2, 0): (5, u"↙"), (2, 1): (6, u"↓"), (2, 2): (7, u"↘")}
        for (rr, cc), (d, sym) in cells.items():
            b = tk.Button(self.pad_landolt, text=sym, width=4, font=("Segoe UI", 11, "bold"), command=lambda dd=d: self.answer(dd))
            b.grid(row=rr, column=cc, padx=1, pady=0)
            self.btn_ans.append(b)
        b = tk.Button(self.pad_landolt, text="?", width=4, command=lambda: self.answer(None))
        b.grid(row=1, column=1)
        self.btn_ans.append(b)
        self.pad_landolt.pack_propagate(True)

        row = tk.Frame(f)
        row.pack(fill="x", pady=(4, 6))
        self.b_start = tk.Button(row, text="Start test", width=12, command=self.start_test)
        self.b_start.pack(side="left")
        self.b_undo = tk.Button(row, text="Undo last", width=10, command=self.undo)
        self.b_undo.pack(side="left", padx=6)
        self.b_stop = tk.Button(row, text="Stop", width=8, command=self.stop_test)
        self.b_stop.pack(side="left")

        self.txt_result = new_text(f, width=52, height=16, wrap="word", font=("Segoe UI", 9), state="disabled")
        self.txt_result.pack(fill="x")
        self.cv_plot = tk.Canvas(f, width=390, height=100, bg="#ffffff", highlightthickness=1, highlightbackground="#bbbbbb")
        self.cv_plot.pack(pady=(6, 0))

    # ---- what is possible right now ---------------------------------------------
    def _dist_mm(self):
        try:
            d = float(self.var_dist.get().replace(",", "."))
        except ValueError:
            return None
        return d * 1000.0 if 0.3 <= d <= 10 else None

    def phone_ready(self):
        st = self.phone
        return bool(self.link and st and st.get("calibrated") and st.get("screen") == "chart"
                    and self.phone_age is not None and self.phone_age < 45)

    def _kind_changed(self):
        self.save_soon()
        self._refresh()

    def _refresh(self):
        """Redraws every label and button from the current state (cheap)."""
        testing = self.run is not None and not self.run.done
        # phone panel
        self.b_session.configure(text="End session" if self.link else "Start phone session", state="disabled" if testing else "normal")
        have = bool(self.link)
        for b in (self.b_copy, self.b_recal, self.b_ruler, self.b_sample):
            b.configure(state="normal" if have and not testing else "disabled")
        if have:
            self.lbl_label.configure(text="Code  %s" % pretty_code(self.link.label))
            self.lbl_addr.configure(text="On the phone open this address and type the code:")
            self.var_addr.set(short_address(self.link.base))
        else:
            self.lbl_label.configure(text="")
            self.lbl_addr.configure(text="")
            self.var_addr.set("")
        st = self.phone
        if not have:
            msg = "No session. Press 'Start phone session', then scan the QR code with the phone."
        elif not self.relay_online:
            msg = "Cannot reach the relay - trying again ..."
        elif self.phone_age is None:
            msg = "Waiting for the phone ...\nScan the QR code, or open the address and type the code (works once, for 15 minutes)."
        elif self.phone_age >= 45:
            msg = "The phone has gone quiet (screen off? browser closed?). Wake it up."
        elif not st.get("v"):                      # only the 'joined' note of the relay, no real status yet
            msg = "The phone has joined. Tap Start on the phone (if it asks for the code, type it)."
        elif not st.get("calibrated"):
            msg = "The phone is calibrating: hold a bank card to the screen and make the blue box exactly as wide as the card's edge."
        else:
            msg = ("Phone ready.\nScreen %.0f x %.0f mm, 1 px = %.3f mm.\nFullscreen: %s    Stays awake: %s" % (
                st.get("w_mm", 0), st.get("h_mm", 0), st.get("mmpx", 0), "yes" if st.get("fs") else "no", "yes" if st.get("wake") else "no"))
        self.lbl_phone.configure(text=msg)
        # geometry panel
        d = self._dist_mm()
        if d is None:
            geom = "Type a distance between 0.3 and 10 metres."
        else:
            lines = ["At %.2f m a letter of 1.0 is %.2f mm tall;  0.5 is %.2f mm." % (d / 1000, height_mm(0.0, d), height_mm(0.3, d))]
            if st and st.get("calibrated"):
                lo, hi = feasible_range(d, st)
                lines.append("This phone can show decimal %.2f down to %.2f at this distance." % (decimal_of(lo), decimal_of(hi)))
                if decimal_of(hi) > 0.5:
                    lines.append("Too far for this small screen: move closer.")
                elif decimal_of(lo) < 1.0:
                    lines.append("Too close for sharp small letters: move further away.")
            else:
                lines.append("Calibrate the phone to see what it can show.")
            geom = "\n".join(lines)
        self.lbl_geom.configure(text=geom)
        # test panel
        sloan = self.var_kind.get() == "sloan"
        if sloan:
            self.pad_landolt.pack_forget()
            self.pad_sloan.pack(anchor="center")
        else:
            self.pad_sloan.pack_forget()
            self.pad_landolt.pack(anchor="center")
        for b in self.btn_ans:
            b.configure(state="normal" if testing else "disabled")
        ready = self.phone_ready() and d is not None and not testing
        self.b_start.configure(state="normal" if ready else "disabled")
        self.b_undo.configure(state="normal" if testing and self.run.est.trials else "disabled")
        self.b_stop.configure(state="normal" if testing else "disabled")
        for w in self.rb_eye + self.rb_kind + [self.cb_glasses, self.cb_dist]:
            try:
                w.configure(state="disabled" if testing else ("readonly" if w is self.cb_glasses else "normal"))
            except Exception:
                pass
        if testing:
            n = len(self.run.est.trials)
            self.lbl_prompt.configure(text="What does the person see?  Type the %s." % ("letter" if sloan else "side of the gap"))
            self.lbl_progress.configure(text="Answer %d of about %d" % (n + 1, max(n + 1, self.run.est.expected_total())))
        elif not self.last_result:
            self.lbl_prompt.configure(text="Press 'Start test' when the phone is at the distance." if ready else
                                      "The test starts when the phone is ready and the distance is set.")
            self.lbl_progress.configure(text="")

    # ---- the phone session -----------------------------------------------------
    def toggle_session(self):
        if self.link:
            self.end_session()
            return
        cfg = read_json(RELAY_PATH, None)
        if not isinstance(cfg, dict) or not cfg.get("url") or not cfg.get("key"):
            messagebox.showinfo(PROGRAM_TITLE, "There is no relay file yet.\n\nRun WebdockTool > Jobs > 'Sight test relay' once, then copy "
                                "sight_relay.json into the folder\n%s\non this PC." % PROGRAM_HF_DIR, parent=self.root)
            return
        link = SightLink(cfg["url"], cfg["key"], self.q)
        self.root.config(cursor="watch")
        self.root.update_idletasks()
        try:
            link.open()
        except LinkError as e:
            messagebox.showerror(PROGRAM_TITLE, "Could not start a session:\n\n%s" % e, parent=self.root)
            return
        finally:
            self.root.config(cursor="")
        self.link = link
        self.phone, self.phone_age, self.relay_online = {}, None, True
        if not draw_qr(self.cv_qr, 250, link.phone_url()):
            self.cv_qr.create_text(125, 125, width=220, justify="center",
                                   text="No QR module installed (pip install qrcode).\nPress 'Copy link' and open it on the phone.")
        self.lbl_status.configure(text="Session started. On the phone: scan the QR code, or open the address and type the code %s." % pretty_code(link.label))
        self._refresh()

    def end_session(self):
        if self.run is not None and not self.run.done:
            self.stop_test(ask=False)
        if self.link:
            self.link.close()
        self.link = None
        self.phone, self.phone_age = {}, None
        self.cv_qr.delete("all")
        self.lbl_status.configure(text="Session ended.")
        self._refresh()

    def copy_link(self):
        if self.link:
            self.root.clipboard_clear()
            self.root.clipboard_append(self.link.phone_url())
            self.lbl_status.configure(text="Link copied. Open it on the phone (it works once, for one phone).")

    def send(self, cmd):
        if self.link:
            self.link.send(cmd)

    def show_sample(self):
        d = self._dist_mm()
        if d is None:
            return
        k = self.var_kind.get()
        mm = round(height_mm(0.0, d), 3)
        self.send({"t": "opt", "k": "s", "ch": "H", "mm": mm} if k == "sloan" else {"t": "opt", "k": "c", "dir": 0, "mm": mm})

    def _pump(self):
        """Takes what the link thread has put on the queue (never touches Tk from another thread)."""
        try:
            while True:
                ev = self.q.get_nowait()
                if ev[0] == "status":
                    if ev[1]:
                        self.phone = ev[1]
                    self.phone_age = ev[2]
                elif ev[0] == "online":
                    self.relay_online = ev[1]
                elif ev[0] == "ended":
                    if self.link:
                        self.link.stop.set()
                        self.link = None
                        self.cv_qr.delete("all")
                        self.phone, self.phone_age = {}, None
                        self.lbl_status.configure(text="The session has ended on the server.")
                        if self.run is not None and not self.run.done:
                            self.run.done = True
                self._refresh()
        except queue.Empty:
            pass
        self.root.after(250, self._pump)

    # ---- the test -----------------------------------------------------------------
    def start_test(self):
        d = self._dist_mm()
        if d is None or not self.phone_ready():
            return
        lo, hi = feasible_range(d, self.phone)
        if hi - lo < 0.5:
            messagebox.showwarning(PROGRAM_TITLE, "At this distance the phone can only show a very narrow range of sizes. Move it closer.", parent=self.root)
            return
        eye = self.var_eye.get()
        if eye != EYES[2]:
            cover = "LEFT" if eye == EYES[0] else "RIGHT"
            if not messagebox.askokcancel(PROGRAM_TITLE, "Cover the %s eye with the palm of your hand (without pressing on it).\n\n"
                                          "Press OK when you are ready." % cover, parent=self.root):
                return
        self._collect()
        self.save_soon()
        self.last_result = None
        self.set_result_text("")
        self.cv_plot.delete("all")
        self.run = TestRun(self.var_kind.get(), d, self.phone, self.send, lambda ms, fn: self.root.after(ms, fn))
        self.run.show_next()
        self.root.focus_set()
        self.lbl_status.configure(text="Test running ...")
        self._refresh()

    def answer(self, ans):
        run = self.run
        if run is None or run.done:
            return
        over = run.answer(ans)
        if over:
            self.finish_test()
        self._refresh()

    def undo(self):
        if self.run is not None and not self.run.done:
            self.run.undo()
            self._refresh()

    def stop_test(self, ask=True):
        run = self.run
        if run is None or run.done:
            return
        if ask and run.est.trials and not messagebox.askyesno(PROGRAM_TITLE, "Stop the test? What has been answered so far is not saved.", parent=self.root):
            return
        run.done = True
        run.token += 1
        self.send({"t": "wait"})
        self.run = None
        self.lbl_status.configure(text="Test stopped.")
        self._refresh()

    def finish_test(self):
        run = self.run
        meta = {"person": self.var_person.get().strip(), "eye": self.var_eye.get(), "glasses": self.var_glasses.get(),
                "label": self.link.label if self.link else ""}
        r = run.result(meta)
        self.last_result = r
        older = load_history()
        try:
            save_history(older + [r])
            saved = "Saved in the history."
        except Exception as e:
            saved = "Could NOT save the history: %s" % e
        self.set_result_text(result_text(r, load_refs(), older))
        self.draw_plot(r)
        self.lbl_prompt.configure(text="Test finished.")
        self.lbl_progress.configure(text=saved)
        self.lbl_status.configure(text="Test finished. %s" % saved)
        self.root.after(2500, lambda: self.send({"t": "wait"}))

    def set_result_text(self, text):
        self.txt_result.configure(state="normal")
        self.txt_result.delete("1.0", "end")
        self.txt_result.insert("1.0", text)
        self.txt_result.configure(state="disabled")

    def draw_plot(self, r):
        """Size of every letter that was shown (up = smaller = harder), green = right, red = wrong, line = the estimate."""
        cv = self.cv_plot
        cv.delete("all")
        W, H, L, T, B = 390, 100, 34, 8, 20
        tr = r["trials"]
        if not tr:
            return
        lo, hi = min(t[0] for t in tr + [[r["logmar"], 1]]) - 0.05, max(t[0] for t in tr + [[r["logmar"], 1]]) + 0.05

        def Y(x):
            return T + (x - lo) / max(0.01, hi - lo) * (H - T - B)

        def X(i):
            return L + (i + 0.5) / len(tr) * (W - L - 8)
        cv.create_text(2, T, text="small", anchor="w", font=("Segoe UI", 7), fill="#777777")
        cv.create_text(2, H - B, text="big", anchor="w", font=("Segoe UI", 7), fill="#777777")
        cv.create_line(L - 4, Y(r["logmar"]), W - 4, Y(r["logmar"]), fill="#3366cc", dash=(4, 3))
        for i, t in enumerate(tr):
            col = "#2a9d3f" if t[1] else "#d03030"
            cv.create_oval(X(i) - 4, Y(t[0]) - 4, X(i) + 4, Y(t[0]) + 4, fill=col, outline="")
        cv.create_text(W // 2, H - 8, text="answer number (green = right, red = wrong, dashed = estimate %.2f)" % r["logmar"],
                       font=("Segoe UI", 7), fill="#555555")

    def _on_key(self, e):
        run = self.run
        if run is None or run.done:
            return
        w = self.root.focus_get()
        if w is not None and w.winfo_class() in ("Entry", "TEntry", "TCombobox", "Text"):
            return
        ks, ch = e.keysym, e.char
        if ks in ("BackSpace",):
            self.undo()
            return "break"
        if ks in ("space", "Return", "KP_Enter") or ch == "?":
            self.answer(None)
            return "break"
        if run.kind == "sloan":
            if ch and ch.isalpha():
                self.answer(ch.upper())
                return "break"
        else:
            dirs = {"Right": 0, "Up": 2, "Left": 4, "Down": 6, "KP_6": 0, "KP_9": 1, "KP_8": 2, "KP_7": 3, "KP_4": 4,
                    "KP_1": 5, "KP_2": 6, "KP_3": 7, "KP_Right": 0, "KP_Prior": 1, "KP_Up": 2, "KP_Home": 3, "KP_Left": 4,
                    "KP_End": 5, "KP_Down": 6, "KP_Next": 7}
            if ks in dirs:
                self.answer(dirs[ks])
                return "break"
            if ch in "98741236" and ch:
                self.answer({"6": 0, "9": 1, "8": 2, "7": 3, "4": 4, "1": 5, "2": 6, "3": 7}[ch])
                return "break"

    # ---- windows --------------------------------------------------------------------
    def show_history(self):
        HistoryWindow(self.root)

    def show_trend(self):
        self._collect()
        TrendWindow(self.root, self.S.get("person", ""))

    def show_refs(self):
        self._collect()
        RefWindow(self.root, self.S.get("person", ""))

    def show_help(self):
        show_text_window(self.root, "Help - " + PROGRAM_TITLE, HELP_TEXT)

    def show_about_dialog(self):
        show_about(self.root, PROGRAM_TITLE, "An eye chart on your phone, run from the PC", u"\U0001F441")

    def toggle_notes(self):
        if self.playertext is not None:
            try:
                if self.playertext.top.winfo_exists():
                    self.playertext.close()
                    return
            except Exception:
                pass
        self.S["show_playertext"] = True
        self.playertext = PlayerTextPopup(
            self.root, self.S, ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel"),
            self.save_soon, THEME, "Notes - " + PROGRAM_TITLE, PROGRAM_HF_DIR, lambda: {}, on_closed=lambda: None)

    def on_close(self):
        if self.run is not None and not self.run.done and self.run.est.trials:
            if not messagebox.askyesno(PROGRAM_TITLE, "A test is running. Quit anyway? It is not saved.", parent=self.root):
                return
        try:
            if self.playertext is not None:
                self.playertext.save_now()
        except Exception:
            pass
        if self.link:
            self.link.close()
        try:
            self.S["geometry"] = self.root.geometry()
        except Exception:
            pass
        self.save_now()
        self.root.destroy()


# *************** DEL 17 - START *****************
def main():
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    App(root)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()


if __name__ == "__main__":
    main()
