#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cubase_helper.py  -  a pocket help for Cubase, plus a guard for the Nektar keyboard files

ALLT I PROGRAMMET SKA ALLTID VARA PÅ ENGELSKA - ALDRIG SVENSKA!
(EVERYTHING IN THIS PROGRAM MUST ALWAYS BE IN ENGLISH - NEVER SWEDISH!)

Settings / data:  <home>\\Helpfiles\\Cubase_helper\\   (settings.json, tips_user.json,
                  Parked\\ = where the parked Nektar files wait, Playertext-*.txt)
Log files:        <home>\\Helpfiles\\0---Empty\\        (Cubase_helper.log, *_crash.log)
Icon:             <home>\\Icons\\Cubase_helper.ico      (external file, not embedded)

Section index (search for "DEL " to jump):
    DEL 01  Imports, constants, palette
    DEL 02  Program home (where my data lives)
    DEL 03  UI helpers (no blink, modal dialogs)
    DEL 04  Window icon (external .ico)
    DEL 05  Open things with my own programs
    DEL 06  Tool popups: movable, zoomable (My notes = Player text)
    DEL 07  About dialog (template)
    DEL 08  Logging, crash catcher
    DEL 09  Settings
    DEL 10  Windows helpers (processes, administrator rights)
    DEL 11  The tips (built-in Cubase help)
    DEL 12  Tip store (built-in + your own, search)
    DEL 13  Keyboard guard engine (park / restore the Nektar files)
    DEL 14  Small dialogs (toast, message, yes/no, Help)
    DEL 15  Tab: Cubase help
    DEL 16  Tip editor dialog
    DEL 17  Tab: Keyboard guard
    DEL 18  Diagnosis dialog
    DEL 19  Main window
    DEL 20  Self-test
    DEL 90  Entry point
"""

# ══════════════════════════════════════════════════════════════════════════
# ToDo
# ══════════════════════════════════════════════════════════════════════════
#
# DONE (2026-10-16, first version):
#   - Tab "Cubase help": searchable list of problems and fixes.  The two that
#     started this program are in it: the metronome clicking when it should not
#     (key C) and the cursor that moves while the view stands still (key F,
#     Autoscroll).  Five QUICK-FIX buttons jump straight to the usual suspects.
#   - Your own tips: New / Edit / Delete.  A built-in tip you edit keeps its
#     original; "Reset" brings it back.  Stored in Helpfiles\Cubase_helper\
#     tips_user.json - nothing is ever written into the program itself.
#   - Tab "Keyboard guard": parks the two Nektar files that froze Cubase when the
#     Impact GX61 was switched on (ImpactGX61SteinbergDAWControl64.dll and
#     ImpactGX49SteinbergDAWControl64.dll in ...\Common Files\Steinberg\Shared
#     Components) and puts them back again.  Windows asks for administrator
#     permission when it has to; that is done by a short elevated PowerShell
#     started by full path - never sys.executable, never a bare name.
#   - AUTO MODE: while the program is open and Cubase is NOT running, the files
#     are parked again by themselves if they reappear (a Nektar update or
#     reinstall puts them back).  Declining the Windows prompt pauses auto mode
#     so it never nags.
#   - My notes (Player text popup), About, hardcoded Help (F1), Diagnosis,
#     crash catcher with log, remembers window size/position and last choices.
#
# DONE (2026-10-18): three more built-in tips - Quantize MIDI Event Ends (and how it
#   differs from Legato / Event Lengths / Fixed Lengths), FX Favorites folders for
#   plug-ins, and "exported files are 0 bytes" (look in the Mixdown folder).
#
# TODO / ideas (nothing here is promised):
#   - A "press the key in Cubase for me" button (needs Cubase's window in front,
#     and C / F are toggles, so it would be a blind toggle - left out on purpose).
#   - More tips as new problems turn up: add them in the program (New tip) or
#     tell Claude what keeps going wrong.
#   - Park other files the same way: "Add file..." already does it.

# *************** DEL 01 - IMPORTS, CONSTANTS, PALETTE ************************

import os
import re
import sys
import json
import time
import glob
import queue
import base64
import shutil
import ctypes
import platform
import tempfile
import threading
import traceback
import subprocess
import webbrowser
import tkinter as tk
import tkinter.font as tkfont
from tkinter import filedialog
from ctypes import wintypes
from datetime import datetime

APP_TITLE   = "Cubase helper"
APP_VERSION = "1.0.0"
APP_AUTHOR  = 'Lars "Issu" Olsson'

DEFAULT_GEOMETRY = "1120x780"
MIN_WIDTH, MIN_HEIGHT = 940, 620

# ---- Colours - change any string freely (any tk colour name or #rrggbb) ------
C_BG      = "#1c1f26"    # main window background
C_BG2     = "#262b35"    # top bar / panels
C_BG3     = "#20242d"    # list and text backgrounds
C_FIELD   = "#14161b"    # input fields
C_FG      = "#e6e6e6"    # normal text
C_FG_DIM  = "#8a93a3"    # dimmed text
C_ACCENT  = "#4fd1c5"    # accent (teal)
C_SEP     = "#3a4150"    # thin lines
C_GOOD    = "#68d391"    # "all fine" text
C_WARN    = "#f6ad55"    # "look at this" text
C_BAD     = "#fc8181"    # "this is the problem" text
C_SELECT  = "#0f5c58"    # selected row in lists

# ---- Button colours - each kind spelled out: (background, text, active bg, active text)
BUTTON_KINDS = {
    "normal":  ("#3a4150", "white", "#505a6e", "white"),   # grey
    "park":    ("#2e7d32", "white", "#3a9740", "white"),   # green  - Park now
    "restore": ("#3a4150", "white", "#505a6e", "white"),   # grey   - Restore all
    "quick":   ("#0f766e", "white", "#14998e", "white"),   # teal   - quick-fix buttons
    "tab":     ("#2f3644", "white", "#3d4658", "white"),   # tab, not selected
    "tab_on":  ("#0f766e", "white", "#14998e", "white"),   # tab, selected
    "danger":  ("#9b2c2c", "white", "#c53030", "white"),   # red    - delete
}

THEME = dict(bg=C_BG, panel=C_BG2, fg=C_FG, dim=C_FG_DIM, accent=C_ACCENT,
             btn=BUTTON_KINDS["normal"][0], btnfg="white",
             field=C_FIELD, field_fg=C_FG)          # for the My notes popup

UI_FONT = "Segoe UI"


def mkbtn(parent, text, command, kind="normal", width=None, height=None, **kw):
    """A tk.Button in one of the named colour kinds above."""
    bg, fg, abg, afg = BUTTON_KINDS[kind]
    opts = dict(text=text, command=command, bg=bg, fg=fg, activebackground=abg,
                activeforeground=afg, relief="flat", bd=0, cursor="hand2",
                padx=10, pady=4, font=(UI_FONT, 10))
    if width:
        opts["width"] = width
    if height:
        opts["height"] = height
    opts.update(kw)
    return tk.Button(parent, **opts)


def set_btn_kind(btn, kind):
    bg, fg, abg, afg = BUTTON_KINDS[kind]
    btn.configure(bg=bg, fg=fg, activebackground=abg, activeforeground=afg)


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

MY_PROGRAM_NAME = PROGRAM_NAME

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


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

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


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


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


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

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


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

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


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


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

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

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


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


class ToolPopup(object):
    resizable = False

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

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

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def before_close(self):
        self.save_now()

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

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

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

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


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

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

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

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

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

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

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

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

# *************** DEL 08 - LOGGING, CRASH CATCHER *****************************
# Logs go to <home>\Helpfiles\0---Empty - logs ONLY, never data.

_ROOT = None                      # set in main(); lets the crash catcher show a dialog


def log_line(kind, msg):
    """One line in LOG_DIR\\Cubase_helper.log.  Never raises."""
    try:
        os.makedirs(LOG_DIR, exist_ok=True)
        path = os.path.join(LOG_DIR, PROGRAM_NAME + ".log")
        try:
            if os.path.getsize(path) > 1000000:
                os.replace(path, path + ".old")
        except OSError:
            pass
        with open(path, "a", encoding="utf-8") as fh:
            fh.write("%s  %-5s %s\n" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                        kind, msg))
    except Exception:
        pass


def crash_log_path():
    return os.path.join(LOG_DIR, PROGRAM_NAME + "_crash.log")


def write_crash(text):
    try:
        os.makedirs(LOG_DIR, exist_ok=True)
        with open(crash_log_path(), "a", encoding="utf-8") as fh:
            fh.write("=" * 70 + "\n%s  %s %s\n%s\n" % (
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"), APP_TITLE,
                APP_VERSION, text))
    except Exception:
        pass


def _crash_handler(exc_type, exc_value, exc_tb):
    """Any uncaught exception: write the report, tell the user, keep running."""
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_tb)
        return
    text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    write_crash(text)
    log_line("CRASH", "%s: %s  (details in %s)" % (
        exc_type.__name__, exc_value, os.path.basename(crash_log_path())))
    try:
        if _ROOT is not None and _ROOT.winfo_exists():
            show_message(_ROOT, "Something went wrong",
                         "%s: %s\n\nThe details were written to:\n%s\n\n"
                         "The program keeps running." % (
                             exc_type.__name__, exc_value, crash_log_path()))
    except Exception:
        pass


def _thread_crash_handler(args):
    _crash_handler(args.exc_type, args.exc_value, args.exc_traceback)


sys.excepthook = _crash_handler
try:
    threading.excepthook = _thread_crash_handler
except Exception:
    pass


# *************** DEL 09 - SETTINGS ******************************************
# Remembers the last time: window size/position, tab, chosen tip, the keyboard
# guard setup, and the My notes popup.  One JSON file, written atomically.

DEFAULT_SETTINGS = {
    "geometry": DEFAULT_GEOMETRY,
    "tab": "help",
    "selected_tip": "",
    "search": "",
    "collapsed_headings": [],       # tip-list headings that are folded (default: all open)
    # keyboard guard
    "guard_files": None,            # None = the two default Nektar files; a list = exactly those
    "guard_source_dir": "",         # empty = the Steinberg Shared Components folder
    "guard_parked_dir": "",         # empty = <Helpfiles>\Cubase_helper\Parked
    "guard_auto": False,
    "guard_interval": 15,           # seconds between auto checks
    "cubase_exe": "",
    # My notes popup (block_popups.py)
    "show_playertext": False,
    "playertext_pos": None,
    "playertext_zoom": 100,
    "playertext_sel": "Notes",
}


def settings_file():
    return os.path.join(PROGRAM_HF_DIR, "settings.json")


def load_settings():
    S = json.loads(json.dumps(DEFAULT_SETTINGS))
    try:
        with open(settings_file(), encoding="utf-8") as fh:
            data = json.load(fh)
        if isinstance(data, dict):
            S.update(data)
    except FileNotFoundError:
        pass
    except Exception as e:
        log_line("WARN", "settings.json unreadable (%r) - starting with defaults" % (e,))
        try:
            os.replace(settings_file(), settings_file() + ".bad")
        except OSError:
            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, ensure_ascii=False)
        os.replace(tmp, settings_file())
    except Exception as e:
        log_line("WARN", "could not save settings: %r" % (e,))


# *************** DEL 10 - WINDOWS HELPERS ************************************
# Which programs are running, and "run this as administrator".
#
# Moving a file out of C:\Program Files needs administrator rights.  The program
# itself runs as a normal user, so it asks Windows (the "runas" verb) to start a
# short PowerShell that does just the moving.  Three rules from 90_lessons_learned:
#   * PowerShell is started by its FULL path, never by bare name;
#   * never sys.executable (in a build that is this program's own .exe);
#   * the command goes in as -EncodedCommand, so no quoting can go wrong with
#     paths that contain spaces, plus signs or apostrophes.

TH32CS_SNAPPROCESS = 0x00000002
SEE_MASK_NOCLOSEPROCESS = 0x00000040
ERROR_CANCELLED = 1223
WAIT_TIMEOUT = 0x102


class PROCESSENTRY32W(ctypes.Structure):
    _fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
                ("th32ProcessID", wintypes.DWORD),
                ("th32DefaultHeapID", ctypes.c_size_t),
                ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
                ("th32ParentProcessID", wintypes.DWORD),
                ("pcPriClassBase", wintypes.LONG), ("dwFlags", wintypes.DWORD),
                ("szExeFile", wintypes.WCHAR * 260)]


class SHELLEXECUTEINFOW(ctypes.Structure):
    _fields_ = [("cbSize", wintypes.DWORD), ("fMask", ctypes.c_ulong),
                ("hwnd", wintypes.HWND), ("lpVerb", wintypes.LPCWSTR),
                ("lpFile", wintypes.LPCWSTR), ("lpParameters", wintypes.LPCWSTR),
                ("lpDirectory", wintypes.LPCWSTR), ("nShow", ctypes.c_int),
                ("hInstApp", wintypes.HINSTANCE), ("lpIDList", ctypes.c_void_p),
                ("lpClass", wintypes.LPCWSTR), ("hkeyClass", wintypes.HKEY),
                ("dwHotKey", wintypes.DWORD), ("hIconOrMonitor", wintypes.HANDLE),
                ("hProcess", wintypes.HANDLE)]


def list_process_names():
    """Lower-case names of all running processes (empty set when it cannot tell)."""
    names = set()
    if platform.system() != "Windows":
        return names
    try:
        k32 = ctypes.WinDLL("kernel32", use_last_error=True)
        k32.CreateToolhelp32Snapshot.restype = ctypes.c_void_p
        k32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
        k32.Process32FirstW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]
        k32.Process32NextW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]
        k32.CloseHandle.argtypes = [ctypes.c_void_p]
        snap = k32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
        if not snap or snap == ctypes.c_void_p(-1).value:
            return names
        try:
            entry = PROCESSENTRY32W()
            entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
            ok = k32.Process32FirstW(snap, ctypes.byref(entry))
            while ok:
                names.add(entry.szExeFile.lower())
                ok = k32.Process32NextW(snap, ctypes.byref(entry))
        finally:
            k32.CloseHandle(snap)
    except Exception as e:
        log_line("WARN", "process list failed: %r" % (e,))
    return names


# Cubase15.exe, Cubase14.exe, Nuendo13.exe ...  NOT Cubase_helper.exe (our own build).
CUBASE_RE = re.compile(r"^(cubase|nuendo)\d[\w.]*\.exe$", re.I)


def cubase_processes():
    return sorted(n for n in list_process_names() if CUBASE_RE.match(n))


def powershell_exe():
    root = os.environ.get("SystemRoot", r"C:\Windows")
    return os.path.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")


def ps_quote(s):
    """A PowerShell single-quoted string literal."""
    return "'" + str(s).replace("'", "''") + "'"


def build_move_script(pairs, result_file):
    """PowerShell text that moves each (src, dst) and reports what happened in
    result_file: OK|src, SKIP|src (not there) or ERR|src|message."""
    lines = [
        "$ErrorActionPreference = 'Stop'",
        "$out = New-Object System.Collections.ArrayList",
        "function Move-One($src, $dst) {",
        "  try {",
        "    if (Test-Path -LiteralPath $src) {",
        "      $dir = Split-Path -Parent $dst",
        "      if (-not (Test-Path -LiteralPath $dir)) {",
        "        New-Item -ItemType Directory -Force -Path $dir | Out-Null }",
        "      if (Test-Path -LiteralPath $dst) {",
        "        Move-Item -LiteralPath $dst -Destination ($dst + '.old') -Force }",
        "      Move-Item -LiteralPath $src -Destination $dst -Force",
        "      [void]$out.Add('OK|' + $src)",
        "    } else { [void]$out.Add('SKIP|' + $src) }",
        "  } catch { [void]$out.Add('ERR|' + $src + '|' + $_.Exception.Message) }",
        "}",
    ]
    for src, dst in pairs:
        lines.append("Move-One %s %s" % (ps_quote(src), ps_quote(dst)))
    lines.append("Set-Content -LiteralPath %s -Value $out -Encoding UTF8"
                 % ps_quote(result_file))
    return "\n".join(lines)


def powershell_arguments(script):
    enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
    return ("-NoProfile -NonInteractive -ExecutionPolicy Bypass "
            "-WindowStyle Hidden -EncodedCommand " + enc)


def run_elevated_powershell(script, wait_ms=90000):
    """Run a PowerShell script as administrator (Windows shows its permission
    prompt).  Returns (started, exit_code, problem):
        started False + problem "cancelled"  -> the user said No to the prompt
        started False + problem "..."        -> Windows refused for another reason
        started True                         -> exit_code 0 = the script finished"""
    try:
        shell32 = ctypes.WinDLL("shell32", use_last_error=True)
        k32 = ctypes.WinDLL("kernel32", use_last_error=True)
        k32.WaitForSingleObject.argtypes = [ctypes.c_void_p, wintypes.DWORD]
        k32.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)]
        k32.CloseHandle.argtypes = [ctypes.c_void_p]
        sei = SHELLEXECUTEINFOW()
        sei.cbSize = ctypes.sizeof(sei)
        sei.fMask = SEE_MASK_NOCLOSEPROCESS
        sei.lpVerb = "runas"
        sei.lpFile = powershell_exe()
        sei.lpParameters = powershell_arguments(script)
        sei.nShow = 0                       # hidden window
        if not shell32.ShellExecuteExW(ctypes.byref(sei)):
            err = ctypes.get_last_error()
            return False, None, ("cancelled" if err == ERROR_CANCELLED
                                 else "Windows error %d" % err)
        handle = sei.hProcess
        if not handle:
            return True, 0, ""
        code = wintypes.DWORD(1)
        waited = k32.WaitForSingleObject(handle, wait_ms)
        if waited == WAIT_TIMEOUT:
            k32.CloseHandle(handle)
            return True, None, "the administrator step did not finish in time"
        k32.GetExitCodeProcess(handle, ctypes.byref(code))
        k32.CloseHandle(handle)
        return True, int(code.value), ""
    except Exception as e:
        return False, None, "%s: %s" % (type(e).__name__, e)



# *************** DEL 11 - THE TIPS (BUILT-IN CUBASE HELP) ********************
# One dict per tip.  Keys:
#   id        short unique name (a tip you edit keeps its id, so "Reset" works)
#   category  the heading in the list
#   title     what you would SAY is wrong
#   keys      the key to press ("" when there is none)
#   symptom   what you see
#   steps     what to do, one string per step
#   notes     extra, optional
#   tags      extra search words
#
# The keys are Cubase's DEFAULT key commands.  Yours can differ: File > Key
# Commands shows and changes them.  Everything here can be edited in the program.

CAT_TRANSPORT = "Transport and display"
CAT_RECORD    = "Recording and MIDI"
CAT_SOUND     = "Sound and audio"
CAT_HANGS     = "Hangs and crashes"
CAT_KEYS      = "Keys"

CATEGORY_ORDER = [CAT_TRANSPORT, CAT_RECORD, CAT_SOUND, CAT_HANGS, CAT_KEYS]

# The quick-fix buttons on the first tab: (button text, tip id)
QUICK_FIXES = [
    ("Metronome is clicking",        "metronome"),
    ("Cursor moves, view stands still", "autoscroll"),
    ("Keyboard plays, no sound",     "keyboard-silent"),
    ("No sound at all",              "no-sound"),
    ("Cubase freezes with the GX61", "gx61-freeze"),
]

DEFAULT_TIPS = [
    {
        "id": "metronome",
        "category": CAT_TRANSPORT,
        "title": "The metronome is clicking and I do not want it",
        "keys": "C",
        "symptom": "A click plays along with the music (or only while recording) "
                   "and you did not switch it on.",
        "steps": [
            "Click once in the Project window so it has the focus, then press C. "
            "C switches the metronome click on and off.",
            "Or show the Transport panel (F2) and click the Click (metronome) "
            "button so that it is no longer lit.",
            "If the click only appears while recording, open Transport > "
            "Metronome Setup and look at the options for click during playback "
            "and during recording.",
        ],
        "notes": "C is a toggle: pressing it blindly can switch the click ON. "
                 "Look at the Click button on the Transport panel to see which "
                 "way it is. A lit Precount button also gives clicks before "
                 "recording starts.",
        "tags": "click metronome beat tick count-in precount",
    },
    {
        "id": "autoscroll",
        "category": CAT_TRANSPORT,
        "title": "The play cursor moves but the screen stands still",
        "keys": "F",
        "symptom": "Playback runs and the cursor (the marker line) moves ahead, but "
                   "the view does not follow, so the cursor disappears off the "
                   "right edge.",
        "steps": [
            "Click in the window you are looking at (the Project window, or the "
            "MIDI / Key editor) and press F. F switches Autoscroll on and off.",
            "Or click the Autoscroll button in that window's toolbar so that it "
            "lights up.",
            "Every editor window has its own Autoscroll button: switching it on "
            "in the Project window does not switch it on in the Key editor.",
        ],
        "notes": "If Autoscroll keeps switching itself off after you edit, look "
                 "for the 'Suspend Autoscroll when Editing' option next to it. "
                 "If the cursor still runs away, check that the view is not "
                 "zoomed in very far.",
        "tags": "follow scroll cursor marker playhead view standing still stuck",
    },
    {
        "id": "transport-panel",
        "category": CAT_TRANSPORT,
        "title": "The Transport panel is gone",
        "keys": "F2",
        "symptom": "There is no Transport panel with Play, Stop, Click and Cycle.",
        "steps": [
            "Press F2 to show or hide the Transport panel.",
            "Or use the Transport menu and choose Transport Panel.",
        ],
        "notes": "If F2 does nothing, click once in the Project window first so "
                 "that Cubase has the keyboard focus.",
        "tags": "transport panel play stop buttons hidden missing",
    },
    {
        "id": "start-stop",
        "category": CAT_TRANSPORT,
        "title": "Start, stop and record from the keyboard",
        "keys": "Space",
        "symptom": "You want the basic transport keys.",
        "steps": [
            "Space: start / stop playback.",
            "Numpad Enter: start playback.",
            "Numpad 0: stop.",
            "Numpad *: record.",
        ],
        "notes": "Defaults - File > Key Commands shows the ones you really have.",
        "tags": "play stop record space transport keys",
    },
    {
        "id": "cycle-loop",
        "category": CAT_TRANSPORT,
        "title": "Playback keeps repeating the same part",
        "keys": "Numpad /",
        "symptom": "Cubase loops a few bars again and again instead of playing on.",
        "steps": [
            "Cycle mode is on. Click the Cycle button on the Transport panel "
            "(or press the numpad / key) so that it is no longer lit.",
            "If you want the loop, the ruler shows the cycle area between the "
            "left and right locator.",
        ],
        "notes": "",
        "tags": "cycle loop repeat locator",
    },
    {
        "id": "return-to-start",
        "category": CAT_TRANSPORT,
        "title": "After Stop the cursor jumps back (or does not)",
        "keys": "",
        "symptom": "You want the cursor to go back to where playback started when "
                   "you press Stop, or you want it to stay where it stopped.",
        "steps": [
            "Open Preferences (the Edit menu on Windows).",
            "Go to the Transport page and look for 'Return to Start Position on "
            "Stop'.",
            "Switch it on to jump back, off to stay where you stopped.",
        ],
        "notes": "",
        "tags": "stop return start position jump back cursor",
    },
    {
        "id": "record-enable",
        "category": CAT_RECORD,
        "title": "I press Record but nothing is recorded",
        "keys": "R",
        "symptom": "The project runs but no recording appears on the track.",
        "steps": [
            "Select the track and press R, or click the red Record Enable button "
            "on the track so that it lights up.",
            "Check the input: an audio track needs its input (for example "
            "input 1 on the Focusrite); a MIDI or instrument track needs MIDI In "
            "set to your keyboard or to All MIDI Inputs.",
            "Check that the Record button on the Transport panel is lit "
            "(numpad * starts recording).",
        ],
        "notes": "",
        "tags": "record enable arm red button input",
    },
    {
        "id": "keyboard-silent",
        "category": CAT_RECORD,
        "title": "The keyboard plays but I hear nothing",
        "keys": "",
        "symptom": "You press keys on the keyboard and there is no sound from the "
                   "instrument in Cubase.",
        "steps": [
            "Select the instrument track (or the MIDI track that feeds an "
            "instrument): live notes go to the selected track.",
            "Look at the track's Input in the Inspector: MIDI In must be your "
            "keyboard or All MIDI Inputs.",
            "Click the Monitor button (speaker) on the track, or record-enable it "
            "(R) so that it listens to the keyboard.",
            "Watch the MIDI activity indicator on the Transport panel while you "
            "play. Does it move?",
            "Studio > Studio Setup > MIDI Port Setup: the keyboard must be listed "
            "and ticked in the 'In All MIDI Inputs' column.",
            "Preferences > MIDI: 'MIDI Thru Active' should be on.",
            "Check the instrument itself: its output is routed, its volume is up "
            "and the track is not muted.",
        ],
        "notes": "If the activity indicator does NOT move, the problem is the "
                 "keyboard, the USB cable or the MIDI port. If it moves but there "
                 "is no sound, it is routing, monitoring or the instrument.",
        "tags": "midi keyboard silent no sound monitor input kontakt swam instrument",
    },
    {
        "id": "no-sound",
        "category": CAT_SOUND,
        "title": "No sound at all from Cubase",
        "keys": "F4",
        "symptom": "Playback runs, the meters move (or not), but nothing comes out "
                   "of the speakers or headphones.",
        "steps": [
            "Studio > Studio Setup > VST Audio System: the ASIO driver should be "
            "your interface (Focusrite USB ASIO). Press Control Panel to see that "
            "it is alive.",
            "Studio > Audio Connections (called VST Connections in older "
            "versions, F4): on the Outputs tab, Stereo Out must be connected to "
            "the real outputs (for example Analogue 1 + 2), not 'Not connected'.",
            "Check that the track and the Stereo Out channel are not muted and "
            "that their faders are up.",
            "Check the interface's own volume knob and the speakers.",
        ],
        "notes": "Cubase talks to the interface through ASIO, so the Windows "
                 "default output device does not matter for Cubase itself.",
        "tags": "audio output asio focusrite speakers headphones silent routing",
    },
    {
        "id": "latency",
        "category": CAT_SOUND,
        "title": "Crackles, pops, or a delay when I play",
        "keys": "",
        "symptom": "The sound breaks up, or there is a noticeable delay between "
                   "pressing a key and hearing it.",
        "steps": [
            "Studio > Studio Setup > VST Audio System > your ASIO driver > "
            "Control Panel: lower the buffer size when playing live (for example "
            "128 or 256 samples), raise it for mixing (512 or 1024).",
            "In the same place, leave ASIO-Guard switched on if it is offered: it "
            "helps when many plug-ins run.",
            "Close CPU-heavy plug-ins or freeze heavy instrument tracks.",
            "Studio > Audio Performance shows how hard the computer is working.",
        ],
        "notes": "Small buffer = low delay but more risk of crackles. Large buffer "
                 "= safe but you hear the delay.",
        "tags": "latency buffer crackle pop dropout cpu asio performance delay",
    },
    {
        "id": "gx61-freeze",
        "category": CAT_HANGS,
        "title": "Cubase freezes when I switch on the Impact GX61",
        "keys": "",
        "symptom": "Cubase stops responding the moment the Nektar Impact GX61 is "
                   "switched on, even with a nearly empty project and whatever "
                   "instrument is loaded. Another keyboard (the Alesis Qmini) "
                   "works fine.",
        "steps": [
            "Close Cubase completely.",
            "Open the 'Keyboard guard' tab in this program and press 'Park now'. "
            "That moves Nektar's two Steinberg DAW-control files out of Cubase's "
            "way (Windows asks for administrator permission).",
            "Start Cubase and switch on the keyboard.",
            "The GX61 still works as an ordinary MIDI keyboard. You only lose "
            "Nektar's special Cubase integration (transport buttons, faders).",
            "If a Nektar update or reinstall puts the files back, press 'Park "
            "now' again, or switch on Auto mode in the Keyboard guard tab.",
            "To undo it: 'Restore all'.",
        ],
        "notes": "Found on 2026-10-16 from a memory dump of the frozen Cubase: its "
                 "main thread was spinning inside Cubase's own remote-device "
                 "handling, not in the MIDI driver and not in SWAM or Kontakt. The "
                 "files are ImpactGX61SteinbergDAWControl64.dll and "
                 "ImpactGX49SteinbergDAWControl64.dll in C:\\Program Files\\Common "
                 "Files\\Steinberg\\Shared Components. Moving them away fixed it; "
                 "what exactly is wrong inside them was not investigated.",
        "tags": "nektar impact gx61 gx49 freeze hang not responding keyboard dll "
                "daw control remote",
    },
    {
        "id": "hang-dump",
        "category": CAT_HANGS,
        "title": "Cubase hangs - how to capture what it is doing",
        "keys": "",
        "symptom": "Cubase is greyed out or 'Not responding' and you want to know "
                   "why.",
        "steps": [
            "Do not close it yet. Press Ctrl+Shift+Esc to open Task Manager and go "
            "to the Details tab.",
            "Right-click Cubase15.exe and choose 'Create memory dump file'.",
            "Wait until Windows shows where the .dmp file was saved. With many "
            "plug-ins it can take minutes and be 8-12 GB.",
            "Give the path to whoever is helping you, and delete the file "
            "afterwards - it is big.",
        ],
        "notes": "Event Viewer (Windows Logs > Application) shows 'Application "
                 "Error' entries for crashes. A plain hang leaves no entry, which "
                 "is why the dump is the way to find out.",
        "tags": "hang freeze not responding dump task manager event viewer",
    },
    {
        "id": "crash-on-exit",
        "category": CAT_HANGS,
        "title": "Cubase crashes when I close it",
        "keys": "",
        "symptom": "Cubase vanishes or shows an error when you quit, or after a "
                   "plug-in has been removed from a track.",
        "steps": [
            "Open Event Viewer > Windows Logs > Application and find the "
            "'Application Error' entry for Cubase15.exe.",
            "Read 'Faulting module name': it names the plug-in that crashed. A "
            "name ending in .vst3_unloaded means the plug-in crashed while it was "
            "being unloaded.",
            "Update or reinstall that plug-in. If it keeps happening, take it "
            "out of the project.",
        ],
        "notes": "The logs for 2026-10-13 to 2026-10-16 named LANDR FX Bass / "
                 "Beats, LANDR Mastering Pro, Scaler EQ Pro and iZCascadia as the "
                 "faulting modules.",
        "tags": "crash exit close plug-in vst3 event viewer faulting module landr scaler",
    },
    {
        "id": "quantize-note-ends",
        "category": CAT_RECORD,
        "title": "Tidy up the ends of MIDI notes without making them all the same",
        "keys": "",
        "symptom": "You have quantized the note starts, but the note ends are still "
                   "loose. Legato is not what you want, because it stretches every "
                   "note to the start of the next one.",
        "steps": [
            "Quantize the starts as usual: Edit > Quantize (key Q).",
            "With the same notes / part still selected, choose Edit > Advanced "
            "Quantize > Quantize MIDI Event Ends.",
            "Each note end now snaps to the nearest point on the quantize grid you "
            "already use. An eighth note stays about an eighth note; only the exact "
            "end point is cleaned up. Differences in length between notes are kept, "
            "and nothing is joined to the next note.",
        ],
        "notes": "Do not mix it up with its neighbours. Legato (MIDI > Functions) "
                 "fills each note out to the next note start. Quantize MIDI Event "
                 "Lengths (same submenu) cuts the notes to one fixed value taken "
                 "from the Length Quantize menu in the Key Editor toolbar - blunter. "
                 "Fixed Lengths (MIDI > Functions) forces all selected notes to the "
                 "same length - good for even staccato, but it wipes out all length "
                 "variation. Event Ends has no default key: if you use it often, "
                 "give it one under File > Key Commands. This is the same thing "
                 "Cakewalk's quantize does with lengths, just as a separate command.",
        "tags": "quantize note ends lengths legato fixed lengths midi key editor "
                "event ends advanced quantize cakewalk",
    },
    {
        "id": "fx-favorites-folders",
        "category": CAT_SOUND,
        "title": "Collect plug-ins in my own folder (e.g. all the RX modules)",
        "keys": "",
        "symptom": "The plug-in menu is long and you want your favourites grouped, "
                   "for example every iZotope RX module in one place.",
        "steps": [
            "Open FX Favorites > Organize (or the Plug-In Manager from the View "
            "menu - it is the same thing).",
            "In the left pane, right-click in the FX Favorites tree and create a "
            "new folder.",
            "In the right pane, find the plug-ins you want (under Plug-Ins > Third "
            "Party or similar) and drag them into the new folder on the left.",
            "Done. The plug-in files themselves stay where they always were; you "
            "have only made a shortcut in the menu.",
        ],
        "notes": "To build the whole structure automatically instead of dragging, "
                 "use FX Favorites > Recreate by Plug-In Names. It makes folders "
                 "from the first word of each plug-in name (an 'iZotope' folder if "
                 "all your RX modules are called 'iZotope RX ...').",
        "tags": "fx favorites plug-in manager organize folder group rx izotope "
                "vst menu shortcut",
    },
    {
        "id": "export-zero-bytes",
        "category": CAT_SOUND,
        "title": "The exported files are 0 bytes",
        "keys": "",
        "symptom": "The files you expected from an export / mixdown show a size of "
                   "0 in Explorer.",
        "steps": [
            "You are most likely looking in the wrong folder.",
            "The right one is usually the project's Mixdown folder - look there "
            "first.",
        ],
        "notes": "",
        "tags": "mixdown export render bounce zero 0 bytes empty file size folder",
    },
    {
        "id": "key-cheatsheet",
        "category": CAT_KEYS,
        "title": "Default key commands that are easy to forget",
        "keys": "",
        "symptom": "You cannot remember a key.",
        "steps": [
            "Space - start / stop",
            "C - metronome click on / off",
            "F - Autoscroll on / off",
            "F2 - Transport panel    F3 - Mixer    F4 - Audio Connections    "
            "F11 - VST Instruments",
            "R - record-enable the selected track",
            "M - mute    S - solo",
            "Q - quantize",
            "Ctrl+Z - undo    Ctrl+Shift+Z - redo    Ctrl+S - save    "
            "Ctrl+D - duplicate",
        ],
        "notes": "These are the defaults. File > Key Commands shows and changes "
                 "yours.",
        "tags": "keys shortcuts keyboard commands cheat sheet",
    },
]


# *************** DEL 12 - TIP STORE (BUILT-IN + YOUR OWN, SEARCH) ***************

TIP_FIELDS = ("id", "category", "title", "keys", "symptom", "steps", "notes", "tags")


def _clean_tip(t):
    """A tip dict with every field present and the right type; None if unusable."""
    if not isinstance(t, dict):
        return None
    out = {}
    for k in TIP_FIELDS:
        v = t.get(k, [] if k == "steps" else "")
        if k == "steps":
            if isinstance(v, str):
                v = [ln for ln in v.splitlines() if ln.strip()]
            v = [str(x) for x in (v or []) if str(x).strip()]
        else:
            v = str(v or "")
        out[k] = v
    if not out["id"] or not out["title"].strip():
        return None
    if not out["category"].strip():
        out["category"] = "My tips"
    return out


class TipStore(object):
    """Built-in tips plus the user's own.  A user tip with the id of a built-in
    one REPLACES it (that is how editing a built-in tip works); deleting that user
    tip brings the original back (Reset)."""

    def __init__(self):
        self.user = []
        self.load()

    @staticmethod
    def path():
        return os.path.join(PROGRAM_HF_DIR, "tips_user.json")

    def load(self):
        self.user = []
        try:
            with open(self.path(), encoding="utf-8") as fh:
                data = json.load(fh)
            for t in (data.get("tips") if isinstance(data, dict) else data) or []:
                c = _clean_tip(t)
                if c:
                    self.user.append(c)
        except FileNotFoundError:
            pass
        except Exception as e:
            log_line("WARN", "tips_user.json unreadable (%r) - kept as .bad" % (e,))
            try:
                os.replace(self.path(), self.path() + ".bad")
            except OSError:
                pass

    def save(self):
        try:
            os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
            tmp = self.path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                json.dump({"tips": self.user}, fh, indent=2, ensure_ascii=False)
            os.replace(tmp, self.path())
            return True
        except Exception as e:
            log_line("WARN", "could not save tips_user.json: %r" % (e,))
            return False

    def builtin_ids(self):
        return set(t["id"] for t in DEFAULT_TIPS)

    def merged(self):
        """Every tip, each with an 'origin': built-in / edited / yours."""
        user_by_id = dict((t["id"], t) for t in self.user)
        out = []
        for t in DEFAULT_TIPS:
            if t["id"] in user_by_id:
                x = dict(user_by_id[t["id"]])
                x["origin"] = "edited"
            else:
                x = dict(_clean_tip(t))
                x["origin"] = "built-in"
            out.append(x)
        builtin = self.builtin_ids()
        for t in self.user:
            if t["id"] not in builtin:
                x = dict(t)
                x["origin"] = "yours"
                out.append(x)
        return out

    def get(self, tid):
        for t in self.merged():
            if t["id"] == tid:
                return t
        return None

    def put(self, tip):
        c = _clean_tip(tip)
        if not c:
            return False
        self.user = [t for t in self.user if t["id"] != c["id"]] + [c]
        return self.save()

    def remove(self, tid):
        """Delete your own tip, or Reset an edited built-in one."""
        self.user = [t for t in self.user if t["id"] != tid]
        return self.save()

    def new_id(self, title):
        slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")[:30] or "tip"
        base, n = "user-" + slug, 1
        taken = set(t["id"] for t in self.merged())
        tid = base
        while tid in taken:
            n += 1
            tid = "%s-%d" % (base, n)
        return tid


def tip_haystack(t):
    return " ".join([t["category"], t["title"], t["keys"], t["symptom"],
                     " ".join(t["steps"]), t["notes"], t["tags"]]).lower()


def search_tips(tips, query):
    """Tips whose text contains EVERY word of the query (empty query = all)."""
    words = [w for w in (query or "").lower().split() if w]
    if not words:
        return list(tips)
    return [t for t in tips if all(w in tip_haystack(t) for w in words)]


def category_sort_key(cat):
    return (CATEGORY_ORDER.index(cat), "") if cat in CATEGORY_ORDER else (99, cat.lower())


# *************** DEL 13 - KEYBOARD GUARD ENGINE ******************************
# The Nektar "Steinberg DAW Control" files that made Cubase freeze when the
# Impact GX61 was switched on.  "Parking" a file = moving it out of Cubase's
# folder into a folder of our own; "restoring" = moving it back.
#
# Moving needs administrator rights (the files live in Program Files).  The
# worker tries a plain move first and only asks Windows for permission when that
# fails.  The worker NEVER touches Tk - it returns a result dict that the main
# thread picks up (a worker thread must not call after()).

GUARD_DEFAULT_FILES = [
    "ImpactGX61SteinbergDAWControl64.dll",
    "ImpactGX49SteinbergDAWControl64.dll",
]


def default_source_dir():
    common = (os.environ.get("CommonProgramW6432")
              or os.environ.get("CommonProgramFiles")
              or r"C:\Program Files\Common Files")
    return os.path.join(common, "Steinberg", "Shared Components")


def default_parked_dir():
    return os.path.join(PROGRAM_HF_DIR, "Parked")


def guard_files(S):
    v = S.get("guard_files")
    if v is None:
        return list(GUARD_DEFAULT_FILES)
    return [str(n).strip() for n in v if str(n).strip()]


def guard_dirs(S):
    src = (S.get("guard_source_dir") or "").strip() or default_source_dir()
    park = (S.get("guard_parked_dir") or "").strip() or default_parked_dir()
    return src, park


def guard_status(S):
    """One dict per managed file: name, state, paths.
    state: active (in Cubase's folder), parked, both, missing."""
    src_dir, park_dir = guard_dirs(S)
    out = []
    for name in guard_files(S):
        sp, pp = os.path.join(src_dir, name), os.path.join(park_dir, name)
        in_src, in_park = os.path.isfile(sp), os.path.isfile(pp)
        state = ("both" if in_src and in_park else "active" if in_src
                 else "parked" if in_park else "missing")
        out.append(dict(name=name, state=state, src=sp, parked=pp))
    return out


def plan_pairs(mode, S):
    """(from, to) moves for mode 'park' or 'restore'."""
    pairs = []
    for d in guard_status(S):
        if mode == "park" and d["state"] in ("active", "both"):
            pairs.append((d["src"], d["parked"]))
        elif mode == "restore" and d["state"] == "parked":
            pairs.append((d["parked"], d["src"]))
    return pairs


def move_direct(src, dst):
    """Move src to dst without administrator rights.  An existing dst is kept as
    dst + '.old' (and put back if the move fails)."""
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    bak = None
    if os.path.exists(dst):
        bak = dst + ".old"
        os.replace(dst, bak)
    try:
        shutil.move(src, dst)
    except Exception:
        if bak:
            try:
                os.replace(bak, dst)
            except OSError:
                pass
        raise


def _needs_admin(exc):
    return isinstance(exc, PermissionError) or getattr(exc, "winerror", None) == 5 \
        or getattr(exc, "errno", None) in (1, 13)


def guard_execute(mode, S, cubase_check=None, elevate=None):
    """Runs in a WORKER thread.  Returns a result dict:
        mode, moved [names], skipped [names], errors [text], elevated (bool),
        cancelled (bool), cubase [process names that blocked it], nothing (bool).
    cubase_check / elevate can be replaced by the self-test."""
    cubase_check = cubase_check or cubase_processes
    elevate = elevate or run_elevated_powershell
    res = dict(mode=mode, moved=[], skipped=[], errors=[], elevated=False,
               cancelled=False, cubase=[], nothing=False, when=time.time())
    running = cubase_check()
    if running:
        res["cubase"] = running
        return res
    pairs = plan_pairs(mode, S)
    if not pairs:
        res["nothing"] = True
        return res
    _src_dir, park_dir = guard_dirs(S)
    try:
        os.makedirs(park_dir, exist_ok=True)
    except OSError as e:
        res["errors"].append("cannot create the parked folder %s: %s" % (park_dir, e))
        return res
    need_admin = []
    for s, d in pairs:
        try:
            move_direct(s, d)
            res["moved"].append(os.path.basename(s))
        except Exception as e:
            if _needs_admin(e):
                need_admin.append((s, d))
            else:
                res["errors"].append("%s: %s" % (os.path.basename(s), e))
    if need_admin:
        res["elevated"] = True
        tmp = tempfile.mkdtemp(prefix="cubase_helper_")
        result_file = os.path.join(tmp, "result.txt")
        try:
            started, code, problem = elevate(build_move_script(need_admin, result_file))
            if not started:
                if problem == "cancelled":
                    res["cancelled"] = True
                else:
                    res["errors"].append("could not start the administrator step: "
                                         + problem)
            else:
                lines = []
                try:
                    with open(result_file, encoding="utf-8-sig") as fh:
                        lines = [ln.rstrip("\r\n") for ln in fh if ln.strip()]
                except OSError:
                    pass
                for ln in lines:
                    parts = ln.split("|", 2)
                    nm = os.path.basename(parts[1]) if len(parts) > 1 else "?"
                    if parts[0] == "OK":
                        res["moved"].append(nm)
                    elif parts[0] == "SKIP":
                        res["skipped"].append(nm)
                    else:
                        res["errors"].append("%s: %s" % (nm, parts[2] if len(parts) > 2
                                                         else "unknown error"))
                if not lines:
                    res["errors"].append(problem or "the administrator step gave no "
                                         "result (exit code %s)" % code)
        finally:
            shutil.rmtree(tmp, ignore_errors=True)
    return res


def find_cubase_exe(S):
    """The Cubase program file: the saved one, else the newest Program Files one."""
    saved = (S.get("cubase_exe") or "").strip()
    if saved and os.path.isfile(saved):
        return saved
    found = []
    for pf in {os.environ.get("ProgramW6432"), os.environ.get("ProgramFiles"),
               r"C:\Program Files"}:
        if pf:
            found += glob.glob(os.path.join(pf, "Steinberg", "Cubase*", "Cubase*.exe"))
    found = [f for f in found if CUBASE_RE.match(os.path.basename(f))]

    def ver(p):
        m = re.search(r"(\d+)", os.path.basename(p))
        return int(m.group(1)) if m else 0
    return max(found, key=ver) if found else ""



# *************** DEL 14 - SMALL DIALOGS (TOAST, MESSAGE, YES/NO, HELP) ********

def center_on(top, parent):
    """Put a dialog over its parent window, kept on the screen."""
    try:
        top.update_idletasks()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        x = parent.winfo_rootx() + (parent.winfo_width() - w) // 2
        y = parent.winfo_rooty() + (parent.winfo_height() - h) // 3
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        top.geometry("+%d+%d" % (max(0, min(x, sw - w)), max(0, min(y, sh - h - 40))))
    except tk.TclError:
        pass


def modal_ready(top):
    """Wait until the dialog is on screen so grab_set() can work."""
    try:
        top.wait_visibility()
    except tk.TclError:
        pass


def toast(root, text, ms=1000):
    """A small 'it worked' note that goes away by itself after 1 second."""
    try:
        t = tk.Toplevel(root)
        t.overrideredirect(True)
        t.attributes("-topmost", True)
        t.configure(bg=C_ACCENT)
        tk.Label(t, text=text, bg=C_BG2, fg=C_FG, font=(UI_FONT, 11),
                 padx=20, pady=10).pack(padx=2, pady=2)
        t.update_idletasks()
        x = root.winfo_rootx() + (root.winfo_width() - t.winfo_reqwidth()) // 2
        y = root.winfo_rooty() + root.winfo_height() - t.winfo_reqheight() - 70
        t.geometry("+%d+%d" % (max(0, x), max(0, y)))
        t.after(ms, t.destroy)
    except Exception:
        pass


def show_message(root, title, text, kind="info"):
    """A modal message.  Enter or Escape closes it."""
    top = tk.Toplevel(root)
    top.title(title)
    top.configure(bg=C_BG2)
    top.resizable(False, False)
    top.transient(root)
    tk.Label(top, text=title, bg=C_BG2, fg=C_BAD if kind == "error" else C_ACCENT,
             font=(UI_FONT, 13, "bold")).pack(anchor="w", padx=22, pady=(16, 4))
    tk.Label(top, text=text, bg=C_BG2, fg=C_FG, font=(UI_FONT, 10), justify="left",
             wraplength=520).pack(anchor="w", padx=22, pady=(0, 12))
    btn = mkbtn(top, "OK", top.destroy, width=10)
    btn.pack(pady=(0, 16))
    top.bind("<Return>", lambda e: top.destroy())
    top.bind("<KP_Enter>", lambda e: top.destroy())
    center_on(top, root)
    modal_ready(top)
    make_modal(top)
    btn.focus_set()
    return top


def ask_yes_no(root, title, text, yes="Yes", no="No", yes_kind="park"):
    """A modal question.  Enter = yes, Escape = no.  Returns True / False."""
    result = {"v": False}
    top = tk.Toplevel(root)
    top.title(title)
    top.configure(bg=C_BG2)
    top.resizable(False, False)
    top.transient(root)
    tk.Label(top, text=title, bg=C_BG2, fg=C_ACCENT,
             font=(UI_FONT, 13, "bold")).pack(anchor="w", padx=22, pady=(16, 4))
    tk.Label(top, text=text, bg=C_BG2, fg=C_FG, font=(UI_FONT, 10), justify="left",
             wraplength=520).pack(anchor="w", padx=22, pady=(0, 12))
    row = tk.Frame(top, bg=C_BG2)
    row.pack(pady=(0, 16))

    def answer(v):
        result["v"] = v
        top.destroy()
    b_yes = mkbtn(row, yes, lambda: answer(True), yes_kind, width=12)
    b_yes.pack(side="left", padx=6)
    mkbtn(row, no, lambda: answer(False), "normal", width=12).pack(side="left", padx=6)
    top.bind("<Return>", lambda e: answer(True))
    top.bind("<KP_Enter>", lambda e: answer(True))
    center_on(top, root)
    modal_ready(top)
    make_modal(top, on_escape=lambda: answer(False))
    b_yes.focus_set()
    root.wait_window(top)
    return result["v"]


HELP_TEXT = """\
# What this program is
Cubase helper is a pocket help for Cubase. It has two tabs: "Cubase help" (what to press or check when Cubase does something annoying) and "Keyboard guard" (keeps two Nektar files out of Cubase's way, so Cubase does not freeze when the Impact GX61 is switched on).

# Tab: Cubase help
- The list on the left holds the tips, grouped under headings. Click one to read it on the right.
- Type in the Search box to narrow the list. Every word you type must appear somewhere in the tip (title, key, text, search words). Ctrl+F jumps to the box; Clear empties it.
- The five QUICK FIXES buttons at the top jump straight to the problems that happen most often.
- A key cap shows the key to press, when there is one. Those are Cubase's DEFAULT keys - File > Key Commands in Cubase shows yours.
- New tip... writes a tip of your own. Edit... changes the tip you are reading. Editing a built-in tip keeps the original: "Reset to original" brings it back. Delete removes your own tips.
- In the tip editor: Enter in a one-line field saves, Ctrl+Enter saves from anywhere, Esc cancels. Write one step per line.
- Your tips live in Helpfiles\\Cubase_helper\\tips_user.json. Nothing is ever changed inside the program itself.

# Tab: Keyboard guard
- Why: with the Nektar Impact GX61 switched on, Cubase froze. A memory dump showed Cubase spinning inside its own remote-device handling. Moving Nektar's two "Steinberg DAW Control" files out of Cubase's folder fixed it. The keyboard still works as an ordinary MIDI keyboard; only Nektar's special Cubase integration (transport buttons, faders) is gone.
- The table shows each file and where it is: ACTIVE (in Cubase's folder - can freeze Cubase), PARKED (safe), BOTH, or NOT FOUND.
- "Park now" moves the files from Cubase's folder to the parked folder. "Restore all" moves them back (after asking). Windows asks for administrator permission when it has to - that is normal, the files live in Program Files.
- Cubase must be closed. If it is running, the program says so and moves nothing.
- AUTO MODE: while this program is open and Cubase is NOT running, the files are parked again by themselves if they come back (a Nektar update or reinstall puts them back). Windows asks for permission each time that happens. If you say No, auto mode pauses so it never nags; "Resume auto mode" or "Park now" starts it again.
- "Start Cubase" starts Cubase. If the files are active it offers to park them first.
- "Add file..." manages another file from Cubase's folder the same way. "Remove" takes a file off the list; it does not move or delete anything.
- The folders can be changed with Browse. Leave them as they are unless you know why.
- The log at the bottom shows what happened. The same lines go to Helpfiles\\0---Empty\\Cubase_helper.log.

# My notes
Opens a movable, zoomable window where you write and save your own texts about Cubase. Pick a text in the drop-down, edit it in place; it saves itself a second after the last key. "New..." starts another text. Files are Helpfiles\\Cubase_helper\\Playertext-<name>.txt.

# Other
- F1 opens this Help. Esc closes any dialog.
- The window remembers its size, position and your last choices.
- Diagnosis shows where the program runs from, which files it uses, what it sees (Cubase running or not) and the latest log lines. Look there first if something does not behave.
- If something goes wrong inside the program, a report is written to Helpfiles\\0---Empty\\Cubase_helper_crash.log and the program keeps running.
"""


class HelpDialog(tk.Toplevel):
    """The hardcoded in-app Help.  Closes with Escape."""

    def __init__(self, root):
        tk.Toplevel.__init__(self, root)
        self.title("Help - " + APP_TITLE)
        self.configure(bg=C_BG2)
        self.transient(root)
        self.geometry("780x640")
        self.minsize(520, 360)
        box = tk.Frame(self, bg=C_BG2)
        box.pack(fill="both", expand=True, padx=10, pady=(10, 4))
        box.rowconfigure(0, weight=1)
        box.columnconfigure(0, weight=1)
        txt = new_text(box, wrap="word", bg=C_BG3, fg=C_FG, relief="flat", bd=0,
                       padx=16, pady=12, highlightthickness=0, cursor="arrow",
                       font=(UI_FONT, 10))
        sb = tk.Scrollbar(box, command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        txt.grid(row=0, column=0, sticky="nsew")
        sb.grid(row=0, column=1, sticky="ns")
        txt.tag_configure("h", font=(UI_FONT, 12, "bold"), foreground=C_ACCENT,
                          spacing1=12, spacing3=4)
        txt.tag_configure("b", lmargin1=10, lmargin2=26, spacing3=4)
        txt.tag_configure("p", spacing3=4)
        for line in HELP_TEXT.splitlines():
            if line.startswith("# "):
                txt.insert("end", line[2:] + "\n", "h")
            elif line.startswith("- "):
                txt.insert("end", u"\u2022  " + line[2:] + "\n", "b")
            elif line.strip():
                txt.insert("end", line + "\n", "p")
        txt.configure(state="disabled")
        txt.bind("<Enter>", lambda e: txt.focus_set())
        mkbtn(self, "Close", self.destroy, width=10).pack(pady=(4, 12))
        center_on(self, root)
        modal_ready(self)
        make_modal(self)


# *************** DEL 15 - TAB: CUBASE HELP ***********************************

class HelpTab(tk.Frame):
    """Quick-fix buttons, a search box, the list of tips and the tip itself."""

    def __init__(self, parent, app):
        tk.Frame.__init__(self, parent, bg=C_BG)
        self.app = app
        self.rows = []              # ("hdr", category) / ("tip", id), same order as the list
        self.current = app.S.get("selected_tip") or ""
        # ToDo: folded headings are remembered in settings.json ("collapsed_headings");
        # a search always shows every heading open so no hit is hidden.
        self.collapsed = set(str(c) for c in (app.S.get("collapsed_headings") or []))

        # ---- quick fixes ----
        tk.Label(self, text="Quick fixes", bg=C_BG, fg=C_FG_DIM,
                 font=(UI_FONT, 9, "bold")).pack(anchor="w", padx=14, pady=(10, 0))
        strip = tk.Frame(self, bg=C_BG)
        strip.pack(fill="x", padx=11, pady=(2, 2))
        for i, (text, tid) in enumerate(QUICK_FIXES):
            strip.columnconfigure(i, weight=1, uniform="quick")
            mkbtn(strip, text, lambda t=tid: self.jump(t), "quick", width=1, height=2,
                  wraplength=150, justify="center").grid(
                      row=0, column=i, sticky="ew", padx=3, pady=3)

        # ---- search ----
        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=14, pady=(6, 2))
        tk.Label(bar, text="Search:", bg=C_BG, fg=C_FG,
                 font=(UI_FONT, 10)).pack(side="left")
        self.var_q = tk.StringVar(value=app.S.get("search", ""))
        self.ent = new_entry(bar, textvariable=self.var_q, width=38, bg=C_FIELD,
                             fg=C_FG, insertbackground=C_FG, relief="flat",
                             font=(UI_FONT, 11))
        self.ent.pack(side="left", padx=8, ipady=4)
        mkbtn(bar, "Clear", self.clear_search, width=7).pack(side="left")
        self.lbl_count = tk.Label(bar, width=16, anchor="w", bg=C_BG, fg=C_FG_DIM,
                                  font=(UI_FONT, 9))
        self.lbl_count.pack(side="left", padx=10)
        self.ent.bind("<Escape>", lambda e: self.clear_search())

        # ---- list (left) and tip (right) ----
        main = tk.Frame(self, bg=C_BG)
        main.pack(fill="both", expand=True, padx=14, pady=(4, 10))
        main.columnconfigure(1, weight=1)
        main.rowconfigure(0, weight=1)

        left = tk.Frame(main, bg=C_BG3)
        left.grid(row=0, column=0, sticky="ns", padx=(0, 8))
        self.lb = tk.Listbox(left, width=46, activestyle="none", exportselection=False,
                             bg=C_BG3, fg=C_FG, selectbackground=C_SELECT,
                             selectforeground="white", bd=0, highlightthickness=0,
                             font=(UI_FONT, 10))
        lsb = tk.Scrollbar(left, command=self.lb.yview)
        self.lb.configure(yscrollcommand=lsb.set)
        self.lb.pack(side="left", fill="both", expand=True)
        lsb.pack(side="left", fill="y")
        self.lb.bind("<<ListboxSelect>>", self._on_select)
        self.lb.bind("<Button-1>", self._on_click)
        self.lb.bind("<Enter>", lambda e: self.lb.focus_set())

        right = tk.Frame(main, bg=C_BG3)
        right.grid(row=0, column=1, sticky="nsew")
        right.rowconfigure(0, weight=1)
        right.columnconfigure(0, weight=1)
        self.txt = new_text(right, wrap="word", bg=C_BG3, fg=C_FG, relief="flat", bd=0,
                            padx=20, pady=14, highlightthickness=0, cursor="arrow",
                            font=(UI_FONT, 10), state="disabled")
        tsb = tk.Scrollbar(right, command=self.txt.yview)
        self.txt.configure(yscrollcommand=tsb.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        tsb.grid(row=0, column=1, sticky="ns")
        self.txt.bind("<Enter>", lambda e: self.txt.focus_set())
        t = self.txt
        t.tag_configure("title", font=(UI_FONT, 16, "bold"), foreground=C_ACCENT,
                        spacing3=2)
        t.tag_configure("meta", font=(UI_FONT, 9), foreground=C_FG_DIM, spacing3=10)
        t.tag_configure("keylabel", font=(UI_FONT, 10, "bold"), foreground=C_FG_DIM)
        t.tag_configure("keycap", font=("Consolas", 16, "bold"), foreground="#101418",
                        background=C_ACCENT)
        t.tag_configure("h", font=(UI_FONT, 10, "bold"), foreground=C_WARN,
                        spacing1=12, spacing3=3)
        t.tag_configure("body", font=(UI_FONT, 11), spacing3=3)
        t.tag_configure("step", font=(UI_FONT, 11), lmargin1=6, lmargin2=30,
                        spacing3=5)
        t.tag_configure("note", font=(UI_FONT, 10, "italic"), foreground=C_FG_DIM,
                        spacing1=4)

        row = tk.Frame(right, bg=C_BG3)
        row.grid(row=1, column=0, columnspan=2, sticky="ew", padx=12, pady=(2, 10))
        mkbtn(row, "New tip...", self.new_tip, width=12).pack(side="left", padx=(0, 6))
        self.btn_edit = mkbtn(row, "Edit...", self.edit_tip, width=12)
        self.btn_edit.pack(side="left", padx=6)
        self.btn_del = mkbtn(row, "Delete", self.delete_tip, "danger", width=18)
        self.btn_del.pack(side="left", padx=6)

        self.var_q.trace_add("write", lambda *a: self.refresh())
        self.refresh()

    # ---- list ----
    def clear_search(self):
        self.var_q.set("")
        self.ent.focus_set()

    def focus_search(self):
        self.ent.focus_set()
        self.ent.select_range(0, "end")

    def refresh(self, keep=None):
        tips = self.app.tips.merged()
        found = search_tips(tips, self.var_q.get())
        cats = sorted(set(t["category"] for t in found), key=category_sort_key)
        want = keep or self.current
        searching = bool(self.var_q.get().strip())
        self.rows = []
        self.lb.delete(0, "end")
        sel = first_tip = None
        for c in cats:
            folded = c in self.collapsed and not searching
            self.rows.append(("hdr", c))
            self.lb.insert("end", ("▸  " if folded else "▾  ") + c.upper())
            i = len(self.rows) - 1
            self.lb.itemconfig(i, fg=C_ACCENT, selectforeground=C_ACCENT,
                               selectbackground=C_BG3)
            if folded:
                continue
            for t in [x for x in found if x["category"] == c]:
                self.rows.append(("tip", t["id"]))
                self.lb.insert("end", "    " + t["title"])
                i = len(self.rows) - 1
                if first_tip is None:
                    first_tip = i
                if t["id"] == want:
                    sel = i
        self.lbl_count.configure(text="%d of %d tips" % (len(found), len(tips))
                                 if searching else "%d tips" % len(tips))
        if sel is None and any(t["id"] == want for t in found):
            # the wanted tip sits under a folded heading: keep showing it, no list selection
            self.lb.selection_clear(0, "end")
            self.current = want
            self.show_tip(want)
            return
        if sel is None:
            sel = first_tip
        if sel is None:
            self.current = ""
            self._show_empty()
            return
        self.lb.selection_clear(0, "end")
        self.lb.selection_set(sel)
        self.lb.see(sel)
        self.current = self.rows[sel][1]
        self.show_tip(self.current)

    def _on_click(self, event):
        """A click on a heading folds / unfolds it (and never selects it)."""
        if self.var_q.get().strip():            # while searching every heading stays open
            return None
        i = self.lb.nearest(event.y)
        bbox = self.lb.bbox(i) if 0 <= i < len(self.rows) else None
        if not bbox or event.y > bbox[1] + bbox[3] or self.rows[i][0] != "hdr":
            return None
        cat = self.rows[i][1]
        if cat in self.collapsed:
            self.collapsed.discard(cat)
        else:
            self.collapsed.add(cat)
        self.app.S["collapsed_headings"] = sorted(self.collapsed)
        save_settings(self.app.S)
        top = self.lb.yview()[0]
        self.refresh()
        self.lb.yview_moveto(top)
        return "break"

    def _on_select(self, event=None):
        sel = self.lb.curselection()
        if not sel:
            return
        i = sel[0]
        kind, val = self.rows[i]
        if kind == "hdr":                       # headings cannot be chosen
            j = i + 1 if i + 1 < len(self.rows) else i - 1
            if 0 <= j < len(self.rows) and self.rows[j][0] == "tip":
                self.lb.selection_clear(0, "end")
                self.lb.selection_set(j)
                self.current = self.rows[j][1]
                self.show_tip(self.current)
            return
        self.current = val
        self.show_tip(val)

    def jump(self, tid):
        """A quick-fix button: show that tip, whatever the search says."""
        self.var_q.set("")
        t = self.app.tips.get(tid)
        if t and t["category"] in self.collapsed:       # open its heading so the tip is seen
            self.collapsed.discard(t["category"])
            self.app.S["collapsed_headings"] = sorted(self.collapsed)
        self.refresh(keep=tid)

    # ---- the tip ----
    def _set_text(self, parts):
        self.txt.configure(state="normal")
        self.txt.delete("1.0", "end")
        for text, tag in parts:
            self.txt.insert("end", text, tag)
        self.txt.configure(state="disabled")
        self.txt.yview_moveto(0)

    def _show_empty(self):
        self._set_text([("No tip matches that search.\n", "title"),
                        ("Try fewer words, or press Clear.  Or write the tip "
                         "yourself with 'New tip...'.", "body")])
        self.btn_edit.configure(state="disabled")
        set_btn_kind(self.btn_del, "normal")
        self.btn_del.configure(text="Delete", state="disabled")

    def show_tip(self, tid):
        t = self.app.tips.get(tid)
        if not t:
            self._show_empty()
            return
        origin = {"built-in": "Built-in tip", "edited": "Built-in tip - your edited version",
                  "yours": "Your own tip"}[t["origin"]]
        parts = [(t["title"] + "\n", "title"), ("%s   -   %s\n" % (t["category"], origin), "meta")]
        if t["keys"].strip():
            parts += [("Key:   ", "keylabel"), (" %s " % t["keys"].strip(), "keycap"),
                      ("\n", "body")]
        if t["symptom"].strip():
            parts += [("What you see\n", "h"), (t["symptom"].strip() + "\n", "body")]
        if t["steps"]:
            parts.append(("What to do\n", "h"))
            for n, s in enumerate(t["steps"], 1):
                parts.append(("%d.   %s\n" % (n, s), "step"))
        if t["notes"].strip():
            parts += [("Good to know\n", "h"), (t["notes"].strip() + "\n", "note")]
        self._set_text(parts)
        self.btn_edit.configure(state="normal")
        if t["origin"] == "yours":
            set_btn_kind(self.btn_del, "danger")
            self.btn_del.configure(text="Delete", state="normal")
        elif t["origin"] == "edited":
            set_btn_kind(self.btn_del, "normal")
            self.btn_del.configure(text="Reset to original", state="normal")
        else:
            set_btn_kind(self.btn_del, "normal")
            self.btn_del.configure(text="Delete", state="disabled")
        self.app.S["selected_tip"] = tid

    # ---- editing ----
    def new_tip(self):
        TipEditor(self.app, None, on_saved=lambda tid: self.refresh(keep=tid))

    def edit_tip(self):
        t = self.app.tips.get(self.current)
        if t:
            TipEditor(self.app, t, on_saved=lambda tid: self.refresh(keep=tid))

    def delete_tip(self):
        t = self.app.tips.get(self.current)
        if not t or t["origin"] == "built-in":
            return
        if t["origin"] == "yours":
            ok = ask_yes_no(self.app.root, "Delete tip",
                            'Delete your tip "%s"?' % t["title"], yes="Delete",
                            yes_kind="danger")
        else:
            ok = ask_yes_no(self.app.root, "Reset tip",
                            'Throw away your edited version of "%s" and go back '
                            'to the built-in one?' % t["title"], yes="Reset")
        if ok:
            self.app.tips.remove(t["id"])
            self.refresh(keep=t["id"])


# *************** DEL 16 - TIP EDITOR DIALOG **********************************

class TipEditor(tk.Toplevel):
    """New tip / edit tip.  Enter in a one-line field saves, Ctrl+Enter saves from
    anywhere, Escape cancels."""

    def __init__(self, app, tip=None, on_saved=None):
        tk.Toplevel.__init__(self, app.root)
        self.app, self.tip, self.on_saved = app, tip, on_saved
        self.title("Edit tip" if tip else "New tip")
        self.configure(bg=C_BG2)
        self.transient(app.root)
        self.geometry("680x700")
        self.minsize(560, 520)
        body = tk.Frame(self, bg=C_BG2)
        body.pack(fill="both", expand=True, padx=16, pady=(14, 4))
        body.columnconfigure(1, weight=1)

        def label(r, text):
            tk.Label(body, text=text, bg=C_BG2, fg=C_FG_DIM, width=12, anchor="ne",
                     font=(UI_FONT, 10)).grid(row=r, column=0, sticky="ne",
                                              padx=(0, 8), pady=5)

        def entry(r, value):
            e = new_entry(body, bg=C_FIELD, fg=C_FG, insertbackground=C_FG,
                          relief="flat", font=(UI_FONT, 11))
            e.insert(0, value)
            e.grid(row=r, column=1, sticky="ew", pady=4, ipady=4)
            e.bind("<Return>", lambda ev: self.save())
            e.bind("<KP_Enter>", lambda ev: self.save())
            return e

        def textbox(r, value, height):
            f = tk.Frame(body, bg=C_FIELD)
            f.grid(row=r, column=1, sticky="nsew", pady=4)
            f.rowconfigure(0, weight=1)
            f.columnconfigure(0, weight=1)
            t = new_text(f, height=height, wrap="word", bg=C_FIELD, fg=C_FG,
                         insertbackground=C_FG, relief="flat", bd=0, padx=6, pady=4,
                         highlightthickness=0, font=(UI_FONT, 10), undo=True)
            sb = tk.Scrollbar(f, command=t.yview)
            t.configure(yscrollcommand=sb.set)
            t.grid(row=0, column=0, sticky="nsew")
            sb.grid(row=0, column=1, sticky="ns")
            t.insert("1.0", value)
            t.edit_reset()
            return t

        tip = tip or {}
        label(0, "Title")
        self.e_title = entry(0, tip.get("title", ""))
        label(1, "Heading")
        # Heading: pick an existing one from the list, or type a new name.
        hrow = tk.Frame(body, bg=C_BG2)
        hrow.grid(row=1, column=1, sticky="ew", pady=4)
        hrow.columnconfigure(0, weight=1)
        self.e_cat = new_entry(hrow, bg=C_FIELD, fg=C_FG, insertbackground=C_FG,
                               relief="flat", font=(UI_FONT, 11))
        self.e_cat.insert(0, tip.get("category", "My tips"))
        self.e_cat.grid(row=0, column=0, sticky="ew", ipady=4)
        self.e_cat.bind("<Return>", lambda ev: self.save())
        self.e_cat.bind("<KP_Enter>", lambda ev: self.save())
        mkbtn(hrow, "▾  Pick", self.pick_heading, width=8).grid(
            row=0, column=1, padx=(6, 0))
        label(2, "Key")
        self.e_keys = entry(2, tip.get("keys", ""))
        label(3, "What you see")
        self.t_symptom = textbox(3, tip.get("symptom", ""), 3)
        label(4, "What to do\n(one step\nper line)")
        self.t_steps = textbox(4, "\n".join(tip.get("steps", [])), 8)
        body.rowconfigure(4, weight=1)
        label(5, "Good to know")
        self.t_notes = textbox(5, tip.get("notes", ""), 4)
        label(6, "Search words")
        self.e_tags = entry(6, tip.get("tags", ""))
        self.lbl_err = tk.Label(body, text="", bg=C_BG2, fg=C_BAD, anchor="w",
                                font=(UI_FONT, 10))
        self.lbl_err.grid(row=7, column=1, sticky="ew")

        row = tk.Frame(self, bg=C_BG2)
        row.pack(pady=(4, 14))
        mkbtn(row, "Save", self.save, "park", width=12).pack(side="left", padx=6)
        mkbtn(row, "Cancel", self.destroy, width=12).pack(side="left", padx=6)
        self.bind("<Control-Return>", lambda e: self.save())
        self.bind("<Control-KP_Enter>", lambda e: self.save())
        center_on(self, app.root)
        modal_ready(self)
        make_modal(self)
        self.e_title.focus_set()

    def pick_heading(self):
        """Drop-down of every heading in use (built-in order first, then your own)."""
        cats = sorted(set(t["category"] for t in self.app.tips.merged()),
                      key=category_sort_key)
        menu = tk.Menu(self, tearoff=0, bg=C_BG3, fg=C_FG, activebackground=C_SELECT,
                       activeforeground="white", font=(UI_FONT, 10))

        def choose(c):
            self.e_cat.delete(0, "end")
            self.e_cat.insert(0, c)
            self.e_cat.focus_set()
        for c in cats:
            menu.add_command(label=c, command=lambda c=c: choose(c))
        x = self.e_cat.winfo_rootx()
        y = self.e_cat.winfo_rooty() + self.e_cat.winfo_height()
        try:
            menu.tk_popup(x, y)
        finally:
            menu.grab_release()

    def save(self):
        title = self.e_title.get().strip()
        if not title:
            self.lbl_err.configure(text="The tip needs a title.")
            self.e_title.focus_set()
            return
        steps = [ln.strip() for ln in self.t_steps.get("1.0", "end").splitlines()
                 if ln.strip()]
        tid = self.tip["id"] if self.tip else self.app.tips.new_id(title)
        new = dict(id=tid, category=self.e_cat.get().strip() or "My tips", title=title,
                   keys=self.e_keys.get().strip(),
                   symptom=self.t_symptom.get("1.0", "end").strip(), steps=steps,
                   notes=self.t_notes.get("1.0", "end").strip(),
                   tags=self.e_tags.get().strip())
        if not self.app.tips.put(new):
            self.lbl_err.configure(text="Could not save - see the log.")
            return
        cb = self.on_saved
        self.destroy()
        if cb:
            cb(tid)


# *************** DEL 17 - TAB: KEYBOARD GUARD ********************************

GUARD_INFO = (
    "With the Nektar Impact GX61 switched on, Cubase froze. The cause was two "
    "Nektar \"Steinberg DAW Control\" files that Cubase loads at start. Parking "
    "them (moving them out of Cubase's folder) fixes it; the keyboard still works "
    "as an ordinary MIDI keyboard. Cubase must be closed while the files are moved.")

STATE_TEXT = {
    "active":  ("ACTIVE in Cubase's folder - can freeze Cubase", C_BAD),
    "parked":  ("Parked - safe", C_GOOD),
    "both":    ("In BOTH places - the Cubase copy can freeze Cubase", C_WARN),
    "missing": ("Not found anywhere", C_FG_DIM),
}


class GuardTab(tk.Frame):
    def __init__(self, parent, app):
        tk.Frame.__init__(self, parent, bg=C_BG)
        self.app = app
        self._sig = None
        S = app.S

        tk.Label(self, text="Keyboard guard", bg=C_BG, fg=C_ACCENT,
                 font=(UI_FONT, 15, "bold")).pack(anchor="w", padx=14, pady=(12, 0))
        tk.Label(self, text=GUARD_INFO, bg=C_BG, fg=C_FG_DIM, justify="left",
                 anchor="w", wraplength=880, font=(UI_FONT, 10)).pack(
                     fill="x", padx=14, pady=(2, 8))

        # ---- folders ----
        fr = tk.Frame(self, bg=C_BG)
        fr.pack(fill="x", padx=14)
        fr.columnconfigure(1, weight=1)
        src, park = guard_dirs(S)
        self.var_src, self.var_park = tk.StringVar(value=src), tk.StringVar(value=park)
        self.e_src = self._folder_row(fr, 0, "Cubase folder:", self.var_src,
                                      "guard_source_dir", default_source_dir)
        self.e_park = self._folder_row(fr, 1, "Parked folder:", self.var_park,
                                       "guard_parked_dir", default_parked_dir)

        # ---- the files ----
        tk.Label(self, text="Files kept out of Cubase's way", bg=C_BG, fg=C_FG,
                 font=(UI_FONT, 10, "bold")).pack(anchor="w", padx=14, pady=(12, 2))
        self.rows_frame = tk.Frame(self, bg=C_BG3)
        self.rows_frame.pack(fill="x", padx=14)
        mkbtn(self, "Add file...", self.add_file, width=12).pack(
            anchor="w", padx=14, pady=(6, 0))

        # ---- actions ----
        act = tk.Frame(self, bg=C_BG)
        act.pack(fill="x", padx=14, pady=(12, 0))
        self.btn_park = mkbtn(act, "Park now", lambda: app.run_guard("park"),
                              "park", width=14)
        self.btn_park.pack(side="left", padx=(0, 6))
        self.btn_restore = mkbtn(act, "Restore all", self.restore, "restore", width=14)
        self.btn_restore.pack(side="left", padx=6)
        mkbtn(act, "Refresh", self.app.refresh_all, width=10).pack(side="left", padx=6)
        mkbtn(act, "Start Cubase", self.app.start_cubase, width=14).pack(
            side="left", padx=6)
        self.lbl_cubase = tk.Label(act, text="", bg=C_BG, fg=C_FG_DIM, anchor="w",
                                   width=36, font=(UI_FONT, 10))
        self.lbl_cubase.pack(side="left", padx=12)

        # ---- auto mode ----
        auto = tk.Frame(self, bg=C_BG)
        auto.pack(fill="x", padx=14, pady=(14, 0))
        self.var_auto = tk.BooleanVar(value=bool(S.get("guard_auto")))
        tk.Checkbutton(auto, text="Auto mode - keep the files parked by itself",
                       variable=self.var_auto, command=self.toggle_auto, bg=C_BG,
                       fg=C_FG, selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_ACCENT, highlightthickness=0,
                       font=(UI_FONT, 10, "bold")).pack(side="left")
        tk.Label(auto, text="   check every", bg=C_BG, fg=C_FG_DIM,
                 font=(UI_FONT, 10)).pack(side="left")
        self.var_interval = tk.StringVar(value=str(S.get("guard_interval", 15)))
        self.sp = tk.Spinbox(auto, from_=5, to=600, width=5, textvariable=self.var_interval,
                             command=self.commit_interval, bg=C_FIELD, fg=C_FG,
                             insertbackground=C_FG, buttonbackground=C_BG2, relief="flat",
                             font=(UI_FONT, 10), insertofftime=0, insertontime=9999999)
        self.sp.pack(side="left", padx=6)
        self.sp.bind("<Return>", lambda e: self.commit_interval())
        self.sp.bind("<FocusOut>", lambda e: self.commit_interval())
        tk.Label(auto, text="seconds", bg=C_BG, fg=C_FG_DIM,
                 font=(UI_FONT, 10)).pack(side="left")
        self.btn_resume = mkbtn(auto, "Resume auto mode", self.app.resume_auto, width=18)
        self.btn_resume.pack(side="left", padx=14)
        self.btn_resume.configure(state="disabled")
        self.lbl_auto = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM, anchor="w",
                                 justify="left", wraplength=880, font=(UI_FONT, 10))
        self.lbl_auto.pack(fill="x", padx=14, pady=(2, 0))
        tk.Label(self, text="Auto mode works while this program is open and Cubase is "
                 "not running. Windows asks for permission each time files have to be "
                 "moved; saying No pauses auto mode.", bg=C_BG, fg=C_FG_DIM,
                 anchor="w", justify="left", wraplength=880,
                 font=(UI_FONT, 9)).pack(fill="x", padx=14)

        # ---- log ----
        lf = tk.Frame(self, bg=C_BG3)
        lf.pack(fill="both", expand=True, padx=14, pady=(10, 12))
        lf.rowconfigure(0, weight=1)
        lf.columnconfigure(0, weight=1)
        self.log_txt = new_text(lf, height=7, wrap="word", bg=C_BG3, fg=C_FG_DIM,
                                relief="flat", bd=0, padx=10, pady=6,
                                highlightthickness=0, cursor="arrow",
                                font=("Consolas", 9), state="disabled")
        sb = tk.Scrollbar(lf, command=self.log_txt.yview)
        self.log_txt.configure(yscrollcommand=sb.set)
        self.log_txt.grid(row=0, column=0, sticky="nsew")
        sb.grid(row=0, column=1, sticky="ns")
        self.log_txt.bind("<Enter>", lambda e: self.log_txt.focus_set())
        self.refresh()

    # ---- folder rows ----
    def _folder_row(self, parent, r, text, var, key, default_fn):
        tk.Label(parent, text=text, bg=C_BG, fg=C_FG_DIM, width=14, anchor="w",
                 font=(UI_FONT, 10)).grid(row=r, column=0, sticky="w", pady=3)
        e = new_entry(parent, textvariable=var, bg=C_FIELD, fg=C_FG,
                      insertbackground=C_FG, relief="flat", font=(UI_FONT, 10))
        e.grid(row=r, column=1, sticky="ew", pady=3, ipady=3, padx=(0, 6))

        def commit(event=None):
            v = var.get().strip()
            self.app.S[key] = "" if (not v or v == default_fn()) else v
            self.app.save()
            self.app.refresh_all()
        e.bind("<Return>", commit)
        e.bind("<FocusOut>", commit)

        def browse():
            d = filedialog.askdirectory(parent=self.app.root, initialdir=var.get() or None,
                                        title=text.strip(":"))
            if d:
                var.set(os.path.normpath(d))
                commit()
        mkbtn(parent, "Browse...", browse, width=10).grid(row=r, column=2, padx=3)
        mkbtn(parent, "Open", lambda: open_path(var.get()), width=7).grid(
            row=r, column=3, padx=3)
        return e

    # ---- rows with the files ----
    def refresh(self):
        S = self.app.S
        st = guard_status(S)
        sig = tuple((d["name"], d["state"]) for d in st)
        if sig != self._sig:
            self._sig = sig
            for w in self.rows_frame.winfo_children():
                w.destroy()
            for d in st:
                row = tk.Frame(self.rows_frame, bg=C_BG3)
                row.pack(fill="x", padx=6, pady=2)
                tk.Label(row, text=d["name"], width=40, anchor="w", bg=C_BG3, fg=C_FG,
                         font=("Consolas", 10)).pack(side="left")
                text, colour = STATE_TEXT[d["state"]]
                tk.Label(row, text=text, width=52, anchor="w", bg=C_BG3, fg=colour,
                         font=(UI_FONT, 10, "bold")).pack(side="left", padx=8)
                mkbtn(row, "Remove", lambda n=d["name"]: self.remove_file(n),
                      width=8, pady=1).pack(side="right")
        active = sum(1 for d in st if d["state"] in ("active", "both"))
        self.btn_park.configure(state="normal" if active else "disabled")
        self.btn_restore.configure(
            state="normal" if any(d["state"] == "parked" for d in st) else "disabled")
        run = self.app.cubase_now
        if run:
            self.lbl_cubase.configure(text="Cubase is RUNNING - close it first",
                                      fg=C_WARN)
        else:
            self.lbl_cubase.configure(text="Cubase is not running.", fg=C_GOOD)
        self.btn_resume.configure(state="normal" if self.app.auto_paused else "disabled")
        self.lbl_auto.configure(text=self.app.auto_status_text(), fg=(
            C_WARN if self.app.auto_paused else C_FG_DIM))

    def set_busy(self, busy):
        state = "disabled" if busy else "normal"
        self.btn_park.configure(state=state)
        self.btn_restore.configure(state=state)

    def log(self, msg):
        stamp = datetime.now().strftime("%H:%M:%S")
        self.log_txt.configure(state="normal")
        self.log_txt.insert("end", "%s  %s\n" % (stamp, msg))
        self.log_txt.see("end")
        self.log_txt.configure(state="disabled")
        log_line("GUARD", msg)

    # ---- actions ----
    def restore(self):
        if ask_yes_no(self.app.root, "Restore the files",
                      "Put the parked files back into Cubase's folder?\n\nCubase may "
                      "freeze again when the Impact GX61 is switched on.",
                      yes="Restore", yes_kind="normal"):
            self.app.run_guard("restore")

    def toggle_auto(self):
        self.app.S["guard_auto"] = bool(self.var_auto.get())
        self.app.auto_paused = False
        self.app.last_auto = 0.0
        self.app.save()
        self.log("Auto mode switched %s." % ("ON" if self.app.S["guard_auto"] else "OFF"))
        self.refresh()

    def commit_interval(self):
        try:
            v = max(5, min(600, int(float(self.var_interval.get()))))
        except ValueError:
            v = 15
        self.var_interval.set(str(v))
        self.app.S["guard_interval"] = v
        self.app.save()

    def add_file(self):
        src_dir, _ = guard_dirs(self.app.S)
        p = filedialog.askopenfilename(parent=self.app.root, initialdir=src_dir,
                                       title="Choose a file in Cubase's folder")
        if not p:
            return
        if os.path.normcase(os.path.dirname(os.path.abspath(p))) != \
                os.path.normcase(os.path.abspath(src_dir)):
            show_message(self.app.root, "Wrong folder",
                         "The file must be in the Cubase folder:\n%s" % src_dir, "error")
            return
        names = guard_files(self.app.S)
        name = os.path.basename(p)
        if name.lower() not in [n.lower() for n in names]:
            names.append(name)
            self.app.S["guard_files"] = names
            self.app.save()
            self.log("Now managing %s." % name)
        self.refresh()

    def remove_file(self, name):
        self.app.S["guard_files"] = [n for n in guard_files(self.app.S)
                                     if n.lower() != name.lower()]
        self.app.save()
        self.log("No longer managing %s (nothing was moved or deleted)." % name)
        self.refresh()


# *************** DEL 18 - DIAGNOSIS DIALOG ***********************************

def diagnosis_text(app):
    S = app.S
    try:
        admin = bool(ctypes.windll.shell32.IsUserAnAdmin())
    except Exception:
        admin = False
    running_from = (sys.executable if getattr(sys, "frozen", False)
                    else os.path.abspath(__file__))
    icon = _find_icon_path()
    src_dir, park_dir = guard_dirs(S)
    L = ["%s %s" % (APP_TITLE, APP_VERSION),
         "Python %s on %s" % (sys.version.split()[0], platform.platform()),
         "Running from : %s%s" % (running_from, "  (frozen build)"
                                  if getattr(sys, "frozen", False) else ""),
         "Program name : %s" % PROGRAM_NAME,
         "Home         : %s" % BASE_DIR,
         "Program data : %s" % PROGRAM_HF_DIR,
         "Logs         : %s" % LOG_DIR,
         "Icon file    : %s" % (icon or "not found (looked for %s.ico in %s)"
                                % (PROGRAM_NAME, ICON_DIR)),
         "Settings     : %s%s" % (settings_file(),
                                  "" if os.path.isfile(settings_file()) else "  (not saved yet)"),
         "Your tips    : %s  (%d)" % (TipStore.path(), len(app.tips.user)),
         "",
         "Cubase       : %s" % (", ".join(app.cubase_now) + " is running"
                                 if app.cubase_now else "not running"),
         "Cubase exe   : %s" % (find_cubase_exe(S) or "not found"),
         "Administrator : %s (the program asks Windows only when it has to move files)"
         % ("yes" if admin else "no"),
         "",
         "Keyboard guard",
         "  Cubase folder : %s%s" % (src_dir, "" if os.path.isdir(src_dir)
                                      else "   <-- does not exist"),
         "  Parked folder : %s" % park_dir]
    for d in guard_status(S):
        L.append("  %-40s %s" % (d["name"], d["state"]))
    L.append("  Auto mode     : %s%s" % (
        "on" if S.get("guard_auto") else "off",
        " (paused: " + app.auto_pause_reason + ")" if app.auto_paused else ""))
    L += ["", "Crash log     : %s%s" % (crash_log_path(), "" if os.path.isfile(
        crash_log_path()) else "  (none - good)"), "", "Latest log lines:"]
    try:
        with open(os.path.join(LOG_DIR, PROGRAM_NAME + ".log"), encoding="utf-8") as fh:
            tail = fh.read().splitlines()[-15:]
        L += ["  " + ln for ln in tail] or ["  (empty)"]
    except OSError:
        L.append("  (no log yet)")
    return "\n".join(L)


class DiagnosisDialog(tk.Toplevel):
    def __init__(self, app):
        tk.Toplevel.__init__(self, app.root)
        self.app = app
        self.title("Diagnosis - " + APP_TITLE)
        self.configure(bg=C_BG2)
        self.transient(app.root)
        self.geometry("860x600")
        self.minsize(520, 320)
        box = tk.Frame(self, bg=C_BG2)
        box.pack(fill="both", expand=True, padx=10, pady=(10, 4))
        box.rowconfigure(0, weight=1)
        box.columnconfigure(0, weight=1)
        self.txt = new_text(box, wrap="none", bg=C_BG3, fg=C_FG, relief="flat", bd=0,
                            padx=12, pady=10, highlightthickness=0,
                            font=("Consolas", 9))
        vs = tk.Scrollbar(box, command=self.txt.yview)
        hs = tk.Scrollbar(box, orient="horizontal", command=self.txt.xview)
        self.txt.configure(yscrollcommand=vs.set, xscrollcommand=hs.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vs.grid(row=0, column=1, sticky="ns")
        hs.grid(row=1, column=0, sticky="ew")
        self.txt.insert("1.0", diagnosis_text(app))
        self.txt.configure(state="disabled")
        row = tk.Frame(self, bg=C_BG2)
        row.pack(pady=(4, 12))
        mkbtn(row, "Copy", self.copy, width=10).pack(side="left", padx=5)
        mkbtn(row, "Open log folder", lambda: open_path(LOG_DIR), width=16).pack(
            side="left", padx=5)
        mkbtn(row, "Close", self.destroy, width=10).pack(side="left", padx=5)
        center_on(self, app.root)
        modal_ready(self)
        make_modal(self)

    def copy(self):
        self.clipboard_clear()
        self.clipboard_append(self.txt.get("1.0", "end-1c"))
        toast(self.app.root, "Copied.")


# *************** DEL 19 - MAIN WINDOW ****************************************

GEOMETRY_RE = re.compile(r"^(\d+)x(\d+)(?:\+(-?\d+)\+(-?\d+))?$")


def valid_geometry(geo, screen_w, screen_h):
    """The saved window geometry if it still fits this screen, else the default
    size (a window saved on a second monitor must not open off-screen)."""
    m = GEOMETRY_RE.match(str(geo or ""))
    if not m:
        return DEFAULT_GEOMETRY
    w, h = int(m.group(1)), int(m.group(2))
    w, h = max(MIN_WIDTH, min(w, screen_w)), max(MIN_HEIGHT, min(h, screen_h))
    if m.group(3) is not None:
        x, y = int(m.group(3)), int(m.group(4))
        if -w + 100 < x < screen_w - 100 and 0 <= y < screen_h - 100:
            return "%dx%d+%d+%d" % (w, h, x, y)
    return "%dx%d" % (w, h)


class App(object):
    def __init__(self, root):
        self.root = root
        self.S = load_settings()
        self.tips = TipStore()
        self.cubase_now = []
        self.guard_busy = False
        self.guard_q = queue.Queue()
        self.auto_paused = False
        self.auto_pause_reason = ""
        self.last_auto = 0.0
        self.last_auto_check = ""
        self.playertext = None

        root.title(APP_TITLE)
        root.configure(bg=C_BG)
        root.minsize(MIN_WIDTH, MIN_HEIGHT)
        root.geometry(valid_geometry(self.S.get("geometry"), root.winfo_screenwidth(),
                                     root.winfo_screenheight()))
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.report_callback_exception = _crash_handler

        # ---- top bar ----
        top = tk.Frame(root, bg=C_BG2)
        top.pack(fill="x")
        tk.Label(top, text=u"\U0001F39B  " + APP_TITLE, bg=C_BG2, fg=C_ACCENT,
                 font=(UI_FONT, 14, "bold")).pack(side="left", padx=(14, 10), pady=8)
        self.tab_btns = {}
        for key, text in (("help", "Cubase help"), ("guard", "Keyboard guard")):
            b = mkbtn(top, text, lambda k=key: self.show_tab(k), "tab", width=16)
            b.pack(side="left", padx=3, pady=8)
            self.tab_btns[key] = b
        mkbtn(top, "About", self.show_about, width=8).pack(side="right", padx=(3, 14),
                                                          pady=8)
        mkbtn(top, "Diagnosis", lambda: DiagnosisDialog(self), width=10).pack(
            side="right", padx=3, pady=8)
        mkbtn(top, "Help (F1)", self.show_help, width=10).pack(side="right", padx=3, pady=8)
        mkbtn(top, "My notes", self.open_playertext, width=10).pack(
            side="right", padx=3, pady=8)

        # ---- status bar ----
        self.var_status = tk.StringVar(value="")
        bar = tk.Frame(root, bg=C_BG2)
        bar.pack(side="bottom", fill="x")
        tk.Label(bar, textvariable=self.var_status, bg=C_BG2, fg=C_FG_DIM, anchor="w",
                 font=(UI_FONT, 9)).pack(fill="x", padx=14, pady=3)

        # ---- tabs ----
        self.body = tk.Frame(root, bg=C_BG)
        self.body.pack(fill="both", expand=True)
        self.tab_help = HelpTab(self.body, self)
        self.tab_guard = GuardTab(self.body, self)
        self.tabs = {"help": self.tab_help, "guard": self.tab_guard}
        self.show_tab(self.S.get("tab") if self.S.get("tab") in self.tabs else "help")

        root.bind("<F1>", lambda e: self.show_help())
        root.bind("<Control-f>", lambda e: (self.show_tab("help"),
                                            self.tab_help.focus_search()))
        if self.S.get("show_playertext"):
            root.after(300, self.open_playertext)
        root.after(400, self._tick)
        log_line("START", "%s %s from %s (home %s)" % (
            APP_TITLE, APP_VERSION, os.path.abspath(__file__), BASE_DIR))

    # ---- settings ----
    def save(self):
        save_settings(self.S)

    # ---- tabs ----
    def show_tab(self, key):
        for k, f in self.tabs.items():
            f.pack_forget()
            set_btn_kind(self.tab_btns[k], "tab_on" if k == key else "tab")
        self.tabs[key].pack(fill="both", expand=True)
        self.S["tab"] = key
        if key == "guard":
            self.tab_guard.refresh()

    # ---- dialogs ----
    def show_help(self):
        HelpDialog(self.root)

    def show_about(self):
        show_about(self.root, APP_TITLE,
                   "A pocket help for Cubase",
                   u"\U0001F39B")

    def open_playertext(self):
        try:
            if self.playertext is not None and self.playertext.top.winfo_exists():
                self.playertext.top.lift()
                return
        except Exception:
            pass
        self.S["show_playertext"] = True
        self.playertext = PlayerTextPopup(
            self.root, self.S,
            ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel"),
            self.save, THEME, "My notes - " + APP_TITLE, PROGRAM_HF_DIR,
            lambda: {"hint": "Your own notes about Cubase. Saved by itself as "
                             "Playertext-<name>.txt in Helpfiles\\Cubase_helper."},
            default_name="Notes")

    # ---- Cubase / keyboard guard ----
    def refresh_all(self):
        self.cubase_now = cubase_processes()
        self.tab_guard.refresh()
        self._update_status_bar()

    def _update_status_bar(self):
        st = guard_status(self.S)
        counts = dict((k, sum(1 for d in st if d["state"] == k))
                      for k in ("active", "parked", "both", "missing"))
        parts = ["Cubase: %s" % ("RUNNING" if self.cubase_now else "not running")]
        if counts["active"] or counts["both"]:
            parts.append("Nektar files: %d in Cubase's folder" %
                         (counts["active"] + counts["both"]))
        elif counts["parked"]:
            parts.append("Nektar files: %d parked" % counts["parked"])
        else:
            parts.append("Nektar files: none found")
        parts.append("Auto mode: %s" % ("PAUSED" if self.auto_paused else
                                        "on" if self.S.get("guard_auto") else "off"))
        self.var_status.set("   |   ".join(parts))

    def auto_status_text(self):
        if self.auto_paused:
            return "Auto mode is paused: %s" % self.auto_pause_reason
        if not self.S.get("guard_auto"):
            return "Auto mode is off."
        if self.cubase_now:
            return "Auto mode is on - waiting for Cubase to be closed."
        return "Auto mode is on - watching. Last check %s." % (self.last_auto_check or "-")

    def resume_auto(self):
        self.auto_paused = False
        self.auto_pause_reason = ""
        self.last_auto = 0.0
        self.tab_guard.log("Auto mode resumed.")
        self.refresh_all()

    def run_guard(self, mode, auto=False):
        if self.guard_busy:
            return
        if not auto:
            self.auto_paused = False
            self.auto_pause_reason = ""
        self.guard_busy = True
        self.tab_guard.set_busy(True)
        S = json.loads(json.dumps(self.S))          # the worker gets its own copy

        def work():
            try:
                res = guard_execute(mode, S)
            except Exception as e:
                res = dict(mode=mode, moved=[], skipped=[], cubase=[], nothing=False,
                           errors=["%s: %s" % (type(e).__name__, e)], elevated=False,
                           cancelled=False, when=time.time())
                write_crash(traceback.format_exc())
            self.guard_q.put((res, auto))
        threading.Thread(target=work, daemon=True).start()
        self.root.after(200, self._poll_guard)

    def _poll_guard(self):
        try:
            res, auto = self.guard_q.get_nowait()
        except queue.Empty:
            self.root.after(200, self._poll_guard)
            return
        self.guard_busy = False
        try:
            self._guard_done(res, auto)
        finally:
            self.refresh_all()

    def _pause_auto(self, why):
        self.auto_paused = True
        self.auto_pause_reason = why
        self.tab_guard.log("Auto mode paused: " + why)

    def _guard_done(self, res, auto):
        g = self.tab_guard
        word = "Parked" if res["mode"] == "park" else "Restored"
        moved = res["moved"]
        if res["cubase"]:
            msg = ("Cubase is running (%s) - the files cannot be moved while it is open."
                   % ", ".join(res["cubase"]))
            g.log(msg)
            if not auto:
                show_message(self.root, "Close Cubase first",
                             msg + "\n\nClose Cubase completely, then try again.")
            return
        if moved:
            g.log("%s %d file%s%s: %s" % (word, len(moved), "" if len(moved) == 1 else "s",
                                         " (with administrator permission)"
                                         if res["elevated"] else "", ", ".join(moved)))
        if res["cancelled"]:
            g.log("Windows permission was declined - nothing was moved.")
            if auto:
                self._pause_auto("you declined the Windows permission prompt")
            else:
                show_message(self.root, "Nothing was moved",
                             "Windows asked for administrator permission and it "
                             "was declined, so nothing was moved.")
        if res["errors"]:
            for e in res["errors"]:
                g.log("ERROR: " + e)
            if auto:
                self._pause_auto("the last attempt failed (see the log)")
            else:
                show_message(self.root, "Could not move everything",
                             "\n".join(res["errors"]), "error")
        if res["nothing"] and not auto:
            g.log("Nothing to move.")
            toast(self.root, "Nothing to move.")
        if moved and not res["errors"] and not res["cancelled"]:
            toast(self.root, "%s %d file%s." % (word, len(moved),
                                                "" if len(moved) == 1 else "s"))

    def start_cubase(self):
        exe = find_cubase_exe(self.S)
        if not exe:
            p = filedialog.askopenfilename(parent=self.root, title="Choose the Cubase program",
                                           filetypes=[("Program", "*.exe")])
            if not p:
                return
            self.S["cubase_exe"] = p
            self.save()
            exe = p
        if self.cubase_now:
            toast(self.root, "Cubase is already running.")
            return
        if any(d["state"] in ("active", "both") for d in guard_status(self.S)):
            if ask_yes_no(self.root, "Park the files first?",
                          "The Nektar files are still in Cubase's folder.\n\nPark them "
                          "before starting Cubase?", yes="Park, then start",
                          no="Start anyway"):
                self.run_guard("park")
                self.root.after(300, lambda: self._start_after_park(exe))
                return
        open_path(exe)
        self.tab_guard.log("Started Cubase: " + exe)

    def _start_after_park(self, exe):
        if self.guard_busy:
            self.root.after(300, lambda: self._start_after_park(exe))
            return
        if any(d["state"] in ("active", "both") for d in guard_status(self.S)):
            self.tab_guard.log("Cubase was not started: the files are still in its folder.")
            return
        open_path(exe)
        self.tab_guard.log("Started Cubase: " + exe)

    # ---- the timer: refreshes the status, runs auto mode ----
    def _tick(self):
        try:
            self.cubase_now = cubase_processes()
            if self.S.get("guard_auto") and not self.guard_busy and not self.auto_paused:
                interval = max(5, int(self.S.get("guard_interval") or 15))
                if time.time() - self.last_auto >= interval:
                    self.last_auto = time.time()
                    self.last_auto_check = datetime.now().strftime("%H:%M:%S")
                    active = [d for d in guard_status(self.S)
                              if d["state"] in ("active", "both")]
                    if active and not self.cubase_now:
                        self.tab_guard.log("Auto mode: %d Nektar file%s in Cubase's "
                                           "folder - parking." % (
                                               len(active), "" if len(active) == 1 else "s"))
                        self.run_guard("park", auto=True)
            self.tab_guard.refresh()
            self._update_status_bar()
        except Exception:
            _crash_handler(*sys.exc_info())
        finally:
            self.root.after(3000, self._tick)

    # ---- closing ----
    def on_close(self):
        try:
            self.S["geometry"] = self.root.geometry()
            self.S["search"] = self.tab_help.var_q.get()
            if self.playertext is not None:
                try:
                    if self.playertext.top.winfo_exists():
                        self.playertext.save_now()
                except Exception:
                    pass
            self.save()
        finally:
            self.root.destroy()


# *************** DEL 20 - SELF-TEST ******************************************
# python Cubase_helper.py --selftest      (no window; checks the logic)

def run_selftest():
    ok = True

    def check(name, cond, detail=""):
        nonlocal ok
        print("%-58s %s %s" % (name, "PASS" if cond else "FAIL", detail))
        ok = ok and bool(cond)

    base = tempfile.mkdtemp(prefix="cubase_helper_test_")
    global PROGRAM_HF_DIR
    saved_hf = PROGRAM_HF_DIR
    PROGRAM_HF_DIR = os.path.join(base, "hf")
    try:
        # tips
        store = TipStore()
        tips = store.merged()
        ids = [t["id"] for t in tips]
        check("built-in tips: unique ids", len(ids) == len(set(ids)), "(%d tips)" % len(ids))
        check("quick-fix buttons point at real tips",
              all(tid in ids for _t, tid in QUICK_FIXES))
        check("search 'metronome' finds the metronome tip",
              any(t["id"] == "metronome" for t in search_tips(tips, "metronome")))
        check("search 'f autoscroll cursor' needs ALL words",
              [t["id"] for t in search_tips(tips, "autoscroll cursor")] == ["autoscroll"])
        check("search nonsense finds nothing", not search_tips(tips, "zzzqqq"))
        mine = dict(id=store.new_id("My trick"), category="My tips", title="My trick",
                    keys="X", symptom="s", steps=["one", "two"], notes="", tags="")
        check("save + reload a user tip", store.put(mine) and any(
            t["id"] == mine["id"] and t["origin"] == "yours" for t in TipStore().merged()))
        ed = dict(_clean_tip(DEFAULT_TIPS[0]))
        ed["title"] = "Edited title"
        store.put(ed)
        check("editing a built-in tip marks it 'edited'",
              store.get(DEFAULT_TIPS[0]["id"])["origin"] == "edited")
        store.remove(DEFAULT_TIPS[0]["id"])
        check("Reset brings the original back",
              store.get(DEFAULT_TIPS[0]["id"])["origin"] == "built-in")

        # PowerShell script quoting
        check("ps_quote doubles apostrophes", ps_quote("a'b") == "'a''b'")
        script = build_move_script([(r"C:\x y\a+b.dll", r"D:\o'k\a+b.dll")], r"C:\t\r.txt")
        check("script holds the odd path intact", "'D:\\o''k\\a+b.dll'" in script)
        enc = powershell_arguments(script).rsplit(" ", 1)[1]
        check("EncodedCommand round-trips",
              base64.b64decode(enc).decode("utf-16-le") == script)

        # guard with real files in temp folders (plain move, no administrator)
        src, park = os.path.join(base, "cubase"), os.path.join(base, "parked")
        os.makedirs(src)
        for n in GUARD_DEFAULT_FILES:
            with open(os.path.join(src, n), "wb") as fh:
                fh.write(b"MZ-test " + n.encode())
        S = dict(DEFAULT_SETTINGS, guard_source_dir=src, guard_parked_dir=park)
        check("status: both files ACTIVE",
              [d["state"] for d in guard_status(S)] == ["active", "active"])
        r = guard_execute("park", S, cubase_check=lambda: ["Cubase15.exe"])
        check("refuses while Cubase runs", r["cubase"] and not r["moved"]
              and len(os.listdir(src)) == 2)
        r = guard_execute("park", S, cubase_check=lambda: [])
        check("park moves both files", len(r["moved"]) == 2 and not r["errors"]
              and not os.listdir(src) and len(os.listdir(park)) == 2)
        check("status: both PARKED",
              [d["state"] for d in guard_status(S)] == ["parked", "parked"])
        r = guard_execute("park", S, cubase_check=lambda: [])
        check("park again = nothing to do", r["nothing"])
        with open(os.path.join(src, GUARD_DEFAULT_FILES[0]), "wb") as fh:
            fh.write(b"MZ-new copy from a Nektar update")
        check("a file that comes back is 'both'", guard_status(S)[0]["state"] == "both")
        r = guard_execute("park", S, cubase_check=lambda: [])
        with open(os.path.join(park, GUARD_DEFAULT_FILES[0]), "rb") as fh:
            newer = fh.read()
        check("park again takes the NEW copy, keeps the old as .old",
              len(r["moved"]) == 1 and newer.startswith(b"MZ-new")
              and os.path.isfile(os.path.join(park, GUARD_DEFAULT_FILES[0] + ".old")))
        r = guard_execute("restore", S, cubase_check=lambda: [])
        check("restore moves both back", len(r["moved"]) == 2 and len(os.listdir(src)) == 2)

        # the administrator path, with a fake 'elevate' that runs the SAME script
        # in a normal PowerShell (proves the script and its quoting work)
        for n in GUARD_DEFAULT_FILES:
            if os.path.isfile(os.path.join(park, n)):
                os.remove(os.path.join(park, n))
        original = move_direct

        def deny(*a):
            raise PermissionError(5, "Access is denied")

        def fake_elevate(script):
            p = subprocess.run([powershell_exe(), "-NoProfile", "-NonInteractive",
                                "-EncodedCommand",
                                base64.b64encode(script.encode("utf-16-le")).decode()],
                               capture_output=True, timeout=60)
            return True, p.returncode, p.stderr.decode(errors="replace")
        globals()["move_direct"] = deny
        try:
            r = guard_execute("park", S, cubase_check=lambda: [], elevate=fake_elevate)
        finally:
            globals()["move_direct"] = original
        check("administrator path moves the files", r["elevated"] and len(r["moved"]) == 2
              and not r["errors"] and not os.listdir(src), str(r["errors"]))
        def declined(script):
            return False, None, "cancelled"
        globals()["move_direct"] = deny
        try:
            r = guard_execute("restore", S, cubase_check=lambda: [], elevate=declined)
        finally:
            globals()["move_direct"] = original
        check("declined permission is reported, nothing moved",
              r["cancelled"] and not r["moved"] and not os.listdir(src))

        # misc
        check("Cubase15.exe counts as Cubase", bool(CUBASE_RE.match("cubase15.exe")))
        check("Cubase_helper.exe does NOT", not CUBASE_RE.match("cubase_helper.exe"))
        check("process list works", len(list_process_names()) > 5)
        check("saved geometry off-screen falls back to size only",
              valid_geometry("1000x700+9000+50", 1920, 1080) == "1000x700")
        check("saved geometry on-screen is kept",
              valid_geometry("1000x700+100+50", 1920, 1080) == "1000x700+100+50")
    finally:
        PROGRAM_HF_DIR = saved_hf
        shutil.rmtree(base, ignore_errors=True)
    print("\nALL PASSED" if ok else "\nSOMETHING FAILED")
    return 0 if ok else 1


# *************** DEL 90 - ENTRY POINT ****************************************

def main():
    global _ROOT
    if "--selftest" in sys.argv[1:]:
        sys.exit(run_selftest())
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    _ROOT = root
    app = App(root)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()


if __name__ == "__main__":
    main()
