# -*- coding: utf-8 -*-
"""Quick_Pins 1.0 - pin folders from ANY drive to Windows Explorer's navigation pane
(Quick access, the list with Desktop / Documents / Pictures ...), and switch between
whole SETS of folders with one click.

RULE: EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments, UI text, Help).

How it works: Explorer's Quick access is controlled through the Windows shell verbs
"pintohome" / "unpinfromhome" (PowerShell + Shell.Application).  The program only ever
touches the folders in ITS OWN list - Desktop, Documents and your other pins stay as they are.
My list + sets live in  <home>\\Helpfiles\\Quick_Pins\\pins.json.
"""

import base64
import ctypes
import json
import os
import platform
import queue
import shutil
import subprocess
import sys
import threading
import webbrowser
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, filedialog, messagebox

VERSION = "1.0"

# ToDo: (1) drag-and-drop of a folder from Explorer onto the list;  (2) a "pin on Windows
# start" switch (a set is applied when the program starts with the argument  --set <name>).

# *************** DEL XX - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico


# *************** DEL XX - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL XX - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL xx - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL **********
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()


# *************** DEL XX - ABOUT DIALOG (TEMPLATE) ****************************
# A TEMPLATE, not verbatim: adapt look / colours / emoji / name to the program,
# but KEEP THE MESSAGE (creator, documentation link, small gift).
# NOT for games - games never carry anything tied to me (see 40_games.md; they
# name the designers instead).
#
# Rules: About closes with ESC; Toplevel order grab_set(), focus_force(), <Escape>
# (make_modal does it).  Links open through open_url(), never webbrowser directly.
# The program NAME shown here has no "Issu" part (Issus, Issu's ...); only the
# creator line keeps Lars "Issu" Olsson.
#
# Needs:  import tkinter as tk
#         block_ui_helpers.py (make_modal)   block_open.py (open_url)
#
# Call:   show_about(root, "MyProgram", "What it is, in one line", "🏢")
# Change the colours by passing colors={...} that match the program's palette.

DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"

ABOUT_COLORS = dict(bg="#1e1e2e", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
                    sep="#3a3a4e", box="#252535", hover="#b4d4ff")


def show_about(root, app_name, tagline, emoji="🏢", colors=None):
    """Stylish About dialog with documentation link and donation info."""
    c = {**ABOUT_COLORS, **(colors or {})}

    top = tk.Toplevel(root)
    top.title("About " + app_name)
    top.configure(bg=c["bg"])
    top.resizable(False, False)
    top.transient(root)
    make_modal(top)                              # grab_set, focus_force, Escape

    # Header
    hdr = tk.Frame(top, bg=c["bg"])
    hdr.pack(fill="x")
    tk.Label(hdr, text=emoji, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 36)).pack(pady=(18, 0))
    tk.Label(hdr, text=app_name, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 20, "bold")).pack()
    tk.Label(hdr, text=tagline, bg=c["bg"], fg=c["dim"],
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20)

    # Creator
    tk.Label(top, text='Created by  Lars "Issu" Olsson', bg=c["bg"], fg=c["fg"],
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    def link(parent, text, url, size=9, **pack):
        lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=c["accent"],
                       font=("Segoe UI", size, "underline"), cursor="hand2")
        lbl.pack(**pack)
        lbl.bind("<Button-1>", lambda e: open_url(url))
        lbl.bind("<Enter>",    lambda e: lbl.configure(fg=c["hover"]))
        lbl.bind("<Leave>",    lambda e: lbl.configure(fg=c["accent"]))
        return lbl

    link(top, "📄  View documentation", DOC_URL, pady=(6, 2))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20, pady=(14, 0))

    # Donation
    tk.Label(top, text="Focusing on us instead of cha-ching\n"
                       "but if you like " + app_name +
                       ", you are welcome to send a token of appreciation",
             bg=c["bg"], fg=c["dim"], font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=c["box"], padx=16, pady=10)
    box.pack(fill="x", padx=20, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        link(box, text, url, pady=1)

    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(8, 16))
    return top



# *************** DEL 10 - SHELL: QUICK ACCESS THROUGH POWERSHELL *****************
# Windows has no plain API for the pinned list, only the shell verbs.  Each call is ONE
# PowerShell run (about a second); the folder lists travel inside the command as base64
# JSON, so odd characters in paths (å ä ö, spaces, ---) are safe.
# The PowerShell exe is started by its FULL path (01_CORE item 8), never by bare name.

PS_EXE = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32",
                      "WindowsPowerShell", "v1.0", "powershell.exe")
CREATE_NO_WINDOW = 0x08000000

PS_HEAD = r"""
$ErrorActionPreference = 'SilentlyContinue'
[Console]::OutputEncoding = [Text.Encoding]::UTF8
$sh = New-Object -ComObject Shell.Application
$qa = $sh.Namespace('shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}')
function Norm($p) { return ([string]$p).TrimEnd('\').ToLower() }
function Pinned {
    $o = @()
    foreach ($i in $qa.Items()) {
        $v = $null
        try { $v = $i.ExtendedProperty('System.Home.IsPinned') } catch {}
        if ($v -eq $true) { $o += $i }
    }
    return $o
}
"""

# D.unpin = paths to unpin, D.pin = paths to pin (in this order).  Answers with the
# pinned list: one line "P|<path>" each.
PS_APPLY = r"""
foreach ($p in @($D.unpin)) {
    foreach ($i in (Pinned)) {
        if ((Norm $i.Path) -eq (Norm $p)) { $i.InvokeVerb('unpinfromhome') }
    }
}
Start-Sleep -Milliseconds 500
$have = @{}
foreach ($i in (Pinned)) { $have[(Norm $i.Path)] = 1 }
foreach ($p in @($D.pin)) {
    if (-not $have.ContainsKey((Norm $p)) -and (Test-Path -LiteralPath $p)) {
        try { $sh.Namespace($p).Self.InvokeVerb('pintohome') } catch {}
        Start-Sleep -Milliseconds 250
    }
}
Start-Sleep -Milliseconds 500
foreach ($i in (Pinned)) { 'P|' + $i.Path }
"""

PS_LIST = r"""
foreach ($i in (Pinned)) { 'P|' + $i.Path }
"""

# Folders of the Explorer windows that are open right now: "W|<path>".
PS_WINDOWS = r"""
foreach ($w in $sh.Windows()) {
    $p = $null
    try { $p = $w.Document.Folder.Self.Path } catch {}
    if ($p -and (Test-Path -LiteralPath $p -PathType Container)) { 'W|' + $p }
}
"""


def norm_path(p):
    """Comparable form of a path: normalised, no trailing backslash, lower case."""
    try:
        return os.path.normpath(p.strip()).rstrip("\\").lower()
    except Exception:
        return str(p).lower()


def run_ps(body, data=None, timeout=120):
    """Run a PowerShell snippet; returns the output lines.  Raises RuntimeError on failure."""
    script = PS_HEAD
    if data is not None:
        b64 = base64.b64encode(json.dumps(data).encode("utf-8")).decode("ascii")
        script += ("$D = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('%s'))"
                   " | ConvertFrom-Json\n" % b64)
    script += body
    enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
    if not os.path.isfile(PS_EXE):
        raise RuntimeError("PowerShell was not found at " + PS_EXE)
    p = subprocess.Popen([PS_EXE, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
                          "-EncodedCommand", enc],
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                         stdin=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
    try:
        out, _err = p.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        p.kill()
        raise RuntimeError("PowerShell did not answer in time.")
    return out.decode("utf-8", "replace").splitlines()


def lines_with(lines, tag):
    """The text after 'tag|' of every output line that starts with it."""
    pre = tag + "|"
    return [ln[len(pre):].strip() for ln in lines if ln.startswith(pre)]


# *************** DEL 20 - DATA (MY LIST + SETS) ***********************************

DATA_FILE = os.path.join(PROGRAM_HF_DIR, "pins.json")
ALL_SETS = "(all sets)"

THEME = dict(bg="#1e1e2e", panel="#252535", fg="#e0e0e0", dim="#9090a8",
             accent="#89b4fa", btn="#3a3a4e", btnfg="#e0e0e0",
             field="#2b2b3d", field_fg="#e0e0e0")


def load_data():
    """-> (items, settings).  items = [{"path":..., "set":...}], never raises."""
    try:
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            d = json.load(f)
        items = []
        for it in d.get("folders", []):
            if isinstance(it, dict) and it.get("path"):
                items.append({"path": str(it["path"]), "set": str(it.get("set", ""))})
        st = d.get("settings", {})
        return items, (st if isinstance(st, dict) else {})
    except Exception:
        return [], {}


def save_data(items, settings):
    """Atomic write: a cut-off save can never leave a half file."""
    try:
        os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
        tmp = DATA_FILE + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump({"folders": items, "settings": settings}, f, indent=2,
                      ensure_ascii=False)
        os.replace(tmp, DATA_FILE)
    except Exception:
        pass


# *************** DEL 30 - HELP ****************************************************

HELP_TEXT = """QUICK PINS - what it does

Explorer's left-hand pane has a "Quick access" list (Desktop, Documents, Pictures ...).
This program puts YOUR folders there - from any drive - so one click in Explorer takes
you to a sub-folder on another hard drive.

THE LIST
 - Add folder...        pick a folder on any drive and put it on my list.
 - Add subfolders...    pick a folder, then tick which of its sub-folders to add.
 - Add open windows     adds the folders of the Explorer windows that are open now.
 - Remove from list     takes it off MY list (it is also unpinned from Explorer).
 - Up / Down            order of my list (and the order they are pinned in).

PINNING
 - Pin / Unpin          the selected rows (Ctrl/Shift for several).
 - Pin shown / Unpin shown   every row currently shown (see Sets).
 - Re-pin in my order   unpins and pins the shown rows again, in list order
                        (Explorer adds new pins at the end - this is the way to reorder).

SETS - switching between drives in one click
 Give rows a set name ("Music drive", "Work", "Archive" ...) with  "Set of selected" + [Set].
 Pick a set in the "Show" menu and press [Switch to this set]: the folders of that set are
 pinned, all my OTHER folders are unpinned.  (Desktop, Documents and any pin that is not on
 my list are never touched.)  "(all sets)" + Switch pins everything on my list.

NOTES
 - A folder on a drive that is not connected shows "Not found"; it cannot be pinned until the
   drive is back (the row stays on the list).
 - Pinning goes through Windows itself; a pin/unpin takes about a second.
 - If Explorer does not show a change at once, press F5 in the Explorer window.
 - Esc closes this window.  Player text = your own notes (saved by themselves).
"""


def show_help(root):
    top = tk.Toplevel(root)
    top.title("Help - Quick Pins")
    top.configure(bg=THEME["bg"])
    top.geometry("700x560")
    top.transient(root)
    make_modal(top)
    txt = new_text(top, bg=THEME["field"], fg=THEME["field_fg"], wrap="word",
                   font=("Segoe UI", 10), relief="flat", padx=12, pady=10)
    sb = tk.Scrollbar(top, command=txt.yview)
    txt.configure(yscrollcommand=sb.set)
    btn = tk.Button(top, text="Close", width=10, command=top.destroy)
    btn.pack(side="bottom", pady=8)
    sb.pack(side="right", fill="y")
    txt.pack(side="left", fill="both", expand=True)
    txt.insert("1.0", HELP_TEXT)
    txt.configure(state="disabled")


# *************** DEL 40 - THE WINDOW ***********************************************

class QuickPins(object):
    def __init__(self, root):
        self.root = root
        self.items, self.S = load_data()
        self.pinned = set()          # norm_path of everything pinned in Quick access now
        self.q = queue.Queue()
        self.busy = False
        self.player = None
        self.set_var = tk.StringVar(value=self.S.get("filter", ALL_SETS))
        self.status_var = tk.StringVar(value="")
        self._build()
        self._redraw()
        self.root.after(100, self._poll)
        self.root.after(200, self.refresh)
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
        if self.S.get("show_playertext"):
            self.root.after(400, self.open_player)

    # ---------- layout (fixed size: nothing reflows because of text) ----------
    def _build(self):
        r, T = self.root, THEME
        r.title("Quick Pins " + VERSION)
        r.configure(bg=T["bg"])
        r.geometry("860x560")
        r.resizable(False, False)

        def button(parent, text, cmd, w):
            return tk.Button(parent, text=text, command=cmd, width=w, bg=T["btn"],
                             fg=T["btnfg"], activebackground=T["accent"], relief="flat",
                             font=("Segoe UI", 9))

        # --- row 0: set filter + switch
        top = tk.Frame(r, bg=T["bg"])
        top.pack(fill="x", padx=10, pady=(10, 4))
        tk.Label(top, text="Show:", bg=T["bg"], fg=T["fg"],
                 font=("Segoe UI", 10, "bold")).pack(side="left")
        self.menu = tk.OptionMenu(top, self.set_var, ALL_SETS, command=lambda v: self._on_filter())
        self.menu.configure(width=24, bg=T["btn"], fg=T["btnfg"], relief="flat",
                            activebackground=T["accent"], highlightthickness=0, anchor="w")
        self.menu.pack(side="left", padx=6)
        button(top, "Switch to this set", self.switch_set, 18).pack(side="left", padx=4)
        tk.Label(top, text="pins this set, unpins my other folders", bg=T["bg"],
                 fg=T["dim"], font=("Segoe UI", 9, "italic")).pack(side="left", padx=8)

        # --- list
        mid = tk.Frame(r, bg=T["bg"])
        mid.pack(fill="both", expand=True, padx=10)
        style = ttk.Style()
        try:
            style.theme_use("clam")
        except Exception:
            pass
        style.configure("QP.Treeview", background=T["field"], fieldbackground=T["field"],
                        foreground=T["field_fg"], rowheight=24, borderwidth=0,
                        font=("Segoe UI", 10))
        style.configure("QP.Treeview.Heading", background=T["panel"], foreground=T["fg"],
                        font=("Segoe UI", 9, "bold"))
        style.map("QP.Treeview", background=[("selected", "#45475a")],
                  foreground=[("selected", "#ffffff")])
        self.tree = ttk.Treeview(mid, style="QP.Treeview", columns=("state", "set", "folder"),
                                 show="headings", selectmode="extended")
        self.tree.heading("state", text="State")
        self.tree.heading("set", text="Set")
        self.tree.heading("folder", text="Folder")
        self.tree.column("state", width=90, stretch=False)
        self.tree.column("set", width=150, stretch=False)
        self.tree.column("folder", width=560, stretch=True)
        sb = tk.Scrollbar(mid, command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)
        self.tree.tag_configure("pinned", foreground="#a6e3a1")
        self.tree.tag_configure("missing", foreground="#f38ba8")
        self.tree.bind("<Double-1>", lambda e: self.open_selected())
        self.tree.bind("<<TreeviewSelect>>", lambda e: self._show_selected_set())

        # --- buttons
        b1 = tk.Frame(r, bg=T["bg"])
        b1.pack(fill="x", padx=10, pady=(8, 2))
        for text, cmd, w in (("Add folder...", self.add_folder, 14),
                             ("Add subfolders...", self.add_subfolders, 16),
                             ("Add open windows", self.add_open_windows, 17),
                             ("Remove from list", self.remove_selected, 16),
                             ("Up", lambda: self.move(-1), 6),
                             ("Down", lambda: self.move(1), 6)):
            button(b1, text, cmd, w).pack(side="left", padx=(0, 6))
        b2 = tk.Frame(r, bg=T["bg"])
        b2.pack(fill="x", padx=10, pady=2)
        for text, cmd, w in (("Pin", self.pin_selected, 8),
                             ("Unpin", self.unpin_selected, 8),
                             ("Pin shown", self.pin_shown, 12),
                             ("Unpin shown", self.unpin_shown, 12),
                             ("Re-pin in my order", self.repin_shown, 18),
                             ("Open", self.open_selected, 8)):
            button(b2, text, cmd, w).pack(side="left", padx=(0, 6))
        b3 = tk.Frame(r, bg=T["bg"])
        b3.pack(fill="x", padx=10, pady=(2, 4))
        tk.Label(b3, text="Set of selected:", bg=T["bg"], fg=T["fg"],
                 font=("Segoe UI", 9)).pack(side="left")
        self.ent_set = new_entry(b3, width=22, bg=T["field"], fg=T["field_fg"],
                                 insertbackground=T["field_fg"], relief="flat",
                                 font=("Segoe UI", 10))
        self.ent_set.pack(side="left", padx=6, ipady=3)
        self.ent_set.bind("<Return>", lambda e: self.set_selected_set())
        button(b3, "Set", self.set_selected_set, 6).pack(side="left", padx=(0, 6))
        for text, cmd, w in (("Refresh", self.refresh, 9),
                             ("Player text", self.open_player, 11),
                             ("Help", lambda: show_help(self.root), 7),
                             ("About", self.about, 7)):
            button(b3, text, cmd, w).pack(side="left", padx=(0, 6))
        # fixed-size status line
        tk.Label(r, textvariable=self.status_var, bg=T["panel"], fg=T["dim"], anchor="w",
                 font=("Segoe UI", 9), width=110, height=1).pack(side="bottom", fill="x")

    # ---------- helpers ----------
    def say(self, text):
        self.status_var.set(text[:150])

    def about(self):
        show_about(self.root, "Quick Pins", "Pin folders from any drive to Explorer's Quick access",
                   "\U0001F4CC")

    def set_names(self):
        return sorted({it["set"] for it in self.items if it["set"]}, key=str.lower)

    def _rebuild_menu(self):
        m = self.menu["menu"]
        m.delete(0, "end")
        for name in [ALL_SETS] + self.set_names():
            m.add_command(label=name, command=lambda n=name: (self.set_var.set(n),
                                                              self._on_filter()))
        if self.set_var.get() not in [ALL_SETS] + self.set_names():
            self.set_var.set(ALL_SETS)

    def shown_indexes(self):
        f = self.set_var.get()
        return [i for i, it in enumerate(self.items) if f == ALL_SETS or it["set"] == f]

    def selected_indexes(self):
        return [int(i) for i in self.tree.selection()]

    def _redraw(self, keep=None):
        self._rebuild_menu()
        sel = set(keep if keep is not None else self.selected_indexes())
        self.tree.delete(*self.tree.get_children())
        for i in self.shown_indexes():
            it = self.items[i]
            exists = os.path.isdir(it["path"])
            if not exists:
                state, tag = "Not found", "missing"
            elif norm_path(it["path"]) in self.pinned:
                state, tag = "Pinned", "pinned"
            else:
                state, tag = "Not pinned", ""
            self.tree.insert("", "end", iid=str(i), values=(state, it["set"], it["path"]),
                             tags=(tag,) if tag else ())
        keepers = [str(i) for i in sel if self.tree.exists(str(i))]
        if keepers:
            self.tree.selection_set(keepers)

    def _on_filter(self):
        self.S["filter"] = self.set_var.get()
        self._save()
        self._redraw(keep=[])

    def _show_selected_set(self):
        sel = self.selected_indexes()
        if sel:
            self.ent_set.delete(0, "end")
            self.ent_set.insert(0, self.items[sel[0]]["set"])

    def _save(self):
        save_data(self.items, self.S)

    # ---------- background PowerShell ----------
    def run_bg(self, body, data, done, what):
        if self.busy:
            self.say("Wait - Windows is still working ...")
            return
        self.busy = True
        self.say(what + " ...")
        self.root.config(cursor="watch")

        def work():
            try:
                res = ("ok", run_ps(body, data))
            except Exception as e:
                res = ("err", str(e))
            self.q.put((done, res))
        threading.Thread(target=work, daemon=True).start()

    def _poll(self):
        try:
            while True:
                done, res = self.q.get_nowait()
                self.busy = False
                self.root.config(cursor="")
                if res[0] == "err":
                    self.say("Error: " + res[1])
                else:
                    done(res[1])
        except queue.Empty:
            pass
        self.root.after(100, self._poll)

    def _got_pinned(self, lines, msg="Done."):
        self.pinned = {norm_path(p) for p in lines_with(lines, "P")}
        self._redraw()
        mine = [it for it in self.items if norm_path(it["path"]) in self.pinned]
        self.say("%s  %d of my %d folders are pinned." % (msg, len(mine), len(self.items)))

    def refresh(self):
        self.run_bg(PS_LIST, None, self._got_pinned, "Reading Quick access")

    def _apply(self, pin, unpin, what):
        self.run_bg(PS_APPLY, {"pin": pin, "unpin": unpin},
                    lambda ln: self._got_pinned(ln, "Done."), what)

    # ---------- the list ----------
    def _add_paths(self, paths):
        have = {norm_path(it["path"]) for it in self.items}
        f = self.set_var.get()
        added = 0
        for p in paths:
            p = os.path.normpath(p)
            if norm_path(p) in have or not os.path.isdir(p):
                continue
            self.items.append({"path": p, "set": "" if f == ALL_SETS else f})
            have.add(norm_path(p))
            added += 1
        self._save()
        self._redraw()
        return added

    def add_folder(self):
        d = filedialog.askdirectory(parent=self.root, title="Pick a folder (any drive)",
                                    mustexist=True)
        if d:
            n = self._add_paths([d.replace("/", "\\")])
            self.say("Added." if n else "That folder is already on the list.")

    def add_subfolders(self):
        d = filedialog.askdirectory(parent=self.root, title="Pick the PARENT folder",
                                    mustexist=True)
        if not d:
            return
        d = d.replace("/", "\\")
        try:
            subs = sorted((e.path for e in os.scandir(d) if e.is_dir()), key=str.lower)
        except Exception as e:
            self.say("Cannot read that folder: %s" % e)
            return
        if not subs:
            self.say("That folder has no sub-folders.")
            return
        top = tk.Toplevel(self.root)
        top.title("Add sub-folders of " + d)
        top.configure(bg=THEME["bg"])
        top.geometry("640x460")
        top.transient(self.root)
        make_modal(top)
        lb = tk.Listbox(top, selectmode="extended", bg=THEME["field"], fg=THEME["field_fg"],
                        font=("Segoe UI", 10), relief="flat", activestyle="none",
                        exportselection=False)
        sb = tk.Scrollbar(top, command=lb.yview)
        lb.configure(yscrollcommand=sb.set)
        bar = tk.Frame(top, bg=THEME["bg"])
        bar.pack(side="bottom", fill="x", pady=8)
        sb.pack(side="right", fill="y")
        lb.pack(side="left", fill="both", expand=True)
        for p in subs:
            lb.insert("end", os.path.basename(p))

        def ok():
            chosen = [subs[i] for i in lb.curselection()]
            top.destroy()
            n = self._add_paths(chosen)
            self.say("Added %d folder(s)." % n)
        tk.Button(bar, text="Select all", width=10,
                  command=lambda: lb.selection_set(0, "end")).pack(side="left", padx=10)
        tk.Button(bar, text="Add selected", width=14, command=ok).pack(side="right", padx=10)
        tk.Button(bar, text="Cancel", width=10, command=top.destroy).pack(side="right")

    def add_open_windows(self):
        def got(lines):
            n = self._add_paths(lines_with(lines, "W"))
            self.say("Added %d folder(s) from the open Explorer windows." % n)
        self.run_bg(PS_WINDOWS, None, got, "Looking at the open Explorer windows")

    def remove_selected(self):
        sel = self.selected_indexes()
        if not sel:
            self.say("Select one or more rows first.")
            return
        paths = [self.items[i]["path"] for i in sel]
        for i in sorted(sel, reverse=True):
            del self.items[i]
        self._save()
        self._redraw(keep=[])
        mine = [p for p in paths if norm_path(p) in self.pinned]
        if mine:
            self._apply([], mine, "Removing and unpinning")
        else:
            self.say("Removed from my list.")

    def move(self, step):
        sel = self.selected_indexes()
        shown = self.shown_indexes()
        if len(sel) != 1 or sel[0] not in shown:
            self.say("Select ONE row to move.")
            return
        k = shown.index(sel[0]) + step
        if not 0 <= k < len(shown):
            return
        a, b = sel[0], shown[k]
        self.items[a], self.items[b] = self.items[b], self.items[a]
        self._save()
        self._redraw(keep=[b])

    def set_selected_set(self):
        sel = self.selected_indexes()
        if not sel:
            self.say("Select one or more rows first.")
            return
        name = self.ent_set.get().strip()
        for i in sel:
            self.items[i]["set"] = name
        self._save()
        self._redraw(keep=sel)
        self.say("Set of %d row(s): %s" % (len(sel), name or "(none)"))

    def open_selected(self):
        sel = self.selected_indexes()
        if sel and os.path.isdir(self.items[sel[0]]["path"]):
            open_path(self.items[sel[0]]["path"])

    # ---------- pinning ----------
    def _paths(self, idx):
        return [self.items[i]["path"] for i in idx]

    def pin_selected(self):
        sel = self.selected_indexes()
        if not sel:
            self.say("Select one or more rows first.")
            return
        self._apply(self._paths(sel), [], "Pinning")

    def unpin_selected(self):
        sel = self.selected_indexes()
        if not sel:
            self.say("Select one or more rows first.")
            return
        self._apply([], self._paths(sel), "Unpinning")

    def pin_shown(self):
        self._apply(self._paths(self.shown_indexes()), [], "Pinning the shown folders")

    def unpin_shown(self):
        self._apply([], self._paths(self.shown_indexes()), "Unpinning the shown folders")

    def repin_shown(self):
        p = self._paths(self.shown_indexes())
        self._apply(p, p, "Re-pinning in my order")

    def switch_set(self):
        f = self.set_var.get()
        shown = set(self.shown_indexes())
        pin = self._paths(sorted(shown))
        unpin = [it["path"] for i, it in enumerate(self.items) if i not in shown]
        self._apply(pin, unpin, "Switching to " + f)

    # ---------- player text + close ----------
    def open_player(self):
        try:
            if self.player is not None and self.player.top.winfo_exists():
                self.player.top.lift()
                return
        except Exception:
            pass
        self.player = PlayerTextPopup(
            self.root, self.S,
            ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel"),
            self._save, THEME, "Player text - Quick Pins", PROGRAM_HF_DIR,
            lambda: {}, on_closed=self._player_closed)
        self.S["show_playertext"] = True
        self._save()

    def _player_closed(self):
        self.S["show_playertext"] = False
        self._save()

    def on_close(self):
        try:
            if self.player is not None:
                self.player.save_now()
        except Exception:
            pass
        self._save()
        self.root.destroy()


# *************** DEL 90 - MAIN ****************************************************

def main():
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    QuickPins(root)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()


if __name__ == "__main__":
    main()
