#!/usr/bin/env python3
# =============================================================================
# Point & Paint  –  |  Python 3 + Tkinter + Pillow
# =============================================================================
#
#   ALLT I PROGRAMMET SKA ALLTID VARA PÅ ENGELSKA - ALDRIG SVENSKA!
#   (EVERYTHING IN THIS PROGRAM MUST ALWAYS BE IN ENGLISH - NEVER SWEDISH!)
#
# =============================================================================
#
# ToDo / changelog
# ----------------
#   [v1.4.0]  DONE  Never lose typed text again.
#                   The Text tool used to throw away everything you had typed
#                   the moment you touched another tool, a menu item, the zoom,
#                   or pressed Escape — silently. Now every action that would
#                   destroy unplaced text goes through one guard that pops up a
#                   modal dialog with three clear choices:
#                       Place the text   /   Discard the text   /   Keep typing
#                   See DEL 26b – UNPLACED-TEXT GUARD.
#   [v1.4.0]  DONE  Global accelerators (Ctrl+N/O/S/Z/Y/X/C/V/A and Delete) no
#                   longer fire while you are typing in a text field, so Delete
#                   deletes a character instead of the selection, and Ctrl+A
#                   selects your text instead of the whole canvas.
#   [v1.5.0]  DONE  Double-click a placed text (Move or Text tool) to re-open
#                   it for editing — font, size, bold and colour come back with
#                   it. The source text now rides along on the object ("meta")
#                   and survives undo/redo.
#   [v1.5.0]  DONE  Font picker "▾" next to the Font field. The list is built
#                   by READING the font files (75 real families here), not from
#                   tkinter's font.families() — two thirds of those 190 names
#                   are aliases Pillow cannot open, so picking one used to give
#                   a silent fallback face instead of the font you chose.
#   [v1.5.0]  DONE  Crashes inside Tk callbacks now reach the crash log.
#                   sys.excepthook never sees those — Tk swallows them and
#                   prints to stderr, which is invisible from a .bat or EXE.
#   [v1.5.0]  DONE  The window can no longer be restored onto a monitor that
#                   is gone; off-screen positions fall back to the primary.
#   [v1.5.0]  DONE  Clicking with the Text tool no longer burns an undo step,
#                   so stray clicks stop flushing the 10-step history.
#   [v1.5.0]  DONE  External program icon Icons/Paint.ico (palette + brush).
#   [v1.5.1]  FIX   Selecting text with the Select/Lasso tool COPIED it instead
#                   of moving it. Text and pasted pictures are objects floating
#                   above the base image; lifting a selection only erased the
#                   BASE pixels, so the object stayed put and kept being drawn
#                   on top — you dragged a copy away and, on drop, the picture
#                   had the text twice. _clear_region_from_objects() now takes
#                   the selected rectangle away from the objects as well, and
#                   an object that is only half-selected keeps its other half.
#                   Delete over a selection had the same hole.
#   [v1.5.2]  FIX   Ctrl+V pasted TWICE: the canvas shortcuts did not stop the
#                   key event, so the toplevel shortcut ran it again. Two
#                   pictures landed on top of each other at the top-left; you
#                   dragged one away and a "copy" stayed behind. The same bug
#                   made Ctrl+Z undo two steps and Ctrl+S open Save twice.
#   [v1.5.2]  DONE  Image menu (Flip, Rotate, Invert, Clear) works on the marked
#                   area when something is marked, else on the whole picture.
#                   See _marked_box() / _region_op().
#   [next]          Consider a colour-per-object edit for shapes too, and a
#                   right-click context menu on the canvas.
#
# =============================================================================

# *************** DEL 01 – PATHS AND DIRECTORY SETUP ***********************

import tkinter as tk
from tkinter import filedialog, messagebox, colorchooser, ttk
import os, sys, json, traceback, datetime, math, random, io, ctypes, platform
import functools
import os
import sys
import shutil
import subprocess
import webbrowser  # the open-with block needs this at module level


# ---- Where Helpfiles and Icons live -----------------------------------------
# Helpfiles is a SIBLING of the program's folder, not a child of it, so the
# answer is "the nearest folder above me that holds Helpfiles". One rule covers
# Py\, Folder-exe\<Name>\ and the old layout alike, so it stops mattering
# where the .py or the .exe is put. Capped at four levels so a stray Helpfiles
# far up the tree is not adopted by accident; nothing found means behave as
# before, which is what keeps a test copy away from live data.
def _find_home(start):
    # Py\ and Folder-exe\<Name>\ are ALWAYS direct children of home, so
    # their own name settles it. This runs BEFORE the walk: a stray
    # Helpfiles inside Py\ used to win the walk and silently became every
    # program's home - that is how Notes lost a day (2026-09-04).
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    if os.path.basename(os.path.dirname(start)).lower() == "folder-exe":
        return os.path.dirname(os.path.dirname(start))
    # Otherwise: the nearest folder above me that HAS a Helpfiles. Capped at
    # four levels so a stray one far up is not adopted by accident; nothing
    # found means behave as before, which keeps a test copy off live data.
    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
    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 checks for this before offering the swap


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# A link, a folder, a PDF, a log or an image opened from here should land in MY
# programs - not in Edge, Explorer, Notepad or Adobe.
#
# Registering them as Windows' default apps is possible but miserable, and
# Windows identifies an application by its .exe PATH: point every file type at
# pythonw.exe and Windows sees ONE app called "Python" for all of them, with
# one icon, and Default Apps cannot tell WhyBrowse from F(re)email.
#
# WHICH program opens WHAT is NOT decided here.  It is decided in one file,
#
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
#
# so changing "PDFs open in X instead of PDFull" is one edit in one place, not
# 122 edits in 122 sources.  This block only reads that table and acts on it.
# _FALLBACK_KINDS below is used only when the file cannot be read, so a
# program still works on a machine that has no DefaultHub.
#
# Three rules this block must never break:
#
#   1. It may never raise.  The Help button has to open even when WhyBrowse is
#      missing, broken, or mid-rebuild, and even when defaults.json is gone.
#   2. It may never hand a thing to ITSELF (File_manager opening a folder,
#      WhyBrowse opening a link) - that is how you build a loop.
#   3. Popen, never run().  run() would freeze this program until the browser
#      is closed again.
#
# NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it would start another copy of this program instead of Python.
# (PyManager did exactly that on 2026-09-04 and fork-bombed the machine.)
#
# Cost, measured 2026-09-05: the table is read ONCE, the first time something
# is actually opened - 0.11 ms cold, 0.05 ms warm, plus 0.04 ms of path
# checks.  Nothing is read at start-up, so start-up is not affected at all.

MY_PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False) else __file__))[0]

# 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 others: a music program
    lives in <root>\\1---Musik\\Py so its 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 it walks
    UP, exactly like _find_home, four levels."""
    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) - it is
    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 ""


_HUB_PY_ROOTS = None


def _hub_py_roots() -> list:
    """The program folders DefaultHub names, or [] meaning "find them yourself".

    EMPTY IS THE DEFAULT AND IT IS THE RIGHT ONE.  An absolute path in a data
    file is the first thing to break when the tree moves to another drive -
    which it did on 2026-09-08, C: to X:.  Nothing else in this block holds a
    drive letter: _find_home walks up from __file__, and the table stores only
    NAMES ("SeeView"), so a move costs nothing.  A list of absolute paths here
    would be the one file that has to be edited every time, and that is exactly
    what this design is for avoiding.

    So a RELATIVE entry ("1---Musik\\Py") is the intended shape: it is
    resolved against every root in _py_folders, and it survives the move too.
    An absolute one is still honoured - it is his tree - but it is on him."""
    global _HUB_PY_ROOTS
    if _HUB_PY_ROOTS is not None:
        return _HUB_PY_ROOTS
    found = []
    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:
                    found = (json.load(fh) or {}).get("py_roots") or []
                break
        except Exception:
            pass                       # unreadable or half-written: automatic
    try:
        _HUB_PY_ROOTS = [str(x).strip() for x in found if str(x).strip()]
    except Exception:
        _HUB_PY_ROOTS = []
    return _HUB_PY_ROOTS


def _py_folders() -> list:
    """Every folder that may hold <Name>.py, nearest first.

    DefaultHub's list first, then the plain <root>\\Py that has always been
    searched.  With no list this is exactly the old behaviour, which is why
    "empty means automatic" costs nothing."""
    out, roots = [], _my_app_roots()
    for entry in _hub_py_roots():
        try:
            if os.path.isabs(entry):
                out.append(entry)
            else:
                for r in roots:
                    out.append(os.path.join(r, entry))
        except Exception:
            continue
    for r in roots:
        out.append(os.path.join(r, "Py"))
    seen, uniq = set(), []
    for d in out:
        try:
            key = os.path.normcase(os.path.abspath(d))
            if key not in seen and os.path.isdir(d):
                seen.add(key)
                uniq.append(d)
        except Exception:
            continue
    return uniq


def _program_candidates(name: str) -> list:
    """Every file that could BE that program, best first.

    ALL the .py folders are searched before ANY build.  The old loop asked
    "script or exe?" one tree at a time, so a stale build in a near tree beat
    the live source in a further one - the very thing "the .py wins" exists to
    prevent."""
    out = []
    for d in _py_folders():
        try:
            p = os.path.join(d, name + ".py")
            if os.path.isfile(p):
                out.append(p)
        except Exception:
            continue
    for root in _my_app_roots():
        try:
            e = os.path.join(root, "Folder-exe", name, name + ".exe")
            if os.path.isfile(e):
                out.append(e)
        except Exception:
            continue
    return out


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, and a build is only the fallback.  The .exe used to be
    preferred, which was wrong on every count:

      * it is not faster - a one-folder build and the .py start in about the
        same time (the ten-times difference was one-FILE builds);
      * it does not help the hand-over - both bind the same port, so a
        running copy takes the argument whichever one is started;
      * and it is the only thing that can be OUT OF DATE.  A build from last
        week does not have this week's source in it, so preferring it means
        quietly running old code.  That is exactly what happened on
        2026-09-05: File_manager's build was a day old and had no command
        line handling at all, so "open this folder" would have opened a
        second window and dropped the path.

    WHERE it looks is DefaultHub's business now, not this block's - see
    _py_folders - so his music programs and the own worlds under 1---Annat
    can be named as targets like anything else.

    subprocess and webbrowser MUST be imported at module level for this to
    work.  They were not, in 57 of 121 programs, and because every call site
    sits inside a bare `except Exception` the failure was completely silent:
    the program simply stopped handing files to his own programs and dropped
    them all on Windows.  That is what made "Save & Open" open nothing at all
    on 2026-09-09, and it left no trace anywhere."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    for path in _program_candidates(name):
        cmd = None
        if path.lower().endswith(".py"):
            pyw = _real_pythonw()
            if pyw:
                cmd = [pyw, path, str(argument)]
            # no interpreter on this machine: try the build instead
        else:
            cmd = [path, str(argument)]
        if not cmd:
            continue
        try:
            subprocess.Popen(cmd, cwd=os.path.dirname(path) or None)
            return True
        except Exception:
            continue                      # try the next candidate
    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


# -----------------------------------------------------------------------------


try:
    from PIL import Image, ImageTk, ImageDraw, ImageFont, ImageOps
except ImportError:
    print("ERROR: Pillow is required.  Run:  pip install Pillow")
    sys.exit(1)

_BASE = _program_home()
_HELP = os.path.join(_BASE, "Helpfiles")
_LOGS = os.path.join(_HELP, "0---Empty")
_SETS = os.path.join(_HELP, "0---Settings")
_CFG  = os.path.join(_SETS, "paint_config.json")

for _d in [_HELP, _LOGS, _SETS]:
    os.makedirs(_d, exist_ok=True)


# *************** DEL 02 – CONSTANTS ***************************************

APP_TITLE   = "Point & Paint"
APP_VER     = "1.5.2"
UNDO_LEVELS = 10
ZOOM_STEPS  = [1, 2, 4, 6, 8]

# ── Hub-modul metadata ──────────────────────────────────────────────────────
WANT_HUB_DIR = False
MODULE_NAME  = "paint"
MENU_LABEL   = "Paint"
MENU_GROUP   = "Extra"
MENU_POS     = "auto"

# 28-colour palette matching Windows 95 Paint
PALETTE = [
    "#000000", "#808080", "#800000", "#808000", "#008000", "#008080",
    "#000080", "#800080", "#808040", "#004040", "#0080FF", "#004080",
    "#8000FF", "#804000",
    "#FFFFFF", "#C0C0C0", "#FF0000", "#FFFF00", "#00FF00", "#00FFFF",
    "#0000FF", "#FF00FF", "#FFFF80", "#00FF80", "#80FFFF", "#8080FF",
    "#FF0080", "#FF8040",
]

# (internal_name, button_label, canvas_cursor, icon_glyph, icon_bg_color)
# Icons are shown large with no caption; names live in the hover/click boxes.
TOOL_DEF = [
    ("move_obj",     "Move",    "fleur",     "✋",   "#FFE0C0"),
    ("free_select",  "Lasso",   "crosshair", "◌",   "#D4E8FF"),
    ("rect_select",  "Select",  "crosshair", "⬚",   "#D4E8FF"),
    ("eraser",       "Eraser",  "crosshair", "🧽",  "#FFE8E8"),
    ("fill",         "Fill",    "crosshair", "🪣",  "#FFF0C0"),
    ("pick_color",   "Picker",  "crosshair", "💉",  "#E8FFE8"),
    ("magnifier",    "Zoom",    "crosshair", "🔍",  "#E8F0FF"),
    ("pencil",       "Pencil",  "pencil",    "✏️",  "#FFFFD0"),
    ("brush",        "Brush",   "crosshair", "🖌️",  "#FFE8FF"),
    ("airbrush",     "Spray",   "crosshair", "💨",  "#E0F8FF"),
    ("text",         "Text",    "xterm",     "🅰️",  "#FFF8E0"),
    ("line",         "Line",    "crosshair", "／",   "#F0F0F0"),
    ("curve",        "Curve",   "crosshair", "〰️",  "#F0F0F0"),
    ("rectangle",    "Rect",    "crosshair", "▭",   "#F5F0FF"),
    ("polygon",      "Polygon", "crosshair", "⬠",   "#F5F0FF"),
    ("ellipse",      "Ellipse", "crosshair", "◯",   "#F5F0FF"),
    ("rounded_rect", "RRect",   "crosshair", "▢",   "#F5F0FF"),
]

# Friendly, readable descriptions shown in the hover box (the tiny button text
# is hard to read, so hovering an icon spells it out here).
TOOL_DESC = {
    "move_obj":     "Move placed text/images",
    "free_select":  "Lasso — free-form select",
    "rect_select":  "Rectangle select",
    "eraser":       "Eraser",
    "fill":         "Fill (paint bucket)",
    "pick_color":   "Colour picker (eyedropper)",
    "magnifier":    "Zoom / magnifier",
    "pencil":       "Pencil — 1-px freehand",
    "brush":        "Brush",
    "airbrush":     "Airbrush / spray",
    "text":         "Text",
    "line":         "Straight line",
    "curve":        "Curve (Bézier)",
    "rectangle":    "Rectangle",
    "polygon":      "Polygon",
    "ellipse":      "Ellipse / circle",
    "rounded_rect": "Rounded rectangle",
}

DEFAULT_CFG = {
    "win_w": 1060, "win_h": 780, "win_x": 80, "win_y": 60,
    "canvas_w": 800, "canvas_h": 600,
    "zoom": 1,
    "fg": "#000000", "bg": "#FFFFFF",
    "tool": "pencil",
    "line_w": 1,
    "brush_size": 6,
    "fill_style": 0,
    "transparent_paste": False,
    "show_toolbar": True,
    "show_colorbox": True,
    "show_statusbar": True,
    "last_dir": "",
    "last_file": "",
    "fav_dir": "",          # user's favourite save/open folder (typed or browsed)
}


# *************** DEL 03 – HELPERS *****************************************

def no_blink(w):
    try:
        w.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass

def auto_popup(parent, title, msg, ms=1000):
    top = tk.Toplevel(parent)
    top.title(title)
    top.resizable(False, False)
    top.grab_set()
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())
    parent.update_idletasks()
    cx = parent.winfo_rootx() + parent.winfo_width()  // 2 - 130
    cy = parent.winfo_rooty() + parent.winfo_height() // 2 -  30
    top.geometry(f"260x58+{cx}+{cy}")
    tk.Label(top, text=msg, pady=12, font=("Arial", 9)).pack()
    top.after(ms, lambda: (top.grab_release(), top.destroy()))

def needs_text_ok(action="continue"):
    """Decorator for PaintApp methods that would destroy text the user has
    typed with the Text tool but has not placed on the canvas yet.

    Before the method runs, the user is asked what to do with that text
    (place it / discard it / keep typing).  If the user chooses "keep typing",
    the decorated method is NOT executed at all — nothing is lost.

    'action' is a short phrase shown in the dialog, e.g. "open another image".
    """
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(self, *a, **kw):
            try:
                if not self._guard_pending_text(action):
                    return None
            except Exception:
                pass          # a broken guard must never block the program
            return fn(self, *a, **kw)
        return wrapper
    return deco


def hex_to_rgb(h):
    h = h.lstrip("#")
    return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))

def rgb_to_hex(r, g, b):
    return f"#{r:02X}{g:02X}{b:02X}"


# *************** DEL 03b – WINDOW ICON (Windows) **************************

def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    script_dir = _program_home()
    prog_name  = os.path.splitext(os.path.basename(__file__))[0]
    ico_path   = os.path.join(script_dir, "Icons", f"{prog_name}.ico")
    if not os.path.isfile(ico_path):
        return

    # Kanal 1: tkinters eget API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Kanal 2: WM_SETICON via Win32 (täcker taskbar + Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        hwnd = user32.FindWindowW(None, root.title())   # ← FindWindowW, inte winfo_id()
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON,  0,  0, LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16, LR_LOADFROMFILE)
        if hbig: user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml: user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL 04 – CRASH CATCHER ***********************************

_app_ref = None

def _crash_handler(etype, evalue, etb):
    if issubclass(etype, KeyboardInterrupt):
        sys.__excepthook__(etype, evalue, etb)
        return
    tb_str = "".join(traceback.format_exception(etype, evalue, etb))
    ts     = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    log    = os.path.join(_LOGS, f"crash_{ts}.log")
    try:
        with open(log, "w", encoding="utf-8") as f:
            f.write(f"Paint  v{APP_VER}  –  Crash Report\n{'='*54}\n")
            f.write(f"Time: {ts}\n\nTraceback:\n{tb_str}\n")
            if _app_ref:
                try:
                    f.write("Config:\n" + json.dumps(_app_ref.cfg.data, indent=2))
                except Exception:
                    pass
    except Exception:
        pass
    try:
        if _app_ref and _app_ref.image:
            _app_ref.image.save(os.path.join(_LOGS, f"autosave_{ts}.png"))
    except Exception:
        pass
    try:
        messagebox.showerror(
            "Crash – Paint",
            f"{etype.__name__}: {evalue}\n\nLog saved:\n{log}"
        )
    except Exception:
        pass

sys.excepthook = _crash_handler

# sys.excepthook alone is NOT enough for a GUI: Tkinter catches every exception
# raised inside a callback (button command, event binding, after-job) and sends
# it to Tk.report_callback_exception, which only prints to stderr — invisible
# when the program is started from a .bat or built as an EXE. Route those to
# the same crash log, and cover worker threads too.
def _tk_callback_crash(self, etype, evalue, etb):
    _crash_handler(etype, evalue, etb)

tk.Tk.report_callback_exception = _tk_callback_crash

try:
    import threading

    def _thread_crash(args):
        _crash_handler(args.exc_type, args.exc_value, args.exc_traceback)

    threading.excepthook = _thread_crash
except Exception:
    pass


# *************** DEL 05 – SETTINGS MANAGER ********************************

class Cfg:
    def __init__(self):
        self.data = dict(DEFAULT_CFG)
        self._load()

    def _load(self):
        try:
            if os.path.isfile(_CFG):
                with open(_CFG, "r", encoding="utf-8") as f:
                    saved = json.load(f)
                    self.data.update(saved)
        except Exception:
            pass

    def save(self):
        try:
            with open(_CFG, "w", encoding="utf-8") as f:
                json.dump(self.data, f, indent=2)
        except Exception:
            pass

    def __getitem__(self, k):
        return self.data.get(k, DEFAULT_CFG.get(k))

    def __setitem__(self, k, v):
        self.data[k] = v


# *************** DEL 06 – MAIN APPLICATION CLASS – INIT ******************

class PaintApp:
    """
    Can be used in two ways:
      1. Standalone:  PaintApp(root)   where root is a tk.Tk()
      2. Embedded:    PaintApp(frame, embedded=True)  where frame is a
                      tk.Frame / ttk.Frame inside a host application (Hub).
    """

    def __init__(self, root, embedded: bool = False):
        global _app_ref
        _app_ref      = self
        self.root     = root
        self.embedded = embedded
        self.cfg      = Cfg()

        cw = max(1, int(self.cfg["canvas_w"]))
        ch = max(1, int(self.cfg["canvas_h"]))
        self.image = Image.new("RGB", (cw, ch), "#FFFFFF")
        self.draw  = ImageDraw.Draw(self.image)
        self.photo = None

        self.undo_stack = []
        self.redo_stack = []
        self.clipboard_image = None

        self._text_editor    = None
        self._text_snap      = None
        # Callbacks of the live Text editor, so the unplaced-text guard can
        # place or drop the text from anywhere in the program (DEL 26b).
        self._text_commit_fn  = None
        self._text_drop_fn    = None
        self._text_guard_busy = False   # re-entrancy lock for the guard dialog
        self._text_fill       = None    # colour of the text being re-edited
        self._last_text_font = "Arial"
        self._last_text_size = 16
        self._last_text_bold = False
        # Last text typed with the Text tool — used as the suggested file name
        # in the Save dialogs.
        self._suggest_name   = ""

        # ── Movable objects ("memory of placed things") ──────────────────────
        # Text and pasted images are kept as separate objects floating above the
        # base image, so each can be clicked and dragged on its own with the
        # Move tool. Everything is flattened into one image on save.
        # Each object: {"img": RGBA Image, "x": int, "y": int, "kind": str}
        self.objects        = []
        self.active_obj     = None   # index of the selected object, or None
        self._obj_drag_off  = None   # (dx, dy) cursor offset while dragging
        self._obj_moved     = False  # has the current drag moved the object?

        # Paste state: keep clean background so we can re-render floating
        # image every frame (needed for transparent mode)
        self._paste_snap        = None   # image BEFORE paste landed
        self._paste_transparent = False  # was transparent mode on at paste-time?

        self.sel_rect        = None
        self.sel_image       = None
        self.sel_floating    = False
        self._sel_drag_start = None

        self.tool       = str(self.cfg["tool"])
        self.fg         = str(self.cfg["fg"])
        self.bg         = str(self.cfg["bg"])
        # Safety: if FG and BG ended up identical (e.g. both white, saved from a
        # previous session or an accidental colour swap), everything you draw or
        # type would be invisible. Nudge FG to a contrasting colour on start.
        if self.fg.upper() == self.bg.upper():
            self.fg = "#000000" if self.bg.upper() != "#000000" else "#FFFFFF"
            self.cfg["fg"] = self.fg
        # ToDo: Always launch at 1× zoom (user preference). The previous
        # session's zoom is intentionally ignored so an opened/pasted image is
        # never blown up to 8× on start and the resize handles stay reachable.
        self.zoom       = 1
        self.cfg["zoom"] = 1
        self.line_w     = max(1, int(self.cfg["line_w"]))
        self.brush_size = max(1, int(self.cfg["brush_size"]))
        self.fill_style = int(self.cfg["fill_style"])
        self.transparent_paste = bool(self.cfg["transparent_paste"])

        self.drawing     = False
        self.start_x     = 0; self.start_y = 0
        self.last_x      = 0; self.last_y  = 0

        # Canvas resize handles
        self._resize_handle  = None   # which handle is being dragged (string or None)
        self._resize_orig_w  = 0
        self._resize_orig_h  = 0
        self._resize_start_cx = 0     # canvas coords at drag start
        self._resize_start_cy = 0

        self._line_snap  = None
        self._shape_snap = None
        self._poly_snap  = None
        self._lasso_snap = None

        self.poly_pts  = []
        self.lasso_pts = []

        self.curve_pts   = []
        self.curve_stage = 0
        self.curve_base  = None

        self.current_file = str(self.cfg["last_file"])
        self.modified     = False

        self._setup_window()
        self._build_menu()
        self._build_status_bar()
        self._build_color_bar()
        self._build_main()
        self._build_toolbar()
        self._build_canvas_area()

        if not self.embedded:
            self.root.protocol("WM_DELETE_WINDOW", self._close)
        self._refresh()
        self._update_title()
        self._select_tool(self.tool)


# *************** DEL 07 – WINDOW SETUP ************************************

    def _setup_window(self):
        if self.embedded:
            return   # window geometry handled by host Hub
        self.root.title(APP_TITLE)
        w = max(640, int(self.cfg["win_w"]))
        h = max(480, int(self.cfg["win_h"]))
        x = int(self.cfg["win_x"])
        y = int(self.cfg["win_y"])

        # Never restore the window onto a screen that no longer exists.
        # Unplugging a second monitor (or changing resolution) used to leave
        # Paint opening far outside the desktop, unreachable, with no way back
        # except deleting the config file by hand.
        try:
            sw = self.root.winfo_screenwidth()
            sh = self.root.winfo_screenheight()
            w  = min(w, sw)
            h  = min(h, sh)
            # Allow a window parked on a second monitor (negative or large
            # coordinates), but demand that a usable corner stays reachable.
            vx1, vy1 = -sw, -sh          # virtual desktop, generous bounds
            vx2, vy2 = sw * 2, sh * 2
            if not (vx1 <= x <= vx2 - 100 and vy1 <= y <= vy2 - 100):
                x, y = 80, 60            # fall back to the primary screen
            if x + 100 > sw * 2 or y + 60 > sh * 2:
                x, y = 80, 60
            # A title bar dragged above the top edge can never be grabbed again.
            if y < 0:
                y = 0
        except Exception:
            pass

        self.root.geometry(f"{w}x{h}+{x}+{y}")
        self.root.minsize(640, 480)


# *************** DEL 08 – MENU BAR ****************************************

    def _build_menu(self):
        # The BooleanVars must always exist (used by the _toggle_* methods)
        self._v_toolbar   = tk.BooleanVar(value=bool(self.cfg["show_toolbar"]))
        self._v_colorbox  = tk.BooleanVar(value=bool(self.cfg["show_colorbox"]))
        self._v_statusbar = tk.BooleanVar(value=bool(self.cfg["show_statusbar"]))

        if not self.embedded:
            # -- STANDALONE: a normal tk.Menu on the window ------------------
            mb = tk.Menu(self.root, tearoff=0)

            fm = tk.Menu(mb, tearoff=0)
            fm.add_command(label="New",          accelerator="Ctrl+N", command=self._new)
            fm.add_command(label="Open…",        accelerator="Ctrl+O", command=self._open)
            fm.add_separator()
            fm.add_command(label="Paste Print Screen…",                command=self._paste_from_screen)
            fm.add_separator()
            fm.add_command(label="Save",         accelerator="Ctrl+S", command=self._save)
            fm.add_command(label="Save As…",                           command=self._save_as)
            fm.add_command(label="Trim & Save As…",                    command=self._trim_save_as)
            fm.add_command(label="Save Selected…",                     command=self._save_selection_as)
            fm.add_separator()
            fm.add_command(label="Set Default Save Folder…",           command=self._set_fav_dir)
            fm.add_separator()
            fm.add_command(label="Exit",                               command=self._close)
            mb.add_cascade(label="File", menu=fm)

            em = tk.Menu(mb, tearoff=0)
            em.add_command(label="Undo",         accelerator="Ctrl+Z", command=self._undo)
            em.add_command(label="Redo",         accelerator="Ctrl+Y", command=self._redo)
            em.add_separator()
            em.add_command(label="Cut",          accelerator="Ctrl+X", command=self._cut)
            em.add_command(label="Copy",         accelerator="Ctrl+C", command=self._copy)
            em.add_command(label="Paste",        accelerator="Ctrl+V", command=self._paste)
            em.add_separator()
            em.add_command(label="Select All",   accelerator="Ctrl+A", command=self._select_all)
            em.add_command(label="Clear Selection",                    command=self._clear_selection)
            em.add_command(label="Delete",       accelerator="Del",    command=self._delete_selection)
            mb.add_cascade(label="Edit", menu=em)

            vm = tk.Menu(mb, tearoff=0)
            zm = tk.Menu(vm, tearoff=0)
            for z in ZOOM_STEPS:
                zm.add_command(label=f"{z}×", command=lambda zz=z: self._set_zoom(zz))
            vm.add_cascade(label="Zoom", menu=zm)
            vm.add_separator()
            vm.add_checkbutton(label="Tool Box",   variable=self._v_toolbar,
                               command=self._toggle_toolbar)
            vm.add_checkbutton(label="Color Box",  variable=self._v_colorbox,
                               command=self._toggle_colorbox)
            vm.add_checkbutton(label="Status Bar", variable=self._v_statusbar,
                               command=self._toggle_statusbar)
            mb.add_cascade(label="View", menu=vm)

            im  = tk.Menu(mb, tearoff=0)
            frm = tk.Menu(im, tearoff=0)
            frm.add_command(label="Flip Horizontal", command=lambda: self._flip("h"))
            frm.add_command(label="Flip Vertical",   command=lambda: self._flip("v"))
            im.add_cascade(label="Flip", menu=frm)
            rot = tk.Menu(im, tearoff=0)
            for deg in [90, 180, 270]:
                rot.add_command(label=f"Rotate {deg}°", command=lambda d=deg: self._rotate(d))
            im.add_cascade(label="Rotate", menu=rot)
            im.add_separator()
            im.add_command(label="Invert Colors",  command=self._invert)
            im.add_command(label="Attributes…",   command=self._attributes_dialog)
            im.add_command(label="Clear Image",    command=self._clear_image)
            mb.add_cascade(label="Image", menu=im)

            cm = tk.Menu(mb, tearoff=0)
            cm.add_command(label="Edit Colors…", command=self._edit_colors)
            mb.add_cascade(label="Colors", menu=cm)

            hm = tk.Menu(mb, tearoff=0)
            hm.add_command(label="Help Contents",      command=self._help_contents)
            hm.add_separator()
            hm.add_command(label="About Point & Paint", command=self._about)
            mb.add_cascade(label="Help", menu=hm)

            self.root.config(menu=mb)

        else:
            # -- EMBEDDED: compact button row with popup menus ----------------
            self._emb_menubar = tk.Frame(self.root, bg="#D4D0C8", relief=tk.RAISED, bd=1)
            self._emb_menubar.pack(side=tk.TOP, fill=tk.X)

            def _popup(btn, menu):
                """Show the popup menu directly below its button."""
                menu.post(btn.winfo_rootx(),
                          btn.winfo_rooty() + btn.winfo_height())

            btn_kw = dict(relief=tk.FLAT, bd=0, padx=6, pady=2,
                          bg="#D4D0C8", activebackground="#B8D4F0",
                          font=("Arial", 8), cursor="hand2")

            # -- File menu ---------------------------------------
            fm = tk.Menu(self.root, tearoff=0)
            fm.add_command(label="New            Ctrl+N", command=self._new)
            fm.add_command(label="Open…          Ctrl+O", command=self._open)
            fm.add_separator()
            fm.add_command(label="Paste Print Screen…",   command=self._paste_from_screen)
            fm.add_separator()
            fm.add_command(label="Save           Ctrl+S", command=self._save)
            fm.add_command(label="Save As…",              command=self._save_as)
            fm.add_command(label="Trim & Save As…",       command=self._trim_save_as)
            fm.add_command(label="Save Selected…",        command=self._save_selection_as)
            fm.add_separator()
            fm.add_command(label="Set Default Save Folder…", command=self._set_fav_dir)
            b_file = tk.Button(self._emb_menubar, text="File", **btn_kw)
            b_file.pack(side=tk.LEFT)
            b_file.config(command=lambda: _popup(b_file, fm))

            # -- Edit menu ---------------------------------------
            em = tk.Menu(self.root, tearoff=0)
            em.add_command(label="Undo           Ctrl+Z", command=self._undo)
            em.add_command(label="Redo           Ctrl+Y", command=self._redo)
            em.add_separator()
            em.add_command(label="Cut            Ctrl+X", command=self._cut)
            em.add_command(label="Copy           Ctrl+C", command=self._copy)
            em.add_command(label="Paste          Ctrl+V", command=self._paste)
            em.add_separator()
            em.add_command(label="Select All     Ctrl+A", command=self._select_all)
            em.add_command(label="Clear Selection",       command=self._clear_selection)
            em.add_command(label="Delete         Del",    command=self._delete_selection)
            b_edit = tk.Button(self._emb_menubar, text="Edit", **btn_kw)
            b_edit.pack(side=tk.LEFT)
            b_edit.config(command=lambda: _popup(b_edit, em))

            # -- View menu ---------------------------------------
            vm = tk.Menu(self.root, tearoff=0)
            zm = tk.Menu(vm, tearoff=0)
            for z in ZOOM_STEPS:
                zm.add_command(label=f"{z}×", command=lambda zz=z: self._set_zoom(zz))
            vm.add_cascade(label="Zoom", menu=zm)
            vm.add_separator()
            vm.add_checkbutton(label="Tool Box",   variable=self._v_toolbar,
                               command=self._toggle_toolbar)
            vm.add_checkbutton(label="Color Box",  variable=self._v_colorbox,
                               command=self._toggle_colorbox)
            vm.add_checkbutton(label="Status Bar", variable=self._v_statusbar,
                               command=self._toggle_statusbar)
            b_view = tk.Button(self._emb_menubar, text="View", **btn_kw)
            b_view.pack(side=tk.LEFT)
            b_view.config(command=lambda: _popup(b_view, vm))

            # -- Image menu --------------------------------------
            im = tk.Menu(self.root, tearoff=0)
            frm2 = tk.Menu(im, tearoff=0)
            frm2.add_command(label="Flip Horizontal", command=lambda: self._flip("h"))
            frm2.add_command(label="Flip Vertical",   command=lambda: self._flip("v"))
            im.add_cascade(label="Flip", menu=frm2)
            rot2 = tk.Menu(im, tearoff=0)
            for deg in [90, 180, 270]:
                rot2.add_command(label=f"Rotate {deg}°", command=lambda d=deg: self._rotate(d))
            im.add_cascade(label="Rotate", menu=rot2)
            im.add_separator()
            im.add_command(label="Invert Colors", command=self._invert)
            im.add_command(label="Attributes…",  command=self._attributes_dialog)
            im.add_command(label="Clear Image",  command=self._clear_image)
            b_img = tk.Button(self._emb_menubar, text="Image", **btn_kw)
            b_img.pack(side=tk.LEFT)
            b_img.config(command=lambda: _popup(b_img, im))

            # -- Colors menu -------------------------------------
            cm = tk.Menu(self.root, tearoff=0)
            cm.add_command(label="Edit Colors…", command=self._edit_colors)
            b_col = tk.Button(self._emb_menubar, text="Colors", **btn_kw)
            b_col.pack(side=tk.LEFT)
            b_col.config(command=lambda: _popup(b_col, cm))

            # -- Help menu ---------------------------------------
            hm = tk.Menu(self.root, tearoff=0)
            hm.add_command(label="Help Contents",      command=self._help_contents)
            hm.add_separator()
            hm.add_command(label="About Point & Paint", command=self._about)
            b_help = tk.Button(self._emb_menubar, text="Help", **btn_kw)
            b_help.pack(side=tk.LEFT)
            b_help.config(command=lambda: _popup(b_help, hm))

            # -- Print Screen button -----------------------------
            tk.Frame(self._emb_menubar, width=1, bg="#AAAAAA").pack(side=tk.LEFT, fill=tk.Y, padx=4, pady=2)
            tk.Button(self._emb_menubar, text="📋 PrtScn→Paste",
                      command=self._paste_from_screen,
                      bg="#FFF8C0", activebackground="#FFE840",
                      relief=tk.RAISED, bd=1, padx=6, pady=2,
                      font=("Arial", 8, "bold"), cursor="hand2"
                      ).pack(side=tk.LEFT, padx=2)

        # Shortcuts are bound to root (standalone) or to the frame (embedded).
        #
        # IMPORTANT: a binding on the toplevel also fires for keys typed INSIDE
        # a Text/Entry widget. Without the _typing_now() check, pressing Delete
        # while writing a caption wiped the selection instead of a character,
        # and Ctrl+A selected the whole canvas instead of the typed text.
        # _acc() lets the focused text field win.
        bind_target = self.root

        def _acc(fn):
            def handler(e):
                if self._typing_now():
                    return None      # let the text field handle this keystroke
                fn()
                return "break"
            return handler

        bind_target.bind("<Control-n>", _acc(self._new))
        bind_target.bind("<Control-o>", _acc(self._open))
        bind_target.bind("<Control-s>", _acc(self._save))
        bind_target.bind("<Control-z>", _acc(self._undo))
        bind_target.bind("<Control-y>", _acc(self._redo))
        bind_target.bind("<Control-x>", _acc(self._cut))
        bind_target.bind("<Control-c>", _acc(self._copy))
        bind_target.bind("<Control-v>", _acc(self._paste))
        bind_target.bind("<Control-a>", _acc(self._select_all))
        bind_target.bind("<Delete>",    _acc(self._delete_selection))



# *************** DEL 09 – MAIN FRAME LAYOUT *******************************

    def _build_main(self):
        self.main_frame = tk.Frame(self.root, bg="#7B7B7B")
        self.main_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)


# *************** DEL 10 – TOOLBAR *****************************************

    def _build_toolbar(self):
        # Fixed width toolbar – wide enough for two equal columns
        TOOLBAR_W = 92

        self.toolbar_frame = tk.Frame(
            self.main_frame,
            width=TOOLBAR_W,
            bg="#E0E0E0",
            relief=tk.RAISED, bd=2
        )
        self.toolbar_frame.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2)
        self.toolbar_frame.pack_propagate(False)

        # Header label
        tk.Label(
            self.toolbar_frame,
            text="TOOLS",
            bg="#E0E0E0",
            fg="#555555",
            font=("Arial", 7, "bold")
        ).pack(pady=(4, 2))

        # Grid container – fixed width so both columns are equal
        btn_grid = tk.Frame(self.toolbar_frame, bg="#E0E0E0")
        btn_grid.pack(padx=4, pady=2)

        # Make both columns the same weight so they don't squeeze
        btn_grid.columnconfigure(0, weight=1, minsize=38)
        btn_grid.columnconfigure(1, weight=1, minsize=38)

        self.tool_btns = {}
        self._tool_btn_cfg = {}  # store bg colors for each tool

        for idx, tool_entry in enumerate(TOOL_DEF):
            name   = tool_entry[0]
            label  = tool_entry[1]
            emoji  = tool_entry[3]
            bg_col = tool_entry[4]

            row = idx // 2
            col = idx  % 2

            # Each button: emoji on top, small text below
            btn_frame = tk.Frame(
                btn_grid,
                bg=bg_col,
                relief=tk.RAISED,
                bd=2,
                cursor="hand2",
                width=36,
                height=36,
            )
            btn_frame.grid(row=row, column=col, padx=2, pady=2, sticky="nsew")
            btn_frame.pack_propagate(False)
            btn_frame.grid_propagate(False)

            # Large icon, no caption (names appear in the hover/click boxes below)
            ico_lbl = tk.Label(
                btn_frame,
                text=emoji,
                bg=bg_col,
                fg="#222222",
                font=("Segoe UI Emoji", 18),
                cursor="hand2",
            )
            ico_lbl.pack(expand=True, fill="both")

            # Click handler + hover on all parts
            for widget in (btn_frame, ico_lbl):
                widget.bind("<Button-1>", lambda e, n=name: self._select_tool(n))
                widget.bind("<Enter>", lambda e, n=name: self._set_hover(n))
                widget.bind("<Leave>", lambda e: self._set_hover(None))

            self.tool_btns[name]     = btn_frame
            self._tool_btn_cfg[name] = bg_col

        # Separator
        sep = tk.Frame(self.toolbar_frame, height=2, bd=1,
                       relief=tk.SUNKEN, bg="#AAAAAA")
        sep.pack(fill=tk.X, padx=4, pady=(4, 2))

        # Active tool name label
        self._tool_name_lbl = tk.Label(
            self.toolbar_frame,
            text=self.tool.replace("_", " ").title(),
            bg="#C8D8F8", fg="#1a1a6e",
            font=("Arial", 7, "bold"),
            relief=tk.SUNKEN, bd=1,
            anchor="center"
        )
        self._tool_name_lbl.pack(fill=tk.X, padx=4, pady=(0, 2))

        # Hover info box — shows whatever icon the mouse is over (read-only).
        # Sits under the clicked-tool box; the click box above is unchanged.
        self._hover_lbl = tk.Label(
            self.toolbar_frame,
            text="Hover an icon…",
            bg="#FFF8DC", fg="#666633",          # light cream = "hover info"
            font=("Arial", 7),
            relief=tk.GROOVE, bd=1,
            anchor="center", justify="center",
            wraplength=TOOLBAR_W - 14,
        )
        self._hover_lbl.pack(fill=tk.X, padx=4, pady=(0, 4))

        sep2 = tk.Frame(self.toolbar_frame, height=2, bd=1,
                        relief=tk.SUNKEN, bg="#AAAAAA")
        sep2.pack(fill=tk.X, padx=4, pady=(0, 4))

        # Options strip below separator
        self.opt_frame = tk.Frame(self.toolbar_frame, bg="#E0E0E0")
        self.opt_frame.pack(fill=tk.X, padx=4)
        self._build_tool_options()


# *************** DEL 11 – TOOL OPTIONS STRIP ******************************

    def _build_tool_options(self):
        # SAFETY NET: the live Text editor lives inside opt_frame, so rebuilding
        # this strip destroys it. Every normal route here is already guarded
        # (DEL 26b), but if some future code path slips through we still ask
        # instead of silently throwing the typed text away. No "keep typing"
        # option here — the caller has already committed to rebuilding.
        if getattr(self, "_text_editor", None):
            self._guard_pending_text("rebuild the tool options",
                                     allow_cancel=False)

        for w in self.opt_frame.winfo_children():
            w.destroy()
        t = self.tool

        lbl_kw = dict(bg="#E0E0E0", font=("Arial", 7), fg="#333333")

        if t in ("pencil", "brush", "line", "curve", "rectangle",
                 "rounded_rect", "ellipse", "polygon", "eraser"):
            tk.Label(self.opt_frame, text="Width:", **lbl_kw).pack(anchor="w")
            wf = tk.Frame(self.opt_frame, bg="#E0E0E0")
            wf.pack()
            for k, s in enumerate((1, 2, 3, 4, 5, 8)):
                b = tk.Button(
                    wf, text=str(s), width=2, font=("Arial", 6),
                    bg="#FFFFFF" if s != self.line_w else "#B0D0FF",
                    relief=tk.SUNKEN if s == self.line_w else tk.RAISED,
                    command=lambda ss=s: self._set_line_w(ss)
                )
                b.grid(row=k // 3, column=k % 3, padx=1, pady=1)   # wrap to rows

        if t in ("rectangle", "rounded_rect", "ellipse", "polygon"):
            tk.Label(self.opt_frame, text="Fill:", **lbl_kw).pack(anchor="w", pady=(5, 0))
            ff = tk.Frame(self.opt_frame, bg="#E0E0E0")
            ff.pack()
            icons = [("□", 0), ("▪", 1), ("▣", 2)]
            for lbl2, val in icons:
                b = tk.Button(
                    ff, text=lbl2, width=2, font=("Arial", 9),
                    bg="#FFFFFF" if val != self.fill_style else "#B0D0FF",
                    relief=tk.SUNKEN if val == self.fill_style else tk.RAISED,
                    command=lambda vv=val: self._set_fill_style(vv)
                )
                b.pack(side=tk.LEFT, padx=1)

        if t == "brush":
            tk.Label(self.opt_frame, text="Size:", **lbl_kw).pack(anchor="w", pady=(5, 0))
            bf = tk.Frame(self.opt_frame, bg="#E0E0E0")
            bf.pack()
            for k, s in enumerate((4, 6, 10, 14, 20)):
                b = tk.Button(
                    bf, text=str(s), width=2, font=("Arial", 6),
                    bg="#FFFFFF" if s != self.brush_size else "#B0D0FF",
                    relief=tk.SUNKEN if s == self.brush_size else tk.RAISED,
                    command=lambda ss=s: self._set_brush_size(ss)
                )
                b.grid(row=k // 3, column=k % 3, padx=1, pady=1)   # wrap to rows

        if t == "magnifier":
            tk.Label(self.opt_frame, text="Zoom:", **lbl_kw).pack(anchor="w")
            zf = tk.Frame(self.opt_frame, bg="#E0E0E0")
            zf.pack()
            for k, z in enumerate(ZOOM_STEPS):
                b = tk.Button(
                    zf, text=f"{z}×", width=2, font=("Arial", 7),
                    bg="#FFFFFF" if z != self.zoom else "#B0D0FF",
                    relief=tk.SUNKEN if z == self.zoom else tk.RAISED,
                    command=lambda zz=z: self._set_zoom(zz)
                )
                b.grid(row=k // 3, column=k % 3, padx=1, pady=1)   # wrap to rows

        if t == "curve":
            tk.Label(
                self.opt_frame,
                text="1: drag line\n2: click bend\n3: click bend2",
                **lbl_kw, justify=tk.LEFT
            ).pack(anchor="w", pady=2)

        if t == "polygon":
            tk.Label(
                self.opt_frame,
                text="Click: add pt\nDbl-click:\nclose poly",
                **lbl_kw, justify=tk.LEFT
            ).pack(anchor="w", pady=2)

        if t == "move_obj":
            tk.Label(
                self.opt_frame,
                text="Click a text,\nshape, line or\npasted image to\nselect it (red\nbox), then drag\nto move ONLY\nthat object.\n\n"
                     "Click empty\nspace = deselect.\nDelete key =\nremove object.\n\n"
                     "Double-click a\ntext to edit it\nagain.",
                **lbl_kw, justify=tk.LEFT
            ).pack(anchor="w", pady=2)

        if t in ("rect_select", "free_select"):
            tk.Label(
                self.opt_frame,
                text="Drag a box, then\nclick inside &\ndrag to move\nthose pixels.\n\n"
                     "Tip: to move\ntext or pasted\nimages, use the\nMove tool (✋)\ninstead.",
                **lbl_kw, justify=tk.LEFT
            ).pack(anchor="w", pady=2)


# *************** DEL 12 – CANVAS AREA (SCROLLABLE) ************************

    def _build_canvas_area(self):
        self.canvas_frame = tk.Frame(self.main_frame, bg="#7B7B7B")
        self.canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        self.h_scroll = tk.Scrollbar(self.canvas_frame, orient=tk.HORIZONTAL)
        self.v_scroll = tk.Scrollbar(self.canvas_frame, orient=tk.VERTICAL)
        self.h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
        self.v_scroll.pack(side=tk.RIGHT,  fill=tk.Y)

        self.canvas = tk.Canvas(
            self.canvas_frame,
            bg="#7B7B7B",
            cursor="crosshair",
            xscrollcommand=self.h_scroll.set,
            yscrollcommand=self.v_scroll.set,
            scrollregion=(0, 0, 1200, 900),
            takefocus=True,   # canvas can receive keyboard focus
        )
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self.h_scroll.config(command=self.canvas.xview)
        self.v_scroll.config(command=self.canvas.yview)

        self.canvas_img_id = self.canvas.create_image(4, 4, anchor=tk.NW)

        self.canvas.bind("<ButtonPress-1>",   self._on_mouse_down)
        self.canvas.bind("<B1-Motion>",       self._on_mouse_drag)
        self.canvas.bind("<ButtonRelease-1>", self._on_mouse_up)
        self.canvas.bind("<ButtonPress-3>",   self._on_right_down)
        self.canvas.bind("<Double-Button-1>", self._on_double_click)
        self.canvas.bind("<Motion>",          self._on_mouse_move)
        self.canvas.bind("<MouseWheel>",          self._on_scroll)
        self.canvas.bind("<Button-4>",  lambda e: self.canvas.yview_scroll(-1, "units"))
        self.canvas.bind("<Button-5>",  lambda e: self.canvas.yview_scroll( 1, "units"))
        self.canvas.bind("<Control-MouseWheel>",  self._on_ctrl_scroll)
        self.canvas.bind("<Control-Button-4>",    lambda e: self._zoom_step(1))
        self.canvas.bind("<Control-Button-5>",    lambda e: self._zoom_step(-1))

        # Key bindings on canvas – essential in embedded/module mode where the
        # host Frame cannot receive keyboard events by itself.
        # THE BUG THIS FIXES (v1.5.2): these handlers used to return None, so Tk
        # went on to the SAME shortcut bound on the toplevel and ran it a second
        # time. Ctrl+V pasted the picture twice at the top-left corner, you
        # dragged one away and the other "copy" stayed behind; Ctrl+Z undid two
        # steps; Ctrl+S opened Save twice. Returning "break" ends the event here.
        def _once(fn):
            def handler(e):
                fn()
                return "break"
            return handler

        self.canvas.bind("<Control-n>", _once(self._new))
        self.canvas.bind("<Control-o>", _once(self._open))
        self.canvas.bind("<Control-s>", _once(self._save))
        self.canvas.bind("<Control-z>", _once(self._undo))
        self.canvas.bind("<Control-y>", _once(self._redo))
        self.canvas.bind("<Control-x>", _once(self._cut))
        self.canvas.bind("<Control-c>", _once(self._copy))
        self.canvas.bind("<Control-v>", _once(self._paste))
        self.canvas.bind("<Control-a>", _once(self._select_all))
        self.canvas.bind("<Delete>",    _once(self._delete_selection))


# *************** DEL 13 – COLOR PALETTE BAR *******************************

    def _build_color_bar(self):
        self.color_bar = tk.Frame(
            self.root, bg="#C8C8C8",
            relief=tk.RAISED, bd=1
        )
        self.color_bar.pack(side=tk.BOTTOM, fill=tk.X)
        # NOTE: no height= and no pack_propagate(False) — let content determine height

        # ── Row 1: colour swatches + paste mode + hint text ───────────────
        row1 = tk.Frame(self.color_bar, bg="#C8C8C8")
        row1.pack(side=tk.TOP, fill=tk.X, padx=4, pady=(4, 1))

        # FG swatch (large, clickable)
        fg_col = tk.Frame(row1, bg="#C8C8C8")
        fg_col.pack(side=tk.LEFT, padx=(0, 1))
        tk.Label(fg_col, text="FG (LMB)", bg="#C8C8C8",
                 font=("Arial", 6), fg="#444").pack()
        self._fg_canvas = tk.Canvas(fg_col, width=28, height=28,
                                    highlightthickness=2,
                                    highlightbackground="#FFD700",
                                    cursor="hand2")
        self._fg_canvas.pack()
        self._fg_canvas.bind("<Button-1>", lambda e: self._pick_fg())
        self._fg_canvas.bind("<Button-3>", lambda e: self._swap_colors())

        # BG swatch (large, clickable)
        bg_col = tk.Frame(row1, bg="#C8C8C8")
        bg_col.pack(side=tk.LEFT, padx=(0, 6))
        tk.Label(bg_col, text="BG (RMB)", bg="#C8C8C8",
                 font=("Arial", 6), fg="#444").pack()
        self._bg_canvas = tk.Canvas(bg_col, width=28, height=28,
                                    highlightthickness=2,
                                    highlightbackground="#888888",
                                    cursor="hand2")
        self._bg_canvas.pack()
        self._bg_canvas.bind("<Button-1>", lambda e: self._pick_bg())
        self._bg_canvas.bind("<Button-3>", lambda e: self._swap_colors())

        # Swap button
        sw_col = tk.Frame(row1, bg="#C8C8C8")
        sw_col.pack(side=tk.LEFT, padx=(0, 8))
        tk.Label(sw_col, text=" ", bg="#C8C8C8", font=("Arial", 6)).pack()
        tk.Button(sw_col, text="⇄", font=("Arial", 9), width=2,
                  bg="#E8E8E8", relief=tk.RAISED,
                  command=self._swap_colors).pack()

        # Paste mode toggle
        paste_col = tk.Frame(row1, bg="#C8C8C8")
        paste_col.pack(side=tk.LEFT, padx=(0, 8))
        tk.Label(paste_col, text="Paste mode:", bg="#C8C8C8",
                 font=("Arial", 6), fg="#444").pack(anchor="w")
        pbr = tk.Frame(paste_col, bg="#C8C8C8"); pbr.pack()
        self._btn_opaque = tk.Button(
            pbr, text="■ Opaque", font=("Arial", 7), width=7,
            bg="#90D090" if not self.transparent_paste else "#D8D8D8",
            relief=tk.SUNKEN if not self.transparent_paste else tk.RAISED,
            command=self._set_opaque_paste
        )
        self._btn_opaque.pack(side=tk.LEFT, padx=1)
        self._btn_transp = tk.Button(
            pbr, text="□ Transp.", font=("Arial", 7), width=7,
            bg="#90D090" if self.transparent_paste else "#D8D8D8",
            relief=tk.SUNKEN if self.transparent_paste else tk.RAISED,
            command=self._set_transparent_paste
        )
        self._btn_transp.pack(side=tk.LEFT, padx=1)

        tk.Frame(row1, width=1, bg="#AAAAAA").pack(side=tk.LEFT, fill=tk.Y, padx=4)

        # ── Palette (2 rows × 14 cols) ────────────────────────────────────
        pal_col = tk.Frame(row1, bg="#C8C8C8")
        pal_col.pack(side=tk.LEFT)
        tk.Label(pal_col, text="Left-click = FG    Right-click = BG",
                 bg="#C8C8C8", font=("Arial", 6), fg="#555").pack(anchor="w")
        pal_fr = tk.Frame(pal_col, bg="#C8C8C8")
        pal_fr.pack()

        for i, col in enumerate(PALETTE):
            cell = tk.Label(
                pal_fr, bg=col, width=2, height=1,
                relief=tk.RAISED, bd=1
            )
            cell.grid(row=i // 14, column=i % 14, padx=1, pady=1, ipadx=1, ipady=2)
            cell.bind("<Button-1>", lambda e, c=col: self._set_fg(c))
            cell.bind("<Button-3>", lambda e, c=col: self._set_bg(c))

        # Draw initial swatch colours
        self._redraw_fg_bg_swatches()

    def _redraw_fg_bg_swatches(self):
        """Fill the FG and BG canvas rectangles with current colours."""
        try:
            self._fg_canvas.delete("all")
            self._fg_canvas.create_rectangle(0, 0, 30, 30, fill=self.fg,
                                              outline="", width=0)
            self._bg_canvas.delete("all")
            self._bg_canvas.create_rectangle(0, 0, 30, 30, fill=self.bg,
                                              outline="", width=0)
        except Exception:
            pass

    def _draw_color_swatches(self):
        """Alias kept for compatibility — redraws both swatches."""
        self._redraw_fg_bg_swatches()

    def _swatch_click(self, e):
        self._pick_fg()

    def _swatch_right_click(self, e):
        self._swap_colors()

# *************** DEL 14 – STATUS BAR **************************************

    def _build_status_bar(self):
        self.status_bar = tk.Frame(
            self.root, height=22, bg="#D8D8D8",
            relief=tk.SUNKEN, bd=1
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        self.status_bar.pack_propagate(False)

        self._s_pos = tk.Label(
            self.status_bar, text="0, 0",
            bg="#D8D8D8", width=10, anchor="w", font=("Arial", 8)
        )
        self._s_pos.pack(side=tk.LEFT, padx=6)

        tk.Frame(self.status_bar, width=1, bg="#AAAAAA").pack(side=tk.LEFT, fill=tk.Y)

        self._s_size = tk.Label(
            self.status_bar,
            text=f"{self.image.width} × {self.image.height}",
            bg="#D8D8D8", width=14, anchor="w", font=("Arial", 8)
        )
        self._s_size.pack(side=tk.LEFT, padx=6)

        tk.Frame(self.status_bar, width=1, bg="#AAAAAA").pack(side=tk.LEFT, fill=tk.Y)

        self._s_tool = tk.Label(
            self.status_bar, text="Pencil",
            bg="#D8D8D8", anchor="w", font=("Arial", 8)
        )
        self._s_tool.pack(side=tk.LEFT, padx=6)

        self._s_zoom = tk.Label(
            self.status_bar, text=f"Zoom: {self.zoom}×",
            bg="#D8D8D8", anchor="e", font=("Arial", 8)
        )
        self._s_zoom.pack(side=tk.RIGHT, padx=6)


# *************** DEL 15 – TOOL SELECTION **********************************

    def _set_hover(self, name):
        """Update the hover info box. name=None → idle hint."""
        try:
            if name:
                self._hover_lbl.config(text=TOOL_DESC.get(name, name.replace("_", " ").title()),
                                       fg="#1a1a6e")
            else:
                self._hover_lbl.config(text="Hover an icon…", fg="#666633")
        except Exception:
            pass

    def _select_tool(self, name: str):
        # Switching tool tears down the live Text editor — ask first (DEL 26b).
        if not self._guard_pending_text("switch to another tool"):
            return
        if self.tool == "polygon" and len(self.poly_pts) >= 2:
            self._commit_polygon()
        if self.tool == "curve" and self.curve_stage > 0:
            self._commit_curve()

        self.tool = name
        self.cfg["tool"] = name

        # Update button visuals: sunken + darker bg = active
        for n, btn_frame in self.tool_btns.items():
            base_bg = self._tool_btn_cfg[n]
            if n == name:
                # Active: sunken relief, slightly darker tint
                btn_frame.config(relief=tk.SUNKEN, bg="#A8C8F8")
                for child in btn_frame.winfo_children():
                    child.config(bg="#A8C8F8")
            else:
                btn_frame.config(relief=tk.RAISED, bg=base_bg)
                for child in btn_frame.winfo_children():
                    child.config(bg=base_bg)

        cursor = next((c for (nm, _, c, *_rest) in TOOL_DEF if nm == name), "crosshair")
        self.canvas.config(cursor=cursor)

        self._build_tool_options()
        self._s_tool.config(text=name.replace("_", " ").title())
        try:
            self._tool_name_lbl.config(text=name.replace("_", " ").title())
        except Exception:
            pass

        if name not in ("rect_select", "free_select"):
            self._commit_selection()

    def _set_line_w(self, w):
        self.line_w = w
        self.cfg["line_w"] = w
        self._build_tool_options()

    def _set_brush_size(self, s):
        self.brush_size = s
        self.cfg["brush_size"] = s
        self._build_tool_options()

    def _set_fill_style(self, v):
        self.fill_style = v
        self.cfg["fill_style"] = v
        self._build_tool_options()

    @needs_text_ok("change the zoom")
    def _set_zoom(self, z):
        self.zoom = z
        self.cfg["zoom"] = z
        self._refresh()
        self._s_zoom.config(text=f"Zoom: {z}×")
        self._build_tool_options()

    def _zoom_step(self, delta):
        idx = ZOOM_STEPS.index(self.zoom) if self.zoom in ZOOM_STEPS else 0
        idx = max(0, min(len(ZOOM_STEPS) - 1, idx + delta))
        self._set_zoom(ZOOM_STEPS[idx])


# *************** DEL 16 – COLOR OPERATIONS ********************************

    def _set_fg(self, c):
        self.fg = c
        self.cfg["fg"] = c
        # Picking a colour while re-editing a placed text means "recolour it".
        if getattr(self, "_text_editor", None):
            self._text_fill = None
            try:
                self._text_editor.event_generate("<KeyRelease>")   # re-preview
            except Exception:
                pass
        try:
            self._redraw_fg_bg_swatches()
        except Exception:
            pass

    def _set_bg(self, c):
        self.bg = c
        self.cfg["bg"] = c
        try:
            self._redraw_fg_bg_swatches()
        except Exception:
            pass

    def _pick_fg(self):
        c = colorchooser.askcolor(color=self.fg, title="Foreground Color")[1]
        if c:
            self._set_fg(c)

    def _pick_bg(self):
        c = colorchooser.askcolor(color=self.bg, title="Background Color")[1]
        if c:
            self._set_bg(c)

    def _swap_colors(self):
        self.fg, self.bg = self.bg, self.fg
        self.cfg["fg"] = self.fg
        self.cfg["bg"] = self.bg
        try:
            self._redraw_fg_bg_swatches()
        except Exception:
            pass

    def _set_opaque_paste(self):
        self.transparent_paste  = False
        self._paste_transparent = False
        try:
            self._btn_opaque.config(bg="#A8D8A8", relief=tk.SUNKEN)
            self._btn_transp.config(bg="#E8E8E8", relief=tk.RAISED)
        except Exception:
            pass
        if self.sel_floating:
            self._refresh()

    def _set_transparent_paste(self):
        self.transparent_paste  = True
        self._paste_transparent = True
        try:
            self._btn_transp.config(bg="#A8D8A8", relief=tk.SUNKEN)
            self._btn_opaque.config(bg="#E8E8E8", relief=tk.RAISED)
        except Exception:
            pass
        if self.sel_floating:
            self._refresh()


# *************** DEL 17 – CANVAS REFRESH / UNDO SAVE *********************

    def _img_coords(self, canvas_x, canvas_y):
        sx = int(self.canvas.canvasx(canvas_x))
        sy = int(self.canvas.canvasy(canvas_y))
        ix = (sx - 4) // self.zoom
        iy = (sy - 4) // self.zoom
        return ix, iy

    def _refresh(self, overlay=None):
        # If we have a floating paste selection, composite it live so
        # opaque/transparent mode is visible while dragging.
        if overlay is None and self.sel_floating and self.sel_image and self.sel_rect and self._paste_snap:
            x1, y1, x2, y2 = self.sel_rect
            base = self._paste_snap.copy()
            ci   = self.sel_image
            if self._paste_transparent:
                ci_rgba = ci.convert("RGBA")
                px = ci_rgba.load()
                pw, ph = ci_rgba.size
                bg_rgb = hex_to_rgb(self.bg)
                for yy in range(ph):
                    for xx in range(pw):
                        r, g, b, a = px[xx, yy]
                        dr = abs(r - bg_rgb[0])
                        dg = abs(g - bg_rgb[1])
                        db = abs(b - bg_rgb[2])
                        if dr + dg + db < 45:
                            px[xx, yy] = (r, g, b, 0)
                base_rgba = base.convert("RGBA")
                base_rgba.paste(ci_rgba, (x1, y1), ci_rgba)
                overlay = base_rgba.convert("RGB")
            else:
                base.paste(ci, (x1, y1))
                overlay = base

        src = overlay if overlay else self.image
        # Composite the movable objects (text / pasted images) on top.
        if self.objects:
            src = self._compose_objects(src)
        z   = self.zoom
        w   = src.width  * z
        h   = src.height * z
        disp = src.resize((w, h), Image.NEAREST) if z != 1 else src.copy()
        self.photo = ImageTk.PhotoImage(disp)
        self.canvas.itemconfig(self.canvas_img_id, image=self.photo)
        self.canvas.config(scrollregion=(0, 0, w + 8, h + 8))

        self.canvas.delete("sel_rect")
        if self.sel_rect:
            x1, y1, x2, y2 = self.sel_rect
            self.canvas.create_rectangle(
                x1 * z + 4, y1 * z + 4,
                x2 * z + 4, y2 * z + 4,
                outline="black", dash=(4, 4), tags="sel_rect"
            )

        # Red dashed box around the selected object (only while Move tool is on).
        self.canvas.delete("obj_sel")
        if (self.tool == "move_obj" and self.active_obj is not None
                and 0 <= self.active_obj < len(self.objects)):
            o = self.objects[self.active_obj]
            ow, oh = o["img"].size
            self.canvas.create_rectangle(
                o["x"] * z + 4,           o["y"] * z + 4,
                (o["x"] + ow) * z + 4,    (o["y"] + oh) * z + 4,
                outline="#FF0000", dash=(3, 3), width=1, tags="obj_sel"
            )

        self._draw_resize_handles(w, h)

# ─────────────────────────────────────────────────────────────────────────────
# MOVABLE OBJECTS  (text / pasted images kept as draggable items)
# ─────────────────────────────────────────────────────────────────────────────

    def _compose_objects(self, base):
        """Return an RGB copy of base with every object pasted on top (alpha)."""
        out = base.convert("RGBA")
        for o in self.objects:
            img = o["img"]
            if img.mode != "RGBA":
                img = img.convert("RGBA")
            out.paste(img, (int(round(o["x"])), int(round(o["y"]))), img)
        return out.convert("RGB")

    def _flatten_objects(self):
        """Bake all objects permanently into the base image and clear the list.
        Used before destructive transforms (flip/rotate/invert/clear/resize)."""
        if self.objects:
            self.image = self._compose_objects(self.image)
            self.draw  = ImageDraw.Draw(self.image)
            self.objects    = []
            self.active_obj = None

    def _clear_region_from_objects(self, x1, y1, x2, y2):
        """Take a rectangle away from every movable object.

        THE BUG THIS FIXES: text (and pasted images) live as objects floating
        above the base image. Lifting or deleting a selection only erased the
        BASE pixels, so the text object stayed exactly where it was and kept
        being composited on top — you dragged away a COPY while the original
        never moved, and committing the selection baked the copy in, leaving
        the text twice on the picture.

        An object fully inside the rectangle is removed; one that only
        overlaps keeps the part outside the rectangle.
        """
        keep = []
        changed = False
        for o in self.objects:
            ow, oh = o["img"].size
            ox, oy = o["x"], o["y"]
            cx1 = max(x1, ox);      cy1 = max(y1, oy)
            cx2 = min(x2, ox + ow); cy2 = min(y2, oy + oh)
            if cx2 <= cx1 or cy2 <= cy1:
                keep.append(o)                 # no overlap — untouched
                continue
            changed = True
            if cx1 <= ox and cy1 <= oy and cx2 >= ox + ow and cy2 >= oy + oh:
                continue                       # fully taken — object is gone
            # Partly taken: punch the overlap out and keep the remainder.
            img = o["img"].copy().convert("RGBA")
            ImageDraw.Draw(img).rectangle(
                [cx1 - ox, cy1 - oy, cx2 - ox - 1, cy2 - oy - 1],
                fill=(0, 0, 0, 0))
            bbox = img.getbbox()
            if not bbox:
                continue                       # nothing visible left
            frag = dict(o)
            frag["img"]  = img.crop(bbox)
            frag["x"]    = ox + bbox[0]
            frag["y"]    = oy + bbox[1]
            frag["meta"] = None                # a fragment is no longer the
            keep.append(frag)                  # original editable text
        if changed:
            self.objects    = keep
            self.active_obj = None
        return changed

    def _add_object(self, img, x, y, kind, meta=None):
        """Add a new movable object and select it.
        'meta' keeps the source of the object (for text: the typed string,
        font, size, bold and colour) so it can be re-opened for editing."""
        if img.mode != "RGBA":
            img = img.convert("RGBA")
        self.objects.append({"img": img, "x": int(x), "y": int(y),
                             "kind": kind, "meta": dict(meta) if meta else None})
        self.active_obj = len(self.objects) - 1
        self.modified = True
        self._update_title()

    def _commit_shape_object(self, draw_fn):
        """Draw a shape onto a transparent, canvas-sized layer via
        draw_fn(ImageDraw), then add the tight crop as a movable object.
        This is how lines/curves/rectangles/ellipses/polygons become objects
        instead of being baked into the picture."""
        layer = Image.new("RGBA", self.image.size, (0, 0, 0, 0))
        draw_fn(ImageDraw.Draw(layer))
        bbox = layer.getbbox()          # tight box of everything drawn
        if not bbox:
            return False
        self._add_object(layer.crop(bbox), bbox[0], bbox[1], "shape")
        return True

    def _obj_at(self, ix, iy):
        """Index of the topmost object whose box contains (ix, iy), else None."""
        for i in range(len(self.objects) - 1, -1, -1):
            o = self.objects[i]
            ow, oh = o["img"].size
            if o["x"] <= ix < o["x"] + ow and o["y"] <= iy < o["y"] + oh:
                return i
        return None

    def _apply_paste_transparency(self, img):
        """Make pixels close to the current BG colour transparent (RGBA)."""
        rgba = img.convert("RGBA")
        px = rgba.load()
        pw, ph = rgba.size
        bg_rgb = hex_to_rgb(self.bg)
        for yy in range(ph):
            for xx in range(pw):
                r, g, b, a = px[xx, yy]
                if abs(r - bg_rgb[0]) + abs(g - bg_rgb[1]) + abs(b - bg_rgb[2]) < 45:
                    px[xx, yy] = (r, g, b, 0)
        return rgba

    # ── Move tool mouse handlers ─────────────────────────────────────────────
    def _move_obj_down(self, ix, iy, e):
        idx = self._obj_at(ix, iy)
        self.active_obj = idx
        self._obj_moved = False
        if idx is not None:
            o = self.objects[idx]
            self._obj_drag_off = (ix - o["x"], iy - o["y"])
        else:
            self._obj_drag_off = None   # clicked empty space → deselect
        self._refresh()

    def _move_obj_drag(self, ix, iy, e):
        if self.active_obj is None or self._obj_drag_off is None:
            return
        if not self._obj_moved:
            self._save_undo()           # snapshot once, on first real move
            self._obj_moved = True
        dx, dy = self._obj_drag_off
        o = self.objects[self.active_obj]
        o["x"] = ix - dx
        o["y"] = iy - dy
        self._refresh()

    def _move_obj_up(self, ix, iy, e):
        self._obj_drag_off = None

# ─────────────────────────────────────────────────────────────────────────────
# CANVAS RESIZE HANDLES  (8 blue squares around the image)
# ─────────────────────────────────────────────────────────────────────────────

    # Handle IDs used as canvas tags:
    #   "E" right-middle, "S" bottom-middle, "SE" bottom-right corner
    #   "W" left-middle,  "N" top-middle,    "NE" "NW" "SW" corners
    _HANDLE_SIZE = 6   # half-size of each square in screen pixels

    def _draw_resize_handles(self, img_w_px, img_h_px):
        """Position the 8 blue resize handles around the image.

        IMPORTANT: the rectangles are created ONCE and afterwards only *moved*
        (via canvas.coords). They must never be deleted-and-recreated mid-drag:
        Tk gives the pressed canvas item an implicit button grab so that
        <B1-Motion> keeps firing even when the pointer leaves the tiny square —
        but deleting that item drops the grab, which is why dragging used to
        only 'jerk once' and then do nothing."""
        hs = self._HANDLE_SIZE
        # image occupies canvas coords  4 .. 4+img_w_px  ×  4 .. 4+img_h_px
        x0, y0 = 4, 4
        x1, y1 = 4 + img_w_px, 4 + img_h_px
        mx, my = (x0 + x1) // 2, (y0 + y1) // 2

        handles = {
            "NW": (x0, y0), "N": (mx, y0), "NE": (x1, y0),
            "W":  (x0, my),                "E":  (x1, my),
            "SW": (x0, y1), "S": (mx, y1), "SE": (x1, y1),
        }
        cursors = {
            "NW": "size_nw_se", "SE": "size_nw_se",
            "NE": "size_ne_sw", "SW": "size_ne_sw",
            "N":  "size_ns",    "S":  "size_ns",
            "W":  "size_we",    "E":  "size_we",
        }
        self._handle_positions = handles

        # Create the rectangles + bindings the first time only.
        if not getattr(self, "_handle_items", None):
            self._handle_items = {}
            for hid in handles:
                item = self.canvas.create_rectangle(
                    0, 0, 0, 0,
                    fill="#0078D7", outline="white", width=1,
                    tags=("rh", f"rh_{hid}"),
                )
                self._handle_items[hid] = item
                self.canvas.tag_bind(f"rh_{hid}", "<ButtonPress-1>",
                                     lambda e, h=hid: self._rh_press(e, h))
                self.canvas.tag_bind(f"rh_{hid}", "<B1-Motion>",
                                     lambda e, h=hid: self._rh_drag(e, h))
                self.canvas.tag_bind(f"rh_{hid}", "<ButtonRelease-1>",
                                     lambda e, h=hid: self._rh_release(e, h))
                cur = cursors.get(hid, "crosshair")
                self.canvas.tag_bind(f"rh_{hid}", "<Enter>",
                                     lambda e, c=cur: self.canvas.config(cursor=c))
                self.canvas.tag_bind(f"rh_{hid}", "<Leave>",
                                     lambda e: self.canvas.config(
                                         cursor=next((c for (nm, _, c, *_r) in TOOL_DEF
                                                      if nm == self.tool), "crosshair")))

        # Reposition (always) and keep the handles on top of the image.
        for hid, (cx, cy) in handles.items():
            self.canvas.coords(self._handle_items[hid],
                               cx - hs, cy - hs, cx + hs, cy + hs)
        self.canvas.tag_raise("rh")

    def _rh_press(self, event, handle):
        # Bake any floating paste/selection into the image FIRST. Otherwise the
        # real content still lives in self.sel_image (composited live by
        # _refresh), so resizing would operate on a blank background — the image
        # would vanish during the drag and snap back to the old composite on
        # release (looking like "no change").
        self._commit_selection()
        self._flatten_objects()      # bake objects in before resizing the canvas
        self._resize_handle   = handle
        self._resize_orig_w   = self.image.width
        self._resize_orig_h   = self.image.height
        self._resize_start_cx = self.canvas.canvasx(event.x)
        self._resize_start_cy = self.canvas.canvasy(event.y)
        self._save_undo()

    def _rh_drag(self, event, handle):
        if not self._resize_handle:
            return
        cx = self.canvas.canvasx(event.x)
        cy = self.canvas.canvasy(event.y)
        dx = int((cx - self._resize_start_cx) / self.zoom)
        dy = int((cy - self._resize_start_cy) / self.zoom)
        ow, oh = self._resize_orig_w, self._resize_orig_h

        # Compute new dimensions based on which handle is dragged
        h = handle
        new_w = ow
        new_h = oh
        if "E" in h:
            new_w = max(1, ow + dx)
        if "W" in h:
            new_w = max(1, ow - dx)
        if "S" in h:
            new_h = max(1, oh + dy)
        if "N" in h:
            new_h = max(1, oh - dy)

        # Resize live: expand = fill with BG, shrink = crop
        new_img = Image.new("RGB", (new_w, new_h), self.bg)
        paste_x = (ow - new_w) if "W" in h else 0
        paste_y = (oh - new_h) if "N" in h else 0
        new_img.paste(self.image.crop((
            max(0, paste_x), max(0, paste_y),
            max(0, paste_x) + min(new_w, ow - max(0, paste_x)),
            max(0, paste_y) + min(new_h, oh - max(0, paste_y))
        )), (0, 0))
        self._resize_preview = new_img
        self._refresh_preview(new_img)

    def _refresh_preview(self, img):
        """Like _refresh but with a temporary image (no undo, no commit)."""
        z = self.zoom
        w = img.width  * z
        h = img.height * z
        disp = img.resize((w, h), Image.NEAREST) if z != 1 else img.copy()
        self.photo = ImageTk.PhotoImage(disp)
        self.canvas.itemconfig(self.canvas_img_id, image=self.photo)
        self.canvas.config(scrollregion=(0, 0, w + 8, h + 8))
        self._draw_resize_handles(w, h)

    def _rh_release(self, event, handle):
        if not self._resize_handle:
            return
        if hasattr(self, "_resize_preview") and self._resize_preview:
            self.image = self._resize_preview
            self.draw  = ImageDraw.Draw(self.image)
            self.cfg["canvas_w"] = self.image.width
            self.cfg["canvas_h"] = self.image.height
            self._s_size.config(text=f"{self.image.width} × {self.image.height}")
            self.modified = True
            self._update_title()
        self._resize_handle  = None
        self._resize_preview = None
        self._refresh()

    def _snapshot(self):
        """Capture image + objects for undo/redo."""
        buf = io.BytesIO()
        self.image.save(buf, format="PNG")
        # "meta" must ride along, or undo/redo would strip the source text off
        # every text object and make it un-editable again.
        objs = [{"img": o["img"].copy(), "x": o["x"], "y": o["y"],
                 "kind": o["kind"],
                 "meta": dict(o["meta"]) if o.get("meta") else None}
                for o in self.objects]
        return {"img": buf.getvalue(), "objs": objs}

    def _restore(self, snap):
        self.image = Image.open(io.BytesIO(snap["img"])).convert("RGB")
        self.draw  = ImageDraw.Draw(self.image)
        self.objects = [{"img": o["img"].copy(), "x": o["x"], "y": o["y"],
                         "kind": o["kind"],
                         "meta": dict(o["meta"]) if o.get("meta") else None}
                        for o in snap["objs"]]
        self.active_obj = None

    def _save_undo(self):
        self.undo_stack.append(self._snapshot())
        if len(self.undo_stack) > UNDO_LEVELS:
            self.undo_stack.pop(0)
        self.redo_stack.clear()
        self.modified = True
        self._update_title()

    def _update_title(self):
        fn  = os.path.basename(self.current_file) if self.current_file else "Untitled"
        mod = " *" if self.modified else ""
        if not self.embedded:
            self.root.title(f"Point & Paint  –  {fn}{mod}")


# *************** DEL 18 – MOUSE EVENT DISPATCH ****************************

    def _on_mouse_move(self, event):
        ix, iy = self._img_coords(event.x, event.y)
        self._s_pos.config(text=f"{ix}, {iy}")

    def _on_mouse_down(self, event):
        self.canvas.focus_set()   # grab keyboard focus so shortcuts work in module mode
        # Ignore canvas clicks that land on a resize handle
        if self._resize_handle is not None:
            return
        items = self.canvas.find_withtag("current")
        if items and "rh" in self.canvas.gettags(items[0]):
            return
        ix, iy = self._img_coords(event.x, event.y)
        self.drawing = True
        self.start_x = ix; self.start_y = iy
        self.last_x  = ix; self.last_y  = iy
        dispatch = {
            "pencil":       self._pencil_down,
            "brush":        self._brush_down,
            "airbrush":     self._airbrush_down,
            "eraser":       self._eraser_down,
            "fill":         self._fill_down,
            "pick_color":   self._pick_color_down,
            "magnifier":    self._magnifier_down,
            "text":         self._text_down,
            "line":         self._line_down,
            "curve":        self._curve_down,
            "rectangle":    self._shape_down,
            "rounded_rect": self._shape_down,
            "ellipse":      self._shape_down,
            "polygon":      self._polygon_down,
            "rect_select":  self._rect_select_down,
            "free_select":  self._free_select_down,
            "move_obj":     self._move_obj_down,
        }
        fn = dispatch.get(self.tool)
        if fn:
            fn(ix, iy, event)

    def _on_mouse_drag(self, event):
        if not self.drawing:
            return
        ix, iy = self._img_coords(event.x, event.y)
        self._s_pos.config(text=f"{ix}, {iy}")
        dispatch = {
            "pencil":       self._pencil_drag,
            "brush":        self._brush_drag,
            "airbrush":     self._airbrush_drag,
            "eraser":       self._eraser_drag,
            "line":         self._line_drag,
            "curve":        self._curve_drag,
            "rectangle":    self._shape_drag,
            "rounded_rect": self._shape_drag,
            "ellipse":      self._shape_drag,
            "polygon":      self._polygon_drag,
            "rect_select":  self._rect_select_drag,
            "free_select":  self._free_select_drag,
            "move_obj":     self._move_obj_drag,
        }
        fn = dispatch.get(self.tool)
        if fn:
            fn(ix, iy, event)
        self.last_x = ix; self.last_y = iy

    def _on_mouse_up(self, event):
        if not self.drawing:
            return
        self.drawing = False
        ix, iy = self._img_coords(event.x, event.y)
        dispatch = {
            "pencil":       self._pencil_up,
            "brush":        self._brush_up,
            "airbrush":     self._airbrush_up,
            "eraser":       self._eraser_up,
            "line":         self._line_up,
            "curve":        self._curve_up,
            "rectangle":    self._shape_up,
            "rounded_rect": self._shape_up,
            "ellipse":      self._shape_up,
            "polygon":      self._polygon_up,
            "rect_select":  self._rect_select_up,
            "free_select":  self._free_select_up,
            "move_obj":     self._move_obj_up,
        }
        fn = dispatch.get(self.tool)
        if fn:
            fn(ix, iy, event)

    def _on_right_down(self, event):
        if self.tool in ("pencil", "brush", "airbrush", "line", "curve",
                         "rectangle", "rounded_rect", "ellipse", "polygon"):
            self._swap_colors()

    def _on_double_click(self, event):
        ix, iy = self._img_coords(event.x, event.y)
        if self.tool == "polygon":
            self._commit_polygon()
            return
        # Double-click a placed text (Move or Text tool) to correct a typo
        # instead of deleting it and typing the whole caption again.
        if self.tool in ("move_obj", "text"):
            idx = self._obj_at(ix, iy)
            if idx is not None and self.objects[idx].get("kind") == "text":
                self._edit_text_object(idx)

    def _on_ctrl_scroll(self, event):
        if event.delta > 0:
            self._zoom_step(1)
        else:
            self._zoom_step(-1)

    def _on_scroll(self, event):
        if event.delta:
            self.canvas.yview_scroll(int(-event.delta / 120), "units")


# *************** DEL 19 – PENCIL TOOL ************************************

    def _pencil_down(self, ix, iy, e):
        self._save_undo()
        self.draw.point((ix, iy), fill=self.fg)
        self._refresh()

    def _pencil_drag(self, ix, iy, e):
        self.draw.line(
            [self.last_x, self.last_y, ix, iy],
            fill=self.fg, width=1
        )
        self._refresh()

    def _pencil_up(self, ix, iy, e):
        pass


# *************** DEL 20 – BRUSH TOOL **************************************

    def _brush_stamp(self, ix, iy, color):
        r = self.brush_size // 2
        self.draw.ellipse([ix - r, iy - r, ix + r, iy + r], fill=color)

    def _brush_down(self, ix, iy, e):
        self._save_undo()
        self._brush_stamp(ix, iy, self.fg)
        self._refresh()

    def _brush_drag(self, ix, iy, e):
        dx = ix - self.last_x; dy = iy - self.last_y
        steps = max(abs(dx), abs(dy), 1)
        for i in range(steps + 1):
            t = i / steps
            x = int(self.last_x + dx * t)
            y = int(self.last_y + dy * t)
            self._brush_stamp(x, y, self.fg)
        self._refresh()

    def _brush_up(self, ix, iy, e):
        pass


# *************** DEL 21 – AIRBRUSH TOOL ***********************************

    def _airbrush_spray(self, ix, iy):
        r   = 16
        rgb = hex_to_rgb(self.fg)
        w, h = self.image.size
        for _ in range(24):
            a = random.uniform(0, 2 * math.pi)
            d = random.uniform(0, r)
            x = int(ix + d * math.cos(a))
            y = int(iy + d * math.sin(a))
            if 0 <= x < w and 0 <= y < h:
                self.image.putpixel((x, y), rgb)

    def _airbrush_down(self, ix, iy, e):
        self._save_undo()
        self._airbrush_spray(ix, iy)
        self._refresh()

    def _airbrush_drag(self, ix, iy, e):
        self._airbrush_spray(ix, iy)
        self._refresh()

    def _airbrush_up(self, ix, iy, e):
        pass


# *************** DEL 22 – ERASER TOOL ************************************

    def _eraser_down(self, ix, iy, e):
        self._save_undo()
        self._erase_at(ix, iy)
        self._refresh()

    def _eraser_drag(self, ix, iy, e):
        self._erase_at(ix, iy)
        self._refresh()

    def _eraser_up(self, ix, iy, e):
        pass

    def _erase_at(self, ix, iy):
        r = max(self.line_w * 3, 6)
        self.draw.rectangle([ix - r, iy - r, ix + r, iy + r], fill=self.bg)


# *************** DEL 23 – FILL TOOL (FLOOD FILL) *************************

    def _fill_down(self, ix, iy, e):
        w, h = self.image.size
        ix = max(0, min(ix, w - 1))
        iy = max(0, min(iy, h - 1))
        target  = self.image.getpixel((ix, iy))
        fill_rgb = hex_to_rgb(self.fg)
        if target[:3] == fill_rgb:
            return
        self._save_undo()
        ImageDraw.floodfill(self.image, (ix, iy), fill_rgb, thresh=15)
        self.draw = ImageDraw.Draw(self.image)
        self._refresh()


# *************** DEL 24 – PICK COLOR TOOL ********************************

    def _pick_color_down(self, ix, iy, e):
        w, h = self.image.size
        ix = max(0, min(ix, w - 1))
        iy = max(0, min(iy, h - 1))
        try:
            px = self.image.getpixel((ix, iy))
            self._set_fg(rgb_to_hex(px[0], px[1], px[2]))
        except Exception:
            pass


# *************** DEL 25 – MAGNIFIER TOOL *********************************

    def _magnifier_down(self, ix, iy, e):
        self._zoom_step(1)


# *************** DEL 26 – TEXT TOOL (live canvas + inline editor) *********

    # Known Windows font file stems  →  (regular file, bold file).
    # This is what makes Bold actually work: e.g. Arial bold lives in
    # "arialbd.ttf", NOT "ArialBold.ttf".
    _FONT_FILES = {
        "arial":           ("arial.ttf",   "arialbd.ttf"),
        "times new roman": ("times.ttf",   "timesbd.ttf"),
        "times":           ("times.ttf",   "timesbd.ttf"),
        "courier new":     ("cour.ttf",    "courbd.ttf"),
        "courier":         ("cour.ttf",    "courbd.ttf"),
        "verdana":         ("verdana.ttf", "verdanab.ttf"),
        "tahoma":          ("tahoma.ttf",  "tahomabd.ttf"),
        "calibri":         ("calibri.ttf", "calibrib.ttf"),
        "cambria":         ("cambria.ttc", "cambriab.ttf"),
        "comic sans ms":   ("comic.ttf",   "comicbd.ttf"),
        "georgia":         ("georgia.ttf", "georgiab.ttf"),
        "segoe ui":        ("segoeui.ttf", "segoeuib.ttf"),
        "trebuchet ms":    ("trebuc.ttf",  "trebucbd.ttf"),
        "impact":          ("impact.ttf",  "impact.ttf"),
    }

    def _load_font(self, name, size, bold):
        """Return an ImageFont for the given family/size, honouring Bold.
        Tries known Windows file names first, then common bold conventions,
        then plain names, then a cross-platform fallback."""
        name = (name or "Arial").strip()
        key  = name.lower()
        base = name.replace(" ", "")
        cands = []

        if key in self._FONT_FILES:
            reg, bd = self._FONT_FILES[key]
            cands.append(bd if bold else reg)
            cands.append(reg)                      # if bold file is missing
        if bold:
            cands += [f"{base}bd.ttf", f"{base}b.ttf",
                      f"{base}-Bold.ttf", f"{base}Bold.ttf", f"{base} Bold.ttf"]
        cands += [f"{base}.ttf", f"{base.lower()}.ttf", name + ".ttf", name]

        # Try each as a bare name (PIL searches the Windows Fonts dir) and as a
        # full Windows path.
        win_fonts = os.path.join(os.environ.get("WINDIR", "C:/Windows"), "Fonts")
        ordered = []
        for c in cands:
            ordered.append(c)
            if c.lower().endswith((".ttf", ".ttc", ".otf")):
                ordered.append(os.path.join(win_fonts, c))
        # Cross-platform fallbacks (Linux)
        ordered += [
            "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold
                else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
            "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf" if bold
                else "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
        ]

        # Cache the result: _load_font runs on EVERY keystroke of the live
        # preview, and a name that is not an exact file stem makes it try a
        # dozen paths on disk each time.
        cache = self.__dict__.setdefault("_font_cache", {})
        ck = (name, size, bool(bold))
        if ck in cache:
            return cache[ck]

        font = None

        # Exact hit in the real font index first — this is what the ▾ picker
        # offers, so a picked name always gives that exact face.
        try:
            self._font_index()
            real = self._font_idx_ci.get(key)
            if real:
                slot = self._font_idx[real]
                path = slot.get("bold" if bold else "regular")
                if path:
                    font = ImageFont.truetype(path, size)
        except Exception:
            font = None

        for cand in ([] if font else ordered):
            try:
                font = ImageFont.truetype(cand, size)
                break
            except Exception:
                pass
        if font is None:
            try:
                font = ImageFont.load_default(size=size)
            except Exception:
                font = ImageFont.load_default()
        if len(cache) > 120:              # keep it from growing forever
            cache.clear()
        cache[ck] = font
        return font

    def _font_index(self):
        """family name -> {"regular": path, "bold": path}, built by reading the
        actual font files on disk.

        Why not tkinter's font.families()? It lists ~190 names on this machine,
        but two thirds of them are style aliases or .ttc members that Pillow
        cannot open ("Arial Black", "Bahnschrift Light", "Arial Cyr" …).
        Offering those in the picker would hand you a silent fallback face
        instead of the font you chose. Reading the files takes ~0.06 s and is
        done once, on first use.
        """
        idx = getattr(self, "_font_idx", None)
        if idx is not None:
            return idx

        idx = {}
        dirs = [os.path.join(os.environ.get("WINDIR", "C:/Windows"), "Fonts"),
                os.path.join(os.environ.get("LOCALAPPDATA", ""),
                             "Microsoft", "Windows", "Fonts"),
                "/usr/share/fonts", os.path.expanduser("~/.fonts")]
        for d in dirs:
            if not d or not os.path.isdir(d):
                continue
            try:
                walk = os.walk(d)
            except Exception:
                continue
            for base, _sub, files in walk:
                for fn in files:
                    if not fn.lower().endswith((".ttf", ".ttc", ".otf")):
                        continue
                    path = os.path.join(base, fn)
                    try:
                        fam, style = ImageFont.truetype(path, 12).getname()
                    except Exception:
                        continue
                    if not fam:
                        continue
                    st = (style or "").lower()
                    if "italic" in st or "oblique" in st:
                        continue           # the Text tool has no italic option
                    slot = idx.setdefault(fam.strip(), {})
                    if "bold" in st:
                        slot.setdefault("bold", path)
                    else:
                        slot.setdefault("regular", path)

        # A family that ships only one weight serves as both.
        for slot in idx.values():
            if "regular" not in slot:
                slot["regular"] = slot.get("bold")
            if "bold" not in slot:
                slot["bold"] = slot.get("regular")

        self._font_idx    = idx
        self._font_idx_ci = {k.lower(): k for k in idx}     # case-insensitive
        return idx

    def _installed_fonts(self):
        """Sorted family names for the Text tool's picker — only fonts that
        really load, so picking one can never give you a different face."""
        cached = getattr(self, "_font_list", None)
        if cached:
            return cached
        out = sorted(self._font_index().keys())
        if not out:                       # nothing found: fall back to the
            out = sorted(n.title() for n in self._FONT_FILES)   # known names
        self._font_list = out
        return out

    def _sanitize_filename(self, text):
        """Turn typed text into a safe, short file-name suggestion."""
        if not text or not text.strip():
            return ""
        first = text.strip().splitlines()[0]
        out = "".join(c for c in first if c not in '\\/:*?"<>|').strip()
        return out[:50].strip()

    def _render_text_object(self, text, font, fill=None):
        """Render (multiline) text onto a tight, transparent RGBA image."""
        measure = ImageDraw.Draw(Image.new("RGB", (1, 1)))
        try:
            bbox = measure.multiline_textbbox((0, 0), text, font=font)
        except Exception:
            bbox = measure.textbbox((0, 0), text, font=font)
        pad = 2
        tw = max(1, bbox[2] - bbox[0] + 2 * pad)
        th = max(1, bbox[3] - bbox[1] + 2 * pad)
        obj = Image.new("RGBA", (tw, th), (0, 0, 0, 0))
        ImageDraw.Draw(obj).multiline_text(
            (pad - bbox[0], pad - bbox[1]), text,
            fill=fill or self.fg, font=font)
        return obj

    def _text_down(self, ix, iy, e):
        if hasattr(self, "_text_editor") and self._text_editor:
            self._commit_text_editor()
        self._open_text_editor(ix, iy)

    def _edit_text_object(self, idx):
        """Re-open an already placed text object for editing.
        The object is lifted off the canvas and put back when you press OK."""
        try:
            o = self.objects[idx]
        except Exception:
            return False
        meta = o.get("meta")
        if o.get("kind") != "text" or not meta:
            return False

        if self._text_editor and not self._guard_pending_text("edit another text"):
            return True                       # user chose to keep typing

        self._save_undo()
        x, y = o["x"], o["y"]
        self.objects.pop(idx)                 # lift it out while editing
        self.active_obj = None
        self._refresh()
        self._select_tool("text")
        self._open_text_editor(x, y, initial=meta)
        return True

    def _open_text_editor(self, ix, iy, initial=None):
        # NOTE: no _save_undo() here. Merely clicking with the Text tool used
        # to push an undo state, so a few stray clicks flushed all 10 real
        # steps out of the history. The snapshot is taken in _commit(), i.e.
        # only when text is actually placed.
        self._text_snap = self.image.copy()
        self._text_ix   = ix
        self._text_iy   = iy

        # Clear opt_frame and build live text editor there
        for w in self.opt_frame.winfo_children():
            w.destroy()

        lbl_kw = dict(bg="#E0E0E0", font=("Arial", 7), fg="#333333")

        tk.Label(self.opt_frame, text="Text (live):", **lbl_kw).pack(anchor="w", pady=(2,0))

        initial = initial or {}
        fv = tk.StringVar(value=initial.get("font",
                          getattr(self, "_last_text_font", "Arial")))
        sv = tk.IntVar(value=int(initial.get("size",
                       getattr(self, "_last_text_size", 16))))
        bv = tk.BooleanVar(value=bool(initial.get("bold",
                           getattr(self, "_last_text_bold", False))))
        # Colour the text was originally written in (re-edit keeps it).
        self._text_fill = initial.get("fill")

        opt_row = tk.Frame(self.opt_frame, bg="#E0E0E0"); opt_row.pack(fill=tk.X)
        tk.Label(opt_row, text="Font:", **lbl_kw).pack(side=tk.LEFT)
        fe = tk.Entry(opt_row, textvariable=fv, width=6, font=("Arial", 7),
                      insertofftime=0, insertontime=9999999, bg="white")
        no_blink(fe); fe.pack(side=tk.LEFT, padx=1)

        # "▾" opens a list of the fonts actually installed. Typing a name by
        # hand still works, but you no longer have to guess the exact spelling
        # ("Comic Sans MS") only to get a silent fallback face when it is wrong.
        def _font_menu():
            m = tk.Menu(self.opt_frame, tearoff=0)
            fams = self._installed_fonts()
            per_col = 28
            for k, fam in enumerate(fams):
                m.add_command(label=fam,
                              columnbreak=(k > 0 and k % per_col == 0),
                              command=lambda f=fam: (fv.set(f), _preview()))
            try:
                m.tk_popup(fe.winfo_rootx(), fe.winfo_rooty() + fe.winfo_height())
            finally:
                m.grab_release()

        tk.Button(opt_row, text="▾", font=("Arial", 6), width=1,
                  bg="#FFFFFF", activebackground="#B0D0FF",
                  command=_font_menu).pack(side=tk.LEFT)

        opt_row2 = tk.Frame(self.opt_frame, bg="#E0E0E0"); opt_row2.pack(fill=tk.X)
        tk.Label(opt_row2, text="Size:", **lbl_kw).pack(side=tk.LEFT)
        # Spinbox = size field with up/down arrows.
        se = tk.Spinbox(opt_row2, from_=6, to=300, increment=1,
                        textvariable=sv, width=4, font=("Arial", 8),
                        insertofftime=0, insertontime=9999999, bg="white",
                        command=lambda: _preview())
        no_blink(se); se.pack(side=tk.LEFT, padx=1)

        # Bold on its OWN row, label BEFORE the checkbox:  "Bold: [x]"
        opt_row3 = tk.Frame(self.opt_frame, bg="#E0E0E0"); opt_row3.pack(fill=tk.X)
        tk.Label(opt_row3, text="Bold:", **lbl_kw).pack(side=tk.LEFT)
        tk.Checkbutton(opt_row3, variable=bv,
                       bg="#E0E0E0", font=("Arial", 8),
                       command=lambda: _preview()).pack(side=tk.LEFT)

        tk.Label(self.opt_frame, text="Text:", **lbl_kw).pack(anchor="w", pady=(4,0))
        txt = tk.Text(self.opt_frame, width=11, height=5,
                      font=("Arial", 9), bg="white",
                      insertofftime=0, insertontime=9999999,
                      relief=tk.SUNKEN, bd=1, wrap=tk.WORD)
        no_blink(txt)
        txt.pack(fill=tk.X, padx=2)
        if initial.get("text"):
            txt.insert("1.0", initial["text"])       # re-editing a placed text
        txt.focus_set()

        # Stacked full-width buttons with plain labels (the old ✓/✗ glyphs
        # rendered as garbage in this button font, and side-by-side they were
        # too wide for the column and got clipped to "Cance").
        btn_row = tk.Frame(self.opt_frame, bg="#E0E0E0"); btn_row.pack(fill=tk.X, pady=3)
        tk.Button(btn_row, text="OK", font=("Arial", 8, "bold"), bg="#C8F0C8",
                  command=lambda: _commit()).pack(fill=tk.X, padx=2, pady=1)
        tk.Button(btn_row, text="Cancel", font=("Arial", 8), bg="#F0C8C8",
                  command=lambda: _cancel()).pack(fill=tk.X, padx=2, pady=1)

        tk.Label(self.opt_frame,
                 text="Ctrl+Enter=OK\nEsc=Cancel",
                 bg="#E0E0E0", font=("Arial", 6), fg="#666").pack()

        self._text_editor = txt   # mark as open

        def _size_val():
            try:
                return max(6, int(float(sv.get())))
            except Exception:
                return 16

        def _get_font():
            return self._load_font(fv.get().strip() or "Arial",
                                   _size_val(), bv.get())

        def _preview(ev=None):
            text = txt.get("1.0", "end-1c")
            # Capture the suggested save name LIVE as the user types, so it is
            # remembered even if they go straight to Save As without pressing OK.
            if text.strip():
                name = self._sanitize_filename(text)
                if name:
                    self._suggest_name = name
            img  = self._text_snap.copy()
            if text.strip():
                ImageDraw.Draw(img).text(
                    (self._text_ix, self._text_iy), text,
                    fill=(self._text_fill or self.fg), font=_get_font()
                )
            self._refresh(img)

        def _commit(ev=None):
            """PLACE the text on the canvas and close the editor."""
            # Guard: may be called twice (e.g. by the unplaced-text dialog and
            # then by the caller); the second call must be a harmless no-op.
            if self._text_snap is None:
                self.root.unbind("<Escape>")
                return
            self._last_text_font = fv.get().strip() or "Arial"
            self._last_text_size = _size_val()
            self._last_text_bold = bv.get()
            text = txt.get("1.0", "end-1c")
            # The preview was drawn on the snapshot; restore the clean base.
            # The text becomes a separate MOVABLE object (Move tool), not baked
            # pixels — so it can be repositioned later on its own.
            self.image = self._text_snap.copy()
            self.draw  = ImageDraw.Draw(self.image)
            if text.strip():
                name = self._sanitize_filename(text)
                if name:
                    self._suggest_name = name
                self._save_undo()          # one undo step per placed text
                fill = self._text_fill or self.fg
                obj_img = self._render_text_object(text, _get_font(), fill)
                # Keep the source text with the object so it can be re-opened
                # and edited later (double-click with the Move tool).
                self._add_object(obj_img, self._text_ix, self._text_iy, "text",
                                 meta={"text": text,
                                       "font": self._last_text_font,
                                       "size": self._last_text_size,
                                       "bold": self._last_text_bold,
                                       "fill": fill})
            self._close_text_editor()
            self._refresh()
            self._build_tool_options()   # restore normal options

        def _drop(ev=None):
            """THROW the typed text away and restore the untouched canvas.
            Asks nothing — the caller has already confirmed."""
            if self._text_snap is None:
                self.root.unbind("<Escape>")
                return
            self.image = self._text_snap.copy()
            self.draw  = ImageDraw.Draw(self.image)
            self._close_text_editor()
            self._refresh()
            self._build_tool_options()

        def _cancel(ev=None):
            """Escape / the Cancel button.
            Typed text is NEVER thrown away without asking first."""
            # Guard: Escape may fire after the editor already closed.
            if self._text_snap is None:
                self.root.unbind("<Escape>")
                return
            if self._pending_text().strip():
                choice = self._ask_pending_text("cancel the text")
                if choice == "cancel":          # back to typing
                    try:
                        txt.focus_set()
                    except Exception:
                        pass
                    return
                if choice == "keep":            # place it after all
                    _commit()
                    return
            _drop()

        # Hand the two end-states to the app so the unplaced-text guard
        # (DEL 26b) can place or drop the text from anywhere in the program.
        self._text_commit_fn = _commit
        self._text_drop_fn   = _drop

        # Live preview on every keystroke
        txt.bind("<KeyRelease>", _preview)
        fe.bind("<KeyRelease>",  _preview)
        se.bind("<KeyRelease>",  _preview)
        txt.bind("<Control-Return>", _commit)
        # Bind Escape on root temporarily
        self.root.bind("<Escape>", lambda e: _cancel())

    def _close_text_editor(self):
        """Forget the live editor — shared by the commit and drop paths."""
        self._text_editor    = None
        self._text_snap      = None
        self._text_commit_fn = None
        self._text_drop_fn   = None
        self._text_fill      = None
        try:
            self.root.unbind("<Escape>")
        except Exception:
            pass

    def _commit_text_editor(self):
        """Place whatever is in the live editor, without asking."""
        if getattr(self, "_text_editor", None):
            fn = getattr(self, "_text_commit_fn", None)
            if callable(fn):
                try:
                    fn()
                    return
                except Exception:
                    pass
            # Fallback: editor is in an unexpected state — clean up.
            self._close_text_editor()
            self._build_tool_options()


# *************** DEL 26b – UNPLACED-TEXT GUARD ****************************
#
# The old behaviour: you typed a caption with the Text tool, then clicked
# another tool / a menu item / pressed Escape — and everything you had typed
# vanished without a word. The live editor lives inside the tool-options
# strip, so anything that rebuilt that strip destroyed it.
#
# The new behaviour: every route that would destroy unplaced text calls
# _guard_pending_text() first. It shows ONE modal dialog with three explicit
# choices, so text can never disappear by accident:
#
#     Place the text   → the text is committed onto the canvas, then the
#                        action you asked for continues
#     Discard          → the text is thrown away (your explicit choice), then
#                        the action continues
#     Keep typing      → the action is cancelled, you are back in the editor
#
# Entry points: @needs_text_ok(...) on the menu/file/edit/image commands,
# an explicit call in _select_tool(), and a safety net in
# _build_tool_options().

    def _pending_text(self) -> str:
        """Text sitting in the live Text editor that has NOT been placed on
        the canvas yet. Returns '' when the editor is closed or empty."""
        ed = getattr(self, "_text_editor", None)
        if not ed:
            return ""
        try:
            if not ed.winfo_exists():
                return ""
            return ed.get("1.0", "end-1c")
        except Exception:
            return ""

    def _ask_pending_text(self, action="continue", allow_cancel=True) -> str:
        """Modal dialog: what should happen to the text you typed but never
        placed? Returns 'keep' (place it), 'discard', or 'cancel'."""
        text = self._pending_text()
        lines = text.strip().splitlines()
        preview = "\n".join(line[:60] for line in lines[:5])
        if len(lines) > 5:
            preview += "\n…"
        if not preview:
            preview = "(empty)"

        result = {"v": "cancel" if allow_cancel else "keep"}

        top = tk.Toplevel(self.root)
        top.title("Unplaced text")
        top.configure(bg="#E8E8E8")
        top.resizable(False, False)
        top.transient(self.root)

        def _choose(v):
            result["v"] = v
            try:
                top.grab_release()
            except Exception:
                pass
            top.destroy()

        top.grab_set()
        top.focus_force()
        top.bind("<Escape>",
                 lambda e: _choose("cancel" if allow_cancel else "keep"))
        top.protocol("WM_DELETE_WINDOW",
                     lambda: _choose("cancel" if allow_cancel else "keep"))
        top.geometry(f"+{self.root.winfo_rootx()+140}+{self.root.winfo_rooty()+130}")

        # Segoe UI, not Arial: the Arial button/label font renders symbol
        # glyphs as garbage (same trap as the old ✓/✗ buttons). Also note the
        # plain "⚠" WITHOUT the U+FE0F variation selector — Tk draws that
        # selector as a stray dot next to the glyph.
        tk.Label(top, text="⚠  You have text that is not placed yet",
                 bg="#E8E8E8", fg="#203050",
                 font=("Segoe UI", 11, "bold")).pack(padx=18, pady=(14, 2), anchor="w")
        tk.Label(top,
                 text=f"You typed this with the Text tool but never pressed OK,\n"
                      f"and you are about to {action}.",
                 bg="#E8E8E8", justify="left",
                 font=("Arial", 9)).pack(padx=18, pady=(0, 8), anchor="w")

        # The typed text itself, so it is obvious what is at stake.
        box = tk.Text(top, width=46, height=min(6, max(2, len(lines) + 1)),
                      font=("Consolas", 9), bg="#FFFFFF", fg="#101010",
                      relief=tk.SUNKEN, bd=1, wrap="word",
                      insertofftime=0, insertontime=9999999)
        no_blink(box)
        box.insert("1.0", preview)
        box.config(state="disabled", cursor="arrow")
        box.pack(padx=18, pady=(0, 10), fill="x")

        bf = tk.Frame(top, bg="#E8E8E8")
        bf.pack(padx=18, pady=(0, 14), fill="x")

        keep_btn = tk.Button(bf, text="Place the text  (Enter)", width=34,
                             font=("Arial", 9, "bold"),
                             bg="#C8F0C8", activebackground="#A8E0A8",
                             command=lambda: _choose("keep"))
        keep_btn.pack(fill="x", pady=2)
        tk.Button(bf, text="Discard the text", width=34,
                  font=("Arial", 9),
                  bg="#F0C8C8", activebackground="#E0A8A8",
                  command=lambda: _choose("discard")).pack(fill="x", pady=2)
        if allow_cancel:
            tk.Button(bf, text="Keep typing  (Esc)", width=34,
                      font=("Arial", 9),
                      bg="#D8D8D8", activebackground="#C0C0C0",
                      command=lambda: _choose("cancel")).pack(fill="x", pady=2)

        top.bind("<Return>",    lambda e: _choose("keep"))
        top.bind("<KP_Enter>",  lambda e: _choose("keep"))
        keep_btn.focus_set()          # the safe choice is the default one

        self.root.wait_window(top)
        return result["v"]

    def _guard_pending_text(self, action="continue", allow_cancel=True) -> bool:
        """Ask about unplaced text before an action that would destroy it.

        Returns True when the caller may proceed (the text was either placed
        or deliberately discarded) and False when the user wants to keep
        typing — in which case the caller must do nothing at all.
        """
        if not self._pending_text().strip():
            # Nothing typed: close an empty editor quietly and carry on.
            if getattr(self, "_text_editor", None):
                fn = getattr(self, "_text_drop_fn", None)
                if callable(fn):
                    fn()
                else:
                    self._close_text_editor()
            return True
        if self._text_guard_busy:
            # A guard dialog is already open; never stack two of them.
            return False

        self._text_guard_busy = True
        try:
            choice = self._ask_pending_text(action, allow_cancel=allow_cancel)
        finally:
            self._text_guard_busy = False

        if choice == "cancel":
            try:
                self._text_editor.focus_set()
            except Exception:
                pass
            return False
        if choice == "keep":
            fn = getattr(self, "_text_commit_fn", None)
            if callable(fn):
                fn()
        else:                                    # discard
            fn = getattr(self, "_text_drop_fn", None)
            if callable(fn):
                fn()
            else:
                self._close_text_editor()
        return True

    def _typing_now(self) -> bool:
        """True when the keyboard focus sits in a text field. Global
        accelerators (Ctrl+A, Delete, Ctrl+C …) must then stay out of the way
        and let the field handle the keystroke itself."""
        try:
            w = self.root.focus_get()
        except Exception:
            return False
        return isinstance(w, (tk.Entry, tk.Text, tk.Spinbox, ttk.Entry))



# *************** DEL 27 – LINE TOOL **************************************

    def _line_down(self, ix, iy, e):
        self._save_undo()
        self._line_snap = self.image.copy()

    def _line_drag(self, ix, iy, e):
        ov = self._line_snap.copy()
        ImageDraw.Draw(ov).line(
            [self.start_x, self.start_y, ix, iy],
            fill=self.fg, width=self.line_w
        )
        self._refresh(ov)

    def _line_up(self, ix, iy, e):
        self._commit_shape_object(
            lambda d: d.line([self.start_x, self.start_y, ix, iy],
                             fill=self.fg, width=self.line_w))
        self._refresh()


# *************** DEL 28 – CURVE TOOL ************************************

    def _curve_down(self, ix, iy, e):
        if self.curve_stage == 0:
            self._save_undo()
            self.curve_base = self.image.copy()
            self.curve_pts  = [(ix, iy), (ix, iy)]
            self.curve_stage = 1
        elif self.curve_stage == 2:
            self.curve_pts.append((ix, iy))
            self.curve_stage = 3
            self._preview_curve()
        elif self.curve_stage == 3:
            self.curve_pts.append((ix, iy))
            self._commit_curve()

    def _curve_drag(self, ix, iy, e):
        if self.curve_stage == 1:
            self.curve_pts[1] = (ix, iy)
            ov = self.curve_base.copy()
            ImageDraw.Draw(ov).line(
                [self.curve_pts[0], self.curve_pts[1]],
                fill=self.fg, width=self.line_w
            )
            self._refresh(ov)

    def _curve_up(self, ix, iy, e):
        if self.curve_stage == 1:
            self.curve_pts[1] = (ix, iy)
            self.curve_stage  = 2
            self._preview_curve()

    def _preview_curve(self):
        if not self.curve_base:
            return
        ov = self.curve_base.copy()
        self._draw_bezier(ImageDraw.Draw(ov))
        self._refresh(ov)

    def _draw_bezier(self, d):
        pts   = self.curve_pts
        steps = 60
        result= []
        if len(pts) == 2:
            result = [pts[0], pts[1]]
        elif len(pts) == 3:
            p0, p1, p2 = pts[0], pts[2], pts[1]
            for i in range(steps + 1):
                t = i / steps
                x = (1-t)**2 * p0[0] + 2*(1-t)*t * p1[0] + t**2 * p2[0]
                y = (1-t)**2 * p0[1] + 2*(1-t)*t * p1[1] + t**2 * p2[1]
                result.append((int(x), int(y)))
        else:
            p0, p3 = pts[0], pts[1]
            p1, p2 = pts[2], pts[3]
            for i in range(steps + 1):
                t = i / steps
                x = ((1-t)**3*p0[0] + 3*(1-t)**2*t*p1[0]
                     + 3*(1-t)*t**2*p2[0] + t**3*p3[0])
                y = ((1-t)**3*p0[1] + 3*(1-t)**2*t*p1[1]
                     + 3*(1-t)*t**2*p2[1] + t**3*p3[1])
                result.append((int(x), int(y)))
        if len(result) >= 2:
            d.line(result, fill=self.fg, width=self.line_w)

    def _commit_curve(self):
        if self.curve_base:
            self._commit_shape_object(lambda d: self._draw_bezier(d))
            self._refresh()
        self.curve_pts   = []
        self.curve_stage = 0
        self.curve_base  = None


# *************** DEL 29 – SHAPE TOOLS ************************************

    def _shape_down(self, ix, iy, e):
        self._save_undo()
        self._shape_snap = self.image.copy()

    def _shape_drag(self, ix, iy, e):
        ov = self._shape_snap.copy()
        self._draw_shape(ImageDraw.Draw(ov), self.start_x, self.start_y, ix, iy)
        self._refresh(ov)

    def _shape_up(self, ix, iy, e):
        self._commit_shape_object(
            lambda d: self._draw_shape(d, self.start_x, self.start_y, ix, iy))
        self._refresh()

    def _draw_shape(self, d, x1, y1, x2, y2):
        col = self.fg
        fw  = self.line_w
        fs  = self.fill_style
        bb  = [min(x1,x2), min(y1,y2), max(x1,x2), max(y1,y2)]
        t   = self.tool

        if t == "rectangle":
            if fs == 1:
                d.rectangle(bb, fill=col)
            elif fs == 2:
                d.rectangle(bb, fill=col, outline=col, width=fw)
            else:
                d.rectangle(bb, outline=col, width=fw)

        elif t == "rounded_rect":
            rr = max(2, min(16, (bb[2]-bb[0])//5, (bb[3]-bb[1])//5))
            if fs == 1:
                d.rounded_rectangle(bb, radius=rr, fill=col)
            elif fs == 2:
                d.rounded_rectangle(bb, radius=rr, fill=col, outline=col, width=fw)
            else:
                d.rounded_rectangle(bb, radius=rr, outline=col, width=fw)

        elif t == "ellipse":
            if fs == 1:
                d.ellipse(bb, fill=col)
            elif fs == 2:
                d.ellipse(bb, fill=col, outline=col, width=fw)
            else:
                d.ellipse(bb, outline=col, width=fw)


# *************** DEL 30 – POLYGON TOOL ***********************************

    def _polygon_down(self, ix, iy, e):
        if not self.poly_pts:
            self._save_undo()
            self._poly_snap = self.image.copy()
        self.poly_pts.append((ix, iy))

    def _polygon_drag(self, ix, iy, e):
        if not self.poly_pts:
            return
        ov = self._poly_snap.copy()
        d  = ImageDraw.Draw(ov)
        pts = self.poly_pts + [(ix, iy)]
        if len(pts) >= 2:
            d.line(pts, fill=self.fg, width=self.line_w)
        self._refresh(ov)

    def _polygon_up(self, ix, iy, e):
        pass

    def _commit_polygon(self):
        if len(self.poly_pts) < 2:
            self.poly_pts = []
            return
        fs  = self.fill_style
        pts = list(self.poly_pts)

        def _draw_poly(d):
            if fs == 1:
                d.polygon(pts, fill=self.fg)
            elif fs == 2:
                d.polygon(pts, fill=self.fg, outline=self.fg)
            else:
                d.line(pts + [pts[0]], fill=self.fg, width=self.line_w)

        self._commit_shape_object(_draw_poly)
        self.poly_pts  = []
        self._poly_snap = None
        self._refresh()


# *************** DEL 31 – RECT SELECT TOOL ********************************

    def _rect_select_down(self, ix, iy, e):
        if self.sel_rect:
            x1, y1, x2, y2 = self.sel_rect
            if x1 <= ix <= x2 and y1 <= iy <= y2:
                # Click inside existing selection → lift content
                if not self.sel_floating:
                    self._lift_selection()
                self._sel_drag_start = (ix, iy)
                return
        self._commit_selection()
        self.sel_rect = (ix, iy, ix, iy)

    def _lift_selection(self):
        """Lift the selected pixels off the canvas and make the selection floating.
        The vacated area is filled with the background colour."""
        crop = self._get_sel_crop()
        if crop is None:
            return
        self._save_undo()
        x1, y1, x2, y2 = self.sel_rect
        # Erase the lifted area with background colour
        self.draw.rectangle([x1, y1, x2, y2], fill=self.bg)
        # …and take it away from the movable objects too, or the text you are
        # lifting stays put and you drag a copy around instead.
        self._clear_region_from_objects(x1, y1, x2, y2)
        # Set up floating state so _refresh composites the image live
        self._paste_snap        = self.image.copy()
        self._paste_transparent = self.transparent_paste
        self.sel_image          = crop
        self.sel_floating       = True
        self._refresh()

    def _rect_select_drag(self, ix, iy, e):
        if self._sel_drag_start:
            ox, oy = self._sel_drag_start
            dx = ix - ox; dy = iy - oy
            if self.sel_rect:
                x1, y1, x2, y2 = self.sel_rect
                self.sel_rect = (x1+dx, y1+dy, x2+dx, y2+dy)
            self._sel_drag_start = (ix, iy)
            self._refresh()
            return
        if self.sel_rect:
            ox, oy = self.start_x, self.start_y
            self.sel_rect = (
                min(ox, ix), min(oy, iy),
                max(ox, ix), max(oy, iy)
            )
            self._refresh()

    def _rect_select_up(self, ix, iy, e):
        self._sel_drag_start = None
        if self.sel_rect:
            x1, y1, x2, y2 = self.sel_rect
            if abs(x2-x1) < 2 or abs(y2-y1) < 2:
                self.sel_rect = None
        self._refresh()


# *************** DEL 32 – FREE SELECT (LASSO) TOOL ************************

    def _free_select_down(self, ix, iy, e):
        self._commit_selection()
        self.lasso_pts  = [(ix, iy)]
        self._lasso_snap = self.image.copy()

    def _free_select_drag(self, ix, iy, e):
        self.lasso_pts.append((ix, iy))
        ov = self._lasso_snap.copy()
        d  = ImageDraw.Draw(ov)
        if len(self.lasso_pts) >= 2:
            d.line(self.lasso_pts, fill="black", width=1)
        self._refresh(ov)

    def _free_select_up(self, ix, iy, e):
        if len(self.lasso_pts) >= 3:
            xs = [p[0] for p in self.lasso_pts]
            ys = [p[1] for p in self.lasso_pts]
            self.sel_rect = (min(xs), min(ys), max(xs), max(ys))
        self.lasso_pts = []
        self._refresh()


# *************** DEL 33 – SELECTION OPERATIONS ***************************

    def _commit_selection(self):
        if self.sel_floating and self.sel_image and self.sel_rect:
            x1, y1 = self.sel_rect[0], self.sel_rect[1]
            ci = self.sel_image
            if self._paste_transparent:
                ci_rgba = ci.convert("RGBA")
                px = ci_rgba.load()
                pw, ph = ci_rgba.size
                bg_rgb = hex_to_rgb(self.bg)
                for yy in range(ph):
                    for xx in range(pw):
                        r, g, b, a = px[xx, yy]
                        dr = abs(r - bg_rgb[0])
                        dg = abs(g - bg_rgb[1])
                        db = abs(b - bg_rgb[2])
                        if dr + dg + db < 45:
                            px[xx, yy] = (r, g, b, 0)
                base_rgba = self.image.convert("RGBA")
                base_rgba.paste(ci_rgba, (x1, y1), ci_rgba)
                self.image = base_rgba.convert("RGB")
            else:
                self.image.paste(ci, (x1, y1))
            self.draw = ImageDraw.Draw(self.image)
        self.sel_rect           = None
        self.sel_image          = None
        self.sel_floating       = False
        self._sel_drag_start    = None
        self._paste_snap        = None
        self._paste_transparent = False

    @needs_text_ok("select all")
    def _select_all(self):
        self._commit_selection()
        w, h = self.image.size
        self.sel_rect = (0, 0, w, h)
        self._refresh()

    @needs_text_ok("clear the selection")
    def _clear_selection(self):
        self.sel_rect = None
        self._refresh()

    @needs_text_ok("delete")
    def _delete_selection(self):
        # Delete the selected movable object first, if any.
        if self.active_obj is not None and 0 <= self.active_obj < len(self.objects):
            self._save_undo()
            self.objects.pop(self.active_obj)
            self.active_obj = None
            self._refresh()
            return
        if not self.sel_rect:
            return
        self._save_undo()
        x1, y1, x2, y2 = self.sel_rect
        self.draw.rectangle([x1, y1, x2, y2], fill=self.bg)
        # Delete has to remove the text/pasted objects in the box as well,
        # otherwise they survive on top of the freshly cleared area.
        self._clear_region_from_objects(x1, y1, x2, y2)
        self._commit_selection()
        self._refresh()

    def _get_sel_crop(self):
        if not self.sel_rect:
            return None
        x1, y1, x2, y2 = self.sel_rect
        x1 = max(0, x1); y1 = max(0, y1)
        x2 = min(self.image.width, x2); y2 = min(self.image.height, y2)
        if x2 <= x1 or y2 <= y1:
            return None
        # Include objects so Copy/Cut/Save-Selection capture what is shown.
        return self._compose_objects(self.image).crop((x1, y1, x2, y2))


# *************** DEL 34 – FILE OPERATIONS *********************************

    @needs_text_ok("start a new image")
    def _new(self):
        if self.modified:
            r = messagebox.askyesnocancel("New", "Save current image first?")
            if r is None: return
            if r: self._save()
        cw = int(self.cfg["canvas_w"]); ch = int(self.cfg["canvas_h"])
        self.image = Image.new("RGB", (cw, ch), "#FFFFFF")
        self.draw  = ImageDraw.Draw(self.image)
        self.objects    = []; self.active_obj = None
        self.undo_stack.clear(); self.redo_stack.clear()
        self._commit_selection()
        self.current_file = ""
        self._suggest_name = ""
        self.modified     = False
        self._refresh()
        self._update_title()
        self._s_size.config(text=f"{cw} × {ch}")

    def _initial_dir(self):
        """Folder that Open/Save dialogs start in.
        Priority: the user's favourite folder (if it still exists) → the last
        used folder → the home directory."""
        fav = self.cfg["fav_dir"]
        if fav and os.path.isdir(fav):
            return fav
        return self.cfg["last_dir"] or os.path.expanduser("~")

    def _suggest_basename(self):
        """Base file name proposed in the Save dialogs.
        Priority: the last text typed with the Text tool → the current file's
        name → a generic 'image'."""
        if self._suggest_name:
            return self._suggest_name
        if self.current_file:
            return os.path.splitext(os.path.basename(self.current_file))[0]
        return "image"

    def _set_fav_dir(self):
        """Let the user type (or browse to) a favourite save/open folder so the
        dialogs no longer open at the Windows default location."""
        top = tk.Toplevel(self.root)
        top.title("Default Save Folder")
        top.configure(bg="#E8E8E8")
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.geometry(f"+{self.root.winfo_rootx()+150}+{self.root.winfo_rooty()+140}")

        tk.Label(top, text="Type your favourite folder for saving/opening,\n"
                           "or click Browse. Leave empty to use the last-used folder.",
                 bg="#E8E8E8", justify="left", font=("Arial", 9)).pack(
                     padx=14, pady=(12, 6), anchor="w")

        row = tk.Frame(top, bg="#E8E8E8")
        row.pack(fill="x", padx=14)
        path_var = tk.StringVar(value=self.cfg["fav_dir"])
        ent = tk.Entry(row, textvariable=path_var, width=46,
                       insertofftime=0, insertontime=9999999)
        no_blink(ent)
        ent.pack(side=tk.LEFT, padx=(0, 6))

        def _browse():
            d = filedialog.askdirectory(
                title="Choose default save folder",
                initialdir=(path_var.get() or self._initial_dir()),
                parent=top)
            if d:
                path_var.set(d)
            ent.focus_set()

        # Button colours are spelled out so they are easy to recolour later.
        tk.Button(row, text="Browse…", width=9, bg="white",
                  command=_browse).pack(side=tk.LEFT)

        def _apply(ev=None):
            p = path_var.get().strip()
            if p and not os.path.isdir(p):
                if messagebox.askyesno("Create folder?",
                                       f"The folder does not exist:\n{p}\n\nCreate it now?",
                                       parent=top):
                    try:
                        os.makedirs(p, exist_ok=True)
                    except Exception as ex:
                        messagebox.showerror("Error", str(ex), parent=top)
                        return
                else:
                    return
            self.cfg["fav_dir"] = p
            self.cfg.save()
            top.destroy()
            auto_popup(self.root, "Saved",
                       "Default folder set." if p else "Default folder cleared.")

        bf = tk.Frame(top, bg="#E8E8E8")
        bf.pack(pady=12)
        tk.Button(bf, text="OK",     width=9, bg="white",
                  command=_apply).pack(side=tk.LEFT, padx=5)
        tk.Button(bf, text="Cancel", width=9, bg="white",
                  command=top.destroy).pack(side=tk.LEFT, padx=5)

        ent.bind("<Return>",   _apply)
        ent.bind("<KP_Enter>", _apply)
        ent.focus_set()

    @needs_text_ok("open another image")
    def _open(self):
        if self.modified:
            r = messagebox.askyesnocancel("Open", "Save current image first?")
            if r is None: return
            if r: self._save()
        ld   = self._initial_dir()
        path = filedialog.askopenfilename(
            title="Open Image",
            initialdir=ld,
            filetypes=[
                ("Image files", "*.bmp *.png *.jpg *.jpeg *.gif *.tiff *.tif"),
                ("BMP",  "*.bmp"), ("PNG", "*.png"),
                ("JPEG", "*.jpg *.jpeg"),
                ("GIF",  "*.gif"), ("All", "*.*"),
            ]
        )
        if not path:
            return
        try:
            img = Image.open(path).convert("RGB")
            self.image = img
            self.draw  = ImageDraw.Draw(self.image)
            self.objects    = []; self.active_obj = None
            self.cfg["canvas_w"] = img.width
            self.cfg["canvas_h"] = img.height
            self.current_file = path
            self.cfg["last_dir"]  = os.path.dirname(path)
            self.cfg["last_file"] = path
            self.modified = False
            self.undo_stack.clear(); self.redo_stack.clear()
            self._commit_selection()
            self._refresh()
            self._update_title()
            self._s_size.config(text=f"{img.width} × {img.height}")
            auto_popup(self.root, "Opened", f"Opened: {os.path.basename(path)}")
        except Exception as ex:
            messagebox.showerror("Open Error", str(ex))

    @needs_text_ok("save")
    def _save(self):
        if self.current_file:
            self._do_save(self.current_file)
        else:
            self._save_as()

    @needs_text_ok("save")
    def _save_as(self):
        ld   = self._initial_dir()
        # Pre-fill the name with a .jpg extension so JPEG is the obvious default
        # and we never start sitting on a same-named .bmp/.png that already
        # exists in the folder (which is what triggered the "overwrite the BMP?"
        # prompt when the user actually wanted a PNG/JPG).
        base = self._suggest_basename()
        path = filedialog.asksaveasfilename(
            title="Save As",
            initialdir=ld,
            initialfile=base + ".jpg",
            defaultextension=".jpg",
            filetypes=[
                ("JPEG", "*.jpg *.jpeg"),
                ("PNG",  "*.png"), ("BMP",  "*.bmp"),
                ("GIF",  "*.gif"),
                ("TIFF", "*.tiff"), ("All", "*.*"),
            ]
        )
        if not path:
            return
        # Safety net: if the user typed a name with no extension, make it .jpg.
        if not os.path.splitext(path)[1]:
            path += ".jpg"
        self._do_save(path)

    def _do_save(self, path):
        try:
            # Flatten objects into the saved file (non-destructively — they
            # stay movable in the editor).
            img = self._compose_objects(self.image) if self.objects else self.image
            ext = os.path.splitext(path)[1].lower()
            if ext in (".jpg", ".jpeg"):
                img = img.convert("RGB")
                img.save(path, dpi=(96, 96))
            else:
                img.save(path)
            self.current_file = path
            self.cfg["last_dir"]  = os.path.dirname(path)
            self.cfg["last_file"] = path
            self.modified = False
            self._update_title()
            auto_popup(self.root, "Saved", f"Saved: {os.path.basename(path)}")
        except Exception as ex:
            messagebox.showerror("Save Error", str(ex))

    def _get_trimmed_image(self):
        """Return a crop of the image containing only the non-background area.
        Background colour is taken from self.bg (top-left pixel as fallback)."""
        img  = self._compose_objects(self.image).convert("RGB")
        w, h = img.size
        bg   = hex_to_rgb(self.bg)

        # Scan rows/cols for any pixel that differs from background
        min_x, min_y = w, h
        max_x, max_y = 0, 0
        pix = img.load()
        for y in range(h):
            for x in range(w):
                r, g, b = pix[x, y]
                if abs(r - bg[0]) + abs(g - bg[1]) + abs(b - bg[2]) > 15:
                    if x < min_x: min_x = x
                    if y < min_y: min_y = y
                    if x > max_x: max_x = x
                    if y > max_y: max_y = y

        if max_x < min_x or max_y < min_y:
            return img   # nothing found – return full image
        return img.crop((min_x, min_y, max_x + 1, max_y + 1))

    @needs_text_ok("trim and save")
    def _trim_save_as(self):
        """Trim to content bounding box and save to a new file."""
        trimmed = self._get_trimmed_image()
        ld   = self._initial_dir()
        path = filedialog.asksaveasfilename(
            title="Trim & Save As",
            initialdir=ld,
            initialfile=self._suggest_basename() + ".jpg",
            defaultextension=".jpg",
            filetypes=[
                ("JPEG", "*.jpg *.jpeg"),
                ("PNG",  "*.png"), ("BMP", "*.bmp"),
                ("All",  "*.*"),
            ]
        )
        if not path:
            return
        try:
            ext = os.path.splitext(path)[1].lower()
            if ext in (".jpg", ".jpeg"):
                trimmed = trimmed.convert("RGB")
            trimmed.save(path)
            self.cfg["last_dir"] = os.path.dirname(path)
            auto_popup(self.root, "Trim saved",
                       f"Trimmed {trimmed.width}×{trimmed.height}  →  {os.path.basename(path)}")
        except Exception as ex:
            messagebox.showerror("Trim Save Error", str(ex))
    @needs_text_ok("save the selection")
    def _save_selection_as(self):
        """Save the content inside the current selection to a new file."""
        crop = self._get_sel_crop()
        if crop is None:
            messagebox.showinfo("Save Selected", "No active selection.\nUse Select or Lasso to mark an area first.")
            return
        ld   = self._initial_dir()
        path = filedialog.asksaveasfilename(
            title="Save Selected As",
            initialdir=ld,
            initialfile=self._suggest_basename() + ".jpg",
            defaultextension=".jpg",
            filetypes=[
                ("JPEG", "*.jpg *.jpeg"),
                ("PNG",  "*.png"),
                ("BMP",  "*.bmp"),
                ("All",  "*.*"),
            ]
        )
        if not path:
            return
        try:
            ext = os.path.splitext(path)[1].lower()
            if ext in (".jpg", ".jpeg"):
                crop = crop.convert("RGB")
            crop.save(path)
            self.cfg["last_dir"] = os.path.dirname(path)
            auto_popup(self.root, "Saved Selection",
                       f"Selection {crop.width}×{crop.height}  →  {os.path.basename(path)}")
        except Exception as ex:
            messagebox.showerror("Save Selected Error", str(ex))


# *************** DEL 35 – UNDO / REDO + CLIPBOARD *************************

    @needs_text_ok("undo")
    def _undo(self):
        if not self.undo_stack:
            return
        self.redo_stack.append(self._snapshot())
        self._restore(self.undo_stack.pop())
        self._commit_selection()
        self._refresh()
        self.modified = True
        self._update_title()

    @needs_text_ok("redo")
    def _redo(self):
        if not self.redo_stack:
            return
        self.undo_stack.append(self._snapshot())
        self._restore(self.redo_stack.pop())
        self._refresh()
        self.modified = True
        self._update_title()

    @needs_text_ok("cut")
    def _cut(self):
        crop = self._get_sel_crop()
        if not crop:
            return
        self.clipboard_image = crop.copy()
        self._delete_selection()

    @needs_text_ok("copy")
    def _copy(self):
        crop = self._get_sel_crop()
        if crop:
            self.clipboard_image = crop.copy()

    @needs_text_ok("paste")
    def _paste(self):
        """Ctrl+V: internal clipboard pastes directly; system clipboard (Print Screen etc) shows crop dialog."""
        # ── Internal clipboard always pastes directly (no dialog) ─────────
        if self.clipboard_image:
            self._do_paste(self.clipboard_image)
            return

        # ── System clipboard (e.g. Print Screen) → crop-preview dialog ────
        sys_img = None
        try:
            from PIL import ImageGrab
            sys_img = ImageGrab.grabclipboard()
        except Exception:
            pass

        if sys_img and hasattr(sys_img, "size"):
            if sys_img.mode != "RGB":
                sys_img = sys_img.convert("RGB")
            self._paste_preview_dialog(sys_img)


    @needs_text_ok("paste a screenshot")
    def _paste_from_screen(self):
        """Dedicated Print Screen paste — always reads system clipboard, ignores internal clipboard."""
        sys_img = None
        try:
            from PIL import ImageGrab
            sys_img = ImageGrab.grabclipboard()
        except Exception:
            pass
        if sys_img and hasattr(sys_img, "size"):
            if sys_img.mode != "RGB":
                sys_img = sys_img.convert("RGB")
            self._paste_preview_dialog(sys_img)
        else:
            messagebox.showinfo("Print Screen Paste",
                                "No image was found on the system clipboard.\n"
                                "Press PrintScreen (or Alt+PrintScreen) first.")

    def _paste_preview_dialog(self, src_img):
        """Show a thumbnail of src_img; user drags a selection rectangle, then pastes that region."""
        top = tk.Toplevel(self.root)
        top.title("Paste from clipboard – select region")
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(True, True)

        MAX_W, MAX_H = 780, 520
        iw, ih = src_img.size
        scale = min(MAX_W / iw, MAX_H / ih, 1.0)
        tw = int(iw * scale); th = int(ih * scale)

        tk.Label(top, text="Drag to select region to paste  (Enter = paste whole image)",
                 font=("Arial", 8), fg="#555555").pack(pady=(6, 2))

        cnv = tk.Canvas(top, width=tw, height=th, cursor="crosshair",
                        highlightthickness=1, highlightbackground="#888888")
        cnv.pack(padx=8, pady=4)

        thumb = src_img.resize((tw, th), Image.LANCZOS)
        _photo = ImageTk.PhotoImage(thumb)
        cnv.create_image(0, 0, anchor=tk.NW, image=_photo)
        cnv._photo_ref = _photo   # keep reference

        sel = {"x0": 0, "y0": 0, "x1": tw, "y1": th, "rect": None, "dragging": False}

        def _draw_sel():
            if sel["rect"]:
                cnv.delete(sel["rect"])
            sel["rect"] = cnv.create_rectangle(
                sel["x0"], sel["y0"], sel["x1"], sel["y1"],
                outline="white", dash=(4, 4), width=1
            )
            cnv.create_rectangle(
                sel["x0"], sel["y0"], sel["x1"], sel["y1"],
                outline="black", dash=(4, 4), width=1
            )

        def _press(e):
            sel["x0"] = e.x; sel["y0"] = e.y
            sel["x1"] = e.x; sel["y1"] = e.y
            sel["dragging"] = True

        def _drag(e):
            sel["x1"] = max(0, min(e.x, tw))
            sel["y1"] = max(0, min(e.y, th))
            _draw_sel()

        def _release(e):
            sel["dragging"] = False
            # Normalize
            x0 = min(sel["x0"], sel["x1"]); x1 = max(sel["x0"], sel["x1"])
            y0 = min(sel["y0"], sel["y1"]); y1 = max(sel["y0"], sel["y1"])
            sel["x0"] = x0; sel["y0"] = y0; sel["x1"] = x1; sel["y1"] = y1

        def _confirm(ev=None):
            x0, y0, x1, y1 = sel["x0"], sel["y0"], sel["x1"], sel["y1"]
            if abs(x1-x0) < 4 or abs(y1-y0) < 4:
                # Too small → use whole image
                crop = src_img
            else:
                # Scale back to original coords
                rx0 = int(x0 / scale); ry0 = int(y0 / scale)
                rx1 = int(x1 / scale); ry1 = int(y1 / scale)
                crop = src_img.crop((rx0, ry0, rx1, ry1))
            top.destroy()
            # Print Screen / clipboard paste: size the canvas to the pasted
            # image so there is no big white margin, and reset zoom to 1×.
            self._do_paste(crop, fit_canvas=True)

        cnv.bind("<ButtonPress-1>",   _press)
        cnv.bind("<B1-Motion>",       _drag)
        cnv.bind("<ButtonRelease-1>", _release)
        top.bind("<Return>",          _confirm)
        top.bind("<KP_Enter>",        _confirm)

        btn_fr = tk.Frame(top); btn_fr.pack(pady=6)
        tk.Button(btn_fr, text="Paste selected (Enter)", width=22, bg="white",
                  command=_confirm).pack(side=tk.LEFT, padx=6)
        tk.Button(btn_fr, text="Cancel", width=10, bg="white",
                  command=top.destroy).pack(side=tk.LEFT, padx=6)

        top.after(50, lambda: top.lift())

    def _do_paste(self, ci, fit_canvas=False):
        """Start a floating paste that can be dragged before committing.

        fit_canvas=False (internal Copy/Paste): the canvas only *expands* if the
        pasted image is larger, so an existing drawing is preserved.

        fit_canvas=True (Print Screen / system-clipboard paste): the canvas is
        resized to EXACTLY the pasted image, so there is never a big white
        margin to the right and below, and zoom drops back to 1× so the result
        is shown at real size instead of the last (possibly 8×) zoom."""
        if ci.mode != "RGB":
            ci = ci.convert("RGB")
        self._save_undo()

        # Commit any existing selection first
        self._commit_selection()

        pw, ph = ci.size

        if fit_canvas:
            # Canvas becomes the pasted image size — no leftover white area.
            self.image = Image.new("RGB", (pw, ph), self.bg)
            self.draw  = ImageDraw.Draw(self.image)
            self.cfg["canvas_w"] = pw
            self.cfg["canvas_h"] = ph
            self._s_size.config(text=f"{pw} × {ph}")
            # Show it at real size, not the previous zoom (e.g. 8×).
            if self.zoom != 1:
                self.zoom = 1
                self.cfg["zoom"] = 1
                self._s_zoom.config(text="Zoom: 1×")
                self._build_tool_options()
        else:
            cw, ch = self.image.size
            # Expand canvas if needed
            if pw > cw or ph > ch:
                new_w = max(pw, cw)
                new_h = max(ph, ch)
                new_img = Image.new("RGB", (new_w, new_h), self.bg)
                new_img.paste(self.image, (0, 0))
                self.image = new_img
                self.draw  = ImageDraw.Draw(self.image)
                self.cfg["canvas_w"] = new_w
                self.cfg["canvas_h"] = new_h
                self._s_size.config(text=f"{new_w} × {new_h}")

        # The pasted picture becomes a MOVABLE object (not baked in), so it can
        # be repositioned on its own with the Move tool. Honour transparent
        # paste mode by knocking out background-coloured pixels.
        obj_img = (self._apply_paste_transparency(ci)
                   if self.transparent_paste else ci)
        self._add_object(obj_img, 0, 0, "paste")

        # Switch to the Move tool so the user can immediately drag it.
        self._select_tool("move_obj")
        self._refresh()



# *************** DEL 36 – IMAGE OPERATIONS ********************************

    # ---- Image menu: marked area if there is one, else the whole picture ----
    def _marked_box(self):
        """Box (x1, y1, x2, y2) of the marked area, clipped to the canvas, or
        None when nothing is marked (= the Image menu works on everything).
        Marking = the dashed rectangle of Select / Lasso / Select All.
        A selection that was lifted and dragged is put down first."""
        if not self.sel_rect:
            return None
        if self.sel_floating and self.sel_image:
            rect = self.sel_rect
            self._commit_selection()          # bakes it at its new place...
            self.sel_rect = rect              # ...and keeps it marked
        x1, y1, x2, y2 = self.sel_rect
        w, h = self.image.size
        x1 = max(0, x1); y1 = max(0, y1)
        x2 = min(w, x2); y2 = min(h, y2)
        if x2 - x1 < 1 or y2 - y1 < 1:
            return None
        return (x1, y1, x2, y2)

    def _region_op(self, box, fn):
        """Run fn(picture) -> picture on the marked box only.

        The box is read WITH the movable objects (text, pasted pictures) on
        top, so what you see is what is turned. Objects inside the area are
        taken out of the object list and end up in the new pixels. If the
        result has another size (90/270° of a non-square area) it keeps the
        old centre, moved back inside the canvas if needed, and the area it
        needs is baked from the objects first so nothing floats on top of it."""
        x1, y1, x2, y2 = box
        w, h = self.image.size
        self._save_undo()
        comp = self._compose_objects(self.image)
        new  = fn(comp.crop(box)).convert("RGB")
        nw, nh = new.size
        nx1 = int(round((x1 + x2) / 2 - nw / 2))
        ny1 = int(round((y1 + y2) / 2 - nh / 2))
        nx1 = max(0, min(nx1, w - nw)) if nw <= w else 0
        ny1 = max(0, min(ny1, h - nh)) if nh <= h else 0
        nx2 = min(w, nx1 + nw); ny2 = min(h, ny1 + nh)
        # Everything the old and the new area touch becomes plain pixels.
        ux1 = min(x1, nx1); uy1 = min(y1, ny1)
        ux2 = max(x2, nx2); uy2 = max(y2, ny2)
        under = comp.crop((ux1, uy1, ux2, uy2))
        self._clear_region_from_objects(ux1, uy1, ux2, uy2)
        self.image.paste(under, (ux1, uy1))
        self.draw = ImageDraw.Draw(self.image)
        self.draw.rectangle([x1, y1, x2 - 1, y2 - 1], fill=self.bg)
        self.image.paste(new, (nx1, ny1))
        self.sel_rect = (nx1, ny1, nx2, ny2)   # the result stays marked
        self.modified = True
        self._update_title()
        self._refresh()

    @needs_text_ok("flip the image")
    def _flip(self, direction):
        op = Image.FLIP_LEFT_RIGHT if direction == "h" else Image.FLIP_TOP_BOTTOM
        box = self._marked_box()
        if box:
            self._region_op(box, lambda im: im.transpose(op))
            return
        self._save_undo()
        self._flatten_objects()
        self.image = self.image.transpose(op)
        self.draw  = ImageDraw.Draw(self.image)
        self._refresh()

    @needs_text_ok("rotate the image")
    def _rotate(self, deg):
        box = self._marked_box()
        if box:
            self._region_op(box, lambda im: im.rotate(-deg, expand=True))
            return
        self._save_undo()
        self._flatten_objects()
        self.image = self.image.rotate(-deg, expand=True)
        self.draw  = ImageDraw.Draw(self.image)
        self.cfg["canvas_w"] = self.image.width
        self.cfg["canvas_h"] = self.image.height
        self._refresh()
        self._s_size.config(text=f"{self.image.width} × {self.image.height}")

    @needs_text_ok("invert the colours")
    def _invert(self):
        box = self._marked_box()
        if box:
            self._region_op(box, lambda im: ImageOps.invert(im.convert("RGB")))
            return
        self._save_undo()
        self._flatten_objects()
        self.image = ImageOps.invert(self.image)
        self.draw  = ImageDraw.Draw(self.image)
        self._refresh()

    @needs_text_ok("clear the canvas")
    def _clear_image(self):
        box = self._marked_box()
        if box:
            if not messagebox.askyesno("Clear Image", "Erase the marked area?"):
                return
            self._region_op(box, lambda im: Image.new("RGB", im.size, self.bg))
            return
        if not messagebox.askyesno("Clear Image", "Erase entire canvas?"):
            return
        self._save_undo()
        self.objects    = []          # drop all placed objects too
        self.active_obj = None
        self.draw.rectangle(
            [0, 0, self.image.width, self.image.height], fill=self.bg
        )
        self._refresh()

    @needs_text_ok("change the canvas size")
    def _attributes_dialog(self):
        top = tk.Toplevel(self.root)
        top.title("Image Attributes")
        top.resizable(False, False)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.geometry(f"+{self.root.winfo_rootx()+180}+{self.root.winfo_rooty()+160}")

        frm = tk.Frame(top); frm.pack(padx=14, pady=10)
        tk.Label(frm, text="Width (px):").grid(row=0, column=0, sticky="e", pady=4)
        w_var = tk.IntVar(value=self.image.width)
        we = tk.Entry(frm, textvariable=w_var, width=8,
                      insertofftime=0, insertontime=9999999)
        no_blink(we); we.grid(row=0, column=1, padx=8)

        tk.Label(frm, text="Height (px):").grid(row=1, column=0, sticky="e", pady=4)
        h_var = tk.IntVar(value=self.image.height)
        he = tk.Entry(frm, textvariable=h_var, width=8,
                      insertofftime=0, insertontime=9999999)
        no_blink(he); he.grid(row=1, column=1, padx=8)

        def _apply(ev=None):
            try:
                nw = max(1, int(w_var.get()))
                nh = max(1, int(h_var.get()))
                self._save_undo()
                self._flatten_objects()
                new_img = Image.new("RGB", (nw, nh), self.bg)
                new_img.paste(self.image, (0, 0))
                self.image = new_img
                self.draw  = ImageDraw.Draw(self.image)
                self.cfg["canvas_w"] = nw; self.cfg["canvas_h"] = nh
                self._refresh()
                self._s_size.config(text=f"{nw} × {nh}")
                top.destroy()
                auto_popup(self.root, "Resized", f"Canvas resized to {nw} × {nh}")
            except Exception as ex:
                messagebox.showerror("Error", str(ex))

        bf = tk.Frame(top); bf.pack(pady=8)
        tk.Button(bf, text="OK",     width=9, bg="white",
                  command=_apply).pack(side=tk.LEFT, padx=5)
        tk.Button(bf, text="Cancel", width=9, bg="white",
                  command=top.destroy).pack(side=tk.LEFT, padx=5)

        we.bind("<Return>", _apply)
        he.bind("<Return>", _apply)
        we.focus_set()


# *************** DEL 37 – VIEW OPERATIONS *********************************

    def _toggle_toolbar(self):
        v = self._v_toolbar.get()
        if v:
            self.toolbar_frame.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2,
                                    before=self.canvas_frame)
        else:
            self.toolbar_frame.pack_forget()
        self.cfg["show_toolbar"] = v

    def _toggle_colorbox(self):
        v = self._v_colorbox.get()
        if v:
            self.color_bar.pack(side=tk.BOTTOM, fill=tk.X,
                                before=self.main_frame)
        else:
            self.color_bar.pack_forget()
        self.cfg["show_colorbox"] = v

    def _toggle_statusbar(self):
        v = self._v_statusbar.get()
        if v:
            self.status_bar.pack(side=tk.BOTTOM, fill=tk.X,
                                 before=self.color_bar)
        else:
            self.status_bar.pack_forget()
        self.cfg["show_statusbar"] = v


# *************** DEL 38 – COLORS MENU ************************************

    @needs_text_ok("edit the colours")
    def _edit_colors(self):
        c = colorchooser.askcolor(color=self.fg, title="Edit Foreground Color")[1]
        if c:
            self._set_fg(c)


# *************** DEL 39 – HELP / ABOUT ************************************

    def _help_contents(self):
        """Scrollable Help window covering all tools and features."""
        BG     = "#1E1E2E"
        BG_TXT = "#12121F"
        ACCENT = "#7EB8F7"
        FG     = "#E0E0F0"
        FG_DIM = "#8888AA"
        SEP    = "#3A3A5A"

        top = tk.Toplevel(self.root)
        top.title("Point & Paint – Help")
        top.configure(bg=BG)
        top.transient(self.root)
        top.geometry(
            f"640x560+{self.root.winfo_rootx()+80}+{self.root.winfo_rooty()+60}"
        )
        top.minsize(480, 400)

        # ── Title bar ─────────────────────────────────────────────────────
        hdr = tk.Frame(top, bg=BG)
        hdr.pack(fill="x", padx=0, pady=0)
        tk.Label(hdr, text="📖  Point & Paint – Help & Reference",
                 bg=BG, fg=ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=16, pady=(14, 2))
        tk.Label(hdr, text=f"Version {APP_VER}",
                 bg=BG, fg=FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(anchor="w", padx=18, pady=(0, 8))
        tk.Frame(top, bg=SEP, height=1).pack(fill="x")

        # ── Scrollable text area ───────────────────────────────────────────
        frame = tk.Frame(top, bg=BG_TXT)
        frame.pack(fill="both", expand=True)

        sb = tk.Scrollbar(frame, bg=BG, troughcolor=BG)
        sb.pack(side=tk.RIGHT, fill=tk.Y)

        txt = tk.Text(
            frame,
            wrap="word",
            bg=BG_TXT, fg=FG,
            font=("Segoe UI", 9),
            relief=tk.FLAT,
            padx=20, pady=14,
            spacing1=2, spacing3=4,
            yscrollcommand=sb.set,
            state="normal",
            cursor="arrow",
            insertofftime=0, insertontime=0,
            selectbackground="#2E4A70",
        )
        txt.pack(side=tk.LEFT, fill="both", expand=True)
        sb.config(command=txt.yview)

        # ── Tag styles ────────────────────────────────────────────────────
        txt.tag_config("h1",  foreground=ACCENT,  font=("Segoe UI", 12, "bold"),
                        spacing1=10, spacing3=4)
        txt.tag_config("h2",  foreground="#A8D4FF", font=("Segoe UI", 10, "bold"),
                        spacing1=8, spacing3=2)
        txt.tag_config("key", foreground="#FFD080", font=("Segoe UI", 9, "bold"))
        txt.tag_config("dim", foreground=FG_DIM,   font=("Segoe UI", 9, "italic"))
        txt.tag_config("sep", foreground=SEP)
        txt.tag_config("tip", foreground="#90E8A0", font=("Segoe UI", 9, "italic"))

        def h1(t):  txt.insert("end", f"\n{t}\n", "h1")
        def h2(t):  txt.insert("end", f"  {t}\n", "h2")
        def p(t):   txt.insert("end", f"    {t}\n")
        def kv(k,v):
            txt.insert("end", f"    {k:<22}", "key")
            txt.insert("end", f"{v}\n")
        def tip(t): txt.insert("end", f"    💡 {t}\n", "tip")
        def sep():  txt.insert("end", "    " + "─"*68 + "\n", "sep")

        # ══════════════════════════════════════════════════════════════════
        # CONTENT
        # ══════════════════════════════════════════════════════════════════

        h1("OVERVIEW")
        p("built with Python 3, Tkinter and Pillow. It supports opening and saving")
        p("common image formats (PNG, JPG, BMP, GIF, TIFF) and provides all the")
        p("classic drawing tools you remember from the original.")

        h1("FILE MENU")
        sep()
        kv("New  (Ctrl+N)",        "Create a blank canvas. Prompts to save if unsaved changes exist.")
        kv("Open…  (Ctrl+O)",      "Open an image file from disk. Supported: PNG, JPG, BMP, GIF, TIFF.")
        kv("Save  (Ctrl+S)",       "Save the current image to its existing file, or prompt Save As.")
        kv("Save As…",             "Choose a new file name and format before saving.")
        kv("Trim & Save As…",      "Automatically crop away white/background borders, then save.")
        kv("Save Selected…",       "Save only the current selection rectangle as a separate file.")
        kv("Paste Print Screen…",  "Grab whatever is on the clipboard (e.g. a screenshot) and paste it.")
        kv("Exit",                 "Close the application. Prompts to save if there are unsaved changes.")

        h1("EDIT MENU")
        sep()
        kv("Undo  (Ctrl+Z)",       f"Step back through the last {UNDO_LEVELS} changes.")
        kv("Redo  (Ctrl+Y)",       "Re-apply an undone change.")
        kv("Cut  (Ctrl+X)",        "Copy the selection to the clipboard and erase it from the canvas.")
        kv("Copy  (Ctrl+C)",       "Copy the selection to the clipboard without erasing it.")
        kv("Paste  (Ctrl+V)",      "Paste the clipboard image as a floating layer you can drag.")
        kv("Select All  (Ctrl+A)", "Select the entire canvas.")
        kv("Clear Selection",      "Deselect without deleting anything.")
        kv("Delete  (Del)",        "Fill the selected area with the background colour.")

        h1("IMAGE MENU")
        sep()
        p("Flip, Rotate, Invert and Clear work on the MARKED area (the dashed")
        p("rectangle of Select / Lasso / Select All). With nothing marked they")
        p("work on the whole picture.")
        kv("Flip Horizontal",      "Mirror left-to-right.")
        kv("Flip Vertical",        "Mirror top-to-bottom.")
        kv("Rotate 90 / 180 / 270°", "Rotate by the chosen angle.")
        kv("Invert Colors",        "Invert every pixel (creates a negative image).")
        kv("Attributes…",         "Change the canvas width and height in pixels.")
        kv("Clear Image",          "Fill the marked area (or the whole canvas) with the background colour.")

        h1("VIEW MENU")
        sep()
        kv("Zoom  1× – 8×",       "Scale the canvas view without changing the actual image.")
        kv("Tool Box",             "Show or hide the left-side toolbar.")
        kv("Color Box",            "Show or hide the colour palette at the bottom.")
        kv("Status Bar",           "Show or hide the status bar at the very bottom.")

        h1("COLORS MENU")
        sep()
        kv("Edit Colors…",         "Open a colour picker to set the foreground (drawing) colour.")
        p("Left-click a palette swatch  →  set foreground colour.")
        p("Right-click a palette swatch →  set background colour.")

        h1("TOOLS")
        sep()

        h2("✏  Pencil")
        p("Draws a free-hand line one pixel wide using the foreground colour.")
        p("Hold Shift to constrain drawing to horizontal or vertical lines.")

        h2("🖌  Brush")
        p("Paints with a soft round brush. Adjust the brush size in the")
        p("Options section below the toolbar.")
        tip("Right-click and drag to paint with the background colour.")

        h2("💨  Airbrush / Spray")
        p("Sprays random dots in a circular area around the cursor,")
        p("simulating a spray can. Move slowly for dense coverage.")

        h2("⬜  Eraser")
        p("Erases pixels by painting them with the background colour.")
        p("Brush-size option controls the eraser diameter.")
        tip("Right-click to erase to the foreground colour instead.")

        h2("🪣  Fill")
        p("Flood-fills a contiguous area of the same colour with the")
        p("foreground colour (left-click) or background colour (right-click).")

        h2("💉  Color Picker / Eyedropper")
        p("Click any pixel on the canvas to pick up its colour as the")
        p("foreground colour. Right-click to pick it as the background colour.")

        h2("🔍  Magnifier / Zoom")
        p("Left-click to zoom in one step; right-click to zoom out one step.")
        p("Zoom levels: 1×, 2×, 4×, 6×, 8×.")

        h2("A  Text")
        p("Click on the canvas to place a text cursor. A small editor appears in")
        p("the Options strip where you can choose font, size and bold, and the")
        p("text is previewed live on the canvas as you type.")
        p("The ▾ button next to the Font field lists the fonts that are actually")
        p("installed — pick one instead of guessing the exact spelling.")
        kv("OK  /  Ctrl+Enter",    "Place the text on the canvas.")
        kv("Cancel  /  Escape",    "Throw the text away (you are asked first).")
        p("Placed text stays a separate MOVABLE object: pick the Move tool (✋)")
        p("and drag it anywhere, or press Delete to remove it again.")
        kv("Double-click a text",  "Re-open it for editing — the text, font, size, bold")
        p("                       and colour all come back. Fix a typo instead of")
        p("                       deleting and retyping the whole caption.")
        tip("Your text is never lost by accident. If you click another tool, a "
            "menu item, the zoom, or press Escape while text is still unplaced, "
            "a dialog asks whether to PLACE it, DISCARD it, or KEEP TYPING.")
        tip("While the text editor has focus, Delete and Ctrl+A act on your "
            "text — not on the canvas selection.")

        h2("╱  Line")
        p("Click and drag to draw a straight line between two points.")
        p("Hold Shift while dragging to snap to 0°, 45° or 90° angles.")

        h2("∿  Curve")
        p("Three-click tool: (1) drag to set the line endpoints, then")
        p("(2) click to pull the midpoint into a curve, and (3) click again")
        p("to finish (or right-click to skip the second control point).")

        h2("□  Rectangle")
        p("Drag to draw a rectangle. Hold Shift to draw a perfect square.")
        p("Fill style (bottom of toolbar): outline only, filled, or both.")

        h2("▢  Rounded Rectangle")
        p("Same as Rectangle but with rounded corners.")

        h2("○  Ellipse")
        p("Drag to draw an ellipse. Hold Shift to draw a perfect circle.")

        h2("⬠  Polygon")
        p("Click to add each vertex. Double-click (or press Enter) to close")
        p("and fill the polygon. Press Escape to cancel.")

        h1("SELECTION TOOLS")
        sep()

        h2("▭  Rectangle Select")
        p("Drag to define a rectangular selection. Once selected you can:")
        p("  • Drag inside the selection to move it.")
        p("  • Cut, Copy, Delete, or Save Selected from the menus.")
        p("  • Paste replaces the selection with clipboard content.")
        tip("Enable 'Transparent Paste' (right-click canvas) to make white pixels")
        tip("in a pasted image transparent when moving.")

        h2("⊘  Lasso (Free Select)")
        p("Draw a freehand outline around any area. Release the mouse to")
        p("close the selection automatically. Works the same as Rect Select")
        p("once the area is defined.")

        h2("✋  Move (object tool)")
        p("Text you type, shapes you draw (line, curve, rectangle, rounded")
        p("rectangle, ellipse, polygon) and images you paste are remembered as")
        p("separate objects that float above the picture. With the Move tool:")
        p("  • Click an object to select it (a red dashed box appears).")
        p("  • Drag it to reposition ONLY that object — nothing else moves.")
        p("  • Click empty space to deselect; press Delete to remove it.")
        p("Objects stay independently movable until you Save (they are then")
        p("flattened into the file) or run Flip / Rotate / Invert / Resize.")
        tip("This is the way to move a single label or a pasted QR code without")
        tip("dragging the pixels around it.")

        h1("KEYBOARD SHORTCUTS")
        sep()
        kv("Ctrl+N",   "New canvas")
        kv("Ctrl+O",   "Open file")
        kv("Ctrl+S",   "Save")
        kv("Ctrl+Z",   "Undo")
        kv("Ctrl+Y",   "Redo")
        kv("Ctrl+X",   "Cut selection")
        kv("Ctrl+C",   "Copy selection")
        kv("Ctrl+V",   "Paste")
        kv("Ctrl+A",   "Select all")
        kv("Delete",   "Delete / clear selection")
        kv("Escape",   "Cancel polygon / deselect / abort text")
        kv("Enter",    "Commit polygon or text")
        kv("Shift",    "Hold while drawing to constrain angle or force square/circle")

        h1("TIPS & TRICKS")
        sep()
        tip("The canvas can be resized by dragging the small handle squares that")
        p("  appear at the right and bottom edges when you hover near them.")
        tip("Paste Print Screen (File menu) lets you grab and annotate screenshots.")
        tip("Use 'Trim & Save As' to automatically remove white borders when")
        p("  saving icons or logos drawn on a white canvas.")
        tip(f"Undo history is kept for the last {UNDO_LEVELS} operations. Saving does")
        p("  NOT clear it — you can still undo after a save.")
        tip("Double-click any placed text (Move or Text tool) to edit it again.")
        tip("Select/Lasso now takes text and pasted pictures WITH it: dragging a")
        p("  selection moves them instead of leaving a copy behind. Select only")
        p("  half of a text and the other half stays where it was.")
        tip("Typed but unplaced text is protected: nothing in the program can")
        p("  throw it away without asking you first — you always get the choice")
        p("  between Place the text, Discard the text, and Keep typing.")

        txt.insert("end", "\n")
        txt.config(state="disabled")

        # ── Close button ──────────────────────────────────────────────────
        tk.Frame(top, bg=SEP, height=1).pack(fill="x")
        bf = tk.Frame(top, bg=BG)
        bf.pack(fill="x")
        tk.Button(bf, text="Close", width=12,
                  bg="#2E2E4E", fg=FG, activebackground="#3A3A6A",
                  activeforeground=FG, relief=tk.FLAT, cursor="hand2",
                  font=("Segoe UI", 9),
                  command=top.destroy).pack(pady=10)

    def _about(self):
        import webbrowser

        # ── Colour palette for the dialog ──────────────────────────────────
        BG      = "#1E1E2E"   # dark background
        BG2     = "#252535"   # slightly lighter (donation box)
        ACCENT  = "#7EB8F7"   # blue accent
        FG      = "#E0E0F0"   # main text
        FG_DIM  = "#8888AA"   # dimmed text
        SEP     = "#3A3A5A"   # separator line

        top = tk.Toplevel(self.root)
        top.title("About Point & Paint")
        top.configure(bg=BG)
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.geometry(
            f"+{self.root.winfo_rootx()+220}+{self.root.winfo_rooty()+130}"
        )

        # ── Header ────────────────────────────────────────────────────────
        hdr = tk.Frame(top, bg=BG)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🎨", bg=BG, fg=ACCENT,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="Point & Paint",
                 bg=BG, fg=ACCENT,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text=f"Version {APP_VER}",
                 bg=BG, fg=FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
        tk.Frame(top, bg=SEP, height=1).pack(fill="x", padx=20)

        # ── Author ────────────────────────────────────────────────────────
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=BG, fg=FG,
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

        # ── Documentation link ────────────────────────────────────────────
        DOC_URL = (
            "https://docs.google.com/document/d/"
            "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
        doc_lbl = tk.Label(top, text="📄  View documentation",
                           bg=BG, fg=ACCENT,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
        doc_lbl.pack(pady=(6, 2))
        doc_lbl.bind("<Button-1>", lambda e: open_url(DOC_URL))
        doc_lbl.bind("<Enter>",    lambda e: doc_lbl.configure(fg="#b4d4ff"))
        doc_lbl.bind("<Leave>",    lambda e: doc_lbl.configure(fg=ACCENT))

        tk.Frame(top, bg=SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))

        # ── Donation section ──────────────────────────────────────────────
        tk.Label(top, text="☕  If you enjoy Point & Paint, a small gift is always welcome!",
                 bg=BG, fg=FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg=BG2, padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))

        REVOLUT_URL = "https://revolut.me/lars72oeh"
        PAYPAL_URL  = "https://paypal.me/issusbarn"
        WISE_URL    = "https://wise.com/pay/me/larsdenniso"

        def _donate_btn(parent, emoji, label, url):
            f = tk.Frame(parent, bg=BG2)
            f.pack(fill="x", pady=2)
            lbl = tk.Label(f, text=f"{emoji}  {label}",
                           bg=BG2, fg=ACCENT,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2", anchor="w")
            lbl.pack(fill="x")
            lbl.bind("<Button-1>", lambda e: open_url(url))
            lbl.bind("<Enter>",    lambda e: lbl.configure(fg="#b4d4ff"))
            lbl.bind("<Leave>",    lambda e: lbl.configure(fg=ACCENT))

        _donate_btn(donate_frame, "💳", "Revolut  –  revolut.me/lars72oeh",    REVOLUT_URL)
        _donate_btn(donate_frame, "🅿️",  "PayPal   –  paypal.me/issusbarn",     PAYPAL_URL)
        _donate_btn(donate_frame, "🌍", "Wise     –  wise.com/pay/me/larsdenniso", WISE_URL)

        tk.Frame(top, bg=SEP, height=1).pack(fill="x", padx=20, pady=(6, 0))

        # ── Tech note + close ─────────────────────────────────────────────
        tk.Label(top, text="Python 3  ·  Tkinter  ·  Pillow",
                 bg=BG, fg=FG_DIM,
                 font=("Segoe UI", 8)).pack(pady=(8, 0))
        tk.Button(top, text="Close", width=12,
                  bg="#2E2E4E", fg=FG, activebackground="#3A3A6A",
                  activeforeground=FG, relief=tk.FLAT, cursor="hand2",
                  font=("Segoe UI", 9),
                  command=top.destroy).pack(pady=(10, 16))


# *************** DEL 40 – WINDOW CLOSE + SAVE SETTINGS *******************

    @needs_text_ok("close the program")
    def _close(self):
        if self.modified:
            r = messagebox.askyesnocancel("Quit", "Save before quitting?")
            if r is None:
                return
            if r:
                self._save()

        self._save_state()
        if not self.embedded:
            self.root.destroy()

    def _save_state(self):
        """Persist config — called both on close and by Hub via save_state()."""
        if not self.embedded:
            try:
                self.cfg["win_w"] = self.root.winfo_width()
                self.cfg["win_h"] = self.root.winfo_height()
                self.cfg["win_x"] = self.root.winfo_x()
                self.cfg["win_y"] = self.root.winfo_y()
            except Exception:
                pass
        self.cfg["zoom"]        = self.zoom
        self.cfg["fg"]          = self.fg
        self.cfg["bg"]          = self.bg
        self.cfg["tool"]        = self.tool
        self.cfg["line_w"]      = self.line_w
        self.cfg["brush_size"]  = self.brush_size
        self.cfg["fill_style"]  = self.fill_style
        self.cfg["transparent_paste"] = self.transparent_paste
        try:
            self.cfg["show_toolbar"]   = self._v_toolbar.get()
            self.cfg["show_colorbox"]  = self._v_colorbox.get()
            self.cfg["show_statusbar"] = self._v_statusbar.get()
        except Exception:
            pass
        self.cfg.save()


# *************** DEL 41 – HUB MODULE WRAPPER ******************************

class EditorFrame(ttk.Frame):
    """
    Hub-compatible wrapper around PaintApp.
    The Hub calls:  EditorFrame(notebook)
    Optional:       set_base_dir(path),  save_state(),  menu_spec()
    """
    WANT_HUB_DIR = WANT_HUB_DIR

    def __init__(self, master, hub=None):
        super().__init__(master)
        self.hub = hub
        # Fill the whole notebook tab
        self.pack(fill=tk.BOTH, expand=True)
        # PaintApp packs its own widgets straight into this frame
        # (self = root). The pack settings (expand, fill, side) are already
        # correct inside PaintApp — do NOT override them here.
        self._app = PaintApp(self, embedded=True)

    def set_base_dir(self, path):
        """The Hub can tell us which folder is currently active."""
        try:
            self._app.cfg["last_dir"] = path
        except Exception:
            pass

    def save_state(self):
        """Called by the Hub on tab change / shutdown."""
        try:
            self._app._save_state()
        except Exception:
            pass

    def menu_spec(self):
        return {"module_name": MODULE_NAME, "menu_label": MENU_LABEL,
                "menu_group": MENU_GROUP, "menu_pos": MENU_POS,
                "want_hub_dir": WANT_HUB_DIR}


# -- Hub API (module level) ---------------------------------------------------
def build_module(master, hub=None):
    return EditorFrame(master, hub=hub)

def menu_spec():
    return {"module_name": MODULE_NAME, "menu_label": MENU_LABEL,
            "menu_group": MENU_GROUP, "menu_pos": MENU_POS,
            "want_hub_dir": WANT_HUB_DIR}


# *************** DEL 42 – ENTRY POINT *************************************

def run_standalone():
    # Rule 1: AppUserModelID BEFORE tk.Tk() -- correct taskbar grouping
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "Issu.Paint.1")
    except Exception:
        pass

    root = tk.Tk()
    root.option_add("*Entry.insertOffTime", 0)
    root.option_add("*Entry.insertOnTime",  9999999)
    root.option_add("*Text.insertOffTime",  0)
    root.option_add("*Text.insertOnTime",   9999999)
    app = PaintApp(root, embedded=False)

    # Rule 2: set the icon via after(0, ...), never directly -- tkinter
    # overwrites it otherwise
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()

if __name__ == "__main__":
    run_standalone()
