"""TalkType - talk or SPELL letters and get the text typed into the app you choose,
and (optionally) have every key you press spoken out loud.

EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments, UI, Help).  The only
non-English things are the spoken-word tables in DEL 10 (Swedish / English words
for letters and punctuation): that is DATA the speech recogniser has to match.

Built from TalkType_template.py by build_TalkType.py, which pastes Lars's rule
blocks (home, icon, ui helpers, open, popups, about) in verbatim.
"""
# ToDo: offline recogniser (Vosk) as a second engine; more languages in DEL 10;
# ToDo: "press this key" voice commands (arrows, Ctrl+C) in words mode.

import os
import sys
import re
import json
import time
import shutil
import ctypes
import queue
import platform
import threading
import subprocess
import webbrowser
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, messagebox
from ctypes import wintypes

APP_NAME = "TalkType"
APP_VERSION = "1.0"

try:
    import speech_recognition as sr          # pip install SpeechRecognition PyAudio
except Exception:                            # missing: the window explains it
    sr = None
try:
    import keyboard as kb                    # pip install keyboard (global key hook)
except Exception:
    kb = None
try:
    import win32com.client as _w32           # pip install pywin32 (SAPI voices)
    import pythoncom as _pycom
except Exception:
    _w32 = _pycom = None

# *************** DEL XX - 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 XX - 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 XX - 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 XX - 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 xx - 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 XX - 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
    # Lars's wording since 2026-11-07 (rule 30): ENGLISH in every language
    tk.Label(top, text="Focusing on us instead of cha-ching\nbut if you like " + app_name +
                       ", you are welcome to send a token of appreciation",
             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 10 - SPOKEN WORDS -> ACTIONS (THE SPELLING ENGINE) ********
# Actions are tuples:
#   ("char", "a")   one typed character          ("punct", ".")   punctuation
#   ("space",)      a blank                      ("word", "hello") a normal word
#   ("key", "enter" | "backspace")               ("caps",)  next letter in capitals
#   ("mode", "letters" | "words")                switch spelling / free dictation
# Scope of a vocabulary row: "b" = both modes, "l" = spelling mode only (words
# that are also normal words, like "tom" or "stor", must not fire while you
# dictate normal sentences).

_V_SV = [
    # letters (the names a Swede says, plus what the recogniser tends to return)
    ("l", ("char", "a"), "a|ah|aa"), ("l", ("char", "b"), "b|be|bé|bee"),
    ("l", ("char", "c"), "c|ce|se|sé|ces"), ("l", ("char", "d"), "d|de|dé|dee"),
    ("l", ("char", "e"), "e|eh|ee|é"), ("l", ("char", "f"), "f|eff|ef|äff"),
    ("l", ("char", "g"), "g|ge|gé|ghe"), ("l", ("char", "h"), "h|hå|håå|ho"),
    ("l", ("char", "i"), "i|ii|ie"), ("l", ("char", "j"), "j|ji|jy|jii"),
    ("l", ("char", "k"), "k|ka|kå|kaa"), ("l", ("char", "l"), "l|ell|el|äll"),
    ("l", ("char", "m"), "m|em|ämm|emm"), ("l", ("char", "n"), "n|en|än|enn"),
    ("l", ("char", "o"), "o|oh|oo"), ("l", ("char", "p"), "p|pe|pé|pee"),
    ("l", ("char", "q"), "q|kvå|ku|kv"), ("l", ("char", "r"), "r|er|ärr|err"),
    ("l", ("char", "s"), "s|ess|es|äss"), ("l", ("char", "t"), "t|te|té|tee"),
    ("l", ("char", "u"), "u|uu"), ("l", ("char", "v"), "v|ve|vé|vee"),
    ("l", ("char", "w"), "w|dubbelve|dubbel ve|dubbelt ve|dubbel v|dubbelv"),
    ("l", ("char", "x"), "x|ex|äx|eks|ecs"), ("l", ("char", "y"), "y|yy|ypsilon"),
    ("l", ("char", "z"), "z|zet|zett|säta|zäta|sätt"),
    ("l", ("char", "å"), "å|åå|ååh"), ("l", ("char", "ä"), "ä|ää|äh"),
    ("l", ("char", "ö"), "ö|öö|öh"),
    ("l", ("char", "0"), "noll"), ("l", ("char", "1"), "ett"),
    ("l", ("char", "2"), "två"), ("l", ("char", "3"), "tre"),
    ("l", ("char", "4"), "fyra"), ("l", ("char", "5"), "fem"),
    ("l", ("char", "6"), "sex"), ("l", ("char", "7"), "sju"),
    ("l", ("char", "8"), "åtta"), ("l", ("char", "9"), "nio"),
    # blank
    ("l", ("space",), "blank|blanksteg|blank steg|mellanslag|mellan slag|mellan|tom|space"),
    # punctuation and symbols
    ("b", ("punct", "."), "punkt|punkten|prick"), ("b", ("punct", ","), "komma"),
    ("b", ("punct", "?"), "frågetecken|fråga tecken|fråge tecken"),
    ("b", ("punct", "!"), "utropstecken|utrops tecken"),
    ("b", ("punct", ":"), "kolon"), ("b", ("punct", ";"), "semikolon"),
    ("b", ("punct", "-"), "bindestreck|bindes streck"),
    ("l", ("punct", "-"), "streck|minus"),
    ("b", ("punct", "_"), "understreck|under streck"),
    ("b", ("punct", "@"), "snabel a|snabela|snabel"), ("l", ("punct", "@"), "at"),
    ("b", ("punct", "/"), "snedstreck|sned streck"),
    ("b", ("punct", "'"), "apostrof"), ("b", ("punct", '"'), "citattecken|citat tecken"),
    # editing
    ("b", ("key", "enter"), "ny rad|nyrad|radbrytning"), ("l", ("key", "enter"), "enter|retur"),
    ("b", ("key", "backspace"), "radera"), ("l", ("key", "backspace"), "ta bort|bort|backa|backsteg"),
    ("b", ("caps",), "stor bokstav|stora bokstaven"), ("l", ("caps",), "stor|versal"),
    # modes
    ("b", ("mode", "letters"), "bokstavsläge|bokstavs läge|stava|bokstäver"),
    ("b", ("mode", "words"), "ordläge|ord läge|vanligt tal|fri text"),
    ("l", ("mode", "words"), "ord"),
]

_V_EN = [
    ("l", ("char", "a"), "a|ay|eh"), ("l", ("char", "b"), "b|be|bee"),
    ("l", ("char", "c"), "c|see|sea|cee"), ("l", ("char", "d"), "d|dee"),
    ("l", ("char", "e"), "e|ee"), ("l", ("char", "f"), "f|ef|eff"),
    ("l", ("char", "g"), "g|gee|jee"), ("l", ("char", "h"), "h|aitch|age"),
    ("l", ("char", "i"), "i|eye|aye"), ("l", ("char", "j"), "j|jay"),
    ("l", ("char", "k"), "k|kay|okay"), ("l", ("char", "l"), "l|el|ell"),
    ("l", ("char", "m"), "m|em"), ("l", ("char", "n"), "n|en"),
    ("l", ("char", "o"), "o|oh"), ("l", ("char", "p"), "p|pee|pea"),
    ("l", ("char", "q"), "q|cue|queue"), ("l", ("char", "r"), "r|ar|are"),
    ("l", ("char", "s"), "s|ess|es"), ("l", ("char", "t"), "t|tee|tea"),
    ("l", ("char", "u"), "u|you"), ("l", ("char", "v"), "v|vee"),
    ("l", ("char", "w"), "w|double u|double you"), ("l", ("char", "x"), "x|ex"),
    ("l", ("char", "y"), "y|why"), ("l", ("char", "z"), "z|zee|zed"),
    ("l", ("char", "0"), "zero"), ("l", ("char", "1"), "one"), ("l", ("char", "2"), "two"),
    ("l", ("char", "3"), "three"), ("l", ("char", "4"), "four"), ("l", ("char", "5"), "five"),
    ("l", ("char", "6"), "six"), ("l", ("char", "7"), "seven"), ("l", ("char", "8"), "eight"),
    ("l", ("char", "9"), "nine"),
    ("l", ("space",), "blank|space|spacebar|space bar"),
    ("b", ("punct", "."), "period|full stop|dot"), ("b", ("punct", ","), "comma"),
    ("b", ("punct", "?"), "question mark"), ("b", ("punct", "!"), "exclamation mark|exclamation point"),
    ("b", ("punct", ":"), "colon"), ("b", ("punct", ";"), "semicolon"),
    ("b", ("punct", "-"), "hyphen|dash"), ("b", ("punct", "_"), "underscore"),
    ("b", ("punct", "@"), "at sign"), ("b", ("punct", "/"), "slash"),
    ("b", ("punct", "'"), "apostrophe"), ("b", ("punct", '"'), "quote|quotation mark"),
    ("b", ("key", "enter"), "new line|newline|new paragraph"), ("l", ("key", "enter"), "enter|return"),
    ("b", ("key", "backspace"), "backspace|delete that"), ("l", ("key", "backspace"), "delete|back"),
    ("b", ("caps",), "capital letter|capitalize"), ("l", ("caps",), "capital|cap|shift"),
    ("b", ("mode", "letters"), "spelling mode|letter mode|letters mode"),
    ("b", ("mode", "words"), "word mode|words mode|dictation mode"),
]

# Languages the recogniser may be asked for -> vocabulary and key-name language.
LANGUAGES = [("sv-SE", "Swedish"), ("en-US", "English (US)"), ("en-GB", "English (UK)")]
_SYMBOLS = ".,;:!?@-_'\"/"


def _build_vocab(rows, scope):
    """phrase -> action for one mode ("l" or "w")."""
    out = {}
    for sc, action, variants in rows:
        if sc != "b" and sc != ("l" if scope == "l" else "never"):
            continue
        for v in variants.split("|"):
            out[v] = action
    return out


VOCAB = {}
for _code, _rows in (("sv", _V_SV), ("en", _V_EN)):
    VOCAB[_code] = {"l": _build_vocab(_rows, "l"), "w": _build_vocab(_rows, "w")}


def lang_family(lang_code):
    return "sv" if str(lang_code).lower().startswith("sv") else "en"


def _tokens(text):
    """Split a recognised phrase into lowercase tokens (symbols kept as they are)."""
    out = []
    for raw in str(text).replace("–", "-").split():
        if raw in _SYMBOLS:
            out.append(raw)
            continue
        t = raw.lower().strip(".,;:!?\"'()[]{}")
        t = t.replace("-", " ").replace("_", " ")
        out.extend(t.split())
    return out


def _spell_word(tok):
    return [("char", c) for c in tok if c.isalnum()]


def parse_letters(text, lang, spell_merged=True):
    """Spelling mode.  Returns (actions, unknown_tokens, known_count)."""
    vocab = VOCAB[lang_family(lang)]["l"]
    toks = _tokens(text)
    acts, unknown, known = [], [], 0
    i = 0
    while i < len(toks):
        hit = None
        for n in (3, 2, 1):
            ph = " ".join(toks[i:i + n])
            if ph in vocab:
                hit = (vocab[ph], n)
                break
        if hit:
            acts.append(hit[0])
            known += 1
            i += hit[1]
            continue
        t = toks[i]
        i += 1
        if t in _SYMBOLS:
            acts.append(("punct", t))
            known += 1
        elif len(t) == 1 and t.isalnum():
            acts.append(("char", t))                    # the recogniser wrote the letter itself
            known += 1
        elif t.isdigit():
            acts.extend(_spell_word(t))
            known += 1
        elif spell_merged and t.isalpha():
            acts.extend(_spell_word(t))                 # "jag" -> j a g (merged letters)
        else:
            unknown.append(t)
    return acts, unknown, known


def parse_words(text, lang):
    """Free dictation: normal words, plus a few spoken commands (full stop, comma ...)."""
    vocab = VOCAB[lang_family(lang)]["w"]
    raw = str(text).split()
    low = [re.sub(r"[.,;:!?\"'()]", "", r.lower()) for r in raw]
    acts, i = [], 0
    while i < len(raw):
        hit = None
        for n in (3, 2, 1):
            ph = " ".join(low[i:i + n])
            if ph in vocab:
                hit = (vocab[ph], n)
                break
        if hit:
            acts.append(hit[0])
            i += hit[1]
        else:
            acts.append(("word", raw[i]))
            i += 1
    return acts


def best_parse(alternatives, mode, lang, spell_merged=True):
    """Pick the best of the recogniser's alternatives.  Returns (actions, unknown, text)."""
    alts = [a for a in alternatives if a and str(a).strip()]
    if not alts:
        return [], [], ""
    if mode == "words":
        return parse_words(alts[0], lang), [], alts[0]
    best = None
    for rank, a in enumerate(alts):
        acts, unk, known = parse_letters(a, lang, spell_merged)
        toks = max(1, len(_tokens(a)))
        score = (len(unk), -(known / toks), rank)         # fewest unknown, most real letter names
        if best is None or score < best[0]:
            best = (score, acts, unk, a)
    return best[1], best[2], best[3]


class Composer(object):
    """Turns actions into typing operations and keeps track of spacing / capitals."""

    def __init__(self, mode="letters", cap_after_stop=True):
        self.mode, self.cap_after_stop = mode, cap_after_stop
        self.reset()

    def reset(self):
        self.last = "none"            # none | letter | space | word | punct
        self.caps = False             # next letter in capitals
        self.start = True             # at the start of a sentence

    def feed(self, actions):
        """-> list of ("type", text) | ("key", name) | ("mode", name)"""
        ops = []
        for a in actions:
            k = a[0]
            if k == "char":
                c = a[1]
                if self.caps and c.isalpha():
                    c, self.caps = c.upper(), False
                ops.append(("type", c))
                self.last, self.start = "letter", False
            elif k == "space":
                ops.append(("type", " "))
                self.last = "space"
            elif k == "word":
                w = a[1]
                if self.cap_after_stop and self.start and w:
                    w = w[0].upper() + w[1:]
                if self.caps and w:
                    w, self.caps = w[0].upper() + w[1:], False
                ops.append(("type", (" " if self.last in ("word", "punct", "letter") else "") + w))
                self.last, self.start = "word", False
            elif k == "punct":
                ops.append(("type", a[1]))
                self.last = "punct" if self.mode == "words" else "letter"
                self.start = a[1] in ".!?"
            elif k == "key":
                ops.append(("key", a[1]))
                if a[1] == "enter":
                    self.last, self.start = "none", True
            elif k == "caps":
                self.caps = True
            elif k == "mode":
                self.mode = a[1]
                ops.append(("mode", a[1]))
        return ops


# *************** DEL 11 - KEY NAMES FOR THE VOICE ******************************
_KEYNAMES = {
    "sv": {"space": "mellanslag", "enter": "retur", "backspace": "backsteg", "tab": "tabb",
           "esc": "escape", "shift": "skift", "ctrl": "kontroll", "alt": "alt", "alt gr": "alt gr",
           "left windows": "windows", "right windows": "windows", "windows": "windows",
           "caps lock": "versallås", "delete": "radera", "insert": "infoga", "home": "hem",
           "end": "slut", "page up": "sida upp", "page down": "sida ner", "up": "pil upp",
           "down": "pil ner", "left": "pil vänster", "right": "pil höger",
           "print screen": "print screen", "scroll lock": "scroll lock", "pause": "paus",
           "num lock": "num lock", "menu": "meny", "apps": "meny",
           ".": "punkt", ",": "komma", "-": "bindestreck", "+": "plus", "/": "snedstreck",
           "*": "stjärna", "=": "lika med", "'": "apostrof", ";": "semikolon", ":": "kolon",
           "\\": "omvänt snedstreck", "<": "mindre än", ">": "större än", "@": "snabel a",
           "decimal": "decimalkomma"},
    "en": {"space": "space", "enter": "enter", "backspace": "backspace", "tab": "tab",
           "esc": "escape", "shift": "shift", "ctrl": "control", "alt": "alt", "alt gr": "alt graph",
           "left windows": "windows", "right windows": "windows", "windows": "windows",
           "caps lock": "caps lock", "delete": "delete", "insert": "insert", "home": "home",
           "end": "end", "page up": "page up", "page down": "page down", "up": "up arrow",
           "down": "down arrow", "left": "left arrow", "right": "right arrow",
           "print screen": "print screen", "scroll lock": "scroll lock", "pause": "pause",
           "num lock": "num lock", "menu": "menu", "apps": "menu",
           ".": "period", ",": "comma", "-": "hyphen", "+": "plus", "/": "slash",
           "*": "star", "=": "equals", "'": "apostrophe", ";": "semicolon", ":": "colon",
           "\\": "backslash", "<": "less than", ">": "greater than", "@": "at sign",
           "decimal": "decimal point"},
}
_MODIFIERS = {"shift", "ctrl", "alt", "alt gr", "left windows", "right windows", "windows",
              "left shift", "right shift", "left ctrl", "right ctrl", "left alt", "right alt"}


def key_category(name):
    """letters | mods | special for a key name from the keyboard module."""
    n = str(name or "").lower()
    if n in _MODIFIERS:
        return "mods"
    if len(n) == 1 and n.isalnum():
        return "letters"
    return "special"


def key_spoken(name, family):
    """What to say for a key.  Letters and digits are said as they are."""
    n = str(name or "").lower()
    for pre in ("left ", "right "):
        if n.startswith(pre) and n[len(pre):] in ("shift", "ctrl", "alt"):
            n = n[len(pre):]
    return _KEYNAMES.get(family, _KEYNAMES["en"]).get(n, n)


# *************** DEL 12 - TYPING INTO OTHER PROGRAMS (SendInput) ***************
ULONG_PTR = ctypes.c_size_t


class _MOUSEINPUT(ctypes.Structure):
    _fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD),
                ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)]


class _KEYBDINPUT(ctypes.Structure):
    _fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD),
                ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)]


class _HARDWAREINPUT(ctypes.Structure):
    _fields_ = [("uMsg", wintypes.DWORD), ("wParamL", wintypes.WORD), ("wParamH", wintypes.WORD)]


class _INPUTUNION(ctypes.Union):
    _fields_ = [("mi", _MOUSEINPUT), ("ki", _KEYBDINPUT), ("hi", _HARDWAREINPUT)]


class _INPUT(ctypes.Structure):
    _fields_ = [("type", wintypes.DWORD), ("u", _INPUTUNION)]


_VK = {"enter": 0x0D, "backspace": 0x08, "tab": 0x09}
KEYEVENTF_KEYUP, KEYEVENTF_UNICODE = 0x0002, 0x0004


def _user32():
    u = ctypes.windll.user32
    u.SendInput.argtypes = [wintypes.UINT, ctypes.POINTER(_INPUT), ctypes.c_int]
    u.SendInput.restype = wintypes.UINT
    u.GetForegroundWindow.restype = wintypes.HWND
    u.SetForegroundWindow.argtypes = [wintypes.HWND]
    u.IsWindowVisible.argtypes = [wintypes.HWND]
    u.IsIconic.argtypes = [wintypes.HWND]
    u.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]
    u.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
    u.GetWindowTextLengthW.argtypes = [wintypes.HWND]
    return u


def list_windows(own_hwnd=0):
    """[(hwnd, title)] of the visible top-level windows with a title."""
    u = _user32()
    found = []
    PROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)

    def cb(hwnd, _lp):
        try:
            if hwnd and hwnd != own_hwnd and u.IsWindowVisible(hwnd):
                n = u.GetWindowTextLengthW(hwnd)
                if n > 0:
                    buf = ctypes.create_unicode_buffer(n + 1)
                    u.GetWindowTextW(hwnd, buf, n + 1)
                    if buf.value.strip() and buf.value != "Program Manager":
                        found.append((int(hwnd), buf.value))
        except Exception:
            pass
        return True
    try:
        u.EnumWindows(PROC(cb), 0)
    except Exception:
        pass
    return found


class Typer(object):
    """Types text and keys into the window in front (or brings a chosen window to the front first)."""

    def __init__(self):
        self.u = _user32()
        self.quiet_until = 0.0          # the key echo ignores our own typing until then

    def busy(self):
        return time.time() < self.quiet_until

    def foreground(self):
        return int(self.u.GetForegroundWindow() or 0)

    def bring_to_front(self, hwnd):
        """True when `hwnd` is in front afterwards."""
        try:
            if self.foreground() == hwnd:
                return True
            if self.u.IsIconic(hwnd):
                self.u.ShowWindow(hwnd, 9)              # SW_RESTORE
            self.u.SetForegroundWindow(hwnd)
            for _ in range(6):
                time.sleep(0.03)
                if self.foreground() == hwnd:
                    return True
            # Windows only lets the program that got the last input take the front.
            # Second try: join the input queue of the window that has it now.
            k32 = ctypes.windll.kernel32
            fg = self.foreground()
            t_fg = self.u.GetWindowThreadProcessId(fg, None) if fg else 0
            t_me = k32.GetCurrentThreadId()
            if t_fg and t_fg != t_me:
                self.u.AttachThreadInput(t_me, t_fg, True)
            try:
                self.u.BringWindowToTop(hwnd)
                self.u.SetForegroundWindow(hwnd)
            finally:
                if t_fg and t_fg != t_me:
                    self.u.AttachThreadInput(t_me, t_fg, False)
            for _ in range(10):
                time.sleep(0.03)
                if self.foreground() == hwnd:
                    return True
        except Exception:
            pass
        return self.foreground() == hwnd

    def _send(self, vk=0, scan=0, flags=0):
        inp = _INPUT(type=1)
        inp.u.ki = _KEYBDINPUT(wVk=vk, wScan=scan, dwFlags=flags, time=0, dwExtraInfo=0)
        self.u.SendInput(1, ctypes.byref(inp), ctypes.sizeof(_INPUT))

    def key(self, name):
        vk = _VK.get(name)
        if not vk:
            return
        self.quiet_until = time.time() + 0.35
        self._send(vk=vk)
        self._send(vk=vk, flags=KEYEVENTF_KEYUP)

    def text(self, s):
        self.quiet_until = time.time() + 0.35 + 0.002 * len(s)
        for ch in s:
            if ch == "\n":
                self.key("enter")
                continue
            if ch == "\t":
                self.key("tab")
                continue
            data = ch.encode("utf-16-le")
            for i in range(0, len(data), 2):
                unit = data[i] | (data[i + 1] << 8)
                self._send(scan=unit, flags=KEYEVENTF_UNICODE)
                self._send(scan=unit, flags=KEYEVENTF_UNICODE | KEYEVENTF_KEYUP)
            time.sleep(0.002)
        self.quiet_until = time.time() + 0.35


# *************** DEL 13 - TEXT TO SPEECH (WINDOWS SAPI VOICE) ******************
class Speaker(object):
    """Speaks short texts on its own thread (COM stays in that thread)."""

    def __init__(self):
        self.q = queue.Queue()
        self.ready = threading.Event()
        self.voices = []                  # [(name, language-id-string)]
        self.error = ""
        if _w32 is None:
            self.error = "pywin32 is not installed (pip install pywin32)"
            self.ready.set()
            return
        threading.Thread(target=self._run, daemon=True).start()

    def _run(self):
        try:
            _pycom.CoInitialize()
            voice = _w32.Dispatch("SAPI.SpVoice")
            vs = voice.GetVoices()
            for i in range(vs.Count):
                v = vs.Item(i)
                try:
                    lang = v.GetAttribute("Language")
                except Exception:
                    lang = ""
                self.voices.append((v.GetDescription(), str(lang).lower()))
        except Exception as e:
            self.error = "No speech voice: %s" % e
            self.ready.set()
            return
        self.ready.set()
        while True:
            item = self.q.get()
            try:
                if item[0] == "quit":
                    return
                if item[0] == "set":
                    _, name, rate, vol = item
                    if name:
                        for i in range(vs.Count):
                            if vs.Item(i).GetDescription() == name:
                                voice.Voice = vs.Item(i)
                                break
                    voice.Rate = int(rate)
                    voice.Volume = int(vol)
                elif item[0] == "say":
                    # 1 = async, 2 = purge what is still being said
                    voice.Speak(item[1], 1 | (2 if item[2] else 0))
                elif item[0] == "stop":
                    voice.Speak("", 2)
            except Exception:
                pass

    def configure(self, voice_name, rate, volume):
        self.q.put(("set", voice_name, rate, volume))

    def say(self, text, interrupt=True):
        if text:
            self.q.put(("say", str(text), interrupt))

    def stop(self):
        self.q.put(("stop",))

    def quit(self):
        self.q.put(("quit",))

    def lang_of(self, voice_name):
        for n, l in self.voices:
            if n == voice_name:
                return l
        return ""


# *************** DEL 14 - LISTENING (MICROPHONE + SPEECH RECOGNISER) ***********
def fix_name(s):
    """PyAudio names arrive as UTF-8 read as cp1252 ("HÃ¶gtalare")."""
    try:
        return s.encode("cp1252").decode("utf-8")
    except Exception:
        return s


def list_microphones():
    """[(index, name)] of the input devices (index None = the Windows default)."""
    out = [(None, "(Windows default microphone)")]
    try:
        import pyaudio
        pa = pyaudio.PyAudio()
        try:
            for i in range(pa.get_device_count()):
                info = pa.get_device_info_by_index(i)
                if info.get("maxInputChannels", 0) > 0:
                    out.append((i, fix_name(str(info.get("name", i)))))
        finally:
            pa.terminate()
    except Exception:
        pass
    return out


class Listener(object):
    """One thread listens for phrases, one sends them to the recogniser, in order."""

    def __init__(self, out_q):
        self.out = out_q
        self.running = False
        self.audio_q = queue.Queue()

    def start(self, mic_index, lang, pause):
        if self.running:
            return
        self.running = True
        threading.Thread(target=self._listen, args=(mic_index, pause), daemon=True).start()
        threading.Thread(target=self._recognise, args=(lang,), daemon=True).start()

    def stop(self):
        self.running = False

    def _listen(self, mic_index, pause):
        try:
            r = sr.Recognizer()
            r.pause_threshold = max(0.3, float(pause))
            r.non_speaking_duration = min(0.3, r.pause_threshold)
            r.dynamic_energy_threshold = True
            with sr.Microphone(device_index=mic_index) as src:
                self.out.put(("status", "Adjusting to the room noise ..."))
                r.adjust_for_ambient_noise(src, duration=0.6)
                self.out.put(("status", "Listening"))
                while self.running:
                    try:
                        audio = r.listen(src, timeout=1, phrase_time_limit=10)
                    except sr.WaitTimeoutError:
                        continue
                    self.audio_q.put((r, audio))
        except Exception as e:
            self.out.put(("error", "Microphone problem: %s" % e))
            self.running = False
            self.out.put(("stopped",))

    def _recognise(self, lang):
        while self.running or not self.audio_q.empty():
            try:
                r, audio = self.audio_q.get(timeout=0.5)
            except queue.Empty:
                continue
            if not self.running:
                continue
            self.out.put(("status", "Recognising ..."))
            try:
                res = r.recognize_google(audio, language=lang, show_all=True)
                alts = [a.get("transcript", "") for a in (res or {}).get("alternative", [])] \
                    if isinstance(res, dict) else []
                self.out.put(("heard", alts))
            except sr.RequestError as e:
                self.out.put(("error", "The speech service cannot be reached (internet?): %s" % e))
            except Exception as e:
                self.out.put(("error", "Recognition failed: %s" % e))
            if self.running:
                self.out.put(("status", "Listening"))


# *************** DEL 15 - SETTINGS *********************************************
SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")
DEFAULTS = {
    "lang": "sv-SE", "mic": "", "mode": "letters", "target": "active", "target_title": "",
    "cap_after_stop": True, "spell_merged": True, "readback": False, "pause": 0.7,
    "echo_on": False, "echo_letters": True, "echo_special": True, "echo_mods": False,
    "echo_words": False, "interrupt": True, "voice": "", "rate": 0, "volume": 100,
    "key_lang": "auto", "hotkey": "f9",
    "show_playtext": False, "playtext_pos": None, "playtext_zoom": 100, "playtext_sel": "",
}


def load_settings():
    s = dict(DEFAULTS)
    try:
        with open(SETTINGS_FILE, encoding="utf-8") as fh:
            s.update(json.load(fh) or {})
    except Exception:
        pass
    return s


def save_settings(s):
    try:
        os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
        tmp = SETTINGS_FILE + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(s, fh, indent=2)
        os.replace(tmp, SETTINGS_FILE)
    except Exception:
        pass


# *************** DEL 16 - HELP TEXT ********************************************
HELP_TEXT = """TalkType - talk, or spell letter by letter, and get the text in the app you choose.
It can also say out loud every key you press.

START
  1. Pick the language you speak (Swedish or English) and your microphone.
  2. Press  Start listening  (or the hotkey, F9 by default - it works from any program).
  3. Click into the app where the text should go (or choose that app under "Type into").
  4. Speak.  Each phrase is typed when you stop talking for a moment.
  The speech is recognised by an online service, so the computer needs internet.

SPELLING MODE (one letter at a time)
  Say the letter names with a short pause, or all in one go:
      "j  a  g   blank   ä  r   blank   h  u  n  g  r  i  g"   ->   jag är hungrig
  Swedish words:  blank / mellanslag / tom = space,  punkt = .,  komma = ,,
      frågetecken = ?,  utropstecken = !,  kolon = :,  bindestreck = -,  snabel a = @,
      ny rad / enter = new line,  radera / ta bort = backspace,  stor = next letter capital,
      noll, ett, två ... nio = digits.
  English words:  blank / space,  period,  comma,  question mark,  new line,  delete,  capital ...
  If the recogniser glues letters into a word ("jag") TalkType spells it out for you
  (setting "Spell out words the recogniser glued together").

WORDS MODE (normal dictation)
  Just talk.  Say "punkt", "komma", "frågetecken", "utropstecken" or "ny rad" for punctuation
  (English: period, comma, question mark ...).  Sentences get a capital letter after a full stop.

SWITCH MODE BY VOICE
  Say "bokstavsläge" (or "stava") for spelling mode, and "ordläge" (or "vanligt tal") for words mode.
  English: "spelling mode" and "word mode".

TYPE INTO
  Active window: the text goes where your cursor is.  If TalkType itself is in front, the text goes
  into the Preview box instead (good for trying it out).
  Chosen window: pick a program in the list; TalkType brings it to the front before it types.
  If that fails (Windows sometimes refuses), nothing is typed and the log says so.

SAY THE KEYS I PRESS
  Tick "Say the keys".  Choose which keys: letters and digits, special keys (Space, Enter,
  Backspace, arrows ...), and Shift/Ctrl/Alt/Windows.  "Say the whole word when I press Space"
  reads each word you have typed.  "Read back what I said" speaks the dictated text.
  The voice list shows the voices Windows has; a Swedish voice is added in Windows Settings >
  Time & language > Speech.  Key names can be Swedish or English (auto = follows the voice).
  TalkType's own typing is never read back as key presses.

NOTES
  Opens a small notepad inside the program for your own texts (saved by itself).
  Everything is also kept in the log at the bottom.  Escape closes this Help.
"""


# *************** DEL 17 - MAIN WINDOW ******************************************
THEME = dict(bg="#1e1e2e", panel="#252535", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
             btn="#3a3a4e", btnfg="#e0e0e0", field="#14141f", field_fg="#e0e0e0",
             good="#a6e3a1", bad="#f38ba8")


class App(object):
    W, H = 900, 760

    def __init__(self, root):
        self.root = root
        self.S = load_settings()
        self.ui_q = queue.Queue()
        self.typer = Typer()
        self.speaker = Speaker()
        self.listener = Listener(self.ui_q)
        self.composer = Composer(self.S["mode"], self.S["cap_after_stop"])
        self.windows = {}                       # label -> hwnd
        self.mics = []
        self.word_buf = ""
        self.down = set()
        self.hotkey_handle = None
        self.playtext = None
        self.own_hwnd = 0
        self.vars = {}
        self._build()
        self.speaker.ready.wait(3)
        self._fill_voices()
        self._apply_voice()
        self._setup_hooks()
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.after(80, self._poll)
        root.after(400, self._find_own_hwnd)
        self.log("TalkType %s ready.  Hotkey %s starts/stops listening." % (APP_VERSION, self.S["hotkey"].upper()))
        for what, mod in (("SpeechRecognition + PyAudio", sr), ("keyboard", kb)):
            if mod is None:
                self.log("MISSING: %s - see Help / install with pip." % what, "bad")
        if self.speaker.error:
            self.log(self.speaker.error, "bad")

    # ---- small widget helpers -------------------------------------------------
    def _var(self, key, kind="s"):
        v = {"s": tk.StringVar, "b": tk.BooleanVar, "d": tk.DoubleVar, "i": tk.IntVar}[kind](value=self.S[key])
        self.vars[key] = v
        v.trace_add("write", lambda *a, k=key, vv=v: self._changed(k, vv))
        return v

    def _changed(self, key, var):
        try:
            self.S[key] = var.get()
        except Exception:
            return
        save_settings(self.S)
        if key == "mode":
            self.composer.mode = self.S["mode"]
            self.composer.reset()
        elif key == "cap_after_stop":
            self.composer.cap_after_stop = bool(self.S[key])
        elif key in ("voice", "rate", "volume"):
            self._apply_voice()
        elif key == "hotkey":
            self._setup_hotkey()
        elif key in ("target",):
            self._target_changed()

    def _lbl(self, parent, text, **kw):
        return tk.Label(parent, text=text, bg=parent.cget("bg"), fg=kw.pop("fg", THEME["fg"]),
                        font=kw.pop("font", ("Segoe UI", 9)), anchor="w", **kw)

    def _chk(self, parent, text, key, **grid):
        c = tk.Checkbutton(parent, text=text, variable=self._var(key, "b"), bg=parent.cget("bg"),
                           fg=THEME["fg"], selectcolor=THEME["field"], activebackground=parent.cget("bg"),
                           activeforeground=THEME["fg"], anchor="w", font=("Segoe UI", 9))
        grid.setdefault("sticky", "w")
        c.grid(**grid)
        return c

    def _btn(self, parent, text, cmd, w=12):
        return tk.Button(parent, text=text, command=cmd, width=w, bg=THEME["btn"], fg=THEME["btnfg"],
                         activebackground=THEME["accent"], relief="flat", font=("Segoe UI", 9))

    def _combo(self, parent, var, width):
        return ttk.Combobox(parent, textvariable=var, state="readonly", width=width)

    def _box(self, parent, title):
        f = tk.LabelFrame(parent, text=" " + title + " ", bg=THEME["bg"], fg=THEME["accent"],
                          font=("Segoe UI", 9, "bold"), bd=1, relief="groove", padx=8, pady=6)
        return f

    # ---- layout ---------------------------------------------------------------
    def _build(self):
        r = self.root
        r.title(APP_NAME + " " + APP_VERSION)
        r.configure(bg=THEME["bg"])
        r.geometry("%dx%d" % (self.W, self.H))
        r.resizable(False, False)
        style = ttk.Style()
        try:
            style.theme_use("clam")
        except Exception:
            pass
        style.configure("TCombobox", fieldbackground=THEME["field"], background=THEME["btn"],
                        foreground=THEME["field_fg"], arrowcolor=THEME["fg"])

        top = tk.Frame(r, bg=THEME["bg"])
        top.place(x=10, y=8, width=self.W - 20, height=56)
        self.btn_listen = tk.Button(top, text="Start listening", width=18, height=2, command=self.toggle,
                                    bg=THEME["good"], fg="#14141f", relief="flat",
                                    font=("Segoe UI", 11, "bold"))
        self.btn_listen.pack(side="left")
        self.lbl_status = tk.Label(top, text="Idle", bg=THEME["bg"], fg=THEME["dim"], width=34, anchor="w",
                                   font=("Segoe UI", 11))
        self.lbl_status.pack(side="left", padx=14)
        for text, cmd in (("Notes", self.open_notes), ("Help", self.show_help), ("About", self.about)):
            self._btn(top, text, cmd, 8).pack(side="right", padx=3)

        # speech to text -------------------------------------------------------
        a = self._box(r, "Speech to text")
        a.place(x=10, y=70, width=self.W - 20, height=224)
        a.grid_columnconfigure(1, weight=1)
        self._lbl(a, "Language").grid(row=0, column=0, sticky="w")
        self.cb_lang = self._combo(a, self._var("lang"), 22)
        self.cb_lang["values"] = [c for c, n in LANGUAGES]
        self.cb_lang.grid(row=0, column=1, sticky="w", padx=6)
        self._lbl(a, "Microphone").grid(row=0, column=2, sticky="w", padx=(18, 0))
        self.cb_mic = self._combo(a, self._var("mic"), 44)
        self.cb_mic.grid(row=0, column=3, sticky="w", padx=6)
        self.mics = list_microphones()
        self.cb_mic["values"] = [n for i, n in self.mics]
        if self.S["mic"] not in self.cb_mic["values"]:
            self.vars["mic"].set(self.mics[0][1])

        self._lbl(a, "Mode").grid(row=1, column=0, sticky="w", pady=(6, 0))
        mf = tk.Frame(a, bg=THEME["bg"])
        mf.grid(row=1, column=1, columnspan=3, sticky="w", pady=(6, 0))
        self._var("mode")
        for text, val in (("Spell letter by letter", "letters"), ("Normal words", "words")):
            tk.Radiobutton(mf, text=text, value=val, variable=self.vars["mode"], bg=THEME["bg"],
                           fg=THEME["fg"], selectcolor=THEME["field"], activebackground=THEME["bg"],
                           activeforeground=THEME["fg"], font=("Segoe UI", 9)).pack(side="left", padx=(0, 18))

        self._lbl(a, "Type into").grid(row=2, column=0, sticky="w", pady=(6, 0))
        tf = tk.Frame(a, bg=THEME["bg"])
        tf.grid(row=2, column=1, columnspan=3, sticky="w", pady=(6, 0))
        self._var("target")
        for text, val in (("Active window", "active"), ("Chosen window:", "window")):
            tk.Radiobutton(tf, text=text, value=val, variable=self.vars["target"], bg=THEME["bg"],
                           fg=THEME["fg"], selectcolor=THEME["field"], activebackground=THEME["bg"],
                           activeforeground=THEME["fg"], font=("Segoe UI", 9)).pack(side="left", padx=(0, 8))
        self.cb_win = self._combo(tf, self._var("target_title"), 52)
        self.cb_win.pack(side="left", padx=4)
        self.cb_win.bind("<Button-1>", lambda e: self.refresh_windows())
        self._btn(tf, "Refresh", self.refresh_windows, 8).pack(side="left", padx=4)

        self._chk(a, "Capital letter after a full stop (words mode)", "cap_after_stop", row=3, column=0, columnspan=3, pady=(6, 0))
        self._chk(a, "Spell out words the recogniser glued together (\"jag\" -> j a g)", "spell_merged", row=3, column=3, pady=(6, 0))
        self._chk(a, "Read back what was typed", "readback", row=4, column=0, columnspan=3)
        pf = tk.Frame(a, bg=THEME["bg"])
        pf.grid(row=4, column=3, sticky="w")
        self._lbl(pf, "Pause that ends a phrase (s)").pack(side="left")
        sp = tk.Spinbox(pf, from_=0.3, to=2.0, increment=0.1, width=5, textvariable=self._var("pause", "d"),
                        bg=THEME["field"], fg=THEME["field_fg"], insertofftime=0, insertontime=9999999)
        sp.pack(side="left", padx=6)

        # key echo ---------------------------------------------------------------
        b = self._box(r, "Say the keys I press")
        b.place(x=10, y=300, width=self.W - 20, height=170)
        self._chk(b, "Say the keys", "echo_on", row=0, column=0, sticky="w")
        self._chk(b, "Letters and digits", "echo_letters", row=0, column=1)
        self._chk(b, "Special keys (Space, Enter, arrows ...)", "echo_special", row=0, column=2)
        self._chk(b, "Shift / Ctrl / Alt / Windows", "echo_mods", row=0, column=3)
        self._chk(b, "Say the whole word when I press Space", "echo_words", row=1, column=0, columnspan=2)
        self._chk(b, "New key cuts off the previous speech", "interrupt", row=1, column=2, columnspan=2)
        self._lbl(b, "Voice").grid(row=2, column=0, sticky="w", pady=(6, 0))
        self.cb_voice = self._combo(b, self._var("voice"), 40)
        self.cb_voice.grid(row=2, column=1, columnspan=2, sticky="w", pady=(6, 0))
        self._lbl(b, "Key names").grid(row=2, column=3, sticky="w", pady=(6, 0))
        kl = self._combo(b, self._var("key_lang"), 10)
        kl["values"] = ["auto", "en", "sv"]
        kl.grid(row=2, column=4, sticky="w", pady=(6, 0), padx=6)
        self._lbl(b, "Speed").grid(row=3, column=0, sticky="w")
        tk.Scale(b, from_=-6, to=8, orient="horizontal", variable=self._var("rate", "i"), length=170,
                 bg=THEME["bg"], fg=THEME["fg"], highlightthickness=0, troughcolor=THEME["field"]).grid(row=3, column=1, sticky="w")
        self._lbl(b, "Volume").grid(row=3, column=2, sticky="e")
        tk.Scale(b, from_=10, to=100, orient="horizontal", variable=self._var("volume", "i"), length=170,
                 bg=THEME["bg"], fg=THEME["fg"], highlightthickness=0, troughcolor=THEME["field"]).grid(row=3, column=3, sticky="w")
        self._btn(b, "Test voice", self.test_voice, 10).grid(row=3, column=4, padx=6)

        hf = tk.Frame(r, bg=THEME["bg"])
        hf.place(x=10, y=476, width=self.W - 20, height=26)
        self._lbl(hf, "Hotkey for start/stop (works in every program)").pack(side="left")
        hk = self._combo(hf, self._var("hotkey"), 8)
        hk["values"] = ["f6", "f7", "f8", "f9", "f10", "f11", "pause", "scroll lock"]
        hk.pack(side="left", padx=8)
        self._btn(hf, "Clear log", self.clear_log, 10).pack(side="right")

        # preview + log ------------------------------------------------------------
        pv = self._box(r, "Preview (text lands here when TalkType itself is in front)")
        pv.place(x=10, y=506, width=self.W - 20, height=92)
        self.txt_prev = new_text(pv, height=3, bg=THEME["field"], fg=THEME["field_fg"], wrap="word",
                                 font=("Segoe UI", 11), relief="flat")
        self.txt_prev.pack(fill="both", expand=True)
        lg = self._box(r, "Log")
        lg.place(x=10, y=602, width=self.W - 20, height=self.H - 612)
        self.txt_log = new_text(lg, height=6, bg=THEME["field"], fg=THEME["field_fg"], wrap="word",
                                font=("Consolas", 9), relief="flat", state="disabled")
        sb = tk.Scrollbar(lg, command=self.txt_log.yview)
        self.txt_log.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.txt_log.pack(fill="both", expand=True)
        self.txt_log.tag_configure("bad", foreground=THEME["bad"])
        self.txt_log.tag_configure("good", foreground=THEME["good"])
        self.txt_log.tag_configure("dim", foreground=THEME["dim"])
        self.refresh_windows()
        r.after(0, lambda: _set_window_icon(r))

    def _find_own_hwnd(self):
        try:
            self.own_hwnd = int(ctypes.windll.user32.GetParent(self.root.winfo_id()) or self.root.winfo_id())
        except Exception:
            self.own_hwnd = 0

    # ---- log / status ------------------------------------------------------------
    def log(self, text, tag=""):
        t = self.txt_log
        t.configure(state="normal")
        t.insert("end", time.strftime("%H:%M:%S  ") + text + "\n", tag or ())
        t.see("end")
        t.configure(state="disabled")

    def clear_log(self):
        self.txt_log.configure(state="normal")
        self.txt_log.delete("1.0", "end")
        self.txt_log.configure(state="disabled")

    def set_status(self, text, color=None):
        self.lbl_status.configure(text=text, fg=color or THEME["fg"])

    # ---- windows list ---------------------------------------------------------------
    def refresh_windows(self):
        self.windows = {}
        labels = []
        for hwnd, title in list_windows(self.own_hwnd):
            lab = "%s   [%d]" % (title[:60], hwnd)
            self.windows[lab] = hwnd
            labels.append(lab)
        self.cb_win["values"] = labels
        cur = self.vars["target_title"].get()
        want = cur.rsplit("[", 1)[0].strip() if cur else ""
        if cur not in self.windows and want:
            for lab in labels:                                   # same title, new handle
                if lab.rsplit("[", 1)[0].strip() == want:
                    self.vars["target_title"].set(lab)
                    break

    def _target_changed(self):
        if self.S["target"] == "window":
            self.refresh_windows()

    # ---- voice -------------------------------------------------------------------------
    def _fill_voices(self):
        names = [n for n, l in self.speaker.voices]
        self.cb_voice["values"] = ["(automatic)"] + names
        if self.S["voice"] not in names:
            pick = ""
            for n, l in self.speaker.voices:                      # prefer a Swedish voice
                if "41d" in l:
                    pick = n
                    break
            self.vars["voice"].set(pick or "(automatic)")

    def _apply_voice(self):
        v = self.S["voice"]
        self.speaker.configure("" if v == "(automatic)" else v, self.S["rate"], self.S["volume"])

    def names_family(self):
        k = self.S["key_lang"]
        if k in ("en", "sv"):
            return k
        return "sv" if "41d" in self.speaker.lang_of(self.S["voice"]) else "en"

    def test_voice(self):
        fam = self.names_family()
        self.speaker.say("Hej, det här är rösten." if fam == "sv" else "Hello, this is the voice.", True)

    # ---- global hooks (hotkey + key echo) -----------------------------------------------
    def _setup_hooks(self):
        if kb is None:
            return
        try:
            kb.hook(self._on_key)
        except Exception as e:
            self.log("Key hook failed: %s" % e, "bad")
        self._setup_hotkey()

    def _setup_hotkey(self):
        if kb is None:
            return
        try:
            if self.hotkey_handle is not None:
                kb.remove_hotkey(self.hotkey_handle)
            self.hotkey_handle = kb.add_hotkey(self.S["hotkey"], lambda: self.ui_q.put(("toggle",)))
        except Exception as e:
            self.log("Hotkey %s failed: %s" % (self.S["hotkey"], e), "bad")

    def _on_key(self, e):
        """Runs on the keyboard module's thread: only queue things, never touch Tk."""
        try:
            if e.event_type == "up":
                self.down.discard(e.scan_code)
                return
            if e.scan_code in self.down:
                return                                            # key auto-repeat
            self.down.add(e.scan_code)
            if not self.S["echo_on"] or self.typer.busy():
                return
            name = (e.name or "").lower()
            cat = key_category(name)
            fam = self.names_family()
            if self.S["echo_words"]:
                if cat == "letters":
                    self.word_buf += name
                elif name == "backspace":
                    self.word_buf = self.word_buf[:-1]
                elif name in ("space", "enter", "tab", ".", ",", "?", "!"):
                    if self.word_buf:
                        self.speaker.say(self.word_buf, self.S["interrupt"])
                        self.word_buf = ""
                        if name in ("space", "enter", "tab"):
                            return
            if cat == "letters" and not self.S["echo_letters"]:
                return
            if cat == "special" and not self.S["echo_special"]:
                return
            if cat == "mods" and not self.S["echo_mods"]:
                return
            self.speaker.say(key_spoken(name, fam), self.S["interrupt"])
        except Exception:
            pass

    # ---- start / stop -------------------------------------------------------------------
    def toggle(self):
        if self.listener.running:
            self.stop_listening()
        else:
            self.start_listening()

    def start_listening(self):
        if sr is None:
            messagebox.showerror(APP_NAME, "SpeechRecognition / PyAudio are not installed.\n\n"
                                 "pip install SpeechRecognition PyAudio", parent=self.root)
            return
        idx = None
        for i, n in self.mics:
            if n == self.S["mic"]:
                idx = i
        self.composer.reset()
        self.composer.mode = self.S["mode"]
        self.listener = Listener(self.ui_q)
        self.listener.start(idx, self.S["lang"], self.S["pause"])
        self.btn_listen.configure(text="Stop listening", bg=THEME["bad"])
        self.set_status("Starting ...", THEME["accent"])
        self.log("Listening started (%s, %s mode)." % (self.S["lang"], self.S["mode"]), "good")

    def stop_listening(self):
        self.listener.stop()
        self.btn_listen.configure(text="Start listening", bg=THEME["good"])
        self.set_status("Idle", THEME["dim"])
        self.log("Listening stopped.", "dim")

    # ---- the main loop: results from the recogniser ------------------------------------------
    def _poll(self):
        try:
            while True:
                ev = self.ui_q.get_nowait()
                k = ev[0]
                if k == "toggle":
                    self.toggle()
                elif k == "status":
                    self.set_status(ev[1], THEME["accent"] if ev[1] == "Listening" else THEME["fg"])
                elif k == "error":
                    self.log(ev[1], "bad")
                elif k == "stopped":
                    self.stop_listening()
                elif k == "heard":
                    self._heard(ev[1])
        except queue.Empty:
            pass
        self.root.after(80, self._poll)

    def _heard(self, alts):
        if not alts:
            self.log("(not understood)", "dim")
            return
        acts, unknown, text = best_parse(alts, self.S["mode"], self.S["lang"], self.S["spell_merged"])
        self.log("heard: %s" % text)
        if unknown:
            self.log("  not understood: %s" % ", ".join(unknown), "dim")
        ops = self.composer.feed(acts)
        typed = []
        for op in ops:
            if op[0] == "mode":
                self.vars["mode"].set(op[1])
                self.composer.mode = op[1]
                self.log("  mode: %s" % ("spelling" if op[1] == "letters" else "words"), "good")
                continue
            if not self._put(op):
                break
            if op[0] == "type":
                typed.append(op[1])
        if typed and self.S["readback"]:
            self.speaker.say("".join(typed), self.S["interrupt"])

    def _put(self, op):
        """Type one operation.  False = could not (and the log says why)."""
        front = self.typer.foreground()
        if self.S["target"] == "window":
            hwnd = self.windows.get(self.S["target_title"])
            if not hwnd:
                self.log("The chosen window is gone - press Refresh and pick it again.", "bad")
                return False
            if not self.typer.bring_to_front(hwnd):
                self.log("Could not bring that window to the front - nothing typed.", "bad")
                return False
        elif front == self.own_hwnd or front == 0:
            return self._to_preview(op)
        if op[0] == "type":
            self.typer.text(op[1])
        else:
            self.typer.key(op[1])
        return True

    def _to_preview(self, op):
        t = self.txt_prev
        if op[0] == "type":
            t.insert("end", op[1])
        elif op[1] == "backspace":
            t.delete("end-2c", "end-1c")
        elif op[1] == "enter":
            t.insert("end", "\n")
        t.see("end")
        return True

    # ---- dialogs -----------------------------------------------------------------------------
    def show_help(self):
        top = tk.Toplevel(self.root)
        top.title(APP_NAME + " - Help")
        top.configure(bg=THEME["bg"])
        top.geometry("760x640")
        top.resizable(False, False)
        top.transient(self.root)
        t = new_text(top, wrap="word", bg=THEME["field"], fg=THEME["field_fg"], font=("Segoe UI", 10), relief="flat")
        sb = tk.Scrollbar(top, command=t.yview)
        t.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        t.pack(fill="both", expand=True, padx=8, pady=8)
        t.insert("1.0", HELP_TEXT)
        t.configure(state="disabled")
        make_modal(top)

    def about(self):
        show_about(self.root, APP_NAME, "Talk or spell - get text in any app, and hear your keys", "\U0001F3A4")

    def open_notes(self):
        if self.playtext is not None:
            try:
                if self.playtext.top.winfo_exists():
                    self.playtext.top.lift()
                    return
            except Exception:
                pass
        self.S["show_playtext"] = True

        def closed():
            self.playtext = None
        self.playtext = PlayerTextPopup(
            self.root, self.S, ("show_playtext", "playtext_pos", "playtext_zoom", "playtext_sel"),
            lambda: save_settings(self.S),
            dict(bg=THEME["bg"], panel=THEME["panel"], fg=THEME["fg"], dim=THEME["dim"], accent=THEME["accent"],
                 btn=THEME["btn"], btnfg=THEME["btnfg"], field=THEME["field"], field_fg=THEME["field_fg"]),
            "Notes", PROGRAM_HF_DIR, lambda: {}, on_closed=closed)

    def on_close(self):
        try:
            self.listener.stop()
            if self.playtext is not None:
                self.playtext.save_now()
            save_settings(self.S)
            if kb is not None:
                kb.unhook_all()
            self.speaker.quit()
        except Exception:
            pass
        self.root.destroy()


# *************** DEL 19 - START ***************************************************
def main():
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    App(root)
    root.mainloop()


if __name__ == "__main__":
    main()
