# -*- coding: utf-8 -*-
# =====================================================================================================================
# Architect.py - a floor-plan / house design program (walls, doors, windows, rooms, furniture, sanitary, kitchen,
# electrical, stairs, several storeys, attic with sloped roof).  Exports DXF (AutoCAD & co), IFC4 (BIM), OBJ, SVG, PDF.
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments, UI, Help) - rule 01_CORE item 1.
# Pure Python (standard library only).  Built from Architect\parts\*.py by Architect\build_Architect.py - edit the parts.
# Also: mansard / gambrel roofs, dormers, roof windows, curved walls, materials + prices + where-to-buy, memos, craftsmen,
# house planner (size, main rooms + sub-rooms, arrange, fit rooms <-> house, build walls/doors/windows).
# 1.4: prices from a web page (one page, confirmed by you), shopping list as PDF, L / T / U / free-outline rooms in the house planner.
# 1.5: straight stairs drawn like a wall (width, then length: steps / tread / slope worked out), LIFT (elevator), turning with the
#      arrow keys + turn knob + buttons, 'Show floor below' tick box, 3D 'Hide roof' (default on) and furniture painted in the right order.
#      Heating list now has heat pumps; new 'Chimney & ventilation' list (chimney, flue, vent shaft/pipe/duct/valve, vent unit, hood);
#      chimneys and vent shafts continue up through the floors (dashed ghost on the plans above, full height in 3D, 'Continues up' row).
# ToDo: DWG (closed format: open the DXF in AutoCAD and save as DWG), refreshing web prices with one click, slanted room edges.
# =====================================================================================================================
import os
import sys
import json
import math
import time
import shutil
import ctypes
import platform
import subprocess
import webbrowser
import tkinter as tk
import tkinter.font as tkfont
from tkinter import messagebox, filedialog

APP_TITLE = "Architect"
APP_VERSION = "1.5"


# *************** DEL 02 - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico


# *************** DEL 03 - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL 04 - OPEN THINGS WITH MY OWN PROGRAMS *******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL 06 - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL 05 - ABOUT DIALOG (TEMPLATE) ****************************
# A TEMPLATE, not verbatim: adapt look / colours / emoji / name to the program,
# but KEEP THE MESSAGE (creator, documentation link, small gift).
# NOT for games - games never carry anything tied to me (see 40_games.md; they
# name the designers instead).
#
# Rules: About closes with ESC; Toplevel order grab_set(), focus_force(), <Escape>
# (make_modal does it).  Links open through open_url(), never webbrowser directly.
# The program NAME shown here has no "Issu" part (Issus, Issu's ...); only the
# creator line keeps Lars "Issu" Olsson.
#
# Needs:  import tkinter as tk
#         block_ui_helpers.py (make_modal)   block_open.py (open_url)
#
# Call:   show_about(root, "MyProgram", "What it is, in one line", "🏢")
# Change the colours by passing colors={...} that match the program's palette.

DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"

ABOUT_COLORS = dict(bg="#1e1e2e", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
                    sep="#3a3a4e", box="#252535", hover="#b4d4ff")


def show_about(root, app_name, tagline, emoji="🏢", colors=None):
    """Stylish About dialog with documentation link and donation info."""
    c = {**ABOUT_COLORS, **(colors or {})}

    top = tk.Toplevel(root)
    top.title("About " + app_name)
    top.configure(bg=c["bg"])
    top.resizable(False, False)
    top.transient(root)
    make_modal(top)                              # grab_set, focus_force, Escape

    # Header
    hdr = tk.Frame(top, bg=c["bg"])
    hdr.pack(fill="x")
    tk.Label(hdr, text=emoji, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 36)).pack(pady=(18, 0))
    tk.Label(hdr, text=app_name, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 20, "bold")).pack()
    tk.Label(hdr, text=tagline, bg=c["bg"], fg=c["dim"],
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20)

    # Creator
    tk.Label(top, text='Created by  Lars "Issu" Olsson', bg=c["bg"], fg=c["fg"],
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    def link(parent, text, url, size=9, **pack):
        lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=c["accent"],
                       font=("Segoe UI", size, "underline"), cursor="hand2")
        lbl.pack(**pack)
        lbl.bind("<Button-1>", lambda e: open_url(url))
        lbl.bind("<Enter>",    lambda e: lbl.configure(fg=c["hover"]))
        lbl.bind("<Leave>",    lambda e: lbl.configure(fg=c["accent"]))
        return lbl

    link(top, "📄  View documentation", DOC_URL, pady=(6, 2))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20, pady=(14, 0))

    # Donation
    # Lars's wording since 2026-11-07 (rule 30): ENGLISH in every language, the wordplay focUSing on US / focuSING cha-CHING
    tk.Label(top, text="Focusing on us instead of cha-ching\nbut if you like " + app_name +
                       ", you are welcome to send a token of appreciation",
             bg=c["bg"], fg=c["dim"], font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=c["box"], padx=16, pady=10)
    box.pack(fill="x", padx=20, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        link(box, text, url, pady=1)

    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(8, 16))
    return top


# *************** DEL 07 - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL **********
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()


# *************** DEL 10 - GEOMETRY HELPERS (2D vectors, polygons, triangulation) *****************
# Everything here is plain maths on (x, y) tuples in MILLIMETRES, y points up (like a drawing).  No tkinter.
# ToDo: a real polygon union (for a joined outline of all rooms of a storey).


def v_sub(a, b):
    return (a[0] - b[0], a[1] - b[1])


def v_add(a, b):
    return (a[0] + b[0], a[1] + b[1])


def v_mul(a, k):
    return (a[0] * k, a[1] * k)


def v_dot(a, b):
    return a[0] * b[0] + a[1] * b[1]


def v_cross(a, b):
    return a[0] * b[1] - a[1] * b[0]


def v_len(a):
    return math.hypot(a[0], a[1])


def v_unit(a):
    n = math.hypot(a[0], a[1])
    return (a[0] / n, a[1] / n) if n > 1e-12 else (1.0, 0.0)


def v_perp(a):
    """Left normal (rotate +90 degrees)."""
    return (-a[1], a[0])


def dist(a, b):
    return math.hypot(b[0] - a[0], b[1] - a[1])


def rot_pt(p, ang_deg, c=(0.0, 0.0)):
    a = math.radians(ang_deg)
    ca, sa = math.cos(a), math.sin(a)
    x, y = p[0] - c[0], p[1] - c[1]
    return (c[0] + x * ca - y * sa, c[1] + x * sa + y * ca)


def seg_point_dist(p, a, b):
    """(distance, t) from point p to segment a-b; t in 0..1 is the closest point's position."""
    dx, dy = b[0] - a[0], b[1] - a[1]
    l2 = dx * dx + dy * dy
    if l2 < 1e-12:
        return dist(p, a), 0.0
    t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2
    t = max(0.0, min(1.0, t))
    return math.hypot(p[0] - (a[0] + t * dx), p[1] - (a[1] + t * dy)), t


def line_isect(p1, d1, p2, d2):
    """Intersection of line p1 + s*d1 with p2 + t*d2, or None when parallel."""
    den = v_cross(d1, d2)
    if abs(den) < 1e-12:
        return None
    s = v_cross(v_sub(p2, p1), d2) / den
    return (p1[0] + s * d1[0], p1[1] + s * d1[1])


def segs_cross(p1, p2, p3, p4):
    """True when the segments cross properly (touching ends do not count)."""
    d1 = v_cross(v_sub(p4, p3), v_sub(p1, p3))
    d2 = v_cross(v_sub(p4, p3), v_sub(p2, p3))
    d3 = v_cross(v_sub(p2, p1), v_sub(p3, p1))
    d4 = v_cross(v_sub(p2, p1), v_sub(p4, p1))
    return (d1 * d2 < -1e-9) and (d3 * d4 < -1e-9)


def poly_area_signed(pts):
    s = 0.0
    n = len(pts)
    for i in range(n):
        x1, y1 = pts[i]
        x2, y2 = pts[(i + 1) % n]
        s += x1 * y2 - x2 * y1
    return s / 2.0


def poly_area(pts):
    return abs(poly_area_signed(pts))


def poly_perimeter(pts):
    return sum(dist(pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts)))


def poly_centroid(pts):
    a = poly_area_signed(pts)
    if abs(a) < 1e-9:
        n = max(1, len(pts))
        return (sum(p[0] for p in pts) / n, sum(p[1] for p in pts) / n)
    cx = cy = 0.0
    n = len(pts)
    for i in range(n):
        x1, y1 = pts[i]
        x2, y2 = pts[(i + 1) % n]
        k = x1 * y2 - x2 * y1
        cx += (x1 + x2) * k
        cy += (y1 + y2) * k
    return (cx / (6 * a), cy / (6 * a))


def point_in_poly(pt, pts):
    x, y = pt
    inside = False
    n = len(pts)
    j = n - 1
    for i in range(n):
        xi, yi = pts[i]
        xj, yj = pts[j]
        if (yi > y) != (yj > y):
            xx = (xj - xi) * (y - yi) / (yj - yi) + xi
            if x < xx:
                inside = not inside
        j = i
    return inside


def label_point(pts):
    """A point INSIDE the polygon, near its middle (centroid when inside, else a scan-line midpoint)."""
    c = poly_centroid(pts)
    if point_in_poly(c, pts):
        return c
    ys = [p[1] for p in pts]
    for fr in (0.5, 0.4, 0.6, 0.3, 0.7):
        y = min(ys) + (max(ys) - min(ys)) * fr
        xs = []
        n = len(pts)
        for i in range(n):
            a, b = pts[i], pts[(i + 1) % n]
            if (a[1] > y) != (b[1] > y):
                xs.append(a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]))
        xs.sort()
        best = None
        for k in range(0, len(xs) - 1, 2):
            if best is None or xs[k + 1] - xs[k] > best[1] - best[0]:
                best = (xs[k], xs[k + 1])
        if best:
            return ((best[0] + best[1]) / 2, y)
    return c


def ensure_ccw(pts):
    pts = [tuple(p) for p in pts]
    return pts if poly_area_signed(pts) >= 0 else pts[::-1]


def ensure_cw(pts):
    pts = [tuple(p) for p in pts]
    return pts if poly_area_signed(pts) <= 0 else pts[::-1]


def clip_poly(poly, inside_fn):
    """Sutherland-Hodgman against ONE half-plane.  inside_fn(p) >= 0 means inside (must be linear in p)."""
    out = []
    n = len(poly)
    if n == 0:
        return out
    for i in range(n):
        a, b = poly[i], poly[(i + 1) % n]
        fa, fb = inside_fn(a), inside_fn(b)
        if fa >= 0:
            out.append(a)
        if (fa >= 0) != (fb >= 0):
            t = fa / (fa - fb)
            out.append((a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])))
    return out


def clip_convex(subject, clip):
    """subject clipped by the convex polygon `clip` (any winding)."""
    clip = ensure_ccw(clip)
    res = [tuple(p) for p in subject]
    n = len(clip)
    for i in range(n):
        a, b = clip[i], clip[(i + 1) % n]
        res = clip_poly(res, lambda p, a=a, b=b: v_cross(v_sub(b, a), v_sub(p, a)))
        if not res:
            break
    return res


def poly_minus_convex(P, R):
    """The convex polygon P with the convex polygon R cut out of it, as a list of convex pieces (no overlap, same winding).
    P untouched (as [P]) when R does not reach into it."""
    R = ensure_ccw(R)
    inter = clip_convex(P, R)
    if len(inter) < 3 or poly_area(inter) < 1.0:
        return [P]
    pieces = []
    rest = [tuple(p) for p in P]
    n = len(R)
    for i in range(n):
        a, b = R[i], R[(i + 1) % n]
        outside = clip_poly(rest, lambda p, a=a, b=b: -v_cross(v_sub(b, a), v_sub(p, a)))
        if len(outside) >= 3 and poly_area(outside) > 1.0:
            pieces.append(outside)
        rest = clip_poly(rest, lambda p, a=a, b=b: v_cross(v_sub(b, a), v_sub(p, a)))
        if len(rest) < 3:
            break
    return pieces


def rdp(points, eps):
    """Douglas-Peucker for an OPEN list of points."""
    if len(points) < 3:
        return list(points)
    a, b = points[0], points[-1]
    dmax, imax = -1.0, 0
    for i in range(1, len(points) - 1):
        d = seg_point_dist(points[i], a, b)[0]
        if d > dmax:
            dmax, imax = d, i
    if dmax > eps:
        left = rdp(points[:imax + 1], eps)
        right = rdp(points[imax:], eps)
        return left[:-1] + right
    return [a, b]


def _cross3(o, a, b):
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def triangulate(poly):
    """Ear clipping.  poly = list of (x, y), may repeat vertices (hole bridges).  Returns (i, j, k) index triples."""
    n = len(poly)
    if n < 3:
        return []
    idx = list(range(n))
    if poly_area_signed(poly) < 0:
        idx.reverse()
    tris = []
    guard = 0
    while len(idx) > 3 and guard < 20000:
        guard += 1
        m = len(idx)
        clipped = False
        for k in range(m):
            i0, i1, i2 = idx[k - 1], idx[k], idx[(k + 1) % m]
            a, b, c = poly[i0], poly[i1], poly[i2]
            if _cross3(a, b, c) <= 1e-9:
                continue
            ok = True
            for j in idx:
                if j in (i0, i1, i2):
                    continue
                p = poly[j]
                if (abs(p[0] - a[0]) < 1e-7 and abs(p[1] - a[1]) < 1e-7) or \
                   (abs(p[0] - b[0]) < 1e-7 and abs(p[1] - b[1]) < 1e-7) or \
                   (abs(p[0] - c[0]) < 1e-7 and abs(p[1] - c[1]) < 1e-7):
                    continue
                if _cross3(a, b, p) >= -1e-9 and _cross3(b, c, p) >= -1e-9 and _cross3(c, a, p) >= -1e-9:
                    ok = False
                    break
            if ok:
                tris.append((i0, i1, i2))
                idx.pop(k)
                clipped = True
                break
        if not clipped:
            # stuck (degenerate input): drop a collinear vertex, else force the best ear
            best, bk = -1e18, 0
            for k in range(m):
                cr = _cross3(poly[idx[k - 1]], poly[idx[k]], poly[idx[(k + 1) % m]])
                if abs(cr) <= 1e-9:
                    best, bk = None, k
                    break
                if cr > best:
                    best, bk = cr, k
            if best is None:
                idx.pop(bk)
            else:
                i0, i1, i2 = idx[bk - 1], idx[bk], idx[(bk + 1) % m]
                tris.append((i0, i1, i2))
                idx.pop(bk)
    if len(idx) == 3:
        if abs(_cross3(poly[idx[0]], poly[idx[1]], poly[idx[2]])) > 1e-9:
            tris.append(tuple(idx))
    return tris


def triangulate_with_holes(outer, holes):
    """Triangles of a polygon with holes (each hole bridged into the outline).  Returns (verts, tris)."""
    outer = ensure_ccw(outer)
    holes = [ensure_cw(h) for h in holes if len(h) >= 3]
    verts = list(outer)
    for hole in sorted(holes, key=lambda h: -max(p[0] for p in h)):
        mi = max(range(len(hole)), key=lambda i: hole[i][0])
        M = hole[mi]
        order = sorted(range(len(verts)), key=lambda i: dist(verts[i], M))
        vi = order[0]
        for cand in order:
            V = verts[cand]
            ok = True
            n = len(verts)
            for i in range(n):
                a, b = verts[i], verts[(i + 1) % n]
                if segs_cross(M, V, a, b):
                    ok = False
                    break
            if ok:
                for h in holes:
                    nh = len(h)
                    for i in range(nh):
                        if segs_cross(M, V, h[i], h[(i + 1) % nh]):
                            ok = False
                            break
                    if not ok:
                        break
            if ok:
                mid = ((M[0] + V[0]) / 2, (M[1] + V[1]) / 2)
                if not point_in_poly(mid, outer) or any(point_in_poly(mid, h) for h in holes):
                    ok = False
            if ok:
                vi = cand
                break
        V = verts[vi]
        ring = hole[mi:] + hole[:mi] + [M]
        verts = verts[:vi + 1] + ring + [V] + verts[vi + 1:]
    return verts, triangulate(verts)


def poly_inside_poly(inner, outer):
    """True when every corner of `inner` is inside `outer` and no edges cross."""
    if not all(point_in_poly(p, outer) for p in inner):
        return False
    n, m = len(inner), len(outer)
    for i in range(n):
        for j in range(m):
            if segs_cross(inner[i], inner[(i + 1) % n], outer[j], outer[(j + 1) % m]):
                return False
    return True


def fmt_m(mm, nd=2):
    return ("%." + str(nd) + "f") % (mm / 1000.0)


def fmt_area(mm2):
    return "%.1f m²" % (mm2 / 1e6)


# *************** DEL 20 - THE MODEL (project, storeys, walls, rooms, roofs) *****************
# One project = one dict (saved as JSON).  All lengths are MILLIMETRES.  Storeys are listed bottom to top; each storey
# holds its own walls / openings / rooms / items / stairs / roofs / dims / texts.  Elements have a project-wide unique "id".
# The attic is just a storey that carries a roof: the roof's inner surface decides how high the walls and the ceiling are.
# ToDo: curved walls (arc walls) are added further down; dormers and roof windows live in DEL 26.

FILE_FORMAT = "architect-project"
FILE_VERSION = 1

WALL_PRESETS = [("Outer wall", 250), ("Inner wall", 100), ("Light partition", 70), ("Thick wall", 400)]
ROOM_TYPES = ["Living room", "Kitchen", "Dining room", "Bedroom", "Bathroom", "WC", "Hall", "Pantry", "Storage",
              "Laundry", "Office", "Attic room", "Stairwell", "Garage", "Room"]

# default size of each opening kind: (width, height, sill, label)
OPENING_KINDS = {
    "door":    (900, 2100, 0, "Door (single)"),
    "door2":   (1600, 2100, 0, "Door (double)"),
    "slide":   (1200, 2100, 0, "Sliding door"),
    "passage": (1000, 2100, 0, "Passage (no leaf)"),
    "window":  (1200, 1200, 900, "Window"),
}

ROOF_TYPES = ["gable", "hip", "shed", "flat", "mansard", "gambrel"]
MANSARD_TYPES = ("mansard", "gambrel")        # broken roofs: a steep lower slope, then a shallower upper slope


def default_settings():
    return {"headroom": [1000, 1900], "snap": 100, "wall_t": 100, "grid": 500}


def new_story(name, height=2500, floor_t=250, base=0):
    return {"id": 0, "name": name, "height": height, "floor_t": floor_t, "base": base,
            "walls": [], "openings": [], "rooms": [], "items": [], "stairs": [], "roofs": [],
            "dims": [], "texts": [], "sections": [], "dormers": [], "rwins": [], "meas": []}


def new_project(name="House"):
    p = {"format": FILE_FORMAT, "version": FILE_VERSION, "name": name, "next_id": 1,
         "settings": default_settings(), "stories": [], "notes": [],
         "shop": {"lines": [], "mode": "auto", "max_stores": 3, "next": 1}}
    s = new_story("Ground floor")
    s["id"] = uid(p)
    p["stories"].append(s)
    return p


def uid(proj):
    n = proj["next_id"]
    proj["next_id"] = n + 1
    return n


def story_elevations(proj):
    """Top of the finished floor of every storey (mm)."""
    out = []
    st = proj["stories"]
    for i, s in enumerate(st):
        if i == 0:
            out.append(float(s.get("base", 0)))
        else:
            out.append(out[-1] + st[i - 1]["height"] + s["floor_t"])
    return out


def story_index(proj, story):
    for i, s in enumerate(proj["stories"]):
        if s is story:
            return i
    return -1


KIND_LISTS = {"wall": "walls", "opening": "openings", "room": "rooms", "item": "items", "stair": "stairs",
              "roof": "roofs", "dim": "dims", "text": "texts", "section": "sections", "dormer": "dormers",
              "rwin": "rwins", "meas": "meas"}


def find_element(story, eid):
    """(kind, dict) of the element with this id in this storey, or (None, None)."""
    for kind, lst in KIND_LISTS.items():
        for e in story[lst]:
            if e["id"] == eid:
                return kind, e
    return None, None


def remove_element(story, eid):
    kind, e = find_element(story, eid)
    if e is None:
        return
    story[KIND_LISTS[kind]].remove(e)
    if kind == "wall":                       # openings in a deleted wall go with it
        story["openings"] = [o for o in story["openings"] if o["wall"] != eid]


def get_wall(story, wid):
    for w in story["walls"]:
        if w["id"] == wid:
            return w
    return None


# ---- adding things (used by the UI, the example house and the tests) ----------------------------------------
def add_wall(proj, story, p1, p2, t=100, h=None, kind=None):
    w = {"id": uid(proj), "p": [float(p1[0]), float(p1[1]), float(p2[0]), float(p2[1])], "t": float(t), "h": h}
    if kind == "curtain":                      # a room-divider curtain (see DEL 28): shut, gathers at both ends
        w["kind"] = "curtain"
        w["open"] = 0.0
        w["gather"] = "Both"
    story["walls"].append(w)
    return w


def add_room(proj, story, pts, name="Room"):
    r = {"id": uid(proj), "name": name, "pts": [[float(x), float(y)] for x, y in pts]}
    story["rooms"].append(r)
    return r


def add_opening(proj, story, wid, pos, kind="door", w=None, h=None, sill=None, hinge=0, swing=1):
    dw, dh, ds, _ = OPENING_KINDS[kind]
    o = {"id": uid(proj), "wall": wid, "kind": kind, "pos": float(pos),
         "w": float(w if w is not None else dw), "h": float(h if h is not None else dh),
         "sill": float(sill if sill is not None else ds), "hinge": hinge, "swing": swing}
    story["openings"].append(o)
    return o


def add_dim(proj, story, a, b, off=600):
    d = {"id": uid(proj), "a": [float(a[0]), float(a[1])], "b": [float(b[0]), float(b[1])], "off": float(off)}
    story["dims"].append(d)
    return d


def add_text(proj, story, x, y, s, h=200, ghost=False):
    """A text on the plan.  ghost=True: a GHOST NOTE (your own working note such as 'Bedroom B'): shown only in the plan, only when
    'Ghost notes' is ticked (default off), never in exports or prints."""
    t = {"id": uid(proj), "x": float(x), "y": float(y), "s": s, "h": float(h), "rot": 0.0}
    if ghost:
        t["ghost"] = True
    story["texts"].append(t)
    return t


def add_roof(proj, story, rect, kind="gable", pitch=35.0, eave=1100.0, ridge=None, fall="S", over=None, t=200.0,
             pitch2=None, run=None):
    """pitch2 / run only matter for the broken roofs (mansard, gambrel): pitch2 = the steep LOWER slope (deg), run = how
    far it reaches in from the eave line (mm, measured in plan); `pitch` is then the shallow UPPER slope."""
    x0, x1 = sorted((rect[0], rect[2]))
    y0, y1 = sorted((rect[1], rect[3]))
    if ridge is None:
        ridge = "x" if (x1 - x0) >= (y1 - y0) else "y"
    if over is None:
        over = 150.0 if kind in MANSARD_TYPES else 400.0     # a 70 degree slope drops fast: keep the overhang short
    r = {"id": uid(proj), "type": kind, "rect": [float(x0), float(y0), float(x1), float(y1)], "pitch": float(pitch),
         "eave": float(eave), "ridge": ridge, "fall": fall, "over": float(over), "t": float(t)}
    if kind in MANSARD_TYPES:
        r["pitch2"] = float(70.0 if pitch2 is None else pitch2)
        r["run"] = float(1200.0 if run is None else run)
    story["roofs"].append(r)
    return r


# ---- roofs ---------------------------------------------------------------------------------------------------
def _side_planes(rect, k, e):
    """The four planes (one per side of the rectangle) that rise with slope k from height e at the rectangle's edge."""
    x0, y0, x1, y1 = rect
    return {"S": (0.0, k, e - k * y0), "N": (0.0, -k, e + k * y1), "W": (k, 0.0, e - k * x0), "E": (-k, 0.0, e + k * x1)}


def roof_planes(roof):
    """[(side, (a, b, c))]: the planes z = a*x + b*y + c (relative to the storey floor) of the roof's inner surface.
    The roof height at a point is the MINIMUM of these planes.  A broken roof (mansard / gambrel) is simply two planes per
    side: the steep lower one (side 'S') and the shallow upper one (side 'S2') that starts where the steep one has run `run`
    mm in - the lower of the two is the roof, so the kink comes out by itself."""
    k = math.tan(math.radians(max(0.0, min(80.0, roof["pitch"]))))
    e = roof["eave"]
    allp = _side_planes(roof["rect"], k, e)
    t = roof["type"]
    if t == "flat":
        return [("F", (0.0, 0.0, e))]
    if t in MANSARD_TYPES:
        k2 = math.tan(math.radians(max(0.0, min(85.0, max(roof.get("pitch2", 70.0), roof["pitch"])))))
        run = max(0.0, roof.get("run", 1200.0))
        steep = _side_planes(roof["rect"], k2, e)
        shallow = _side_planes(roof["rect"], k, e + (k2 - k) * run)
        if t == "mansard":
            sides = ["S", "N", "W", "E"]
        else:
            sides = ["S", "N"] if roof.get("ridge", "x") == "x" else ["W", "E"]
        return [(s, steep[s]) for s in sides] + [(s + "2", shallow[s]) for s in sides]
    if t == "hip":
        sides = ["S", "N", "W", "E"]
    elif t == "shed":
        sides = [roof.get("fall", "S") if roof.get("fall", "S") in allp else "S"]
    else:
        sides = ["S", "N"] if roof.get("ridge", "x") == "x" else ["W", "E"]
    return [(s, allp[s]) for s in sides]


def roof_rect_poly(roof, grow=0.0):
    x0, y0, x1, y1 = roof["rect"]
    return [(x0 - grow, y0 - grow), (x1 + grow, y0 - grow), (x1 + grow, y1 + grow), (x0 - grow, y1 + grow)]


def roof_height(roof, x, y, grow=0.0):
    """Inner roof surface height at (x, y) relative to the storey floor, or None when (x, y) is outside the roof
    (the rectangle grown by `grow`; the slope simply continues over the eaves)."""
    x0, y0, x1, y1 = roof["rect"]
    if x < x0 - 1 - grow or x > x1 + 1 + grow or y < y0 - 1 - grow or y > y1 + 1 + grow:
        return None
    return min(a * x + b * y + c for _, (a, b, c) in roof_planes(roof))


def roof_facets(roof, grow=None):
    """The planar pieces of the roof: [{"poly": [(x, y)...], "plane": (a, b, c), "side": 'S'}], over the roof rectangle
    grown by `grow` (default: the overhang)."""
    g = roof["over"] if grow is None else grow
    base = roof_rect_poly(roof, g)
    planes = roof_planes(roof)
    out = []
    for i, (side, pi) in enumerate(planes):
        poly = base
        for j, (_, pj) in enumerate(planes):
            if i == j:
                continue
            poly = clip_poly(poly, lambda p, pi=pi, pj=pj: (pj[0] - pi[0]) * p[0] + (pj[1] - pi[1]) * p[1] + (pj[2] - pi[2]))
            if len(poly) < 3:
                break
        if roof["type"] in MANSARD_TYPES and len(poly) >= 3:
            # the steep lower slope would otherwise run on below the attic floor over the overhang
            poly = clip_poly(poly, lambda p, pi=pi: pi[0] * p[0] + pi[1] * p[1] + pi[2])
        if len(poly) >= 3 and poly_area(poly) > 1.0:
            out.append({"poly": poly, "plane": pi, "side": side})
    return out


def story_roof_height(story, x, y):
    """Highest inner roof surface over (x, y) of this storey (relative to its floor), or None when no roof covers it.
    Inside a dormer the dormer's own (higher) ceiling counts."""
    best = host_roof_height(story, x, y)
    for dm in story.get("dormers", []):
        h = dormer_ceiling_height(story, dm, x, y)
        if h is not None and (best is None or h > best):
            best = h
    return best


def roof_ridge_height(roof):
    return max(roof_height(roof, (roof["rect"][0] + roof["rect"][2]) / 2, (roof["rect"][1] + roof["rect"][3]) / 2) or 0,
               roof["eave"])


def headroom_regions(story, limit):
    """Plan polygons where the inner roof is LOWER than `limit` (mm above the floor)."""
    out = []
    for r in story["roofs"]:
        inner = roof_rect_poly(r, 0)
        for f in roof_facets(r, 0.0):
            a, b, c = f["plane"]
            poly = clip_poly(f["poly"], lambda p, a=a, b=b, c=c: limit - (a * p[0] + b * p[1] + c))
            if len(poly) >= 3 and poly_area(poly) > 1.0:
                out.append(poly)
    return out


def headroom_contours(story, limit):
    """Line segments of the plan where the roof is exactly `limit` high (for the dashed headroom line)."""
    segs = []
    for r in story["roofs"]:
        for f in roof_facets(r, 0.0):
            a, b, c = f["plane"]
            if abs(a) < 1e-9 and abs(b) < 1e-9:
                continue
            # line a*x + b*y + c = limit crossed with the facet polygon
            poly = f["poly"]
            pts = []
            n = len(poly)
            for i in range(n):
                p, q = poly[i], poly[(i + 1) % n]
                fp = a * p[0] + b * p[1] + c - limit
                fq = a * q[0] + b * q[1] + c - limit
                if (fp >= 0) != (fq >= 0):
                    t = fp / (fp - fq)
                    pts.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
            if len(pts) >= 2:
                segs.append((pts[0], pts[1]))
    return segs


def room_headroom_area(story, room, limit):
    """Area (mm^2) of the room where the free height is at least `limit` (roofs that do not cover = no limit)."""
    pts = [tuple(p) for p in room["pts"]]
    total = poly_area(pts)
    low = 0.0
    high_dorm = dormer_high_polys(story, limit)          # inside a dormer the ceiling may be high enough
    for r in story["roofs"]:
        inner = roof_rect_poly(r, 0)
        for f in roof_facets(r, 0.0):
            a, b, c = f["plane"]
            piece = clip_poly(f["poly"], lambda p, a=a, b=b, c=c: limit - (a * p[0] + b * p[1] + c))
            if len(piece) < 3:
                continue
            sub = clip_convex(pts, piece) if poly_area_signed(pts) >= 0 else clip_convex(pts[::-1], piece)
            if len(sub) >= 3:
                low += poly_area(sub)
                for dh in high_dorm:
                    both = clip_convex(sub, dh)
                    if len(both) >= 3:
                        low -= poly_area(both)
    return max(0.0, total - low)


# ---- curved walls --------------------------------------------------------------------------------------------
# A wall with "sag" != 0 is an ARC: sag = how far the middle of the arc lies from the straight line start -> end (mm, positive
# = to the LEFT of start -> end).  Everything that needs wall geometry first calls expand_curved(story): it returns a copy
# of the storey where every curved wall is replaced by a chain of short straight walls (id < 0, "src" = the real wall,
# "s0"/"s1" = where along the arc they start / end) and every door or window sits in the one short wall it belongs to.  The
# chain pieces meet in mitred corners like any other walls, so plan, 3D, sections, room detection and all exports work
# unchanged.  A door or window in a curved wall is flat (a chord of the arc), as in real life.
ARC_STEP_DEG = 7.5


def wall_arc(w):
    """None for a straight wall, else {"c": centre, "r": radius, "a0": start angle, "sweep": signed angle, "length": arc length}
    (angles in radians; the arc runs from the wall's start to its end)."""
    sag = float(w.get("sag") or 0.0)
    A = (w["p"][0], w["p"][1])
    B = (w["p"][2], w["p"][3])
    chord = dist(A, B)
    if chord < 1.0 or abs(sag) < 1.0:
        return None
    s = max(-0.9 * chord, min(0.9 * chord, sag))
    half = chord / 2.0
    R = (half * half + s * s) / (2.0 * abs(s))
    d = v_unit(v_sub(B, A))
    n = v_perp(d)
    k = s - math.copysign(R, s)
    C = ((A[0] + B[0]) / 2.0 + n[0] * k, (A[1] + B[1]) / 2.0 + n[1] * k)
    theta = 4.0 * math.atan2(2.0 * abs(s), chord)
    return {"c": C, "r": R, "a0": math.atan2(A[1] - C[1], A[0] - C[0]), "sweep": -math.copysign(theta, s), "length": R * theta}


def wall_length(w):
    arc = wall_arc(w)
    return arc["length"] if arc else dist((w["p"][0], w["p"][1]), (w["p"][2], w["p"][3]))


def wall_arc_at(w, s):
    """(point, unit tangent) on the centre line at distance s from the wall's start (straight or curved)."""
    arc = wall_arc(w)
    if arc is None:
        A = (w["p"][0], w["p"][1])
        d = v_unit((w["p"][2] - A[0], w["p"][3] - A[1]))
        return (A[0] + d[0] * s, A[1] + d[1] * s), d
    ang = arc["a0"] + arc["sweep"] * max(0.0, min(1.0, s / arc["length"]))
    sg = 1.0 if arc["sweep"] > 0 else -1.0
    return ((arc["c"][0] + arc["r"] * math.cos(ang), arc["c"][1] + arc["r"] * math.sin(ang)),
            (-math.sin(ang) * sg, math.cos(ang) * sg))


def wall_arc_polyline(w, step_deg=ARC_STEP_DEG):
    """Points along the centre line of a wall (2 for a straight wall)."""
    arc = wall_arc(w)
    if arc is None:
        return [(w["p"][0], w["p"][1]), (w["p"][2], w["p"][3])]
    n = max(2, int(math.ceil(abs(arc["sweep"]) / math.radians(step_deg))))
    return [wall_arc_at(w, arc["length"] * i / n)[0] for i in range(n + 1)]


def expand_curved(story):
    """The storey with its curved walls replaced by chains of straight ones (the same storey object when nothing is curved)."""
    if not any(wall_arc(w) for w in story["walls"]):
        return story
    by_wall = {}
    for o in story["openings"]:
        by_wall.setdefault(o["wall"], []).append(o)
    walls, opens = [], []
    for w in story["walls"]:
        arc = wall_arc(w)
        ops = by_wall.get(w["id"], [])
        if arc is None:
            walls.append(w)
            opens += ops
            continue
        L = arc["length"]
        n = max(2, int(math.ceil(abs(arc["sweep"]) / math.radians(ARC_STEP_DEG))))
        spans = [(max(0.0, o["pos"] - o["w"] / 2.0), min(L, o["pos"] + o["w"] / 2.0)) for o in ops]
        sv = {0.0, round(L, 3)}
        for a, b in spans:
            sv.add(round(a, 3))
            sv.add(round(b, 3))
        for k in range(1, n):                         # regular points, but none inside a door / window
            s = L * k / n
            if not any(a - 8.0 < s < b + 8.0 for a, b in spans):
                sv.add(round(s, 3))
        svals = []
        for s in sorted(sv):
            if not svals or s - svals[-1] >= 2.0:
                svals.append(s)
        if svals[-1] < L - 2.0:
            svals.append(round(L, 3))
        pts = [wall_arc_at(w, s)[0] for s in svals]
        subs = []
        for k in range(len(svals) - 1):
            subs.append({"id": -(w["id"] * 1000 + k + 1), "p": [pts[k][0], pts[k][1], pts[k + 1][0], pts[k + 1][1]], "t": w["t"],
                         "h": w.get("h"), "src": w["id"], "s0": svals[k], "s1": svals[k + 1]})
        walls += subs
        for o in ops:
            k = next((i for i, sw in enumerate(subs) if sw["s0"] - 0.01 <= o["pos"] <= sw["s1"] + 0.01), len(subs) - 1)
            sw = subs[k]
            chord = dist((sw["p"][0], sw["p"][1]), (sw["p"][2], sw["p"][3]))
            o2 = dict(o)
            o2["wall"] = sw["id"]
            o2["pos"] = (o["pos"] - sw["s0"]) / max(1e-9, sw["s1"] - sw["s0"]) * chord
            opens.append(o2)
    s2 = dict(story)
    s2["walls"] = walls
    s2["openings"] = opens
    return s2


def story_wall_points(story):
    """Every corner / arc point of the walls (for roofs and bounding boxes)."""
    sx = expand_curved(story)
    return [(w["p"][i], w["p"][i + 1]) for w in sx["walls"] for i in (0, 2)]


def wall_plan_polys(story):
    """[(wall id, polygon)]: footprints of the walls with the doors and windows cut out.  The pieces of a curved wall that join
    end to end come out as ONE outline."""
    sx = expand_curved(story)
    geo = wall_geometry(sx)
    out = []
    cur = {}

    def flush(src):
        c = cur.pop(src, None)
        if c:
            out.append((src, c[0] + c[1][::-1]))
    for w in sx["walls"]:
        if w.get("kind") == "curtain":              # a curtain is drawn by curtain_plan_prims, not as a wall footprint
            continue
        g = geo[w["id"]]
        pieces = wall_plan_pieces(sx, w, g)
        src = w.get("src")
        if src is None:
            out += [(w["id"], pc) for pc in pieces]
            continue
        for pc in pieces:                              # pc = [R0, R1, L1, L0]
            c = cur.get(src)
            if c and dist(c[0][-1], pc[0]) < 1.0 and dist(c[1][-1], pc[3]) < 1.0:
                c[0].append(pc[1])
                c[1].append(pc[2])
            else:
                flush(src)
                cur[src] = ([pc[0], pc[1]], [pc[3], pc[2]])
    for src in list(cur):
        flush(src)
    return out

# ---- walls ---------------------------------------------------------------------------------------------------
def wall_geometry(story):
    """Per wall: centre line, side lines with MITRED corners where exactly two walls meet at an end.
    Returns {wall id: {"A","B","d","n","h","len","L0","L1","R0","R1"}}   (L = left side, R = right side, 0 = start, 1 = end)."""
    geo = {}
    ends = []
    for w in story["walls"]:
        A = (w["p"][0], w["p"][1])
        B = (w["p"][2], w["p"][3])
        d = v_unit(v_sub(B, A))
        n = v_perp(d)
        h = w["t"] / 2.0
        geo[w["id"]] = {"A": A, "B": B, "d": d, "n": n, "h": h, "len": dist(A, B),
                        "L0": v_add(A, v_mul(n, h)), "R0": v_sub(A, v_mul(n, h)),
                        "L1": v_add(B, v_mul(n, h)), "R1": v_sub(B, v_mul(n, h))}
        ends.append((w["id"], "A", A))
        ends.append((w["id"], "B", B))
    for wid, which, E in ends:
        others = [o for o in ends if o[0] != wid and dist(o[2], E) < 3.0]
        if len(others) != 1:
            continue
        g1 = geo[wid]
        g2 = geo[others[0][0]]
        da1 = g1["d"] if which == "A" else v_mul(g1["d"], -1)
        da2 = g2["d"] if others[0][1] == "A" else v_mul(g2["d"], -1)
        if abs(v_cross(da1, da2)) < 1e-4:          # collinear (or folded back): nothing to mitre
            continue
        n1, n2 = v_perp(da1), v_perp(da2)
        h1, h2 = g1["h"], g2["h"]
        P1 = line_isect(v_add(E, v_mul(n1, h1)), da1, v_sub(E, v_mul(n2, h2)), da2)
        P2 = line_isect(v_sub(E, v_mul(n1, h1)), da1, v_add(E, v_mul(n2, h2)), da2)
        if P1 is None or P2 is None:
            continue
        lim = 8.0 * max(h1, h2)
        if dist(P1, E) > lim or dist(P2, E) > lim:
            continue
        if which == "A":
            g1["L0"], g1["R0"] = P1, P2
        else:
            g1["R1"], g1["L1"] = P1, P2
    return geo


def wall_openings(story, wid):
    """The openings of one wall as [(a, b, opening)] sorted by position (a, b = distances along the wall)."""
    out = []
    for o in story["openings"]:
        if o["wall"] == wid:
            out.append((o["pos"] - o["w"] / 2.0, o["pos"] + o["w"] / 2.0, o))
    out.sort(key=lambda t: t[0])
    return out


def wall_intervals(story, w, g, cut=True):
    """Solid stretches of a wall between its openings: [(uL0, uR0, uL1, uR1)] (u = distance along the wall).
    cut=False: the wall is whole."""
    A, d = g["A"], g["d"]
    uL0 = v_dot(v_sub(g["L0"], A), d)
    uR0 = v_dot(v_sub(g["R0"], A), d)
    uL1 = v_dot(v_sub(g["L1"], A), d)
    uR1 = v_dot(v_sub(g["R1"], A), d)
    cur = (uL0, uR0)
    out = []
    for a, b, _ in (wall_openings(story, w["id"]) if cut else []):
        a = max(a, 0.0)
        b = min(b, g["len"])
        if b <= a:
            continue
        if a > max(cur) + 1.0:
            out.append((cur[0], cur[1], a, a))
        cur = (max(b, cur[0]), max(b, cur[1]))
    if uL1 > cur[0] + 1.0 and uR1 > cur[1] + 1.0:
        out.append((cur[0], cur[1], uL1, uR1))
    return out


def wall_point(g, u, side):
    """Point on the left (+1), right (-1) or centre line (0) at distance u along the wall."""
    return (g["A"][0] + g["d"][0] * u + g["n"][0] * g["h"] * side,
            g["A"][1] + g["d"][1] * u + g["n"][1] * g["h"] * side)


def wall_plan_pieces(story, w, g):
    """Footprint polygons (CCW) of the solid stretches of a wall (openings cut out)."""
    out = []
    for uL0, uR0, uL1, uR1 in wall_intervals(story, w, g):
        out.append([wall_point(g, uR0, -1), wall_point(g, uR1, -1), wall_point(g, uL1, 1), wall_point(g, uL0, 1)])
    return out


def wall_roof_breaks(story, g):
    """Distances along the wall where the roof height changes slope (ridge crossings, roof edges)."""
    ts = set()
    A, B = g["A"], g["B"]
    ln = g["len"]
    if ln < 1:
        return []
    for r in story["roofs"]:
        planes = [p for _, p in roof_planes(r)]

        def f(pl, t):
            return pl[0] * (A[0] + (B[0] - A[0]) * t) + pl[1] * (A[1] + (B[1] - A[1]) * t) + pl[2]
        for i in range(len(planes)):
            for j in range(i + 1, len(planes)):
                d0 = f(planes[i], 0) - f(planes[j], 0)
                d1 = f(planes[i], 1) - f(planes[j], 1)
                if abs(d1 - d0) > 1e-9:
                    t = -d0 / (d1 - d0)
                    if 0.0005 < t < 0.9995:
                        ts.add(t)
        x0, y0, x1, y1 = r["rect"]
        o = r["over"]
        for val, ia in ((x0 - o, 0), (x1 + o, 0), (y0 - o, 1), (y1 + o, 1)):
            da = B[ia] - A[ia]
            if abs(da) > 1e-9:
                t = (val - A[ia]) / da
                if 0.0005 < t < 0.9995:
                    ts.add(t)
    return sorted(t * ln for t in ts)


def top_z(story, elev, x, y, cap):
    """Top of a wall at (x, y): the lower of the wall's own height and the inner roof surface."""
    rh = story_roof_height(story, x, y)
    if rh is None:
        return cap
    return min(cap, elev + rh)


def wall_solids(proj, sidx, w, g, story=None, cut=True):
    """The 3D pieces of a wall as hexahedra: [{"poly": 4 plan corners (CCW), "zb": [4], "zt": [4], "part": str}].
    Openings are cut out (a piece under a window / above a door), the top follows the roof.  `story` = the storey with its
    curved walls expanded (expand_curved), cut=False: the wall is left whole (IFC makes the holes with IfcOpeningElement)."""
    if story is None:
        story = expand_curved(proj["stories"][sidx])
    elev = story_elevations(proj)[sidx]
    zbase = elev - story["floor_t"]
    cap = elev + (w["h"] if w.get("h") else story["height"])
    breaks = wall_roof_breaks(story, g)
    pieces = []

    def stretch(stations, zb, zt_limit, part):
        # stations: [(uL, uR)] from start to end; one piece between neighbouring stations
        for i in range(len(stations) - 1):
            (l0, r0), (l1, r1) = stations[i], stations[i + 1]
            if max(l1 - l0, r1 - r0) < 1.0:
                continue
            poly = [wall_point(g, r0, -1), wall_point(g, r1, -1), wall_point(g, l1, 1), wall_point(g, l0, 1)]
            zt = [top_z(story, elev, p[0], p[1], cap) for p in poly]
            if zt_limit is not None:
                zt = [min(t, zt_limit) for t in zt]
            zt = [max(t, zb) for t in zt]
            if max(t - zb for t in zt) < 1.0:
                continue
            pieces.append({"poly": poly, "zb": [zb] * 4, "zt": zt, "part": part})

    def stations_for(l0, r0, l1, r1):
        st = [(l0, r0)]
        lo, hi = min(l0, r0), max(l1, r1)
        for u in breaks:
            if lo + 1.0 < u < hi - 1.0:
                st.append((u, u))
        st.append((l1, r1))
        return st

    for l0, r0, l1, r1 in wall_intervals(story, w, g, cut):
        stretch(stations_for(l0, r0, l1, r1), zbase, None, "wall")
    for a, b, o in (wall_openings(story, w["id"]) if cut else []):
        a = max(a, 0.0)
        b = min(b, g["len"])
        if b - a < 1.0:
            continue
        st = stations_for(a, a, b, b)
        stretch(st, zbase, elev + o["sill"], "wall")                       # under the opening (slab edge, sill wall)
        stretch(st, elev + o["sill"] + o["h"], None, "wall")                # above the opening
    return pieces


# ---- stairs --------------------------------------------------------------------------------------------------
def stair_total_rise(proj, sidx):
    """Floor-to-floor height a stair of this storey has to climb."""
    el = story_elevations(proj)
    st = proj["stories"]
    if sidx + 1 < len(st):
        return el[sidx + 1] - el[sidx]
    return st[sidx]["height"] + 250.0


def stair_has_floor_above(proj, sidx):
    return sidx + 1 < len(proj["stories"])


def stair_rise(proj, sidx, st=None):
    """The height a given stair climbs: its own 'rise' (an exception typed in by hand) or the floor-to-floor height."""
    if st is not None:
        try:
            r = float(st.get("rise") or 0.0)
        except (TypeError, ValueError):
            r = 0.0
        if r >= 300.0:
            return r
    return stair_total_rise(proj, sidx)


STAIR_KINDS = ["straight", "L", "spiral", "lift"]     # "lift" = elevator shaft (w x dep), no steps
LIFT_W, LIFT_DEP = 1100.0, 1400.0                       # default inside size of a passenger lift cabin + shaft


def stair_steps_for(rise, riser=175.0):
    """Number of risers for a floor-to-floor height, aiming at a riser height of about `riser` mm (at least 3)."""
    try:
        riser = max(100.0, float(riser))
    except (TypeError, ValueError):
        riser = 175.0
    return max(3, int(round(rise / riser)))


def stair_best_steps(rise, length):
    """AUTO number of risers for the space there is: the one whose riser R and tread T come closest to the comfort rule
    2*R + T = 630 mm (riser kept between 120 and 220 mm when possible).  Never refuses: a short run just gives steep stairs."""
    best, bn = None, 3
    for n in range(3, 61):
        R = rise / float(n)
        T = length / float(n - 1)
        score = abs(2.0 * R + T - 630.0) + 4.0 * max(0.0, R - 220.0, 120.0 - R)
        if best is None or score < best:
            best, bn = score, n
    return bn


def stair_from_width_and_run(a, b, cursor, rise, riser=175.0, top=False):
    """The straight stairs that are drawn like a wall: A-B is the WIDTH of one end of the stairs, the cursor tells which
    side the stairs run to and how long they are.  top=False: A-B is the foot (bottom), they climb towards the cursor;
    top=True: A-B is the TOP edge (where you step onto the floor above), they go DOWN towards the cursor.
    riser = wanted riser height in mm, or None = automatic: the number of steps is chosen to fit the length you pull out.
    Returns a dict with x, y (the foot), rot, w, n, tread, length, slope (deg), riser, ok (comfortable: tread 200-350 mm,
    slope <= 42 deg) or None when A-B is too short or the cursor is on the line."""
    w = dist(a, b)
    if w < 300.0:
        return None
    e = v_unit(v_sub(b, a))
    nrm = v_perp(e)
    mid = ((a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0)
    s = v_dot(v_sub(cursor, mid), nrm)
    if abs(s) < 1.0:
        return None
    d = v_mul(nrm, 1.0 if s > 0 else -1.0)             # from the clicked edge towards the cursor
    length = abs(s)
    n = stair_best_steps(rise, length) if riser is None else stair_steps_for(rise, riser)
    tread = length / (n - 1)
    R = rise / n
    slope = math.degrees(math.atan2(R, tread))
    if top:
        c = v_mul(d, -1.0)                               # climbing direction is back towards the clicked edge
        foot = (mid[0] + d[0] * length, mid[1] + d[1] * length)
    else:
        c, foot = d, mid
    return {"x": foot[0], "y": foot[1], "rot": math.degrees(math.atan2(-c[0], c[1])) % 360.0, "w": w, "n": n,
            "tread": tread, "length": length, "slope": slope, "riser": R, "ok": 200.0 <= tread <= 350.0 and slope <= 42.0}


def add_stair(proj, story, sidx, x, y, kind="straight", rot=0.0, w=900.0, tread=250.0, n=None, turn="R", dep=None, rise=None):
    own = bool(rise)
    rise = float(rise) if rise else stair_total_rise(proj, sidx)
    if n is None:
        n = stair_steps_for(rise)
    if kind == "lift":
        w = LIFT_W if w == 900.0 else w
    s = {"id": uid(proj), "kind": kind, "x": float(x), "y": float(y), "rot": float(rot), "w": float(w),
         "tread": float(tread), "n": int(n), "turn": turn, "r": 1000.0, "ang": 22.5, "cw": 0,
         "dep": float(dep if dep is not None else LIFT_DEP)}
    if own and (abs(rise - stair_total_rise(proj, sidx)) > 0.5 or not stair_has_floor_above(proj, sidx)):
        s["rise"] = float(rise)                      # an exception: this stair does not climb exactly one floor
    story["stairs"].append(s)
    return s


def stair_layout(st, total_rise):
    """Local geometry of a stair (origin = start of the first step, middle of its width, +y = direction of the first
    flight, spiral: origin = centre).  Returns dict: outline, treads [(poly, ztop)], lines [(p, q)], arrow [pts],
    n, rise, solid (bool)."""
    n = max(2, int(st["n"]))
    R = total_rise / n
    T = st["tread"]
    w = st["w"]
    kind = st["kind"]
    treads, lines = [], []
    if kind == "lift":                         # elevator: a shaft rectangle with a cross, no steps
        hw = w / 2.0
        dep = st.get("dep", LIFT_DEP)
        return {"outline": [(-hw, 0), (hw, 0), (hw, dep), (-hw, dep)], "treads": [],
                "lines": [((-hw, 0), (hw, dep)), ((-hw, dep), (hw, 0))],
                "arrow": [(0, dep * 0.3), (0, dep * 0.7)], "n": 1, "rise": total_rise, "solid": True}
    if kind == "spiral":
        rad = st["r"]
        rin = 100.0
        th = st["ang"] * (-1 if st.get("cw") else 1)
        a0 = 90.0
        for k in range(1, n):
            ang0 = a0 + (k - 1) * th
            ang1 = a0 + k * th
            poly = [(rin * math.cos(math.radians(ang0)), rin * math.sin(math.radians(ang0))),
                    (rad * math.cos(math.radians(ang0)), rad * math.sin(math.radians(ang0))),
                    (rad * math.cos(math.radians(ang1)), rad * math.sin(math.radians(ang1))),
                    (rin * math.cos(math.radians(ang1)), rin * math.sin(math.radians(ang1)))]
            treads.append((poly, k * R))
            lines.append((poly[0], poly[1]))
        outline = [(rad * math.cos(math.radians(i * 15)), rad * math.sin(math.radians(i * 15))) for i in range(24)]
        mid = rad * 0.6
        arrow = [(mid * math.cos(math.radians(a0 + (j + 0.5) * th)), mid * math.sin(math.radians(a0 + (j + 0.5) * th)))
                 for j in range(n - 1)]
        return {"outline": outline, "treads": treads, "lines": lines, "arrow": arrow, "n": n, "rise": R, "solid": False}
    if kind == "L":
        a = max(1, (n - 2) // 2)
        b = max(0, n - 2 - a)
        s = 1.0 if st.get("turn", "R") == "R" else -1.0
        hw = w / 2.0
        for k in range(1, a + 1):
            treads.append(([(-hw, (k - 1) * T), (hw, (k - 1) * T), (hw, k * T), (-hw, k * T)], k * R))
            lines.append(((-hw, k * T), (hw, k * T)))
        ly = a * T
        treads.append(([(-hw, ly), (hw, ly), (hw, ly + w), (-hw, ly + w)], (a + 1) * R))
        for j in range(1, b + 1):
            x0, x1 = s * (hw + (j - 1) * T), s * (hw + j * T)
            treads.append(([(x0, ly), (x1, ly), (x1, ly + w), (x0, ly + w)], (a + 1 + j) * R))
            lines.append(((x1, ly), (x1, ly + w)))
        xe = s * (hw + b * T)
        outline = [(-hw, 0), (hw, 0), (hw, ly), (xe, ly), (xe, ly + w), (-hw, ly + w)]
        if s < 0:
            outline = outline[::-1]
        arrow = [(0, T / 2), (0, ly + w / 2), (xe - s * T / 2, ly + w / 2)]
        return {"outline": outline, "treads": treads, "lines": lines, "arrow": arrow, "n": n, "rise": R, "solid": True}
    hw = w / 2.0
    for k in range(1, n):
        treads.append(([(-hw, (k - 1) * T), (hw, (k - 1) * T), (hw, k * T), (-hw, k * T)], k * R))
        lines.append(((-hw, k * T), (hw, k * T)))
    L = (n - 1) * T
    return {"outline": [(-hw, 0), (hw, 0), (hw, L), (-hw, L)], "treads": treads, "lines": lines,
            "arrow": [(0, T / 2), (0, max(T, L - T / 2))], "n": n, "rise": R, "solid": True}


def stair_to_world(st, pts):
    return [v_add(rot_pt(p, st["rot"]), (st["x"], st["y"])) for p in pts]


def stair_world_outline(proj, sidx, st):
    lay = stair_layout(st, stair_rise(proj, sidx, st))
    return stair_to_world(st, lay["outline"])


# *************** DEL 25 - ITEM CATALOG (furniture, sanitary, kitchen, electrical): plan symbols + 3D boxes *****************
# Item local frame: origin = centre of the item, +y = the BACK (the side that goes against a wall), +x = to the right when
# you look at the front.  Rotation turns the item counter-clockwise on the plan.  z = height of the item's underside above
# the floor (outlets, wall cabinets); z = -1 means "hangs from the ceiling".
# ToDo: more types (corner kitchen, stairs railings, fixed wardrobes under the roof slope); user-made catalog entries.

# key: (name, category, w, d, h, z, material, symbol, ifc class, wall-snap)
_CAT = [
    ("wc", "Toilet", "Bathroom", 400, 700, 800, 0, "sanitary", "wc", "IfcSanitaryTerminal", True),
    ("basin", "Basin", "Bathroom", 550, 450, 850, 0, "sanitary", "basin", "IfcSanitaryTerminal", True),
    ("basin2", "Double basin", "Bathroom", 1200, 500, 850, 0, "sanitary", "basin2", "IfcSanitaryTerminal", True),
    ("shower", "Shower 90x90", "Bathroom", 900, 900, 2000, 0, "sanitary", "shower", "IfcSanitaryTerminal", True),
    ("shower2", "Shower 120x80", "Bathroom", 1200, 800, 2000, 0, "sanitary", "shower", "IfcSanitaryTerminal", True),
    ("bath", "Bathtub", "Bathroom", 1700, 750, 550, 0, "sanitary", "bath", "IfcSanitaryTerminal", True),
    ("washer", "Washing machine", "Bathroom", 600, 600, 850, 0, "appliance", "washer", "IfcElectricAppliance", True),
    ("dryer", "Tumble dryer", "Bathroom", 600, 600, 850, 0, "appliance", "washer", "IfcElectricAppliance", True),
    ("towelrad", "Towel radiator", "Bathroom", 500, 100, 1000, 300, "heat", "radiator", "IfcSpaceHeater", True),

    ("counter", "Base cabinet 60", "Kitchen", 600, 600, 900, 0, "wood_light", "cabinet", "IfcFurniture", True),
    ("counter2", "Base cabinet 120", "Kitchen", 1200, 600, 900, 0, "wood_light", "cabinet", "IfcFurniture", True),
    ("wallcab", "Wall cabinet", "Kitchen", 600, 350, 700, 1400, "wood_light", "cabinet", "IfcFurniture", True),
    ("ksink", "Kitchen sink", "Kitchen", 1200, 600, 900, 0, "wood_light", "ksink", "IfcSanitaryTerminal", True),
    ("stove", "Cooker / hob", "Kitchen", 600, 600, 900, 0, "appliance", "stove", "IfcElectricAppliance", True),
    ("fridge", "Fridge-freezer", "Kitchen", 600, 650, 1850, 0, "appliance", "fridge", "IfcElectricAppliance", True),
    ("fridge_low", "Under-counter fridge", "Kitchen", 600, 600, 850, 0, "appliance", "fridge", "IfcElectricAppliance", True),
    ("dishwasher", "Dishwasher", "Kitchen", 600, 600, 850, 0, "appliance", "washer", "IfcElectricAppliance", True),
    ("island", "Kitchen island", "Kitchen", 1800, 900, 900, 0, "wood_light", "cabinet", "IfcFurniture", False),
    # floor-to-ceiling units (2300 mm; change the height in the panel to fit your ceiling)
    ("tall40", "Tall cabinet 40 (floor to ceiling)", "Kitchen", 400, 600, 2300, 0, "wood_light", "tall", "IfcFurniture", True),
    ("tall60", "Tall cabinet 60 (floor to ceiling)", "Kitchen", 600, 600, 2300, 0, "wood_light", "tall", "IfcFurniture", True),
    ("tall80", "Tall cabinet 80 (floor to ceiling)", "Kitchen", 800, 600, 2300, 0, "wood_light", "tall", "IfcFurniture", True),
    ("tall120", "Tall cabinet 120, 2 doors (kitchen wardrobe)", "Kitchen", 1200, 600, 2300, 0, "wood_light", "tall", "IfcFurniture", True),
    ("larder60", "Larder / pantry 60 (floor to ceiling)", "Kitchen", 600, 600, 2300, 0, "wood_light", "pantry", "IfcFurniture", True),
    ("larder90", "Larder / pantry 90 (floor to ceiling)", "Kitchen", 900, 600, 2300, 0, "wood_light", "pantry", "IfcFurniture", True),
    ("larder120", "Larder / pantry 120, double (floor to ceiling)", "Kitchen", 1200, 600, 2300, 0, "wood_light", "pantry", "IfcFurniture", True),
    ("tall_oven", "Tall oven cabinet 60 (built-in oven)", "Kitchen", 600, 600, 2300, 0, "wood_light", "tall_oven", "IfcFurniture", True),
    ("tall_fridge", "Tall fridge cabinet 60 (built-in fridge-freezer)", "Kitchen", 600, 650, 2300, 0, "wood_light", "tall_fridge", "IfcFurniture", True),
    ("fridge_top", "Cabinet above fridge-freezer", "Kitchen", 600, 600, 450, 1850, "wood_light", "cabinet", "IfcFurniture", True),

    ("bed1", "Bed 90", "Bedroom", 900, 2000, 500, 0, "fabric", "bed", "IfcFurniture", True),
    ("bed120", "Bed 120", "Bedroom", 1200, 2000, 500, 0, "fabric", "bed", "IfcFurniture", True),
    ("bed2", "Bed 160 (double)", "Bedroom", 1600, 2000, 500, 0, "fabric", "bed", "IfcFurniture", True),
    ("bed180", "Bed 180 (king)", "Bedroom", 1800, 2000, 500, 0, "fabric", "bed", "IfcFurniture", True),
    ("bunk", "Bunk bed", "Bedroom", 900, 2000, 1700, 0, "wood", "bunk", "IfcFurniture", True),
    ("crib", "Cot", "Bedroom", 600, 1200, 900, 0, "wood_light", "bed", "IfcFurniture", True),
    ("wardrobe", "Wardrobe 100", "Bedroom", 1000, 600, 2100, 0, "wood_light", "wardrobe", "IfcFurniture", True),
    ("wardrobe2", "Wardrobe 180", "Bedroom", 1800, 600, 2100, 0, "wood_light", "wardrobe", "IfcFurniture", True),
    ("dresser", "Chest of drawers", "Bedroom", 1000, 500, 900, 0, "wood", "cabinet", "IfcFurniture", True),
    ("nightstand", "Bedside table", "Bedroom", 450, 400, 500, 0, "wood", "cabinet", "IfcFurniture", True),

    ("sofa2", "Sofa 2-seat", "Living", 1600, 900, 850, 0, "fabric", "sofa", "IfcFurniture", True),
    ("sofa3", "Sofa 3-seat", "Living", 2100, 900, 850, 0, "fabric", "sofa", "IfcFurniture", True),
    ("armchair", "Armchair", "Living", 850, 850, 850, 0, "fabric", "sofa", "IfcFurniture", False),
    ("coffee", "Coffee table", "Living", 1000, 600, 450, 0, "wood", "table", "IfcFurniture", False),
    ("tvbench", "TV bench", "Living", 1600, 450, 500, 0, "wood", "cabinet", "IfcFurniture", True),
    ("bookshelf", "Bookshelf 80", "Living", 800, 300, 2000, 0, "wood", "bookshelf", "IfcFurniture", True),
    ("bookshelf2", "Bookshelf 120", "Living", 1200, 300, 2000, 0, "wood", "bookshelf", "IfcFurniture", True),
    ("bookshelf_low", "Low bookshelf", "Living", 800, 300, 1000, 0, "wood", "bookshelf", "IfcFurniture", True),
    ("sideboard", "Sideboard", "Living", 1600, 450, 800, 0, "wood", "cabinet", "IfcFurniture", True),
    ("woodstove", "Wood stove / fireplace", "Living", 600, 500, 1100, 0, "metal", "fireplace", "IfcFurniture", True),

    ("dining", "Dining table", "Dining & work", 1600, 900, 750, 0, "wood", "table", "IfcFurniture", False),
    ("tableround", "Round table", "Dining & work", 1000, 1000, 750, 0, "wood", "tableround", "IfcFurniture", False),
    ("chair", "Chair", "Dining & work", 450, 450, 850, 0, "wood", "chair", "IfcFurniture", False),
    ("desk", "Desk", "Dining & work", 1400, 700, 750, 0, "wood", "table", "IfcFurniture", True),
    ("ochair", "Office chair", "Dining & work", 550, 550, 900, 0, "fabric", "chair", "IfcFurniture", False),

    ("pantry", "Pantry cupboard", "Storage", 600, 600, 2100, 0, "wood_light", "pantry", "IfcFurniture", True),
    ("pantryshelf", "Pantry shelving", "Storage", 2000, 400, 2100, 0, "wood_light", "pantry", "IfcFurniture", True),
    ("shoes", "Shoe cabinet", "Storage", 800, 350, 1000, 0, "wood_light", "bookshelf", "IfcFurniture", True),

    ("outlet", "Outlet", "Electrical", 180, 60, 80, 300, "elec", "outlet", "IfcOutlet", True),
    ("outlet2", "Double outlet", "Electrical", 300, 60, 80, 300, "elec", "outlet2", "IfcOutlet", True),
    ("outlet_hi", "Outlet (worktop height)", "Electrical", 180, 60, 80, 1100, "elec", "outlet", "IfcOutlet", True),
    ("switch", "Light switch", "Electrical", 180, 60, 80, 1100, "elec", "switch", "IfcSwitchingDevice", True),
    ("data", "Data / TV outlet", "Electrical", 180, 60, 80, 300, "elec", "data", "IfcOutlet", True),
    ("lightc", "Ceiling light", "Electrical", 300, 300, 60, -1, "elec", "lightc", "IfcLightFixture", False),
    ("lightw", "Wall light", "Electrical", 200, 120, 120, 1900, "elec", "lightw", "IfcLightFixture", True),
    ("smoke", "Smoke detector", "Electrical", 150, 150, 40, -1, "elec", "smoke", "IfcSensor", False),
    ("fusebox", "Fuse box", "Electrical", 400, 120, 600, 1400, "elec", "fusebox", "IfcElectricDistributionBoard", True),

    ("radiator", "Radiator", "Heating", 1000, 100, 600, 150, "heat", "radiator", "IfcSpaceHeater", True),
    ("hp_out", "Heat pump, outdoor unit (air)", "Heating", 1100, 450, 900, 0, "metal", "hp_out", "IfcUnitaryEquipment", True),
    ("hp_in", "Heat pump, indoor unit (tank + pump)", "Heating", 600, 700, 1800, 0, "appliance", "hp_in", "IfcUnitaryEquipment", True),
    ("hp_exh", "Exhaust-air heat pump (indoor)", "Heating", 600, 600, 1800, 0, "appliance", "hp_in", "IfcUnitaryEquipment", True),
    ("hp_split", "Air-to-air heat pump, wall unit", "Heating", 900, 250, 300, 1900, "appliance", "hp_split", "IfcUnitaryEquipment", True),
    ("hwtank", "Hot-water cylinder", "Heating", 600, 600, 1700, 0, "appliance", "tank", "IfcTank", True),
    ("boiler", "Boiler / electric boiler", "Heating", 600, 450, 850, 0, "appliance", "boiler", "IfcBoiler", True),

    # Chimney + ventilation.  h = 0 means "as tall as the storey" (set when the item is placed, editable afterwards).  Such a
    # shaft is shown as a dashed ghost on the storeys above it as long as it reaches them (see plan_prims).
    ("chimney", "Chimney 400 x 400 (brick / block)", "Chimney & ventilation", 400, 400, 0, 0, "brick", "chimney", "IfcBuildingElementProxy", False),
    ("chimney2", "Chimney 500 x 500 (brick / block)", "Chimney & ventilation", 500, 500, 0, 0, "brick", "chimney", "IfcBuildingElementProxy", False),
    ("flue", "Flue pipe, round (steel)", "Chimney & ventilation", 200, 200, 0, 0, "metal", "flue", "IfcBuildingElementProxy", False),
    ("vent_shaft", "Ventilation shaft 300 x 200", "Chimney & ventilation", 300, 200, 0, 0, "duct", "vent_shaft", "IfcDuctSegment", False),
    ("vent_pipe", "Ventilation pipe, round 160", "Chimney & ventilation", 160, 160, 0, 0, "duct", "vent_pipe", "IfcDuctSegment", False),
    ("vent_pipe125", "Ventilation pipe, round 125", "Chimney & ventilation", 125, 125, 0, 0, "duct", "vent_pipe", "IfcDuctSegment", False),
    ("vent_duct", "Ventilation duct, horizontal (under ceiling)", "Chimney & ventilation", 2000, 200, 200, -1, "duct", "vent_duct", "IfcDuctSegment", False),
    ("vent_valve", "Air valve (ceiling)", "Chimney & ventilation", 160, 160, 60, -1, "duct", "vent_valve", "IfcAirTerminal", False),
    ("vent_unit", "Ventilation unit (heat recovery)", "Chimney & ventilation", 800, 600, 1200, 0, "appliance", "vent_unit", "IfcUnitaryEquipment", True),
    ("hood", "Cooker hood", "Chimney & ventilation", 600, 450, 400, 1600, "metal", "hood", "IfcAirTerminal", True),
]

CATALOG = {}
CATEGORIES = []
for _k, _n, _c, _w, _d, _h, _z, _m, _s, _i, _sn in _CAT:
    CATALOG[_k] = {"key": _k, "name": _n, "cat": _c, "w": _w, "d": _d, "h": _h, "z": _z, "mat": _m, "sym": _s,
                   "ifc": _i, "snap": _sn}
    if _c not in CATEGORIES:
        CATEGORIES.append(_c)

CAT_LAYER = {"Bathroom": "A-FURN-SANI", "Kitchen": "A-FURN-CASE", "Bedroom": "A-FURN", "Living": "A-FURN",
             "Dining & work": "A-FURN", "Storage": "A-FURN-CASE", "Electrical": "E-POWR", "Heating": "M-HVAC",
             "Chimney & ventilation": "M-HVAC"}


def is_shaft(it):
    """True for chimneys / flues / vent shafts: catalog height 0 = a vertical shaft that runs up through the floors."""
    c = CATALOG.get(it["type"])
    return bool(c) and c["h"] <= 0


def add_item(proj, story, typ, x, y, rot=0.0, **over):
    c = CATALOG[typ]
    h = float(c["h"]) if c["h"] > 0 else float(story.get("height", 2500))        # shafts are as tall as the storey
    it = {"id": uid(proj), "type": typ, "x": float(x), "y": float(y), "rot": float(rot), "w": float(c["w"]),
          "d": float(c["d"]), "h": h, "z": float(c["z"]), "label": ""}
    if c["h"] <= 0:
        it["up"] = 1                                           # shaft: continues up through the storeys above
    for k, v in over.items():
        it[k] = v
    story["items"].append(it)
    return it


def item_layer(it):
    c = CATALOG.get(it["type"])
    if not c:
        return "A-FURN"
    if it["type"] in ("lightc", "lightw", "smoke"):
        return "E-LITE"
    return CAT_LAYER.get(c["cat"], "A-FURN")


def item_to_world(it, p):
    q = rot_pt(p, it["rot"])
    return (q[0] + it["x"], q[1] + it["y"])


def item_outline(it):
    """World polygon of the item's footprint."""
    w, d = it["w"] / 2.0, it["d"] / 2.0
    return [item_to_world(it, p) for p in ((-w, -d), (w, -d), (w, d), (-w, d))]


def _rect(cx, cy, w, d):
    return [(cx - w / 2, cy - d / 2), (cx + w / 2, cy - d / 2), (cx + w / 2, cy + d / 2), (cx - w / 2, cy + d / 2)]


def _ell(cx, cy, rx, ry, n=28):
    return [(cx + rx * math.cos(2 * math.pi * i / n), cy + ry * math.sin(2 * math.pi * i / n)) for i in range(n)]


def item_symbol(it):
    """Plan symbol in LOCAL coordinates: [("p", pts, closed) | ("c", cx, cy, r) | ("t", x, y, text, height)]."""
    w, d = it["w"], it["d"]
    sym = CATALOG[it["type"]]["sym"] if it["type"] in CATALOG else "box"
    out = [("p", _rect(0, 0, w, d), True)]
    hw, hd = w / 2.0, d / 2.0
    if sym == "wc":
        out.append(("p", _rect(0, hd - 0.14 * d, w, 0.28 * d), True))
        out.append(("p", _ell(0, -0.14 * d, 0.46 * w, 0.36 * d), True))
    elif sym in ("basin", "basin2"):
        n = 2 if sym == "basin2" else 1
        for i in range(n):
            cx = (i - (n - 1) / 2.0) * w / n
            out.append(("p", _ell(cx, -0.05 * d, 0.34 * w / n * (1 if n == 1 else 1.2), 0.32 * d), True))
            out.append(("c", cx, hd - 0.12 * d, 25))
    elif sym == "shower":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(-hw, hd), (hw, -hd)], False))
        out.append(("c", 0, 0, 40))
    elif sym == "bath":
        out.append(("p", _rect(0, 0, w - 120, d - 120), True))
        out.append(("c", -hw + 160, 0, 30))
    elif sym == "washer":
        out.append(("c", 0, -0.05 * d, 0.32 * min(w, d)))
        out.append(("c", 0, -0.05 * d, 0.2 * min(w, d)))
    elif sym == "ksink":
        out.append(("p", _rect(-w * 0.22, 0, w * 0.4, d * 0.7), True))
        out.append(("p", _rect(w * 0.22, 0, w * 0.4, d * 0.7), True))
        out.append(("c", 0, hd - 0.1 * d, 20))
    elif sym == "stove":
        for sx in (-1, 1):
            for sy in (-1, 1):
                out.append(("c", sx * w * 0.22, sy * d * 0.22, w * 0.15))
    elif sym == "fridge":
        out.append(("p", [(-hw, hd - 0.12 * d), (hw, hd - 0.12 * d)], False))
        out.append(("t", 0, 0, "F", 160))
    elif sym == "cabinet":
        out.append(("p", [(-hw, -hd + 40), (hw, -hd + 40)], False))
    elif sym == "bed":
        pw = w * 0.42 if w > 1000 else w * 0.72
        if w > 1000:
            out.append(("p", _rect(-w * 0.24, hd - 260, pw, 400), True))
            out.append(("p", _rect(w * 0.24, hd - 260, pw, 400), True))
        else:
            out.append(("p", _rect(0, hd - 260, pw, 400), True))
        out.append(("p", [(-hw, hd - 700), (hw, hd - 700)], False))
    elif sym == "bunk":
        out.append(("p", _rect(0, hd - 260, w * 0.72, 400), True))
        out.append(("p", [(-hw, -hd + 80), (hw, -hd + 80)], False))
    elif sym == "sofa":
        out.append(("p", _rect(0, hd - 0.13 * d, w, 0.26 * d), True))
        out.append(("p", _rect(-hw + 70, 0, 140, d), True))
        out.append(("p", _rect(hw - 70, 0, 140, d), True))
    elif sym == "table":
        out.append(("p", _rect(0, 0, w - 80, d - 80), True))
    elif sym == "tableround":
        out = [("p", _ell(0, 0, w / 2, d / 2, 36), True)]
    elif sym == "chair":
        out.append(("p", [(-hw, hd - 50), (hw, hd - 50)], False))
    elif sym == "wardrobe":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(0, -hd), (0, hd)], False))
    elif sym in ("bookshelf", "pantry"):
        n = max(2, int(w / 200))
        for i in range(1, n):
            x = -hw + i * w / n
            out.append(("p", [(x, hd - d * 0.45), (x, hd)], False))
        if sym == "pantry":
            out.append(("t", 0, -d * 0.12, "Pantry", min(150, w / 6.0)))
    elif sym in ("tall", "tall_oven", "tall_fridge"):       # floor-to-ceiling unit: front line + cross (= tall unit in CAD)
        out.append(("p", [(-hw, -hd + 40), (hw, -hd + 40)], False))
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(-hw, hd), (hw, -hd)], False))
        if w >= 1000:                                       # two doors
            out.append(("p", [(0, -hd), (0, -hd + 40)], False))
        if sym == "tall_oven":
            out.append(("c", 0, 0, 0.26 * min(w, d)))
            out.append(("t", 0, 0, "OV", min(120, w * 0.2)))
        elif sym == "tall_fridge":
            out.append(("t", 0, 0, "F", 150))
    elif sym == "fireplace":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(-hw, hd), (hw, -hd)], False))
    elif sym == "radiator":
        n = max(3, int(w / 60))
        for i in range(1, n):
            x = -hw + i * w / n
            out.append(("p", [(x, -hd), (x, hd)], False))
    elif sym in ("outlet", "outlet2"):
        out = []
        cnt = 2 if sym == "outlet2" else 1
        for i in range(cnt):
            cx = (i - (cnt - 1) / 2.0) * 130
            out.append(("c", cx, 0, 60))
        out.append(("p", [(-hw, hd), (hw, hd)], False))
    elif sym == "switch":
        out = [("c", 0, 0, 50), ("p", [(0, 0), (0, 150)], False), ("p", [(-80, 150), (80, 150)], False)]
    elif sym == "data":
        out = [("p", [(-70, -60), (70, -60), (0, 80)], True)]
    elif sym == "lightc":
        out = [("c", 0, 0, w / 2), ("p", [(-w / 2 * .7, -w / 2 * .7), (w / 2 * .7, w / 2 * .7)], False),
               ("p", [(-w / 2 * .7, w / 2 * .7), (w / 2 * .7, -w / 2 * .7)], False)]
    elif sym == "lightw":
        out = [("c", 0, -20, 70), ("p", [(-100, hd), (100, hd)], False)]
    elif sym == "smoke":
        out = [("c", 0, 0, 70), ("t", 0, 0, "S", 80)]
    elif sym == "fusebox":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
    elif sym == "hp_out":                                   # outdoor unit: box with a fan
        r = 0.36 * min(w, d)
        out.append(("c", -w * 0.2, 0, r))
        out.append(("c", -w * 0.2, 0, r * 0.35))
        out.append(("p", [(w * 0.18, -hd + 40), (w * 0.18, hd - 40)], False))
        out.append(("t", w * 0.34, 0, "HP", min(130, d * 0.4)))
    elif sym == "hp_in":                                    # indoor unit (tank + pump)
        out.append(("c", 0, 0.1 * d, 0.3 * min(w, d)))
        out.append(("t", 0, 0.1 * d, "HP", min(150, min(w, d) * 0.28)))
    elif sym == "hp_split":                                 # wall-hung air-to-air unit
        for i in (-1, 0, 1):
            out.append(("p", [(-hw + 60, i * d * 0.25), (hw - 60, i * d * 0.25)], False))
        out.append(("t", 0, -d * 1.1, "HP", 130))
    elif sym == "tank":
        out = [("c", 0, 0, 0.5 * min(w, d)), ("c", 0, 0, 0.36 * min(w, d)), ("t", 0, 0, "HW", min(150, min(w, d) * 0.25))]
    elif sym == "boiler":
        out.append(("t", 0, 0, "B", min(200, min(w, d) * 0.4)))
    elif sym in ("chimney", "flue"):                        # masonry stack: outer square, flue square, diagonals
        if sym == "flue":
            out = [("c", 0, 0, w / 2.0), ("c", 0, 0, w / 2.0 - 25)]
            out.append(("p", [(-w * 0.35, -w * 0.35), (w * 0.35, w * 0.35)], False))
            out.append(("p", [(-w * 0.35, w * 0.35), (w * 0.35, -w * 0.35)], False))
        else:
            ins = 100.0
            out.append(("p", _rect(0, 0, w - 2 * ins, d - 2 * ins), True))
            out.append(("p", [(-hw + ins, -hd + ins), (hw - ins, hd - ins)], False))
            out.append(("p", [(-hw + ins, hd - ins), (hw - ins, -hd + ins)], False))
    elif sym == "vent_shaft":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(-hw, hd), (hw, -hd)], False))
        out.append(("t", 0, 0, "V", min(100, d * 0.5)))
    elif sym == "vent_pipe":                                # round ventilation pipe seen from above
        out = [("c", 0, 0, w / 2.0), ("c", 0, 0, w / 2.0 * 0.62), ("t", 0, 0, "V", max(50, w * 0.45))]
    elif sym == "vent_duct":                                # horizontal duct, centre line + end crosses
        out.append(("p", [(-hw, 0), (hw, 0)], False))
        out.append(("p", [(-hw, -hd), (-hw + d, hd)], False))
        out.append(("p", [(hw - d, -hd), (hw, hd)], False))
        out.append(("t", 0, 0, "V", min(100, d * 0.5)))
    elif sym == "vent_valve":
        out = [("c", 0, 0, w / 2.0), ("c", 0, 0, w / 2.0 * 0.55), ("p", [(-w / 2.0, 0), (w / 2.0, 0)], False),
               ("p", [(0, -w / 2.0), (0, w / 2.0)], False)]
    elif sym == "vent_unit":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(-hw, hd), (hw, -hd)], False))
        out.append(("t", 0, 0, "VU", min(150, d * 0.3)))
    elif sym == "hood":
        out.append(("p", [(-hw, -hd), (hw, hd)], False))
        out.append(("p", [(-hw, hd), (hw, -hd)], False))
    if it.get("label"):
        out.append(("t", 0, 0, it["label"], min(150, max(60, w / 8.0))))
    return out


def item_boxes(it):
    """3D shape of an item as boxes (x0, y0, z0, x1, y1, z1, material) in the item frame (z from the item's base)."""
    c = CATALOG.get(it["type"])
    w, d, h = it["w"], it["d"], it["h"]
    hw, hd = w / 2.0, d / 2.0
    m = c["mat"] if c else "wood"
    sym = c["sym"] if c else "box"
    if sym == "bed":
        return [(-hw, -hd, 0, hw, hd, 300, "wood"), (-hw + 30, -hd + 30, 300, hw - 30, hd - 30, h, "fabric"),
                (-hw, hd - 60, 0, hw, hd, h + 400, "wood")]
    if sym == "bunk":
        return [(-hw, -hd, 0, hw, hd, 300, "wood"), (-hw + 30, -hd + 30, 300, hw - 30, hd - 30, 500, "fabric"),
                (-hw, -hd, 1150, hw, hd, 1250, "wood"), (-hw + 30, -hd + 30, 1250, hw - 30, hd - 30, 1450, "fabric"),
                (-hw, -hd, 0, -hw + 60, -hd + 60, h, "wood"), (hw - 60, -hd, 0, hw, -hd + 60, h, "wood"),
                (-hw, hd - 60, 0, -hw + 60, hd, h, "wood"), (hw - 60, hd - 60, 0, hw, hd, h, "wood")]
    if sym == "sofa":
        return [(-hw, -hd, 0, hw, hd, 420, m), (-hw, hd - 0.25 * d, 420, hw, hd, h, m),
                (-hw, -hd, 420, -hw + 150, hd - 0.25 * d, 650, m), (hw - 150, -hd, 420, hw, hd - 0.25 * d, 650, m)]
    if sym == "chair":
        return [(-hw, -hd, 0, hw, hd, 450, m), (-hw, hd - 50, 450, hw, hd, h, m)]
    if sym in ("table", "tableround"):
        lg = 60.0
        top = h - 40
        return [(-hw, -hd, top, hw, hd, h, m), (-hw + 40, -hd + 40, 0, -hw + 40 + lg, -hd + 40 + lg, top, m),
                (hw - 40 - lg, -hd + 40, 0, hw - 40, -hd + 40 + lg, top, m),
                (-hw + 40, hd - 40 - lg, 0, -hw + 40 + lg, hd - 40, top, m),
                (hw - 40 - lg, hd - 40 - lg, 0, hw - 40, hd - 40, top, m)]
    if sym == "wc":
        return [(-hw, -hd, 0, hw, hd - 0.28 * d, 420, m), (-hw, hd - 0.28 * d, 0, hw, hd, h, m)]
    if sym == "shower":
        return [(-hw, -hd, 0, hw, hd, 80, m), (-hw, -hd, 80, hw, -hd + 10, h, "glass"),
                (-hw, -hd, 80, -hw + 10, hd, h, "glass")]
    if sym in ("basin", "basin2"):
        return [(-hw, -hd, h - 160, hw, hd, h, m), (-60, hd - 140, 0, 60, hd - 20, h - 160, m)]
    return [(-hw, -hd, 0, hw, hd, h, m)]


# *************** DEL 26 - DORMERS AND ROOF WINDOWS (on the roof of an attic storey) *****************
# A dormer stands on the roof slope: vertical front wall (with a window), two cheek walls that run back until they meet the
# roof, and its own little roof (gable / shed / flat).  Its position is the middle of its FRONT face; `rot` is the direction
# the front faces (0 = south, 90 = east ...).  Local frame: u = across (to the right of the front), v = into the roof.
# The dormer's inner ceiling is a set of planes just like the main roof's (relative to the storey floor), so headroom areas and
# wall heights can use it.  A roof window lies IN the roof plane at its position.
# The main roof is cut open under a dormer / roof window (build_mesh splits the roof facets around the hole); in the IFC file the
# roof stays whole and an IfcOpeningElement makes the hole instead.
# ToDo: hip dormers, dormers with an eyebrow roof, ridge-to-ridge dormers (trapezoid wall dormer).

DORMER_KINDS = [("gable", "Gable dormer"), ("shed", "Shed dormer"), ("flat", "Flat dormer")]
DORMER_WT = 150.0
_DORMER_MEMO = {}


def add_dormer(proj, story, x, y, rot=0.0, kind="gable", w=1800.0, fh=1300.0, pitch=30.0, d=0.0, win_w=900.0,
               win_h=900.0, sill=200.0):
    """d = 0 means: as deep as it has to be to meet the roof (computed)."""
    dm = {"id": uid(proj), "kind": kind, "x": float(x), "y": float(y), "rot": float(rot), "w": float(w), "d": float(d),
          "fh": float(fh), "pitch": float(pitch), "over": 150.0, "rt": 120.0, "wt": DORMER_WT,
          "win_w": float(win_w), "win_h": float(win_h), "sill": float(sill)}
    story["dormers"].append(dm)
    return dm


def add_rwin(proj, story, x, y, w=780.0, h=1180.0):
    rw = {"id": uid(proj), "x": float(x), "y": float(y), "w": float(w), "h": float(h)}
    story["rwins"].append(rw)
    return rw


# ---- the main roof under a point -----------------------------------------------------------------------------
def host_roof_height(story, x, y):
    """Highest inner surface of the MAIN roofs over (x, y) (relative to the floor), or None."""
    best = None
    for r in story["roofs"]:
        h = roof_height(r, x, y, r["over"])          # a wall's outer face may lie outside the roof rectangle
        if h is not None and (best is None or h > best):
            best = h
    return best


def roof_at(story, x, y):
    """(roof, (a, b, c)): the roof that is highest over (x, y) and the plane that makes its surface there, or None."""
    best = None
    for r in story["roofs"]:
        h = roof_height(r, x, y, r["over"])
        if h is None:
            continue
        if best is None or h > best[0]:
            pl = min(roof_planes(r), key=lambda sp: sp[1][0] * x + sp[1][1] * y + sp[1][2])[1]
            best = (h, r, pl)
    return (best[1], best[2]) if best else None


def default_dormer_rot(story, x, y):
    """The way the roof falls at (x, y): a dormer normally faces down the slope."""
    res = roof_at(story, x, y)
    if res is None:
        return 0.0
    a, b, _ = res[1]
    if math.hypot(a, b) < 1e-6:
        return 0.0
    gx, gy = -a, -b
    return round(math.degrees(math.atan2(gx, -gy)) % 360.0, 1)


# ---- dormer geometry -----------------------------------------------------------------------------------------
def dormer_pt(dm, u, v):
    """Plan point of the dormer's local (u, v)."""
    r = math.radians(dm["rot"])
    c, s = math.cos(r), math.sin(r)
    return (dm["x"] + c * u - s * v, dm["y"] + s * u + c * v)


def dormer_local(dm, x, y):
    r = math.radians(-dm["rot"])
    c, s = math.cos(r), math.sin(r)
    dx, dy = x - dm["x"], y - dm["y"]
    return (c * dx - s * dy, s * dx + c * dy)


def dormer_zf(story, dm):
    h = host_roof_height(story, dm["x"], dm["y"])
    return 0.0 if h is None else h


def _dormer_k(dm):
    return 0.0 if dm["kind"] == "flat" else math.tan(math.radians(max(0.0, min(60.0, dm["pitch"]))))


def dormer_planes(story, dm):
    """Inner ceiling planes of the dormer (relative to the floor), the ceiling is the MINIMUM of them."""
    zc = dormer_zf(story, dm) + dm["fh"]
    k = _dormer_k(dm)
    w = dm["w"]
    r = math.radians(dm["rot"])
    eu = (math.cos(r), math.sin(r))
    ev = (-math.sin(r), math.cos(r))

    def world(z0, pu, pv):
        a = pu * eu[0] + pv * ev[0]
        b = pu * eu[1] + pv * ev[1]
        return (a, b, z0 - a * dm["x"] - b * dm["y"])
    if dm["kind"] == "gable":
        return [world(zc + k * w / 2.0, k, 0.0), world(zc + k * w / 2.0, -k, 0.0)]
    if dm["kind"] == "shed":
        return [world(zc, 0.0, k)]
    return [world(zc, 0.0, 0.0)]


def dormer_depth(story, dm):
    """Depth of the dormer (front face to the back).  d > 0 in the dormer = chosen by the user, else: as far back as the roof
    is lower than the dormer's own ceiling at the middle line."""
    if dm.get("d", 0.0) > 100.0:
        return dm["d"]
    key = (dm["x"], dm["y"], dm["rot"], dm["w"], dm["fh"], dm["pitch"], dm["kind"],
           tuple((r["type"], tuple(r["rect"]), r["pitch"], r["eave"], r.get("pitch2"), r.get("run"), r.get("ridge"),
                  r.get("fall")) for r in story["roofs"]))
    if key in _DORMER_MEMO:
        return _DORMER_MEMO[key]
    planes = dormer_planes(story, dm)
    val = 2000.0
    prev = None
    for i in range(0, 161):
        v = i * 50.0
        P = dormer_pt(dm, 0.0, v)
        h = host_roof_height(story, P[0], P[1])
        if h is None:
            break
        dif = h - min(a * P[0] + b * P[1] + c for a, b, c in planes)
        if dif >= -0.5:
            if prev is not None and dif - prev > 1e-6:
                v = v - 50.0 + 50.0 * (-prev) / (dif - prev)
            val = max(900.0, v)
            break
        prev = dif
    if len(_DORMER_MEMO) > 400:
        _DORMER_MEMO.clear()
    _DORMER_MEMO[key] = val
    return val


def dormer_poly(dm, d, inner=False):
    w, wt = dm["w"], dm.get("wt", DORMER_WT)
    i = 1.0 if inner else 0.0
    u0, u1, v0 = -w / 2.0 + i * wt, w / 2.0 - i * wt, i * wt
    return [dormer_pt(dm, u0, v0), dormer_pt(dm, u1, v0), dormer_pt(dm, u1, d), dormer_pt(dm, u0, d)]


def dormer_ceiling_height(story, dm, x, y):
    """Inner ceiling height of the dormer at (x, y) when that point is inside the dormer, else None."""
    u, v = dormer_local(dm, x, y)
    wt = dm.get("wt", DORMER_WT)
    if abs(u) > dm["w"] / 2.0 - wt or v < wt or v > dormer_depth(story, dm):
        return None
    return min(a * x + b * y + c for a, b, c in dormer_planes(story, dm))


def dormer_high_polys(story, limit):
    """Convex plan pieces inside the dormers where the dormer's ceiling is at least `limit` high."""
    out = []
    for dm in story.get("dormers", []):
        poly = dormer_poly(dm, dormer_depth(story, dm), True)
        for a, b, c in dormer_planes(story, dm):
            poly = clip_poly(poly, lambda p, a=a, b=b, c=c: a * p[0] + b * p[1] + c - limit)
            if len(poly) < 3:
                break
        if len(poly) >= 3 and poly_area(poly) > 1.0:
            out.append(poly)
    return out


def dormer_low_polys(story, dm, limit):
    """Pieces inside the dormer where its ceiling is lower than `limit` (for the shading in the plan)."""
    base = dormer_poly(dm, dormer_depth(story, dm), True)
    planes = dormer_planes(story, dm)
    out = []
    for i, pi in enumerate(planes):
        poly = base
        for j, pj in enumerate(planes):
            if i != j:
                poly = clip_poly(poly, lambda p, pi=pi, pj=pj: (pj[0] - pi[0]) * p[0] + (pj[1] - pi[1]) * p[1] + (pj[2] - pi[2]))
                if len(poly) < 3:
                    break
        if len(poly) < 3:
            continue
        poly = clip_poly(poly, lambda p, pi=pi: limit - (pi[0] * p[0] + pi[1] * p[1] + pi[2]))
        if len(poly) >= 3 and poly_area(poly) > 1.0:
            out.append(poly)
    return out


# ---- solids ----------------------------------------------------------------------------------------------------
def _newell(f):
    nx = ny = nz = 0.0
    n = len(f)
    for i in range(n):
        p, q = f[i], f[(i + 1) % n]
        nx += (p[1] - q[1]) * (p[2] + q[2])
        ny += (p[2] - q[2]) * (p[0] + q[0])
        nz += (p[0] - q[0]) * (p[1] + q[1])
    return nx, ny, nz


def orient_outward(faces):
    """Flip the faces of a CONVEX solid so every normal points away from its middle."""
    pts = [p for f in faces for p in f]
    c = (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts), sum(p[2] for p in pts) / len(pts))
    out = []
    for f in faces:
        n = _newell(f)
        fc = (sum(p[0] for p in f) / len(f), sum(p[1] for p in f) / len(f), sum(p[2] for p in f) / len(f))
        dot = n[0] * (fc[0] - c[0]) + n[1] * (fc[1] - c[1]) + n[2] * (fc[2] - c[2])
        out.append(f if dot >= 0 else f[::-1])
    return out


def _uz_prism(dm, elev, poly_uz, v0, v1):
    """Faces of a polygon in the (u, z) plane pushed from v0 to v1."""
    A = [dormer_pt(dm, u, v0) + (elev + z,) for u, z in poly_uz]
    B = [dormer_pt(dm, u, v1) + (elev + z,) for u, z in poly_uz]
    n = len(A)
    faces = [A, B[::-1]]
    for i in range(n):
        j = (i + 1) % n
        faces.append([A[i], A[j], B[j], B[i]])
    return orient_outward(faces)


def _dormer_window(story, dm):
    """(u half width, z bottom, z top) of the front window (relative to the floor) or None."""
    w, wt = dm["w"], dm.get("wt", DORMER_WT)
    ww = min(dm.get("win_w", 0.0), w - 2 * wt - 100.0)
    zf = dormer_zf(story, dm)
    zb = zf + dm.get("sill", 200.0)
    wh = min(dm.get("win_h", 0.0), zf + dm["fh"] - 100.0 - zb)
    if ww < 300.0 or wh < 300.0:
        return None
    return ww / 2.0, zb, zb + wh


def dormer_solids(proj, sidx, dm, cut=True):
    """All 3D pieces of one dormer.  cut=False: the front wall is whole and the window opening is returned as a separate
    "void" solid (used by the IFC export)."""
    story = proj["stories"][sidx]
    elev = story_elevations(proj)[sidx]
    w, wt, kind = dm["w"], dm.get("wt", DORMER_WT), dm["kind"]
    k = _dormer_k(dm)
    zf = dormer_zf(story, dm)
    zc = zf + dm["fh"]
    d = dormer_depth(story, dm)
    over, rt = dm.get("over", 150.0), dm.get("rt", 120.0)
    out = []

    def H(u, v):
        h = host_roof_height(story, *dormer_pt(dm, u, v))
        return zf if h is None else h

    def ztop(u, v=0.0):
        if kind == "gable":
            return zc + k * (w / 2.0 - abs(u))
        if kind == "shed":
            return zc + k * v
        return zc

    def add(typ, mat, faces, name, ifc, lay=None):
        out.append(_solid(typ, mat, faces, sidx, dm["id"], name, True, ifc, {"lay": lay} if lay else None))

    def tops(u0, u1, v=0.0):
        pts = [(u1, ztop(u1, v)), (u0, ztop(u0, v))]
        if kind == "gable" and u0 < 0.0 < u1:
            pts.insert(1, (0.0, ztop(0.0, v)))
        return pts

    def piece(u0, u1, zb0, zb1, top_pts, v0, v1):
        poly = [(u0, zb0), (u1, zb1)] + top_pts
        if abs(poly_area_signed(poly)) < 1.0:
            return
        add("wall", "wall", _uz_prism(dm, elev, poly, v0, v1), "Dormer wall", "IfcWall", 2.5)

    def bz(u, v=0.0):
        return min(H(u, v), ztop(u, v))
    win = _dormer_window(story, dm)
    if win is not None and cut:
        hw, zbw, zwt = win
        piece(-w / 2.0, -hw, bz(-w / 2.0), bz(-hw), tops(-w / 2.0, -hw), 0.0, wt)
        piece(hw, w / 2.0, bz(hw), bz(w / 2.0), tops(hw, w / 2.0), 0.0, wt)
        piece(-hw, hw, min(bz(-hw), zbw), min(bz(hw), zbw), [(hw, zbw), (-hw, zbw)], 0.0, wt)
        piece(-hw, hw, zwt, zwt, tops(-hw, hw), 0.0, wt)
    else:
        piece(-w / 2.0, w / 2.0, bz(-w / 2.0), bz(w / 2.0), tops(-w / 2.0, w / 2.0), 0.0, wt)
    if win is not None:
        hw, zbw, zwt = win

        def box(u0, u1, v0, v1, z0, z1, mat):
            poly = [dormer_pt(dm, u0, v0), dormer_pt(dm, u1, v0), dormer_pt(dm, u1, v1), dormer_pt(dm, u0, v1)]
            add("window", mat, prism_faces(poly, [elev + z0] * 4, [elev + z1] * 4), "Dormer window", "IfcWindow")
        fw = 50.0
        box(-hw, -hw + fw, 0.0, wt, zbw, zwt, "frame")
        box(hw - fw, hw, 0.0, wt, zbw, zwt, "frame")
        box(-hw, hw, 0.0, wt, zbw, zbw + fw, "frame")
        box(-hw, hw, 0.0, wt, zwt - fw, zwt, "frame")
        box(-hw + fw, hw - fw, wt / 2.0 - 6.0, wt / 2.0 + 6.0, zbw + fw, zwt - fw, "glass")
    # rear wall: only when the dormer is shorter than it needs to be (else it is buried in the roof)
    if max(ztop(u, d) - H(u, d) for u in (-w / 2.0, 0.0, w / 2.0)) > 30.0:
        piece(-w / 2.0, w / 2.0, bz(-w / 2.0, d), bz(w / 2.0, d), tops(-w / 2.0, w / 2.0, d), d - wt, d)
    # cheek walls: from the front back to where the roof reaches their top
    for sgn in (-1.0, 1.0):
        uo, ui = sgn * w / 2.0, sgn * (w / 2.0 - wt)
        v = 0.0
        while v < d and H(uo, v) < ztop(uo, v) - 1.0:
            v += 25.0
        vc = min(v, d)
        if vc < 60.0:
            continue
        uv = [(uo, 0.0), (ui, 0.0), (ui, vc), (uo, vc)]
        poly = [dormer_pt(dm, u, vv) for u, vv in uv]
        zt = [elev + ztop(u, vv) for u, vv in uv]
        zb = [elev + bz(u, vv) for u, vv in uv]
        add("wall", "wall", prism_faces(poly, zb, zt), "Dormer wall", "IfcWall", 2.5)
    # the dormer's roof
    tv = rt * math.sqrt(1.0 + k * k)

    def facet(u0, u1, fz):
        uv = [(u0, -over), (u1, -over), (u1, d), (u0, d)]
        zi = [elev + fz(u, v) for u, v in uv]
        add("roof", "roof", prism_faces([dormer_pt(dm, u, v) for u, v in uv], zi, [z + tv for z in zi]), "Dormer roof", "IfcRoof", 2.6)
    if kind == "gable":
        facet(-w / 2.0 - over, 0.0, lambda u, v: zc + k * (w / 2.0 + u))
        facet(0.0, w / 2.0 + over, lambda u, v: zc + k * (w / 2.0 - u))
    elif kind == "shed":
        facet(-w / 2.0 - over, w / 2.0 + over, lambda u, v: zc + k * v)
    else:
        facet(-w / 2.0 - over, w / 2.0 + over, lambda u, v: zc)
    if not cut and win is not None:
        hw, zbw, zwt = win
        poly = [dormer_pt(dm, -hw, -20.0), dormer_pt(dm, hw, -20.0), dormer_pt(dm, hw, wt + 20.0), dormer_pt(dm, -hw, wt + 20.0)]
        out.append(_solid("void", "glass", prism_faces(poly, [elev + zbw] * 4, [elev + zwt] * 4), sidx, dm["id"], "Dormer window opening",
                          True, "IfcOpeningElement", {"host": ("wall", dm["id"]), "fill": ("window", dm["id"]),
                                                     "vkey": "dw%d" % dm["id"]}))
    return out


def dormer_void_solids(proj, sidx, dm):
    """The hollow inside a dormer (one or two convex pieces): cuts the hole in the main roof (section view, IFC)."""
    story = proj["stories"][sidx]
    elev = story_elevations(proj)[sidx]
    w, wt, kind = dm["w"], dm.get("wt", DORMER_WT), dm["kind"]
    k = _dormer_k(dm)
    zf = dormer_zf(story, dm)
    zc = zf + dm["fh"]
    d = dormer_depth(story, dm)
    if d < wt + 100.0:
        return []

    def H(u, v):
        h = host_roof_height(story, *dormer_pt(dm, u, v))
        return zf if h is None else h

    def ceil(u, v):
        if kind == "gable":
            return zc + k * (w / 2.0 - abs(u))
        if kind == "shed":
            return zc + k * v
        return zc
    halves = [(-w / 2.0 + wt, 0.0), (0.0, w / 2.0 - wt)] if kind == "gable" else [(-w / 2.0 + wt, w / 2.0 - wt)]
    res = roof_at(story, dm["x"], dm["y"])
    host = ("roof", res[0]["id"]) if res else None
    out = []
    for u0, u1 in halves:
        uv = [(u0, wt), (u1, wt), (u1, d), (u0, d)]
        zt = [ceil(u, v) for u, v in uv]
        zb = [min(H(u, v), t) for (u, v), t in zip(uv, zt)]
        if sum(t - b for t, b in zip(zt, zb)) < 10.0:
            continue
        poly = [dormer_pt(dm, u, v) for u, v in uv]
        out.append(_solid("void", "void", prism_faces(poly, [elev + z for z in zb], [elev + z for z in zt]), sidx, dm["id"],
                          "Dormer hollow", True, "IfcOpeningElement", {"lay": 1.5, "host": host, "fill": None,
                                                                       "vkey": "dh%d" % dm["id"]}))
    return out


# ---- roof windows ----------------------------------------------------------------------------------------------
def rwin_info(story, rw):
    """Frame of a roof window: lies in the roof plane under its position.  None when no roof covers it."""
    res = roof_at(story, rw["x"], rw["y"])
    if res is None:
        return None
    roof, (a, b, c) = res
    grad = math.hypot(a, b)
    g = (-a / grad, -b / grad) if grad > 1e-6 else (0.0, -1.0)
    return {"roof": roof, "plane": (a, b, c), "g": g, "q": v_perp(g), "grad": grad,
            "Lp": rw["h"] / math.sqrt(1.0 + grad * grad)}


def rwin_pt(info, rw, s, t):
    return (rw["x"] + info["q"][0] * s + info["g"][0] * t, rw["y"] + info["q"][1] * s + info["g"][1] * t)


def rwin_outline(story, rw):
    info = rwin_info(story, rw)
    if info is None:
        return None
    hw, hl = rw["w"] / 2.0, info["Lp"] / 2.0
    return [rwin_pt(info, rw, -hw, -hl), rwin_pt(info, rw, hw, -hl), rwin_pt(info, rw, hw, hl), rwin_pt(info, rw, -hw, hl)]


def rwin_solids(proj, sidx, rw, cut=True):
    story = proj["stories"][sidx]
    elev = story_elevations(proj)[sidx]
    info = rwin_info(story, rw)
    if info is None:
        return []
    a, b, c = info["plane"]
    zin = lambda p: elev + a * p[0] + b * p[1] + c
    tv = info["roof"]["t"] * math.sqrt(1.0 + info["grad"] ** 2)
    hw, hl = rw["w"] / 2.0, info["Lp"] / 2.0
    fw = 60.0
    fl = fw / math.sqrt(1.0 + info["grad"] ** 2)
    out = []

    def box(s0, s1, t0, t1, dz0, dz1, mat):
        poly = [rwin_pt(info, rw, s0, t0), rwin_pt(info, rw, s1, t0), rwin_pt(info, rw, s1, t1), rwin_pt(info, rw, s0, t1)]
        zi = [zin(p) for p in poly]
        out.append(_solid("window", mat, prism_faces(poly, [z + dz0 for z in zi], [z + dz1 for z in zi]), sidx, rw["id"],
                          "Roof window", True, "IfcWindow"))
    box(-hw, -hw + fw, -hl, hl, 0.0, tv + 40.0, "frame")
    box(hw - fw, hw, -hl, hl, 0.0, tv + 40.0, "frame")
    box(-hw + fw, hw - fw, hl - fl, hl, 0.0, tv + 40.0, "frame")
    box(-hw + fw, hw - fw, -hl, -hl + fl, 0.0, tv + 40.0, "frame")
    box(-hw + fw, hw - fw, -hl + fl, hl - fl, tv + 10.0, tv + 25.0, "glass")
    if not cut:
        poly = [rwin_pt(info, rw, -hw, -hl), rwin_pt(info, rw, hw, -hl), rwin_pt(info, rw, hw, hl), rwin_pt(info, rw, -hw, hl)]
        zi = [zin(p) for p in poly]
        out.append(_solid("void", "glass", prism_faces(poly, [z - 60.0 for z in zi], [z + tv + 80.0 for z in zi]), sidx, rw["id"],
                          "Roof window opening", True, "IfcOpeningElement",
                          {"host": ("roof", info["roof"]["id"]), "fill": ("window", rw["id"]), "vkey": "rw%d" % rw["id"]}))
    return out


# *************** DEL 27 - STAIR PARTS (steps, and the space UNDER straight stairs: shelves, wardrobe, drawers) *****************
# A straight stair can have st["under"] = {"mode": "solid" | "open" | "cupboard", "side": "right" | "left",
#   "sections": [{"type": "shelves" | "hanging" | "drawers" | "empty", "n": shelves / drawers, "front": "closed" | "open" |
#   "open middle"}, ...]}.  Sections share the run of the stairs equally; section 0 is the one under the HIGH end.  Each section
# is a box whose roof is the lowest underside of the steps above it.  The sections share only the part of the run where the space
# under the steps is at least CB_MIN_H high (the low end near the foot stays open).
# The front (doors / drawer fronts) is on the right or the left side of the stairs (right = on your right when you walk up).
# Everything is in the stair frame: x across (width), y along the run, z up from the floor of the stair's storey.
# BESPOKE (under["bespoke"] = True): the cupboard is made to measure for the stairs - the boards, the back and the front follow the
#   steps (one slice per tread), nothing is left open: the low foot end (lower than BESPOKE_MIN_H) is a closed filler block, every
#   section has closed doors or drawer fronts on the side, shelves / rail are cut short where the steps come down.
# ToDo: L-shaped stairs (space under the first flight), a landing cupboard, sloped section tops that follow the steps exactly.

UNDER_MODES = [("solid", "Closed block (as before)"), ("open", "Open underneath"), ("cupboard", "Cupboard under the stairs")]
SECTION_TYPES = ["shelves", "hanging", "drawers", "empty"]
FRONT_TYPES = ["closed", "open", "open middle"]
STAIR_STRUCT = 150.0       # how thick the steps are underneath (tread + beam), mm
CB_T = 18.0                # board thickness, mm
CB_MIN_H = 450.0           # a section under the stairs lower than this is not built
BESPOKE_MIN_H = 250.0      # bespoke: sections start where the space is at least this high; lower than that = closed filler block


def stair_under(st):
    u = st.get("under")
    if not isinstance(u, dict) or u.get("mode") not in dict(UNDER_MODES):
        return {"mode": "solid", "side": "right", "sections": []}
    return u


def default_cupboard(count=3):
    """A cupboard under the stairs: wardrobe with a hanging rail at the high end, shelves in the middle, open low part."""
    kinds = [("hanging", 0, "closed"), ("shelves", 4, "closed"), ("drawers", 3, "closed"), ("shelves", 2, "open"),
             ("empty", 0, "open"), ("empty", 0, "open")]
    return {"mode": "cupboard", "side": "right",
            "sections": [{"type": k[0], "n": k[1], "front": k[2]} for k in kinds[:max(1, min(6, count))]]}


def stair_hollow(st):
    """True when the steps are drawn as thin slabs (open underneath) instead of a solid block."""
    return st.get("kind") == "straight" and stair_under(st)["mode"] in ("open", "cupboard")


def stair_run_length(st):
    return (max(2, int(st["n"])) - 1) * st["tread"]


def stair_under_height(st, rise, y):
    """Height of the underside of the steps at distance y from the foot (mm), measured from the floor."""
    n = max(2, int(st["n"]))
    R = rise / float(n)
    k = min(n - 1, max(1, int(y / st["tread"] + 1e-6) + 1))
    return max(0.0, k * R - STAIR_STRUCT)


def stair_bespoke(st):
    return bool(stair_under(st).get("bespoke")) and st.get("kind") == "straight"


def stair_cupboard_start(st, rise):
    """Distance from the foot where the space under the stairs gets high enough (CB_MIN_H, bespoke: BESPOKE_MIN_H) for a cupboard."""
    n = max(2, int(st["n"]))
    T = st["tread"]
    R = rise / float(n)
    minh = BESPOKE_MIN_H if stair_bespoke(st) else CB_MIN_H
    for k in range(1, n):
        if k * R - STAIR_STRUCT >= minh:
            return (k - 1) * T
    return stair_run_length(st)


SEC_MIN_W = 200.0          # a section is never narrower than this (mm) when the widths are shared out


def section_width_set(s):
    """The width (mm) typed for a section, or None = 'auto' (the sections without one share the rest equally)."""
    try:
        w = float(s.get("w") or 0.0)
    except (TypeError, ValueError):
        return None
    return w if w >= 100.0 else None


def stair_section_widths(secs, avail):
    """Widths (mm, along the stairs) of the sections, section 0 first: typed widths are kept, the others share the rest equally.
    When it does not add up (too wide / all typed) every width is scaled so that the sections exactly fill the space."""
    fixed = [section_width_set(s) for s in secs]
    auto = [i for i, f in enumerate(fixed) if f is None]
    f_sum = sum(f for f in fixed if f is not None)
    if auto:
        aw = (avail - f_sum) / len(auto)
        if aw < SEC_MIN_W:
            aw = SEC_MIN_W
        w = [aw if f is None else f for f in fixed]
    else:
        w = list(fixed)
    tot = sum(w)
    if abs(tot - avail) > 0.01 and tot > 0:
        k = avail / tot
        w = [x * k for x in w]
    return w


def stair_sections(st, rise):
    """The sections of a cupboard under straight stairs: [{i, y0, y1, h, type, n, front, ok}] (i = 0 under the high end)."""
    u = stair_under(st)
    if st.get("kind") != "straight" or u["mode"] != "cupboard":
        return []
    secs = u.get("sections") or []
    if not secs:
        return []
    L = stair_run_length(st)
    N = len(secs)
    y_start = stair_cupboard_start(st, rise)
    if L - y_start < 300.0:
        return []                                      # the stairs are too short / too flat to get a cupboard under them
    out = []
    widths = stair_section_widths(secs, L - y_start)
    yb = L
    for i, s in enumerate(secs):                       # the sections share the part of the run that is high enough
        ya = yb - widths[i]
        h = stair_under_height(st, rise, ya + 1.0)
        h1 = stair_under_height(st, rise, yb - 1.0)
        be = stair_bespoke(st)
        out.append({"i": i, "y0": ya, "y1": yb, "h": h, "h1": h1, "w": yb - ya, "d": st["w"], "type": s.get("type", "shelves"),
                    "n": max(0, int(s.get("n", 0))), "front": "closed" if be else s.get("front", "closed"),
                    "ok": h >= (BESPOKE_MIN_H if be else CB_MIN_H), "wset": section_width_set(s)})
        yb = ya
    return out


def _profile_slices(st, rise, y0, y1):
    """The underside of the steps as slices: [(ya, yb, height)], one per tread, clipped to y0..y1."""
    n = max(2, int(st["n"]))
    T = st["tread"]
    R = rise / float(n)
    out = []
    for k in range(1, n):
        a, b = max(y0, (k - 1) * T), min(y1, k * T)
        if b - a > 0.5:
            out.append((a, b, max(0.0, k * R - STAIR_STRUCT)))
    return out


def _y_where_high(st, rise, z, y0, y1):
    """First y in y0..y1 where the underside of the steps is at least z high (None if never)."""
    for a, b, h in _profile_slices(st, rise, y0, y1):
        if h >= z:
            return a
    return None


def stair_bespoke_boxes(st, rise):
    """Cupboard made to measure: follows the steps, no open surfaces (filler block + sections with doors / drawer fronts)."""
    out = []
    secs = stair_sections(st, rise)
    if not secs:
        return out
    u = stair_under(st)
    hw = st["w"] / 2.0
    sg = 1.0 if u.get("side", "right") == "right" else -1.0
    t = CB_T
    L = stair_run_length(st)

    def box(x0, y0, x1, y1, z0, z1, mat):
        xa, xb = sorted((x0 * sg, x1 * sg))
        if y1 - y0 > 0.5 and xb - xa > 0.5 and z1 - z0 > 0.5:
            out.append((xa, y0, xb, y1, z0, z1, mat))

    def cut(x0, x1, y0, y1, zlo, zhi, mat):                 # a board that follows the underside of the steps
        for a, b, h in _profile_slices(st, rise, y0, y1):
            top = min(zhi, h)
            if top - zlo >= 20.0:
                box(x0, a, x1, b, zlo, top, mat)
    ys = secs[-1]["y0"]
    cut(-hw, hw, 0.0, ys, 0.0, 1e9, "wood_light")           # the low foot end: a closed filler block
    for s in secs:
        ya, yb, i = s["y0"], s["y1"], s["i"]
        hmax = max([h for _a, _b, h in _profile_slices(st, rise, ya, yb)] or [0.0])
        box(-hw, ya, hw, yb, 0.0, t, "wood_light")                                   # bottom
        cut(-hw, -hw + t, ya, yb, t, 1e9, "wood_light")                              # back (side away from the front)
        if i < len(secs) - 1:
            cut(-hw + t, hw, ya, ya + t, t, 1e9, "wood_light")                       # divider to the section below
        if i == 0:
            cut(-hw + t, hw, yb - t, yb, t, 1e9, "wood_light")                       # end wall under the top step
        ix0, ix1, iy0, iy1 = -hw + t, hw - t, ya + t, yb - t
        kind, cnt = s["type"], s["n"]
        if kind == "shelves":
            for j in range(1, cnt + 1):
                z = t + (hmax - t) * j / (cnt + 1.0)
                y_in = _y_where_high(st, rise, z + t, iy0, iy1)
                if y_in is not None:
                    box(ix0, y_in, ix1, iy1, z - t / 2.0, z + t / 2.0, "wood_light")
        elif kind == "hanging":
            zr = hmax - 250.0
            y_in = _y_where_high(st, rise, zr + 120.0, iy0, iy1)
            if y_in is not None and zr > 600.0:
                xm = (ix0 + ix1) / 2.0
                box(xm - 15.0, y_in, xm + 15.0, iy1, zr, zr + 30.0, "metal")
            y_hat = _y_where_high(st, rise, hmax - 120.0 + t, iy0, iy1)
            if y_hat is not None:
                box(ix0, y_hat, ix1, iy1, hmax - 120.0, hmax - 120.0 + t, "wood_light")
        elif kind == "drawers":
            cnt = max(1, cnt)
            for k in range(cnt):
                z0 = t + (hmax - t) * k / float(cnt)
                z1 = t + (hmax - t) * (k + 1) / float(cnt)
                cut(hw - t, hw, ya + 1.5, yb - 1.5, z0 + 3.0, z1 - 3.0, "wood")      # drawer front (cut to the steps)
                y_in = _y_where_high(st, rise, z0 + 40.0, iy0 + 20.0, iy1 - 20.0)
                if y_in is not None:
                    box(ix0 + 20.0, y_in, hw - t, iy1 - 20.0, z0 + 8.0, z0 + 20.0, "wood_light")
            continue
        ln = yb - ya                                                                 # doors, cut to the steps
        if ln > 700.0:
            mid = (ya + yb) / 2.0
            cut(hw - t, hw, ya + 1.5, mid - 1.5, t, 1e9, "door")
            cut(hw - t, hw, mid + 1.5, yb - 1.5, t, 1e9, "door")
        else:
            cut(hw - t, hw, ya + 1.5, yb - 1.5, t, 1e9, "door")
    return out


def stair_cupboard_boxes(st, rise):
    """The boards, shelves, rails, drawer fronts and doors under the stairs: [(x0, y0, x1, y1, z0, z1, material)]."""
    if stair_bespoke(st):
        return stair_bespoke_boxes(st, rise)
    out = []
    u = stair_under(st)
    hw = st["w"] / 2.0
    sg = 1.0 if u.get("side", "right") == "right" else -1.0
    t = CB_T

    def box(x0, y0, x1, y1, z0, z1, mat):
        xa, xb = sorted((x0 * sg, x1 * sg))
        if y1 - y0 > 0.5 and xb - xa > 0.5 and z1 - z0 > 0.5:
            out.append((xa, y0, xb, y1, z0, z1, mat))
    for s in stair_sections(st, rise):
        if not s["ok"]:
            continue
        ya, yb, h = s["y0"], s["y1"], s["h"]
        box(-hw, ya, hw, yb, 0.0, t, "wood_light")                       # bottom
        box(-hw, ya, -hw + t, yb, t, h, "wood_light")                    # back (the side away from the front)
        box(-hw + t, ya, hw, ya + t, t, h, "wood_light")                 # divider at the low end of the section
        if s["i"] == 0:
            box(-hw + t, yb - t, hw, yb, t, h, "wood_light")             # end wall under the top step
        box(-hw + t, ya, hw, yb, h - t, h, "wood_light")                 # top
        ix0, ix1, iy0, iy1, iz0, iz1 = -hw + t, hw - t, ya + t, yb - t, t, h - t
        kind, cnt = s["type"], s["n"]
        if kind == "shelves":
            for j in range(1, cnt + 1):
                z = iz0 + (iz1 - iz0) * j / (cnt + 1.0)
                box(ix0, iy0, ix1, iy1, z - t / 2.0, z + t / 2.0, "wood_light")
        elif kind == "hanging":
            xm = (ix0 + ix1) / 2.0
            box(xm - 15.0, iy0, xm + 15.0, iy1, iz1 - 200.0, iz1 - 170.0, "metal")
            box(ix0, iy0, ix1, iy1, iz1 - 120.0, iz1 - 120.0 + t, "wood_light")      # hat shelf
        elif kind == "drawers":
            cnt = max(1, cnt)
            for k in range(cnt):
                z0 = iz0 + (iz1 - iz0) * k / float(cnt)
                z1 = iz0 + (iz1 - iz0) * (k + 1) / float(cnt)
                box(hw - t, iy0 + 3.0, hw, iy1 - 3.0, z0 + 3.0, z1 - 3.0, "wood")    # drawer front
                box(ix0 + 20.0, iy0 + 20.0, hw - t, iy1 - 20.0, z0 + 8.0, z0 + 20.0, "wood_light")   # drawer bottom
            continue
        ln = iy1 - iy0
        if s["front"] == "closed":
            if ln > 700.0:
                mid = (iy0 + iy1) / 2.0
                box(hw - t, iy0, hw, mid - 1.5, iz0, iz1, "door")
                box(hw - t, mid + 1.5, hw, iy1, iz0, iz1, "door")
            else:
                box(hw - t, iy0, hw, iy1, iz0, iz1, "door")
        elif s["front"] == "open middle":
            w = min(ln / 4.0, 350.0)
            box(hw - t, iy0, hw, iy0 + w, iz0, iz1, "door")
            box(hw - t, iy1 - w, hw, iy1, iz0, iz1, "door")
    return out


def stair_cupboard_plan_lines(st, rise):
    """Dashed lines for the plan (stair frame): the dividers between the sections and a heavy line on the front side."""
    secs = stair_sections(st, rise)
    if not secs:
        return []
    hw = st["w"] / 2.0
    sg = 1.0 if stair_under(st).get("side", "right") == "right" else -1.0
    out = []
    for s in secs:
        if s["ok"]:
            out.append([(-hw, s["y0"]), (hw, s["y0"])])
            out.append([(sg * (hw - 60.0), s["y0"]), (sg * (hw - 60.0), s["y1"])])
    return out


# *************** DEL 28 - CURTAIN WALL (room divider: a rail under the ceiling + a drape that slides) *****************
# A wall with w["kind"] == "curtain" is NOT a solid wall: no wall polygon, no wall solids, not in the wall lists of the shopping
# list.  It is a ceiling rail with a drape on it, used instead of a wall with a door.  Fields of the wall dict:
#   "open"   0.0 = drawn shut .. 1.0 = pushed fully aside (gathered into a pack)
#   "gather" "Start" / "End" / "Both" (two drapes that meet in the middle) = where the drape piles up when it is opened
# The wall's "t" is the thickness of the smooth cloth; the gathered pack is thicker.
# ToDo: curved curtain rails (an arc), a drape that follows a sloping roof, section-view cut of the cloth.

CURTAIN_T = 60.0            # default cloth thickness shown in plan / 3D (mm)
CURTAIN_RAIL = 40.0         # the rail: 40 x 40 mm, its top touches the ceiling
CURTAIN_GAP = 30.0          # the cloth ends this far above the floor
CURTAIN_FOLD = 0.16         # a fully gathered drape (per side) is this share of the rail's length, but at least 250 mm
CURTAIN_PACK_T = 180.0      # thickness of the gathered pack
CURTAIN_FULLNESS = 2.0      # fabric needed = finished width x this (wave folds), used in the shopping list
CURTAIN_GATHER = ["Start", "End", "Both"]
CURTAIN_COLORS = {"Green": "curtain_green", "Red": "curtain_red"}   # w["color"]; never the blue of beds / sheets


def is_curtain(w):
    return w.get("kind") == "curtain"


def curtain_pieces(w, length):
    """Where the cloth is along the rail: [(u0, u1, "pack" | "cloth")] with u = distance from the wall's start (mm)."""
    op = min(1.0, max(0.0, float(w.get("open", 0.0))))
    mode = w.get("gather", "Both")
    halves = [(0.0, length / 2.0, "Start"), (length / 2.0, length, "End")] if mode == "Both" else [(0.0, length, mode)]
    out = []
    for a, b, side in halves:
        L = b - a
        if L < 1.0:
            continue
        P = min(L * 0.5, max(250.0, CURTAIN_FOLD * L))           # pack width when fully open
        pw = P * op
        e = pw + (L - pw) * (1.0 - op)                           # the free edge of the drape, measured from the gathered end
        segs = []
        if pw > 1.0:
            segs.append((0.0, pw, "pack"))
        if e - pw > 1.0:
            segs.append((pw, e, "cloth"))
        for s0, s1, kind in segs:
            out.append((a + s0, a + s1, kind) if side == "Start" else (b - s1, b - s0, kind))
    out.sort(key=lambda q: q[0])
    return out


def curtain_top(proj, sidx, w, story=None):
    """Height (mm, absolute) of the underside of the ceiling the rail hangs on: the wall height, lowered where a roof slopes down."""
    if story is None:
        story = proj["stories"][sidx]
    elev = story_elevations(proj)[sidx]
    cap = elev + (w["h"] if w.get("h") else story["height"])
    ztop = cap
    for k in range(9):
        t = k / 8.0
        x, y = w["p"][0] + (w["p"][2] - w["p"][0]) * t, w["p"][1] + (w["p"][3] - w["p"][1]) * t
        ztop = min(ztop, top_z(story, elev, x, y, cap))
    return max(ztop, elev + 600.0)


def curtain_boxes(w, length, ztop, zfloor):
    """3D boxes in the wall's own frame: [(u0, u1, v0, v1, z0, z1, material)], v across the wall, z absolute."""
    t = max(10.0, float(w.get("t", CURTAIN_T))) / 2.0
    z1 = ztop - CURTAIN_RAIL
    cloth = CURTAIN_COLORS.get(w.get("color", "Green"), "curtain_green")
    out = [(0.0, length, -CURTAIN_RAIL / 2, CURTAIN_RAIL / 2, z1, ztop, "metal")]
    for u0, u1, kind in curtain_pieces(w, length):
        hv = max(t, CURTAIN_PACK_T / 2.0) if kind == "pack" else t
        out.append((u0, u1, -hv, hv, zfloor + CURTAIN_GAP, z1, cloth))
    return out


def curtain_plan_prims(w, g, pp, tx=None):
    """Plan drawing of a curtain wall: dashed rail, wavy line for the smooth cloth, boxed zig-zag for the gathered pack.
    `pp(points, closed, dash, lw)` makes one primitive (the caller adds layer / element id)."""
    A, d, n, L = g["A"], g["d"], g["n"], g["len"]
    at = lambda u, v: (A[0] + d[0] * u + n[0] * v, A[1] + d[1] * u + n[1] * v)
    out = [pp([at(0.0, 0.0), at(L, 0.0)], False, True, 0.13)]                      # the rail (dashed centre line)
    for u0, u1, kind in curtain_pieces(w, L):
        if kind == "cloth":
            amp, wl = 22.0, 110.0
        else:
            amp, wl = 70.0, 70.0
            hv = CURTAIN_PACK_T / 2.0
            out.append(pp([at(u0, -hv), at(u1, -hv), at(u1, hv), at(u0, hv)], True, False, 0.18))
        n_steps = max(2, int(round((u1 - u0) / (wl / 2.0))))
        pts = []
        for i in range(n_steps + 1):
            u = u0 + (u1 - u0) * i / n_steps
            pts.append(at(u, 0.0 if i in (0, n_steps) else (amp if i % 2 else -amp)))
        out.append(pp(pts, False, False, 0.25))
    return out


# *************** DEL 29 - GHOST MEASURES (a second ghost layer: rulers + measured rooms, plan only, never exported) *****************
# story["meas"] = list of measures, three kinds:
#   "ruler"  {"a": [x, y], "b": [x, y]}            a ruler laid out between two points (ticks every 100 mm, numbers every metre)
#   "rect"   {"a": [x, y], "b": [x, y]}            a marked rectangle - needs NO walls (curtain, open plan ...)
#   "poly"   {"pts": [[x, y], ...]}                the outline of a room (a real room or the space inside closed walls)
# Every measure also has "name" (optional own prefix).  The label of a rect / poly is  <prefix>  W x D m  area:  the prefix is
# the name you typed, else the text of the GHOST NOTES that stand inside the outline ("Bedroom B"), else nothing.
# Like the ghost notes the layer is off by default, belongs to its storey, shows in the plan only and is never exported.
# ToDo: heights (ceiling) and volume, measures that follow a room when it is edited, a printed measure list.

MEAS_KINDS = ["ruler", "rect", "poly"]
MEAS_MODES = ["Rectangle", "Room (click inside)", "Ruler"]


def add_meas(proj, story, kind, a=None, b=None, pts=None, name=""):
    m = {"id": uid(proj), "kind": kind, "name": name}
    if kind == "poly":
        m["pts"] = [[float(p[0]), float(p[1])] for p in pts]
    else:
        m["a"] = [float(a[0]), float(a[1])]
        m["b"] = [float(b[0]), float(b[1])]
    story.setdefault("meas", []).append(m)
    return m


def meas_outline(m):
    """The corner points of a measure (a ruler gives its two end points)."""
    if m["kind"] == "poly":
        return [tuple(p) for p in m["pts"]]
    (x0, y0), (x1, y1) = m["a"], m["b"]
    if m["kind"] == "ruler":
        return [(x0, y0), (x1, y1)]
    lx, hx, ly, hy = min(x0, x1), max(x0, x1), min(y0, y1), max(y0, y1)
    return [(lx, ly), (hx, ly), (hx, hy), (lx, hy)]


def _right_angled_quad(pts):
    if len(pts) != 4:
        return False
    for i in range(4):
        a, b, c = pts[i], pts[(i + 1) % 4], pts[(i + 2) % 4]
        u, v = v_unit(v_sub(b, a)), v_unit(v_sub(c, b))
        if abs(v_dot(u, v)) > 0.02:
            return False
    return True


def meas_size(m):
    """{"len": ruler length, "w": width, "d": depth, "area": mm2, "exact": False when W x D is only the bounding box}."""
    pts = meas_outline(m)
    if m["kind"] == "ruler":
        return {"len": dist(pts[0], pts[1]), "w": 0.0, "d": 0.0, "area": 0.0, "exact": True}
    area = poly_area(pts)
    if _right_angled_quad(pts):                          # a rectangle, also a turned one
        return {"len": 0.0, "w": dist(pts[0], pts[1]), "d": dist(pts[1], pts[2]), "area": area, "exact": True}
    xs, ys = [p[0] for p in pts], [p[1] for p in pts]
    return {"len": 0.0, "w": max(xs) - min(xs), "d": max(ys) - min(ys), "area": area, "exact": False}


def meas_prefix(story, m):
    """What stands in front of the measures: own name, else the ghost notes inside the outline (left to right)."""
    if m.get("name"):
        return m["name"]
    if m["kind"] == "ruler":
        return ""
    pts = meas_outline(m)
    inside = [t for t in story["texts"] if t.get("ghost") and point_in_poly((t["x"], t["y"]), pts)]
    inside.sort(key=lambda t: (t["x"], t["y"]))
    return " / ".join(t["s"] for t in inside)


def meas_dims_text(m):
    sz = meas_size(m)
    if m["kind"] == "ruler":
        return "%s m" % fmt_m(sz["len"])
    box = "" if sz["exact"] else " (box)"
    return "%s x %s m%s  %s" % (fmt_m(sz["w"]), fmt_m(sz["d"]), box, fmt_area(sz["area"]))


def meas_label(story, m):
    pre = meas_prefix(story, m)
    return (pre + "  " if pre else "") + meas_dims_text(m)


def meas_report(proj, sidx=None):
    """The measures as plain text, one line per measure, grouped by storey (sidx = only that storey)."""
    lines = []
    for i, st in enumerate(proj["stories"]):
        if sidx is not None and i != sidx:
            continue
        ms = st.get("meas", [])
        if not ms:
            continue
        lines.append("%s" % st["name"])
        for m in ms:
            pre = meas_prefix(st, m) or ("Ruler" if m["kind"] == "ruler" else "(no name)")
            lines.append("  %s: %s" % (pre, meas_dims_text(m)))
    return "\n".join(lines)


def meas_prims(story, m, pp, tx):
    """Plan drawing.  pp(points, closed, dash, lw) -> primitive, tx(point, text, height, rot) -> primitive."""
    out = []
    pts = meas_outline(m)
    if m["kind"] == "ruler":
        a, b = pts
        ln = dist(a, b)
        if ln < 1:
            return out
        d = v_unit(v_sub(b, a))
        n = v_perp(d)
        body = 120.0
        out.append(pp([a, b, v_add(b, v_mul(n, body)), v_add(a, v_mul(n, body))], True, False, 0.18))
        step = 100.0 if ln <= 30000 else 1000.0
        k = 0
        while k * step <= ln + 1e-6:
            u = k * step
            mm = u % 1000.0 < 1e-6
            half = u % 500.0 < 1e-6
            tl = 100.0 if mm else (70.0 if half else 40.0)
            p0 = v_add(a, v_mul(d, u))
            out.append(pp([p0, v_add(p0, v_mul(n, tl))], False, False, 0.13))
            if mm and u > 0:
                out.append(tx(v_add(p0, v_mul(n, body + 90.0)), "%d" % round(u / 1000.0), 90.0, math.degrees(math.atan2(d[1], d[0]))))
            k += 1
        mid = v_add(v_add(a, v_mul(d, ln / 2.0)), v_mul(n, body + 260.0))
        ang = math.degrees(math.atan2(d[1], d[0]))
        if ang > 90 or ang <= -90:
            ang += 180
        pre = meas_prefix(story, m)
        out.append(tx(mid, (pre + "  " if pre else "") + "%s m" % fmt_m(ln), 170.0, ang))
        return out
    out.append(pp(pts + [pts[0]], True, True, 0.25))
    sz = meas_size(m)
    c = poly_centroid(pts)
    pre = meas_prefix(story, m)
    if pre:
        out.append(tx((c[0], c[1] + 130.0), pre, 200.0, 0.0))
    out.append(tx((c[0], c[1] - (110.0 if pre else 0.0)), meas_dims_text(m), 150.0, 0.0))
    sgn = 1.0 if poly_area_signed(pts) >= 0 else -1.0
    rect = m["kind"] == "rect" or _right_angled_quad(pts)
    edges = range(2) if rect else range(len(pts))
    for i in edges:
        p, q = pts[i], pts[(i + 1) % len(pts)]
        ln = dist(p, q)
        if ln < 400:
            continue
        d = v_unit(v_sub(q, p))
        nrm = (d[1] * sgn, -d[0] * sgn)                  # outward normal
        pos = v_add(v_add(p, v_mul(d, ln / 2.0)), v_mul(nrm, 190.0))
        ang = math.degrees(math.atan2(d[1], d[0]))
        if ang > 90 or ang <= -90:
            ang += 180
        out.append(tx(pos, fmt_m(ln), 140.0, ang))        # (a rectangle: the opposite edges are equal, so only two are labelled)
    return out


# *************** DEL 30 - 3D MESH BUILDER AND SECTION CUTS *****************
# build_mesh() turns the project into "solids": every wall piece, slab, roof facet, door, window, item and stair step is a
# list of faces (polygons of (x, y, z) in mm).  The 3D view, OBJ, IFC and 3D-DXF exports and the section view all use it.
# ToDo: ceilings under flat roofs, railings, roof windows.

MATERIALS = {   # name: (r, g, b, alpha) 0..1
    "wall": (0.88, 0.85, 0.78, 1.0), "slab": (0.62, 0.62, 0.64, 1.0), "roof": (0.60, 0.27, 0.22, 1.0),
    "door": (0.55, 0.36, 0.18, 1.0), "frame": (0.93, 0.93, 0.92, 1.0), "glass": (0.62, 0.82, 0.95, 0.35),
    "wood": (0.68, 0.50, 0.30, 1.0), "wood_light": (0.86, 0.78, 0.62, 1.0), "fabric": (0.42, 0.50, 0.64, 1.0),
    "sanitary": (0.96, 0.96, 0.98, 1.0), "metal": (0.60, 0.62, 0.66, 1.0), "appliance": (0.80, 0.81, 0.84, 1.0),
    "elec": (0.88, 0.18, 0.16, 1.0), "heat": (0.92, 0.92, 0.90, 1.0), "stair": (0.66, 0.50, 0.34, 1.0),
    "brick": (0.64, 0.33, 0.26, 1.0), "duct": (0.72, 0.74, 0.78, 1.0),
    "curtain_green": (0.24, 0.62, 0.34, 1.0), "curtain_red": (0.80, 0.16, 0.20, 1.0),     # curtains must not look like beds (blue fabric)
}


def prism_faces(poly, zb, zt):
    """Faces of a prism over a plan polygon with its own bottom / top height at every corner."""
    poly = [tuple(p) for p in poly]
    zb, zt = list(zb), list(zt)
    if poly_area_signed(poly) < 0:
        poly.reverse()
        zb.reverse()
        zt.reverse()
    n = len(poly)
    top = [(poly[i][0], poly[i][1], zt[i]) for i in range(n)]
    bot = [(poly[i][0], poly[i][1], zb[i]) for i in range(n)]
    faces = [top, bot[::-1]]
    for i in range(n):
        j = (i + 1) % n
        faces.append([bot[i], bot[j], top[j], top[i]])
    return faces


def _solid(typ, mat, faces, sidx, ref=None, name="", convex=True, ifc="", extra=None):
    d = {"type": typ, "mat": mat, "faces": faces, "sidx": sidx, "ref": ref, "name": name, "convex": convex, "ifc": ifc}
    if extra:
        d.update(extra)
    return d


def slab_solid(proj, sidx, room, holes):
    story = proj["stories"][sidx]
    elev = story_elevations(proj)[sidx]
    z0, z1 = elev - story["floor_t"], elev
    outer = ensure_ccw([tuple(p) for p in room["pts"]])
    holes = [ensure_cw(h) for h in holes]
    verts, tris = triangulate_with_holes(outer, holes)
    faces = []
    for a, b, c in tris:
        faces.append([(verts[a][0], verts[a][1], z1), (verts[b][0], verts[b][1], z1), (verts[c][0], verts[c][1], z1)])
        faces.append([(verts[c][0], verts[c][1], z0), (verts[b][0], verts[b][1], z0), (verts[a][0], verts[a][1], z0)])
    for ring in [outer] + holes:
        n = len(ring)
        for i in range(n):
            p, q = ring[i], ring[(i + 1) % n]
            faces.append([(p[0], p[1], z0), (q[0], q[1], z0), (q[0], q[1], z1), (p[0], p[1], z1)])
    return _solid("slab", "slab", faces, sidx, room["id"], room["name"] + " floor", False, "IfcSlab",
                  {"prism": (outer, holes, z0, z1)})


def stair_holes_for(proj, sidx, room_pts):
    """Outlines of the stairs coming up from the storey below that lie completely inside this room: they become holes."""
    out = []
    if sidx <= 0:
        return out
    below = proj["stories"][sidx - 1]
    for st in below["stairs"]:
        o = stair_world_outline(proj, sidx - 1, st)
        if poly_inside_poly(o, room_pts):
            out.append(o)
    return out


def lift_boxes(st, rise):
    """The elevator shaft as boxes in the stair frame: (x0, y0, x1, y1, z0, z1, material).  Front (y = 0) stays open = the door
    side; glass walls, a metal cabin floor and a metal frame post in every corner of the open side."""
    hw, dep, t = st["w"] / 2.0, st.get("dep", LIFT_DEP), 50.0
    return [(-hw, 0, hw, dep, 0.0, 100.0, "metal"),
            (-hw, dep - t, hw, dep, 100.0, rise, "glass"),
            (-hw, 0, -hw + t, dep, 100.0, rise, "glass"),
            (hw - t, 0, hw, dep, 100.0, rise, "glass"),
            (-hw, 0, -hw + 80.0, 80.0, 100.0, rise, "metal"),
            (hw - 80.0, 0, hw, 80.0, 100.0, rise, "metal")]


def tile_face(face, maxlen=1200.0, limit=400):
    """Cuts a triangle / quad face into pieces whose longest edge is at most `maxlen` (a longer face is painted in one piece
    by the painter's algorithm of the 3D view, so it can end up in front of / behind the wrong things)."""
    out, stack = [], [list(face)]
    mid = lambda p, q: ((p[0] + q[0]) / 2.0, (p[1] + q[1]) / 2.0, (p[2] + q[2]) / 2.0)
    while stack:
        f = stack.pop()
        n = len(f)
        if n > 4:
            for i in range(1, n - 1):
                stack.append([f[0], f[i], f[i + 1]])
            continue
        best, bi = 0.0, 0
        for i in range(n):
            a, b = f[i], f[(i + 1) % n]
            d = math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)
            if d > best:
                best, bi = d, i
        if best <= maxlen or len(out) + len(stack) + 2 > limit:
            out.append(f)
            continue
        j = (bi + 1) % n
        m = mid(f[bi], f[j])
        if n == 3:
            c = f[(bi + 2) % 3]
            stack.append([f[bi], m, c])
            stack.append([m, f[j], c])
        else:
            k, l = (bi + 2) % 4, (bi + 3) % 4
            m2 = mid(f[k], f[l])
            stack.append([f[bi], m, m2, f[l]])
            stack.append([m, f[j], f[k], m2])
    return out


def opening_boxes(o, g, elev):
    """Frame / leaf / glass boxes of a door or window in the wall frame: (u0, u1, v0, v1, z0, z1, material)."""
    a, b = o["pos"] - o["w"] / 2.0, o["pos"] + o["w"] / 2.0
    t = g["h"] * 2
    z0 = elev + o["sill"]
    z1 = elev + o["sill"] + o["h"]
    fw = 50.0
    boxes = []
    if o["kind"] == "window":
        boxes += [(a, a + fw, -t / 2, t / 2, z0, z1, "frame"), (b - fw, b, -t / 2, t / 2, z0, z1, "frame"),
                  (a, b, -t / 2, t / 2, z0, z0 + fw, "frame"), (a, b, -t / 2, t / 2, z1 - fw, z1, "frame"),
                  (a + fw, b - fw, -6, 6, z0 + fw, z1 - fw, "glass")]
        return boxes
    boxes += [(a, a + fw, -t / 2, t / 2, z0, z1, "frame"), (b - fw, b, -t / 2, t / 2, z0, z1, "frame"),
              (a, b, -t / 2, t / 2, z1 - fw, z1, "frame")]
    if o["kind"] == "door":
        boxes.append((a + fw, b - fw, -20, 20, z0, z1 - fw, "door"))
    elif o["kind"] == "door2":
        m = (a + b) / 2
        boxes.append((a + fw, m - 5, -20, 20, z0, z1 - fw, "door"))
        boxes.append((m + 5, b - fw, -20, 20, z0, z1 - fw, "door"))
    elif o["kind"] == "slide":
        boxes.append((a + fw, b - fw, t / 2 + 5, t / 2 + 45, z0, z1 - fw, "door"))
    return boxes


def build_mesh(proj, upto=None, with_roofs=True, with_items=True, with_stairs=True, cut=True, first=None):
    """All solids of the project (storeys first .. upto, default all).  cut=False (IFC): walls are NOT split around their doors
    and windows; the openings come back as extra solids of type "void" ({"host": (type, ref), "fill": (type, ref)})."""
    solids = []
    elevs = story_elevations(proj)
    last = len(proj["stories"]) - 1 if upto is None else min(upto, len(proj["stories"]) - 1)
    for sidx in range(max(0, min(first or 0, last)), last + 1):          # first = lowest storey shown (3D "Show from")
        story = proj["stories"][sidx]
        elev = elevs[sidx]
        sx = expand_curved(story)                    # curved walls as chains of short straight ones
        geo = wall_geometry(sx)
        # walls (a curved wall keeps the id of the real wall, so it is ONE element in the IFC file)
        for w in sx["walls"]:
            g = geo[w["id"]]
            if g["len"] < 1.0:
                continue
            if is_curtain(w):                        # rail + drape instead of a wall (only with the furniture / items)
                if with_items:
                    ztop = curtain_top(proj, sidx, w, sx)
                    for u0, u1, v0, v1, z0, z1, mat in curtain_boxes(w, g["len"], ztop, elev):
                        poly = [(g["A"][0] + g["d"][0] * u + g["n"][0] * v, g["A"][1] + g["d"][1] * u + g["n"][1] * v)
                                for u, v in ((u0, v0), (u1, v0), (u1, v1), (u0, v1))]
                        solids.append(_solid("curtain", mat, prism_faces(poly, [z0] * 4, [z1] * 4), sidx, w["id"],
                                             "Curtain", True, "IfcFurniture"))
                continue
            for pc in wall_solids(proj, sidx, w, g, sx, cut):
                solids.append(_solid("wall", "wall", prism_faces(pc["poly"], pc["zb"], pc["zt"]), sidx, w.get("src", w["id"]),
                                     "Wall", True, "IfcWall"))
        # doors and windows
        for o in sx["openings"]:
            w = get_wall(sx, o["wall"])
            if w is None:
                continue
            g = geo[w["id"]]
            typ = "window" if o["kind"] == "window" else "door"
            P = lambda u, v, g=g: (g["A"][0] + g["d"][0] * u + g["n"][0] * v, g["A"][1] + g["d"][1] * u + g["n"][1] * v)
            for u0, u1, v0, v1, z0, z1, mat in opening_boxes(o, g, elev):
                poly = [P(u0, v0), P(u1, v0), P(u1, v1), P(u0, v1)]
                solids.append(_solid(typ, mat, prism_faces(poly, [z0] * 4, [z1] * 4), sidx, o["id"],
                                     OPENING_KINDS[o["kind"]][3], True, "IfcWindow" if typ == "window" else "IfcDoor"))
            if not cut:                             # IFC: the hole in the whole wall is an IfcOpeningElement of its own
                a, b = o["pos"] - o["w"] / 2.0, o["pos"] + o["w"] / 2.0
                tt = g["h"] * 2 + 20.0
                poly = [P(a, -tt / 2), P(b, -tt / 2), P(b, tt / 2), P(a, tt / 2)]
                z0, z1 = elev + o["sill"], elev + o["sill"] + o["h"]
                solids.append(_solid("void", "glass", prism_faces(poly, [z0] * 4, [z1] * 4), sidx, o["id"],
                                     OPENING_KINDS[o["kind"]][3] + " opening", True, "IfcOpeningElement",
                                     {"host": ("wall", w.get("src", w["id"])), "fill": (typ, o["id"]), "vkey": "op%d" % o["id"]}))
        # floors
        for r in story["rooms"]:
            if len(r["pts"]) >= 3:
                pts = [tuple(p) for p in r["pts"]]
                solids.append(slab_solid(proj, sidx, r, stair_holes_for(proj, sidx, pts)))
        # roofs
        if with_roofs:
            for rf in story["roofs"]:
                holes = []
                if cut:                                     # the roof is open under a dormer and a roof window
                    holes = [dormer_poly(dm, dormer_depth(story, dm)) for dm in story.get("dormers", [])]
                    holes += [ol for ol in (rwin_outline(story, rw) for rw in story.get("rwins", [])) if ol]
                for f in roof_facets(rf):
                    a, b, c = f["plane"]
                    tv = rf["t"] * math.sqrt(1.0 + a * a + b * b)      # vertical thickness of a slab `t` thick, measured square to the slope
                    pieces = [f["poly"]]
                    for hole in holes:
                        pieces = [q for pc in pieces for q in poly_minus_convex(pc, hole)]
                    for pc in pieces:
                        zi = [elev + a * p[0] + b * p[1] + c for p in pc]
                        solids.append(_solid("roof", "roof", prism_faces(pc, zi, [z + tv for z in zi]), sidx, rf["id"],
                                             "Roof", True, "IfcRoof"))
            for dm in story.get("dormers", []):
                solids += dormer_solids(proj, sidx, dm, cut)
                if not cut:
                    solids += dormer_void_solids(proj, sidx, dm)
            for rw in story.get("rwins", []):
                solids += rwin_solids(proj, sidx, rw, cut)
        # stairs
        if with_stairs:
            for st in story["stairs"]:
                rise = stair_rise(proj, sidx, st)
                lay = stair_layout(st, rise)
                for poly, zt in lay["treads"]:
                    wp = stair_to_world(st, poly)
                    zb = elev if lay["solid"] else elev + zt - 60.0
                    if lay["solid"] and stair_hollow(st):                  # open underneath / cupboard: the steps are thin slabs
                        zb = max(elev, elev + zt - STAIR_STRUCT)
                    solids.append(_solid("stair", "stair", prism_faces(wp, [zb] * len(wp), [elev + zt] * len(wp)), sidx,
                                         st["id"], "Stair", True, "IfcStair"))
                for x0, y0, x1, y1, z0, z1, mat in stair_cupboard_boxes(st, rise):       # cupboard / wardrobe under the stairs
                    wp = stair_to_world(st, [(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
                    solids.append(_solid("cupboard", mat, prism_faces(wp, [elev + z0] * 4, [elev + z1] * 4), sidx, st["id"],
                                         "Stair cupboard", True, "IfcFurniture"))
                if st["kind"] == "lift":
                    for x0, y0, x1, y1, z0, z1, mat in lift_boxes(st, rise):
                        wp = stair_to_world(st, [(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
                        solids.append(_solid("stair", mat, prism_faces(wp, [elev + z0] * 4, [elev + z1] * 4), sidx, st["id"],
                                             "Lift", True, "IfcTransportElement"))
                if st["kind"] == "spiral":
                    col = [(100 * math.cos(math.radians(a)), 100 * math.sin(math.radians(a))) for a in range(0, 360, 30)]
                    wp = stair_to_world(st, col)
                    solids.append(_solid("stair", "metal", prism_faces(wp, [elev] * len(wp), [elev + rise] * len(wp)), sidx,
                                         st["id"], "Stair column", True, "IfcStair"))
        # items
        if with_items:
            for it in story["items"]:
                if is_shaft(it) and it.get("up") and it["z"] >= 0 and sidx < last:
                    it = dict(it)                        # a shaft that "continues up": as tall as the storeys drawn above it
                    it["h"] = max(it["h"], elevs[last] + proj["stories"][last]["height"] - elev - it["z"])
                cz = it["z"]
                base = elev + (story["height"] - it["h"] if cz < 0 else cz)
                for x0, y0, z0, x1, y1, z1, mat in item_boxes(it):
                    poly = [item_to_world(it, p) for p in ((x0, y0), (x1, y0), (x1, y1), (x0, y1))]
                    solids.append(_solid("item", mat, prism_faces(poly, [base + z0] * 4, [base + z1] * 4), sidx, it["id"],
                                         CATALOG[it["type"]]["name"] if it["type"] in CATALOG else it["type"], True,
                                         CATALOG[it["type"]]["ifc"] if it["type"] in CATALOG else "IfcFurniture"))
    return solids


def mesh_bounds(solids):
    xs, ys, zs = [], [], []
    for s in solids:
        for f in s["faces"]:
            for p in f:
                xs.append(p[0])
                ys.append(p[1])
                zs.append(p[2])
    if not xs:
        return (0, 0, 0, 1, 1, 1)
    return (min(xs), min(ys), min(zs), max(xs), max(ys), max(zs))


# ---- section cut ---------------------------------------------------------------------------------------------
def _slice_convex(solid, A, e, nrm):
    pts = []
    for f in solid["faces"]:
        n = len(f)
        for i in range(n):
            p, q = f[i], f[(i + 1) % n]
            dp = (p[0] - A[0]) * nrm[0] + (p[1] - A[1]) * nrm[1]
            dq = (q[0] - A[0]) * nrm[0] + (q[1] - A[1]) * nrm[1]
            if abs(dp) < 1e-6:
                pts.append(p)
            if (dp > 1e-6 and dq < -1e-6) or (dp < -1e-6 and dq > 1e-6):
                t = dp / (dp - dq)
                pts.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1]), p[2] + t * (q[2] - p[2])))
    uniq = []
    for p in pts:
        s = (p[0] - A[0]) * e[0] + (p[1] - A[1]) * e[1]
        q = (round(s, 1), round(p[2], 1))
        if q not in uniq:
            uniq.append(q)
    if len(uniq) < 3:
        return None
    cx = sum(p[0] for p in uniq) / len(uniq)
    cy = sum(p[1] for p in uniq) / len(uniq)
    uniq.sort(key=lambda p: math.atan2(p[1] - cy, p[0] - cx))
    if poly_area(uniq) < 1.0:
        return None
    return uniq


def _slice_slab(solid, A, e, B):
    outer, holes, z0, z1 = solid["prism"]
    ts = []
    for ring in [outer] + holes:
        n = len(ring)
        for i in range(n):
            p, q = ring[i], ring[(i + 1) % n]
            d = v_sub(B, A)
            ed = v_sub(q, p)
            den = v_cross(d, ed)
            if abs(den) < 1e-9:
                continue
            t = v_cross(v_sub(p, A), ed) / den          # position along the cut line 0..1
            u = v_cross(v_sub(p, A), d) / den            # position along the polygon edge 0..1
            if 0.0 <= u < 1.0:
                ts.append(t)
    ts.sort()
    L = dist(A, B)
    out = []
    for k in range(0, len(ts) - 1, 2):
        s0, s1 = max(0.0, ts[k] * L), min(L, ts[k + 1] * L)
        if s1 - s0 > 1.0:
            out.append([(s0, z0), (s1, z0), (s1, z1), (s0, z1)])
    return out


def section_cut(proj, A, B, solids=None):
    """Cut the model by the vertical plane through A-B and look towards the LEFT of A->B.
    Returns [{"poly": [(s, z)...], "mat": str, "type": str, "sidx": int}] with s = distance along A->B."""
    if solids is None:
        solids = build_mesh(proj, with_items=False)
    L = dist(A, B)
    e = v_unit(v_sub(B, A))
    nrm = v_perp(e)
    out = []
    for s in solids:
        if s["type"] not in ("wall", "slab", "roof", "stair", "cupboard"):
            continue
        if s.get("prism"):
            for poly in _slice_slab(s, A, e, B):
                out.append({"poly": poly, "mat": s["mat"], "type": s["type"], "sidx": s["sidx"], "lay": s.get("lay")})
            continue
        poly = _slice_convex(s, A, e, nrm)
        if poly is None:
            continue
        poly = clip_poly(poly, lambda p: p[0])
        poly = clip_poly(poly, lambda p: L - p[0])
        if len(poly) >= 3 and poly_area(poly) > 1.0:
            out.append({"poly": poly, "mat": s["mat"], "type": s["type"], "sidx": s["sidx"], "lay": s.get("lay")})
    return out


# *************** DEL 40 - PLAN DRAWING PRIMITIVES (one source for the screen AND every export) *****************
# plan_prims() turns one storey into plain drawing primitives:
#   {"k": "poly", "pts": [...], "closed": bool, "fill": None|"wall"|"room"|"head1"|"head2", "layer": str, "lw": mm, "dash": bool, "eid": id}
#   {"k": "circle", "c": (x, y), "r": mm, ...}     {"k": "arc", "c": (x, y), "r": mm, "a0": deg, "a1": deg, ...}
#   {"k": "text", "p": (x, y), "s": str, "h": mm, "rot": deg, "layer": str, "eid": id}
# ToDo: hatch patterns instead of solid wall fill; door tags; north arrow.

LAYERS = {   # name: (AutoCAD colour index, screen colour)
    "A-WALL": (7, "#1c1c1c"), "A-WALL-PATT": (8, "#3a3a3a"), "A-DOOR": (3, "#1a8f3a"), "A-GLAZ": (5, "#1f5fd0"),
    "A-AREA": (9, "#9aa0a6"), "A-AREA-IDEN": (2, "#7a5d00"), "A-AREA-HEAD": (8, "#8a8a8a"),
    "A-FURN": (6, "#a02c9a"), "A-FURN-SANI": (4, "#0b8a9a"), "A-FURN-CASE": (30, "#c26a00"),
    "E-POWR": (1, "#d01818"), "E-LITE": (1, "#d01818"), "M-HVAC": (30, "#c06040"), "A-STRS": (172, "#6a4a2a"),
    "A-ROOF": (32, "#8a3a2a"), "A-ANNO-DIMS": (2, "#1a1a8a"), "A-ANNO-TEXT": (7, "#202020"), "A-SECT": (1, "#d01818"),
    "A-CURT": (6, "#8a3aa0"), "A-NOTE": (5, "#4f7bd0"), "A-MEAS": (3, "#14907f"), "A-GHOST": (9, "#c4c4c4"), "A-DORM": (200, "#7a3a8a"), "A-WALL-CEN": (8, "#8a8a8a"),
}
FILL_COLORS = {"wall": "#2b2b2b", "room": "#f3efe6", "head1": "#c9a9a9", "head2": "#e6d9c4", "clear": "#f3efe6"}


def _pp(pts, layer, closed=True, fill=None, lw=0.25, dash=False, eid=None):
    return {"k": "poly", "pts": [tuple(p) for p in pts], "closed": closed, "fill": fill, "layer": layer, "lw": lw,
            "dash": dash, "eid": eid}


def _tx(p, s, h, layer, rot=0.0, eid=None, anchor="c"):
    return {"k": "text", "p": tuple(p), "s": s, "h": h, "rot": rot, "layer": layer, "eid": eid, "anchor": anchor,
            "lw": 0.18, "dash": False, "fill": None}


def _arc_pts(c, r, a0, a1, n=16):
    return [(c[0] + r * math.cos(math.radians(a0 + (a1 - a0) * i / n)),
             c[1] + r * math.sin(math.radians(a0 + (a1 - a0) * i / n))) for i in range(n + 1)]


def _door_prims(o, g, t, eid):
    P = []
    a, b = o["pos"] - o["w"] / 2.0, o["pos"] + o["w"] / 2.0
    d, n = g["d"], g["n"]

    def pt(u, v):
        return (g["A"][0] + d[0] * u + n[0] * v, g["A"][1] + d[1] * u + n[1] * v)
    sw = 1 if o.get("swing", 1) >= 0 else -1
    k = o["kind"]
    if k == "window":
        for v in (-t / 6.0, 0.0, t / 6.0):
            P.append(_pp([pt(a, v), pt(b, v)], "A-GLAZ", False, lw=0.18, eid=eid))
        P.append(_pp([pt(a, -t / 2), pt(b, -t / 2), pt(b, t / 2), pt(a, t / 2)], "A-GLAZ", True, lw=0.18, eid=eid))
        return P
    P.append(_pp([pt(a, -t / 2), pt(a, t / 2)], "A-DOOR", False, lw=0.18, eid=eid))
    P.append(_pp([pt(b, -t / 2), pt(b, t / 2)], "A-DOOR", False, lw=0.18, eid=eid))
    if k == "passage":
        return P
    if k == "slide":
        v = sw * (t / 2 + 30)
        P.append(_pp([pt(a, v - 20), pt(b, v - 20), pt(b, v + 20), pt(a, v + 20)], "A-DOOR", True, lw=0.18, eid=eid))
        return P

    def leaf(hinge_u, free_u, width):
        hv = sw * t / 2
        H = pt(hinge_u, hv)
        tip = (H[0] + n[0] * sw * width, H[1] + n[1] * sw * width)
        P.append(_pp([H, tip], "A-DOOR", False, lw=0.3, eid=eid))
        J = pt(free_u, hv)
        a0 = math.degrees(math.atan2(J[1] - H[1], J[0] - H[0]))
        a1 = math.degrees(math.atan2(tip[1] - H[1], tip[0] - H[0]))
        if (a1 - a0) % 360 > 180:
            a0, a1 = a1, a0
        if (a1 - a0) % 360 != 0:
            a1 = a0 + ((a1 - a0) % 360)
        P.append({"k": "arc", "c": H, "r": width, "a0": a0, "a1": a1, "layer": "A-DOOR", "lw": 0.13, "dash": False,
                  "eid": eid, "pts": _arc_pts(H, width, a0, a1)})
    if k == "door2":
        m = (a + b) / 2.0
        leaf(a, m, o["w"] / 2.0)
        leaf(b, m, o["w"] / 2.0)
    else:
        if o.get("hinge", 0) == 0:
            leaf(a, b, o["w"])
        else:
            leaf(b, a, o["w"])
    return P


def dormer_shade_prims(story, dm, lims):
    """Under the shading of the low roof: a clear patch where the dormer is, with its own shading of low dormer ceiling."""
    d = dormer_depth(story, dm)
    P = [_pp(dormer_poly(dm, d), "A-DORM", True, fill="clear", lw=0.05, eid=dm["id"])]
    for i, lim in enumerate(lims[:2]):
        for poly in dormer_low_polys(story, dm, lim):
            P.append(_pp(poly, "A-AREA-HEAD", True, fill="head2" if i == 0 else "head1", lw=0.05))
    return P


def dormer_symbol_prims(story, dm):
    d = dormer_depth(story, dm)
    w, wt = dm["w"], dm.get("wt", DORMER_WT)
    P = [_pp(dormer_poly(dm, d), "A-DORM", True, lw=0.35, eid=dm["id"]),
         _pp(dormer_poly(dm, d, True), "A-DORM", True, lw=0.13, eid=dm["id"])]
    if dm["kind"] == "gable":
        P.append(_pp([dormer_pt(dm, 0.0, -150.0), dormer_pt(dm, 0.0, d)], "A-DORM", False, lw=0.13, dash=True, eid=dm["id"]))
    win = _dormer_window(story, dm)
    if win is not None:
        hw = win[0]
        for v in (0.0, wt / 2.0, wt):
            P.append(_pp([dormer_pt(dm, -hw, v), dormer_pt(dm, hw, v)], "A-GLAZ", False, lw=0.18, eid=dm["id"]))
    return P


def rwin_symbol_prims(story, rw):
    poly = rwin_outline(story, rw)
    if poly is None:
        return []
    return [_pp(poly, "A-GLAZ", True, lw=0.25, eid=rw["id"]), _pp([poly[0], poly[2]], "A-GLAZ", False, lw=0.13, eid=rw["id"]),
            _pp([poly[1], poly[3]], "A-GLAZ", False, lw=0.13, eid=rw["id"])]


def plan_prims(proj, sidx, opt=None):
    o = {"rooms": True, "roof": True, "headroom": True, "dims": True, "texts": True, "items": True, "stairs": True,
         "area": True, "sections": True}
    if opt:
        o.update(opt)
    story = proj["stories"][sidx]
    P = []
    if o["rooms"]:
        for r in story["rooms"]:
            if len(r["pts"]) >= 3:
                P.append(_pp(r["pts"], "A-AREA", True, fill="room", lw=0.13, eid=r["id"]))
    if o["headroom"] and story["roofs"]:
        lims = sorted(proj["settings"].get("headroom", [1000, 1900]), reverse=True)
        for i, lim in enumerate(lims[:2]):
            for poly in headroom_regions(story, lim):
                P.append(_pp(poly, "A-AREA-HEAD", True, fill="head2" if i == 0 else "head1", lw=0.05))
        for dm in story.get("dormers", []):
            P += dormer_shade_prims(story, dm, lims)
    sx = expand_curved(story)
    geo = wall_geometry(sx)
    for eid, poly in wall_plan_polys(story):
        P.append(_pp(poly, "A-WALL", True, fill="wall", lw=0.35, eid=eid))
    for op in sx["openings"]:
        w = get_wall(sx, op["wall"])
        if w is not None:
            P += _door_prims(op, geo[w["id"]], w["t"], op["id"])
    for w in sx["walls"]:                                            # curtain walls: rail + drape
        if is_curtain(w) and geo[w["id"]]["len"] >= 1.0:
            P += curtain_plan_prims(w, geo[w["id"]], lambda pts, closed, dash, lw, e=w["id"]: _pp(pts, "A-CURT", closed, lw=lw, dash=dash, eid=e))
    if o.get("arcs"):                       # CAD files: the real arc (ARC entity) of every curved wall as a centre line
        for w in story["walls"]:
            arc = wall_arc(w)
            if arc:
                a0, a1 = math.degrees(arc["a0"]), math.degrees(arc["a0"] + arc["sweep"])
                if arc["sweep"] < 0:
                    a0, a1 = a1, a0           # an ARC always runs counter-clockwise
                P.append({"k": "arc", "c": arc["c"], "r": arc["r"], "a0": a0, "a1": a1, "layer": "A-WALL-CEN", "lw": 0.13,
                          "dash": True, "eid": w["id"], "pts": wall_arc_polyline(w)})
    if o["roof"]:
        for rf in story["roofs"]:
            P.append(_pp(roof_rect_poly(rf, rf["over"]), "A-ROOF", True, lw=0.13, dash=True, eid=rf["id"]))
            for f in roof_facets(rf, 0.0):
                P.append(_pp(f["poly"], "A-ROOF", True, lw=0.13, dash=True, eid=rf["id"]))
        if o["headroom"]:
            for lim in proj["settings"].get("headroom", [1000, 1900])[:2]:
                for k, (p, q) in enumerate(headroom_contours(story, lim)):
                    P.append(_pp([p, q], "A-AREA-HEAD", False, lw=0.18, dash=True))
                    if k == 0:
                        P.append(_tx(((p[0] + q[0]) / 2, (p[1] + q[1]) / 2), "h=" + fmt_m(lim), 120, "A-AREA-HEAD"))
        for dm in story.get("dormers", []):
            P += dormer_symbol_prims(story, dm)
        for rw in story.get("rwins", []):
            P += rwin_symbol_prims(story, rw)
    if o["items"]:
        for it in story["items"]:
            lay = item_layer(it)
            for pr in item_symbol(it):
                if pr[0] == "p":
                    P.append(_pp([item_to_world(it, q) for q in pr[1]], lay, pr[2], lw=0.18, eid=it["id"]))
                elif pr[0] == "c":
                    c = item_to_world(it, (pr[1], pr[2]))
                    P.append({"k": "circle", "c": c, "r": pr[3], "layer": lay, "lw": 0.18, "dash": False, "eid": it["id"]})
                else:
                    c = item_to_world(it, (pr[1], pr[2]))
                    P.append(_tx(c, pr[3], pr[4], lay, 0.0, it["id"]))
        if sidx > 0 and o.get("below_stairs", True):           # chimneys / flues / vent shafts that come up from storeys below
            for k in range(sidx):
                for it in proj["stories"][k]["items"]:
                    if not is_shaft(it) or not it.get("up"):
                        continue                                # not a shaft, or it is switched off ("Continues up" = No)
                    if any(math.hypot(b["x"] - it["x"], b["y"] - it["y"]) < 150 for b in story["items"] if b["type"] == it["type"]):
                        continue                                # this storey has its own copy in the same place
                    for pr in item_symbol(it):
                        if pr[0] == "p":
                            P.append(_pp([item_to_world(it, q) for q in pr[1]], "A-GHOST", pr[2], lw=0.13, dash=True))
                        elif pr[0] == "c":
                            c = item_to_world(it, (pr[1], pr[2]))
                            P.append({"k": "circle", "c": c, "r": pr[3], "layer": "A-GHOST", "lw": 0.13, "dash": True})
    if o["stairs"]:
        for st in story["stairs"]:
            lay = stair_layout(st, stair_rise(proj, sidx, st))
            P.append(_pp(stair_to_world(st, lay["outline"]), "A-STRS", True, lw=0.25, eid=st["id"]))
            for p, q in lay["lines"]:
                P.append(_pp(stair_to_world(st, [p, q]), "A-STRS", False, lw=0.13, eid=st["id"]))
            P.append(_pp(stair_to_world(st, lay["arrow"]), "A-STRS", False, lw=0.18, eid=st["id"]))
            for seg in stair_cupboard_plan_lines(st, stair_rise(proj, sidx, st)):       # cupboard under the stairs (dashed)
                P.append(_pp(stair_to_world(st, seg), "A-STRS", False, lw=0.13, dash=True, eid=st["id"]))
            a = stair_to_world(st, [lay["arrow"][0]])[0]
            P.append(_tx(a, "LIFT" if st["kind"] == "lift" else "UP", 140, "A-STRS", 0.0, st["id"]))
        if sidx > 0 and o.get("below_stairs", True):          # the stairs / lift that arrive from the storey below
            for st in proj["stories"][sidx - 1]["stairs"]:
                lay = stair_layout(st, stair_rise(proj, sidx - 1, st))
                P.append(_pp(stair_to_world(st, lay["outline"]), "A-STRS", True, lw=0.18, dash=True))
                for p, q in lay["lines"]:
                    P.append(_pp(stair_to_world(st, [p, q]), "A-STRS", False, lw=0.09, dash=True))
                e = stair_to_world(st, [lay["arrow"][-1]])[0]
                P.append(_tx(e, "LIFT" if st["kind"] == "lift" else "DN", 140, "A-STRS"))
    if o["rooms"] and o["area"]:
        for r in story["rooms"]:
            if len(r["pts"]) >= 3:
                c = label_point([tuple(p) for p in r["pts"]])
                P.append(_tx((c[0], c[1] + 100), r["name"], 220, "A-AREA-IDEN", 0.0, r["id"]))
                txt = fmt_area(poly_area(r["pts"]))
                if story["roofs"]:
                    lim = proj["settings"].get("headroom", [1000, 1900])[-1]
                    txt += "  (h>=%s: %s)" % (fmt_m(lim), fmt_area(room_headroom_area(story, r, lim)))
                P.append(_tx((c[0], c[1] - 160), txt, 150, "A-AREA-IDEN", 0.0, r["id"]))
    if o["dims"]:
        for dm in story["dims"]:
            P += dim_prims(dm)
    if o["texts"]:
        for tx in story["texts"]:
            if tx.get("ghost"):                    # ghost notes are not annotations: never in the real drawing / exports
                continue
            P.append(_tx((tx["x"], tx["y"]), tx["s"], tx["h"], "A-ANNO-TEXT", tx.get("rot", 0.0), tx["id"], "w"))
    if o.get("meas"):                              # the second ghost layer: rulers + measured rooms, on screen only
        for ms in story.get("meas", []):
            def _mp(pts, closed, dash, lw, e=ms["id"]):
                return _pp(pts, "A-MEAS", closed, lw=lw, dash=dash, eid=e)

            def _mt(p, s, h, rot=0.0, e=ms["id"]):
                pr = _tx(p, s, h, "A-MEAS", rot, e, "c")
                pr["meas"] = True
                return pr
            P += meas_prims(story, ms, _mp, _mt)
    if o.get("notes"):                             # the ghost layer, on screen only (the plan window asks for it)
        for tx in story["texts"]:
            if tx.get("ghost"):
                pr = _tx((tx["x"], tx["y"]), tx["s"], tx["h"], "A-NOTE", tx.get("rot", 0.0), tx["id"], "w")
                pr["note"] = True
                P.append(pr)
    if o["sections"]:
        for sc in story["sections"]:
            a, b = tuple(sc["a"]), tuple(sc["b"])
            e = v_unit(v_sub(b, a))
            nn = v_perp(e)
            P.append(_pp([a, b], "A-SECT", False, lw=0.35, dash=True, eid=sc["id"]))
            for q in (a, b):
                P.append(_pp([q, v_add(q, v_mul(nn, 500))], "A-SECT", False, lw=0.35, eid=sc["id"]))
                P.append(_tx(v_add(q, v_mul(nn, 750)), sc.get("name", "A"), 250, "A-SECT", 0.0, sc["id"]))
    return P


def dim_prims(dm):
    a, b = tuple(dm["a"]), tuple(dm["b"])
    ln = dist(a, b)
    if ln < 1:
        return []
    e = v_unit(v_sub(b, a))
    n = v_perp(e)
    off = dm["off"]
    sg = 1 if off >= 0 else -1
    p1, p2 = v_add(a, v_mul(n, off)), v_add(b, v_mul(n, off))
    ext = v_mul(n, sg * 120)
    P = [_pp([a, v_add(p1, ext)], "A-ANNO-DIMS", False, lw=0.13, eid=dm["id"]),
         _pp([b, v_add(p2, ext)], "A-ANNO-DIMS", False, lw=0.13, eid=dm["id"]),
         _pp([p1, p2], "A-ANNO-DIMS", False, lw=0.18, eid=dm["id"])]
    tk_ = v_mul(v_unit((e[0] + n[0], e[1] + n[1])), 110)
    for q in (p1, p2):
        P.append(_pp([v_sub(q, tk_), v_add(q, tk_)], "A-ANNO-DIMS", False, lw=0.3, eid=dm["id"]))
    ang = math.degrees(math.atan2(e[1], e[0]))
    if ang > 90 or ang <= -90:
        ang += 180
    mid = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
    tp = v_add(mid, v_mul(n, sg * 110))
    P.append(_tx(tp, fmt_m(ln), 150, "A-ANNO-DIMS", ang, dm["id"]))
    return P


def ghost_prims(proj, sidx):
    """Outline of the walls of the storey BELOW, light grey (screen only)."""
    out = []
    if sidx <= 0:
        return out
    story = proj["stories"][sidx - 1]
    for _, poly in wall_plan_polys(story):
        out.append(_pp(poly, "A-GHOST", True, lw=0.13))
    return out


def plan_bounds(proj, sidx):
    story = proj["stories"][sidx]
    xs, ys = [], []
    for p in story_wall_points(story):
        xs.append(p[0])
        ys.append(p[1])
    for r in story["rooms"]:
        for p in r["pts"]:
            xs.append(p[0])
            ys.append(p[1])
    for rf in story["roofs"]:
        xs += [rf["rect"][0] - rf["over"], rf["rect"][2] + rf["over"]]
        ys += [rf["rect"][1] - rf["over"], rf["rect"][3] + rf["over"]]
    for it in story["items"]:
        xs.append(it["x"])
        ys.append(it["y"])
    if not xs:
        return (0.0, 0.0, 10000.0, 8000.0)
    return (min(xs), min(ys), max(xs), max(ys))


# *************** DEL 50 - SAVE / LOAD AND EXPORTS (DXF, SVG, PDF, OBJ, IFC4, CSV) *****************
# DXF is written as R12 ASCII (AC1009): the oldest, simplest dialect, read by AutoCAD, BricsCAD, LibreCAD, QCAD, DraftSight ...
# Units are MILLIMETRES.  DWG is a closed format: open the DXF in AutoCAD and "Save as" DWG (or use the free ODA File Converter).
# IFC4 uses tessellated geometry (IfcTriangulatedFaceSet): Revit / ArchiCAD / FreeCAD / BIMvision import it.
# ToDo: DXF R2000 with LWPOLYLINE/HATCH; IFC wall openings as IfcOpeningElement; DWG via ODA converter if installed.
import uuid
import re


# ---- save / load ----------------------------------------------------------------------------------------------
def load_project(path):
    with open(path, encoding="utf-8-sig") as fh:
        p = json.load(fh)
    if p.get("format") != FILE_FORMAT:
        raise ValueError("This is not an Architect project file.")
    p.setdefault("settings", default_settings())
    for k, v in default_settings().items():
        p["settings"].setdefault(k, v)
    mx = p.get("next_id", 1)
    for s in p["stories"]:
        for k in KIND_LISTS.values():
            s.setdefault(k, [])
        s.setdefault("floor_t", 250)
        s.setdefault("base", 0)
        for lst in KIND_LISTS.values():
            for e in s[lst]:
                mx = max(mx, e["id"] + 1)
        mx = max(mx, s.get("id", 0) + 1)
    p["next_id"] = mx
    ensure_extras(p)
    return p


def save_project(proj, path):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(proj, fh, ensure_ascii=False, indent=1)
    os.replace(tmp, path)


def safe_name(s):
    s = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", s).strip(" .")
    return s or "project"


# ---- DXF -----------------------------------------------------------------------------------------------------
class Dxf(object):
    def __init__(self):
        self.ents = []
        self.layers = {}

    def _l(self, layer):
        if layer not in self.layers:
            self.layers[layer] = LAYERS.get(layer, (7, "#000000"))[0] if not layer.startswith("3D-") else 7
        return layer

    def _e(self, *pairs):
        for c, v in pairs:
            self.ents.append("%d\n%s" % (c, v))

    @staticmethod
    def _f(v):
        return "%.4f" % v

    def line(self, p, q, layer, dash=False):
        self._e((0, "LINE"), (8, self._l(layer)), *([(6, "DASHED")] if dash else []),
                (10, self._f(p[0])), (20, self._f(p[1])), (30, "0.0"), (11, self._f(q[0])), (21, self._f(q[1])), (31, "0.0"))

    def poly(self, pts, layer, closed, dash=False):
        if len(pts) == 2 and not closed:
            return self.line(pts[0], pts[1], layer, dash)
        self._e((0, "POLYLINE"), (8, self._l(layer)), *([(6, "DASHED")] if dash else []),
                (66, 1), (10, "0.0"), (20, "0.0"), (30, "0.0"), (70, 1 if closed else 0))
        for p in pts:
            self._e((0, "VERTEX"), (8, layer), (10, self._f(p[0])), (20, self._f(p[1])), (30, "0.0"))
        self._e((0, "SEQEND"), (8, layer))

    def circle(self, c, r, layer):
        self._e((0, "CIRCLE"), (8, self._l(layer)), (10, self._f(c[0])), (20, self._f(c[1])), (30, "0.0"), (40, self._f(r)))

    def arc(self, c, r, a0, a1, layer):
        self._e((0, "ARC"), (8, self._l(layer)), (10, self._f(c[0])), (20, self._f(c[1])), (30, "0.0"), (40, self._f(r)),
                (50, self._f(a0 % 360)), (51, self._f(a1 % 360)))

    def text(self, p, s, h, rot, layer, anchor="c"):
        s = "".join(ch if ord(ch) < 128 else {"²": "^2", "å": "a", "ä": "a", "ö": "o", "Å": "A",
                                              "Ä": "A", "Ö": "O"}.get(ch, "?") for ch in s)
        if anchor == "c":
            self._e((0, "TEXT"), (8, self._l(layer)), (10, self._f(p[0])), (20, self._f(p[1])), (30, "0.0"),
                    (40, self._f(h)), (1, s), (50, self._f(rot)), (72, 1), (11, self._f(p[0])), (21, self._f(p[1])),
                    (31, "0.0"), (73, 2))
        else:
            self._e((0, "TEXT"), (8, self._l(layer)), (10, self._f(p[0])), (20, self._f(p[1])), (30, "0.0"),
                    (40, self._f(h)), (1, s), (50, self._f(rot)))

    def solid(self, pts, layer):
        """Filled polygon (triangulated into SOLIDs)."""
        if len(pts) == 4:
            tris = [(0, 1, 2, 3)]
        else:
            tris = [(a, b, c, c) for a, b, c in triangulate(pts)]
        for a, b, c, d in tris:
            q = [pts[a], pts[b], pts[d], pts[c]]       # SOLID corner order is 1, 2, 4, 3
            self._e((0, "SOLID"), (8, self._l(layer)))
            for i, p in enumerate(q):
                self._e((10 + i, self._f(p[0])), (20 + i, self._f(p[1])), (30 + i, "0.0"))

    def face3d(self, pts, layer):
        q = list(pts)
        while len(q) < 4:
            q.append(q[-1])
        self._e((0, "3DFACE"), (8, self._l(layer)))
        for i, p in enumerate(q[:4]):
            self._e((10 + i, self._f(p[0])), (20 + i, self._f(p[1])), (30 + i, self._f(p[2])))

    def text_out(self):
        o = []
        a = o.append
        a("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1009\n0\nENDSEC")
        a("0\nSECTION\n2\nTABLES")
        a("0\nTABLE\n2\nLTYPE\n70\n2\n0\nLTYPE\n2\nCONTINUOUS\n70\n0\n3\nSolid line\n72\n65\n73\n0\n40\n0.0\n"
          "0\nLTYPE\n2\nDASHED\n70\n0\n3\nDashed\n72\n65\n73\n2\n40\n150.0\n49\n100.0\n49\n-50.0\n0\nENDTAB")
        a("0\nTABLE\n2\nLAYER\n70\n%d\n0\nLAYER\n2\n0\n70\n0\n62\n7\n6\nCONTINUOUS" % (len(self.layers) + 1))
        for name, col in sorted(self.layers.items()):
            a("0\nLAYER\n2\n%s\n70\n0\n62\n%d\n6\nCONTINUOUS" % (name, col))
        a("0\nENDTAB")
        a("0\nTABLE\n2\nSTYLE\n70\n1\n0\nSTYLE\n2\nSTANDARD\n70\n0\n40\n0.0\n41\n1.0\n50\n0.0\n71\n0\n42\n200.0\n3\ntxt\n4\n\n0\nENDTAB")
        a("0\nENDSEC")
        a("0\nSECTION\n2\nENTITIES")
        o.extend(self.ents)
        a("0\nENDSEC\n0\nEOF")
        return "\n".join(o) + "\n"


def prims_to_dxf(dxf, prims, dx=0.0, dy=0.0, fill_walls=True):
    sh = lambda p: (p[0] + dx, p[1] + dy)
    for pr in prims:
        k = pr["k"]
        if k == "poly":
            pts = [sh(p) for p in pr["pts"]]
            if pr["fill"] == "wall" and fill_walls:
                dxf.solid(pts, "A-WALL-PATT")
            if pr["fill"] in ("head1", "head2", "clear"):
                continue
            dxf.poly(pts, pr["layer"], pr["closed"], pr["dash"])
        elif k == "circle":
            dxf.circle(sh(pr["c"]), pr["r"], pr["layer"])
        elif k == "arc":
            dxf.arc(sh(pr["c"]), pr["r"], pr["a0"], pr["a1"], pr["layer"])
        elif k == "text":
            dxf.text(sh(pr["p"]), pr["s"], pr["h"], pr["rot"], pr["layer"], pr.get("anchor", "c"))


def export_dxf_story(proj, sidx, path, fill_walls=True):
    d = Dxf()
    prims_to_dxf(d, plan_prims(proj, sidx, {"sections": True, "arcs": True}), 0, 0, fill_walls)
    with open(path, "w", encoding="ascii", newline="\r\n") as fh:
        fh.write(d.text_out())


def export_dxf_combined(proj, path, fill_walls=True):
    d = Dxf()
    dx = 0.0
    for i in range(len(proj["stories"])):
        x0, y0, x1, y1 = plan_bounds(proj, i)
        prims_to_dxf(d, plan_prims(proj, i, {"arcs": True}), dx - x0, 0, fill_walls)
        d.text((dx - x0 + (x0 + x1) / 2, y1 + 1500), proj["stories"][i]["name"], 400, 0, "A-ANNO-TEXT")
        dx += (x1 - x0) + 4000
    with open(path, "w", encoding="ascii", newline="\r\n") as fh:
        fh.write(d.text_out())


def export_dxf_3d(proj, path):
    d = Dxf()
    names = {"wall": "3D-WALL", "slab": "3D-SLAB", "roof": "3D-ROOF", "door": "3D-DOOR", "window": "3D-WINDOW",
             "item": "3D-ITEM", "stair": "3D-STAIR", "cupboard": "3D-ITEM", "curtain": "3D-CURTAIN"}
    for s in build_mesh(proj):
        lay = names.get(s["type"], "3D-OTHER")
        for f in s["faces"]:
            if len(f) <= 4:
                d.face3d(f, lay)
            else:
                for i in range(1, len(f) - 1):
                    d.face3d([f[0], f[i], f[i + 1]], lay)
    with open(path, "w", encoding="ascii", newline="\r\n") as fh:
        fh.write(d.text_out())


# ---- SVG -----------------------------------------------------------------------------------------------------
def _hexrgb(h):
    return (int(h[1:3], 16) / 255.0, int(h[3:5], 16) / 255.0, int(h[5:7], 16) / 255.0)


def export_svg_story(proj, sidx, path, scale=50, fill_walls=True):
    prims = plan_prims(proj, sidx)
    x0, y0, x1, y1 = plan_bounds(proj, sidx)
    m = 1500.0
    x0, y0, x1, y1 = x0 - m, y0 - m, x1 + m, y1 + m
    W, H = x1 - x0, y1 - y0
    esc = lambda s: s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
    o = ['<?xml version="1.0" encoding="UTF-8"?>',
         '<svg xmlns="http://www.w3.org/2000/svg" width="%.1fmm" height="%.1fmm" viewBox="%.1f %.1f %.1f %.1f">' %
         (W / scale, H / scale, x0, -y1, W, H),
         '<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="#ffffff"/>' % (x0, -y1, W, H)]
    for pr in prims:
        col = LAYERS.get(pr["layer"], (7, "#000000"))[1]
        sw = max(0.05, pr["lw"]) * scale
        dash = ' stroke-dasharray="%.0f %.0f"' % (3 * scale, 1.5 * scale) if pr.get("dash") else ""
        if pr["k"] == "poly":
            pts = " ".join("%.1f,%.1f" % (p[0], -p[1]) for p in pr["pts"])
            if pr["fill"] == "wall":
                fl = "#1c1c1c" if fill_walls else "none"
            elif pr["fill"]:
                fl = FILL_COLORS[pr["fill"]] if pr["fill"] not in ("room", "clear") else ("#ffffff" if pr["fill"] == "clear" else "none")
            else:
                fl = "none"
            tag = "polygon" if pr["closed"] else "polyline"
            o.append('<%s points="%s" fill="%s" stroke="%s" stroke-width="%.1f"%s/>' % (tag, pts, fl, col, sw, dash))
        elif pr["k"] == "circle":
            o.append('<circle cx="%.1f" cy="%.1f" r="%.1f" fill="none" stroke="%s" stroke-width="%.1f"/>' %
                     (pr["c"][0], -pr["c"][1], pr["r"], col, sw))
        elif pr["k"] == "arc":
            pts = " ".join("%.1f,%.1f" % (p[0], -p[1]) for p in pr["pts"])
            o.append('<polyline points="%s" fill="none" stroke="%s" stroke-width="%.1f"/>' % (pts, col, sw))
        elif pr["k"] == "text":
            anc = "middle" if pr.get("anchor", "c") == "c" else "start"
            o.append('<text transform="translate(%.1f,%.1f) rotate(%.1f)" font-family="Arial" font-size="%.1f" '
                     'text-anchor="%s" dominant-baseline="middle" fill="%s">%s</text>' %
                     (pr["p"][0], -pr["p"][1], -pr["rot"], pr["h"], anc, col, esc(pr["s"])))
    o.append('<text x="%.1f" y="%.1f" font-family="Arial" font-size="%.1f" fill="#000">%s - %s - 1:%d</text>' %
             (x0 + 400, -y0 - 400, 300, esc(proj["name"]), esc(proj["stories"][sidx]["name"]), scale))
    o.append("</svg>")
    with open(path, "w", encoding="utf-8") as fh:
        fh.write("\n".join(o))


# ---- PDF -----------------------------------------------------------------------------------------------------
PAPERS = {"A4": (297, 210), "A3": (420, 297), "A2": (594, 420), "A1": (841, 594)}


def _pdf_esc(s):
    b = s.encode("cp1252", "replace")
    return b.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)")


def export_pdf(proj, path, paper="A3", scale=None, fill_walls=True, stories=None):
    """One page per storey, vector, true scale (1:scale on the paper)."""
    pw, ph = PAPERS.get(paper, PAPERS["A3"])
    idxs = list(range(len(proj["stories"]))) if stories is None else stories
    k = 72.0 / 25.4
    pages = []
    for sidx in idxs:
        x0, y0, x1, y1 = plan_bounds(proj, sidx)
        w, h = x1 - x0 + 2000, y1 - y0 + 2000
        landscape = (w >= h)
        PW, PH = (pw, ph) if landscape else (ph, pw)
        sc = scale
        if not sc:
            for cand in (10, 20, 25, 50, 75, 100, 125, 150, 200, 250, 500):
                if w / cand <= PW - 30 and h / cand <= PH - 30:
                    sc = cand
                    break
            sc = sc or 500
        ox = (PW - (x1 - x0) / sc) / 2.0 - x0 / sc
        oy = (PH - (y1 - y0) / sc) / 2.0 - y0 / sc
        T = lambda p: ((p[0] / sc + ox) * k, (p[1] / sc + oy) * k)
        c = []
        for pr in plan_prims(proj, sidx):
            col = _hexrgb(LAYERS.get(pr["layer"], (7, "#000000"))[1])
            lw = max(0.05, pr["lw"]) * k
            c.append("%.3f %.3f %.3f RG %.3f %.3f %.3f rg %.2f w" % (col + col + (lw,)))
            c.append("[%.1f %.1f] 0 d" % (3 * k, 1.5 * k) if pr.get("dash") else "[] 0 d")
            if pr["k"] in ("poly", "arc"):
                pts = pr["pts"]
                if len(pts) < 2:
                    continue
                s = []
                for i, p in enumerate(pts):
                    q = T(p)
                    s.append("%.2f %.2f %s" % (q[0], q[1], "m" if i == 0 else "l"))
                closed = pr["k"] == "poly" and pr["closed"]
                fl = pr.get("fill") if pr["k"] == "poly" else None
                if fl == "wall" and fill_walls:
                    c.append("0.11 0.11 0.11 rg")
                    c.append(" ".join(s) + (" h B" if closed else " S"))
                elif fl in ("head1", "head2", "clear"):
                    cc = _hexrgb(FILL_COLORS[fl] if fl != "clear" else "#ffffff")
                    c.append("%.3f %.3f %.3f rg" % cc)
                    c.append(" ".join(s) + " h f")
                else:
                    c.append(" ".join(s) + (" h S" if closed else " S"))
            elif pr["k"] == "circle":
                pts = [(pr["c"][0] + pr["r"] * math.cos(a * math.pi / 18), pr["c"][1] + pr["r"] * math.sin(a * math.pi / 18))
                       for a in range(36)]
                s = ["%.2f %.2f %s" % (T(p) + ("m" if i == 0 else "l",)) for i, p in enumerate(pts)]
                c.append(" ".join(s) + " h S")
            elif pr["k"] == "text":
                size = pr["h"] / sc * k
                if size < 1.6:
                    continue
                a = math.radians(pr["rot"])
                px, py = T(pr["p"])
                wd = 0.52 * size * len(pr["s"])
                if pr.get("anchor", "c") == "c":
                    px -= math.cos(a) * wd / 2 - math.sin(a) * size * 0.35
                    py -= math.sin(a) * wd / 2 + math.cos(a) * size * 0.35
                c.append(("0 g BT /F1 %.2f Tf %.4f %.4f %.4f %.4f %.2f %.2f Tm (" % (
                    size, math.cos(a), math.sin(a), -math.sin(a), math.cos(a), px, py)).encode("latin-1")
                    + _pdf_esc(pr["s"]) + b") Tj ET")
        c.append(("0 g BT /F1 12 Tf %.1f %.1f Td (" % (15 * k, 10 * k)).encode("latin-1")
                 + _pdf_esc("%s - %s - 1:%d" % (proj["name"], proj["stories"][sidx]["name"], sc)) + b") Tj ET")
        body = b"\n".join(x if isinstance(x, bytes) else x.encode("latin-1") for x in c)
        pages.append((PW * k, PH * k, body))
    pdf_write_pages(pages, path)


def pdf_write_pages(pages, path):
    """pages = [(width pt, height pt, content stream bytes)].  Fonts: /F1 = Helvetica, /F2 = Helvetica-Bold (WinAnsi).
    Shared by the plan PDF and the shopping-list PDF."""
    objs = []
    n = len(pages)
    objs.append(b"<< /Type /Catalog /Pages 2 0 R >>")
    kids = " ".join("%d 0 R" % (5 + 2 * i) for i in range(n))
    objs.append(("<< /Type /Pages /Kids [%s] /Count %d >>" % (kids, n)).encode())
    objs.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>")
    objs.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>")
    for i, (wd, ht, body) in enumerate(pages):
        objs.append(("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.1f %.1f] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> "
                     "/Contents %d 0 R >>" % (wd, ht, 6 + 2 * i)).encode())
        objs.append(b"<< /Length %d >>\nstream\n" % len(body) + body + b"\nendstream")
    out = bytearray(b"%PDF-1.4\n")
    offs = []
    for i, ob in enumerate(objs):
        offs.append(len(out))
        out += ("%d 0 obj\n" % (i + 1)).encode() + ob + b"\nendobj\n"
    xr = len(out)
    out += ("xref\n0 %d\n0000000000 65535 f \n" % (len(objs) + 1)).encode()
    for o_ in offs:
        out += ("%010d 00000 n \n" % o_).encode()
    out += ("trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (len(objs) + 1, xr)).encode()
    with open(path, "wb") as fh:
        fh.write(bytes(out))


# ---- OBJ -----------------------------------------------------------------------------------------------------
def export_obj(proj, path):
    """Wavefront OBJ + MTL, metres, Y up (x, z, -y)."""
    solids = build_mesh(proj)
    base = os.path.splitext(path)[0]
    mtl_name = os.path.basename(base) + ".mtl"
    vmap = {}
    verts = []
    lines = ["# Architect export - %s" % proj["name"], "mtllib " + mtl_name]
    groups = {}
    for s in solids:
        groups.setdefault((s["sidx"], s["type"], s["mat"]), []).append(s)
    for (sidx, typ, mat), lst in sorted(groups.items(), key=lambda t: (t[0][0], t[0][1], t[0][2])):
        lines.append("o %s_%s" % (safe_name(proj["stories"][sidx]["name"]).replace(" ", "_"), typ))
        lines.append("usemtl " + mat)
        for s in lst:
            for f in s["faces"]:
                ids = []
                for p in f:
                    key = (round(p[0], 1), round(p[1], 1), round(p[2], 1))
                    if key not in vmap:
                        vmap[key] = len(verts) + 1
                        verts.append(key)
                    ids.append(vmap[key])
                lines.append("f " + " ".join(str(i) for i in ids))
    vl = ["v %.4f %.4f %.4f" % (x / 1000.0, z / 1000.0, -y / 1000.0) for x, y, z in verts]
    with open(path, "w", encoding="utf-8") as fh:
        fh.write("\n".join(lines[:2] + vl + lines[2:]) + "\n")
    ml = []
    for name, (r, g, b, a) in MATERIALS.items():
        ml.append("newmtl %s\nKd %.3f %.3f %.3f\nKa 0.1 0.1 0.1\nd %.2f\nillum 2\n" % (name, r, g, b, a))
    with open(base + ".mtl", "w", encoding="utf-8") as fh:
        fh.write("\n".join(ml))


# ---- IFC4 ----------------------------------------------------------------------------------------------------
_B64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"


def ifc_guid(key):
    n = uuid.uuid5(uuid.NAMESPACE_URL, "architect:" + key).int
    s = ""
    for _ in range(22):
        s = _B64[n % 64] + s
        n //= 64
    return s


def ifc_str(s):
    out = []
    for ch in s.replace("\\", "\\\\").replace("'", "''"):
        o = ord(ch)
        out.append(ch if 32 <= o < 127 else "\\X2\\%04X\\X0\\" % o)
    return "'" + "".join(out) + "'"


def _ff(v):
    s = "%.3f" % v
    return s


class IfcWriter(object):
    def __init__(self):
        self.lines = []

    def add(self, text):
        self.lines.append(text)
        return len(self.lines)

    def ref(self, n):
        return "#%d" % n


IFC_CLASS_ARGS = {   # class -> trailing arguments after Tag
    "IfcWall": ".STANDARD.", "IfcSlab": ".FLOOR.", "IfcRoof": ".NOTDEFINED.", "IfcStair": ".NOTDEFINED.",
    "IfcSanitaryTerminal": ".NOTDEFINED.", "IfcElectricAppliance": ".NOTDEFINED.", "IfcOutlet": ".NOTDEFINED.",
    "IfcSwitchingDevice": ".NOTDEFINED.", "IfcLightFixture": ".NOTDEFINED.", "IfcSpaceHeater": ".NOTDEFINED.",
    "IfcSensor": ".NOTDEFINED.", "IfcElectricDistributionBoard": ".NOTDEFINED.", "IfcTransportElement": ".ELEVATOR.",
    "IfcUnitaryEquipment": ".NOTDEFINED.", "IfcTank": ".NOTDEFINED.", "IfcBoiler": ".NOTDEFINED.",
    "IfcDuctSegment": ".NOTDEFINED.", "IfcAirTerminal": ".NOTDEFINED.",
}


def export_ifc(proj, path):
    W = IfcWriter()
    A = W.add
    pt0 = A("IFCCARTESIANPOINT((0.,0.,0.))")
    ax0 = A("IFCAXIS2PLACEMENT3D(#%d,$,$)" % pt0)
    ctx = A("IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#%d,$)" % ax0)
    sub = A("IFCGEOMETRICREPRESENTATIONSUBCONTEXT('Body','Model',*,*,*,*,#%d,$,.MODEL_VIEW.,$)" % ctx)
    u1 = A("IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.)")
    u2 = A("IFCSIUNIT(*,.AREAUNIT.,$,.SQUARE_METRE.)")
    u3 = A("IFCSIUNIT(*,.VOLUMEUNIT.,$,.CUBIC_METRE.)")
    u4 = A("IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.)")
    units = A("IFCUNITASSIGNMENT((#%d,#%d,#%d,#%d))" % (u1, u2, u3, u4))
    prj = A("IFCPROJECT('%s',$,%s,$,$,$,$,(#%d),#%d)" % (ifc_guid("project"), ifc_str(proj["name"]), ctx, units))

    def placement(parent=None):
        p = A("IFCLOCALPLACEMENT(%s,#%d)" % ("#%d" % parent if parent else "$", ax0))
        return p
    pl_site = placement()
    site = A("IFCSITE('%s',$,'Site',$,$,#%d,$,$,.ELEMENT.,$,$,$,$,$)" % (ifc_guid("site"), pl_site))
    pl_b = placement(pl_site)
    bld = A("IFCBUILDING('%s',$,%s,$,$,#%d,$,$,.ELEMENT.,$,$,$)" % (ifc_guid("building"), ifc_str(proj["name"]), pl_b))
    A("IFCRELAGGREGATES('%s',$,$,$,#%d,(#%d))" % (ifc_guid("rel-p-s"), prj, site))
    A("IFCRELAGGREGATES('%s',$,$,$,#%d,(#%d))" % (ifc_guid("rel-s-b"), site, bld))
    elevs = story_elevations(proj)
    styles = {}

    def style(mat):
        if mat not in styles:
            r, g, b, a = MATERIALS.get(mat, (0.8, 0.8, 0.8, 1.0))
            c = A("IFCCOLOURRGB($,%.3f,%.3f,%.3f)" % (r, g, b))
            rd = A("IFCSURFACESTYLERENDERING(#%d,%.2f,$,$,$,$,$,$,.NOTDEFINED.)" % (c, 1.0 - a))
            styles[mat] = A("IFCSURFACESTYLE($,.BOTH.,(#%d))" % rd)
        return styles[mat]

    def tess(faces, mat, styled=True):
        idx, pts, tris = {}, [], []
        for f in faces:
            ids = []
            for p in f:
                key = (round(p[0], 2), round(p[1], 2), round(p[2], 2))
                if key not in idx:
                    idx[key] = len(pts) + 1
                    pts.append(key)
                ids.append(idx[key])
            for i in range(1, len(ids) - 1):
                if len({ids[0], ids[i], ids[i + 1]}) == 3:
                    tris.append((ids[0], ids[i], ids[i + 1]))
        if not tris:
            return None
        pl = A("IFCCARTESIANPOINTLIST3D((%s))" % ",".join("(%s,%s,%s)" % (_ff(x), _ff(y), _ff(z)) for x, y, z in pts))
        fs = A("IFCTRIANGULATEDFACESET(#%d,$,.T.,(%s),$)" % (pl, ",".join("(%d,%d,%d)" % t for t in tris)))
        if styled:
            A("IFCSTYLEDITEM(#%d,(#%d),$)" % (fs, style(mat)))
        sr = A("IFCSHAPEREPRESENTATION(#%d,'Body','Tessellation',(#%d))" % (sub, fs))
        return A("IFCPRODUCTDEFINITIONSHAPE($,$,(#%d))" % sr)

    # cut=False: walls and roofs come back WHOLE and every door / window / dormer hole as a separate "void" solid, written
    # below as IfcOpeningElement + IfcRelVoidsElement (hole in the wall) + IfcRelFillsElement (door / window in the hole)
    solids = build_mesh(proj, cut=False)
    groups = {}
    voids = {}
    for s in solids:
        if s["type"] == "void":
            voids.setdefault((s["sidx"], s["vkey"]), []).append(s)
        else:
            groups.setdefault((s["sidx"], s["type"], s["ref"]), []).append(s)
    ent = {}                                              # (storey index, type, ref) -> IFC entity number

    def filling_size(story, typ, ref, default):
        """(height, width) of a door / window, whether it sits in a wall, a dormer or the roof."""
        o = next((x for x in story["openings"] if x["id"] == ref), None)
        if o:
            return o["h"], o["w"]
        dm = next((x for x in story.get("dormers", []) if x["id"] == ref), None)
        if dm:
            win = _dormer_window(story, dm)
            if win:
                return win[2] - win[1], 2.0 * win[0]
        rw = next((x for x in story.get("rwins", []) if x["id"] == ref), None)
        if rw:
            return rw["h"], rw["w"]
        return default
    for sidx, story in enumerate(proj["stories"]):
        pl_s = placement(pl_b)
        st = A("IFCBUILDINGSTOREY('%s',$,%s,$,$,#%d,$,$,.ELEMENT.,%s)" % (ifc_guid("story%d" % story["id"]),
                                                                            ifc_str(story["name"]), pl_s, _ff(elevs[sidx])))
        A("IFCRELAGGREGATES('%s',$,$,$,#%d,(#%d))" % (ifc_guid("rel-b-s%d" % story["id"]), bld, st))
        members = []
        for (si, typ, ref), lst in sorted(groups.items(), key=lambda t: (t[0][1], t[0][2] or 0)):
            if si != sidx:
                continue
            faces = [f for s in lst for f in s["faces"]]
            cls = lst[0]["ifc"] or "IfcBuildingElementProxy"
            pds = tess(faces, lst[0]["mat"])
            if pds is None:
                continue
            pl = placement(pl_s)
            name = ifc_str(lst[0]["name"])
            g = ifc_guid("%s-%s-%s" % (story["id"], typ, ref))
            if cls == "IfcDoor" or cls == "IfcWindow":
                hh, ww = filling_size(story, typ, ref, (2100.0, 900.0))
                e = A("%s('%s',$,%s,$,$,#%d,#%d,$,%s,%s,%s,.NOTDEFINED.,$)" %
                      (cls.upper(), g, name, pl, pds, _ff(hh), _ff(ww), ".DOOR." if cls == "IfcDoor" else ".WINDOW."))
            elif cls == "IfcFurniture" or cls == "IfcFurnishingElement":
                e = A("IFCFURNISHINGELEMENT('%s',$,%s,$,$,#%d,#%d,$)" % (g, name, pl, pds))
            elif cls in IFC_CLASS_ARGS:
                e = A("%s('%s',$,%s,$,$,#%d,#%d,$,%s)" % (cls.upper(), g, name, pl, pds, IFC_CLASS_ARGS[cls]))
            else:
                e = A("IFCBUILDINGELEMENTPROXY('%s',$,%s,$,$,#%d,#%d,$,.NOTDEFINED.)" % (g, name, pl, pds))
            members.append(e)
            ent[(sidx, typ, ref)] = e
        # holes: IfcOpeningElement cut out of the host (wall / dormer wall / roof) and filled by the door or window
        for (si, vkey), lst in sorted(voids.items(), key=lambda t: str(t[0][1])):
            if si != sidx:
                continue
            host = ent.get((sidx,) + tuple(lst[0]["host"])) if lst[0].get("host") else None
            if host is None:
                continue
            pds = tess([f for s in lst for f in s["faces"]], "void", False)
            if pds is None:
                continue
            op = A("IFCOPENINGELEMENT('%s',$,%s,$,$,#%d,#%d,$,.OPENING.)" %
                   (ifc_guid("%s-open-%s" % (story["id"], vkey)), ifc_str(lst[0]["name"]), placement(pl_s), pds))
            A("IFCRELVOIDSELEMENT('%s',$,$,$,#%d,#%d)" % (ifc_guid("%s-void-%s" % (story["id"], vkey)), host, op))
            fill = lst[0].get("fill")
            if fill and (sidx,) + tuple(fill) in ent:
                A("IFCRELFILLSELEMENT('%s',$,$,$,#%d,#%d)" % (ifc_guid("%s-fill-%s" % (story["id"], vkey)), op, ent[(sidx,) + tuple(fill)]))
        # rooms as IfcSpace (volume from floor to ceiling height)
        for r in story["rooms"]:
            if len(r["pts"]) < 3:
                continue
            pts = [tuple(p) for p in r["pts"]]
            faces = prism_faces(pts, [elevs[sidx]] * len(pts), [elevs[sidx] + story["height"]] * len(pts))
            pds = tess(faces, "glass")
            if pds is None:
                continue
            pl = placement(pl_s)
            sp = A("IFCSPACE('%s',$,%s,$,$,#%d,#%d,%s,.ELEMENT.,.INTERNAL.,%s)" %
                   (ifc_guid("space%d" % r["id"]), ifc_str(r["name"]), pl, pds, ifc_str(r["name"]), _ff(elevs[sidx])))
            A("IFCRELAGGREGATES('%s',$,$,$,#%d,(#%d))" % (ifc_guid("rel-sp%d" % r["id"]), st, sp))
        if members:
            A("IFCRELCONTAINEDINSPATIALSTRUCTURE('%s',$,$,$,(%s),#%d)" %
              (ifc_guid("cont%d" % story["id"]), ",".join("#%d" % m for m in members), st))
    head = ["ISO-10303-21;", "HEADER;", "FILE_DESCRIPTION(('ViewDefinition [ReferenceView_V1.2]'),'2;1');",
            "FILE_NAME(%s,'%s',(''),(''),'Architect','Architect','');" % (ifc_str(os.path.basename(path)),
                                                                          time.strftime("%Y-%m-%dT%H:%M:%S")),
            "FILE_SCHEMA(('IFC4'));", "ENDSEC;", "DATA;"]
    body = ["#%d=%s;" % (i + 1, t) for i, t in enumerate(W.lines)]
    with open(path, "w", encoding="ascii", newline="\n") as fh:
        fh.write("\n".join(head + body + ["ENDSEC;", "END-ISO-10303-21;"]) + "\n")


# ---- room list -----------------------------------------------------------------------------------------------
def rooms_table(proj):
    rows = [["Storey", "Room", "Area m2", "Perimeter m", "Area with height >= %s m" % fmt_m(proj["settings"]["headroom"][-1])]]
    for s in proj["stories"]:
        for r in s["rooms"]:
            if len(r["pts"]) < 3:
                continue
            pts = [tuple(p) for p in r["pts"]]
            rows.append([s["name"], r["name"], "%.2f" % (poly_area(pts) / 1e6), "%.2f" % (poly_perimeter(pts) / 1000.0),
                         "%.2f" % (room_headroom_area(s, r, proj["settings"]["headroom"][-1]) / 1e6)])
    return rows


def export_csv(proj, path):
    with open(path, "w", encoding="utf-8-sig", newline="") as fh:
        for row in rooms_table(proj):
            fh.write(";".join(row) + "\n")


def export_all(proj, folder, fill_walls=True, paper="A3", scale=None):
    """Every format into one folder.  Returns the list of files written."""
    os.makedirs(folder, exist_ok=True)
    base = safe_name(proj["name"])
    out = []
    for i, s in enumerate(proj["stories"]):
        p = os.path.join(folder, "%s_%02d_%s.dxf" % (base, i + 1, safe_name(s["name"])))
        export_dxf_story(proj, i, p, fill_walls)
        out.append(p)
        p = os.path.join(folder, "%s_%02d_%s.svg" % (base, i + 1, safe_name(s["name"])))
        export_svg_story(proj, i, p, scale or 50, fill_walls)
        out.append(p)
    for fn, ext in ((lambda p: export_dxf_combined(proj, p, fill_walls), "_all_storeys.dxf"),
                    (lambda p: export_dxf_3d(proj, p), "_3D.dxf"),
                    (lambda p: export_pdf(proj, p, paper, scale, fill_walls), ".pdf"),
                    (lambda p: export_obj(proj, p), ".obj"),
                    (lambda p: export_ifc(proj, p), ".ifc"),
                    (lambda p: export_csv(proj, p), "_rooms.csv")):
        p = os.path.join(folder, base + ext)
        fn(p)
        out.append(p)
        if ext == ".obj":
            out.append(os.path.join(folder, base + ".mtl"))
    return out


# *************** DEL 53 - HOUSE PLANNER LOGIC: house size + list of rooms -> arranged rooms -> walls, rooms, doors, windows ***************
# A LAYOUT lives in storey["layout"]:
#   frame  W x D (mm) as typed, "dims" = "outer" (outside of the outer walls) or "inner" (inside), outer wall thickness t_out, inner wall t_in
#   cells  main rooms (and sub-units: parent = id of the main room).  A main room is a rectangular SLOT (x, y, w, d, rot) in the inner
#          area of the house; its sub-units (hall, toilet, wardrobe ...) are carved from one corner of the slot, side by side in a strip,
#          so the main room becomes L-shaped.  Sizes are INNER sizes (between the wall faces).  rot = 0/90/180/270 turns the slot.
#          1.4: a main room can also be an L, T, U or FREE outline (90-degree edges), see "room shapes" below.
#   The "fit" commands: rooms -> house (the rooms shrink / grow, the house stays) and house -> rooms (the rooms are exact, the house changes).
# lay_apply() builds the walls, rooms, doors and windows in the storey; everything it makes is marked "gen" and is replaced next time.
# ToDo: slanted / curved room edges, sub-rooms inside shaped rooms, rooms that fill the notch of an L automatically, several bands > 2,
#       doors that avoid furniture, stairs placed by the planner.

CELL_TYPES = ["Kitchen", "Living room", "Bedroom", "Bathroom", "WC", "Hall", "Corridor", "Wardrobe", "Pantry", "Laundry", "Office",
              "Storage", "Garage", "Room"]
SUB_PRESETS = {"Hall": (1600, 2400), "Toilet": (1200, 2000), "Wardrobe": (1200, 2000), "Bathroom": (1800, 2400),
               "Pantry": (1200, 1800), "Laundry": (1800, 2000)}
SIZE_DEFAULT = {"Kitchen": (3600, 3900), "Living room": (5000, 4400), "Bedroom": (3500, 3500), "Bathroom": (2200, 2400),
                "WC": (1200, 2000), "Hall": (2200, 2400), "Wardrobe": (1200, 2000), "Pantry": (1200, 1800), "Laundry": (1800, 2000),
                "Office": (3000, 3200), "Storage": (1800, 2200), "Garage": (3200, 6000), "Room": (3500, 3500), "Corridor": (1200, 4000)}
NO_WINDOW = ("Corridor", "Wardrobe", "Hall", "Pantry", "Storage")
SMALL_DOOR = ("WC", "Toilet", "Wardrobe", "Pantry", "Storage")
CORNERS = {"SW": (-1, -1), "SE": (1, -1), "NW": (-1, 1), "NE": (1, 1)}
CORNER_OF = {v: k for k, v in CORNERS.items()}


def lay_new(w=10000.0, d=29000.0, t_out=250.0, t_in=100.0, dims="outer"):
    return {"frame": {"w": float(w), "d": float(d), "dims": dims, "t_out": float(t_out), "t_in": float(t_in)}, "cells": [], "next": 1,
            "opts": {"corridor": True, "corridor_w": 1200.0, "bands": 0, "doors": True, "windows": True}}


def lay_outer(lay):
    f = lay["frame"]
    return (f["w"], f["d"]) if f["dims"] == "outer" else (f["w"] + 2 * f["t_out"], f["d"] + 2 * f["t_out"])


def lay_inner(lay):
    """(x0, y0, x1, y1) inside the outer walls."""
    wo, do = lay_outer(lay)
    t = lay["frame"]["t_out"]
    return (t, t, wo - t, do - t)


def lay_set_inner(lay, iw, idp):
    f = lay["frame"]
    if f["dims"] == "outer":
        f["w"], f["d"] = iw + 2 * f["t_out"], idp + 2 * f["t_out"]
    else:
        f["w"], f["d"] = iw, idp


def lay_cell(lay, name, typ="Room", w=None, d=None, parent=None, x=0.0, y=0.0, rot=0, corner="auto"):
    sw, sd = SIZE_DEFAULT.get(typ, (3500, 3500))
    c = {"id": lay["next"], "name": name, "type": typ, "w": float(w if w else sw), "d": float(d if d else sd), "x": float(x), "y": float(y),
         "rot": int(rot) % 360, "parent": parent, "corner": corner}
    lay["next"] += 1
    lay["cells"].append(c)
    return c


def lay_get(lay, cid):
    return next((c for c in lay["cells"] if c["id"] == cid), None)


def lay_mains(lay):
    return [c for c in lay["cells"] if c["parent"] is None]


def lay_subs(lay, c):
    return [s for s in lay["cells"] if s["parent"] == c["id"]]


def lay_remove(lay, cid):
    """Removes a cell; the sub-units of a main room go with it."""
    lay["cells"] = [c for c in lay["cells"] if c["id"] != cid and c["parent"] != cid]


def cell_dims(c):
    """(extent along x, extent along y) of the slot of a main room after its rotation."""
    return (c["d"], c["w"]) if c["rot"] % 180 == 90 else (c["w"], c["d"])


def set_effective(c, ex, ey):
    if c["rot"] % 180 == 90:
        c["w"], c["d"] = ey, ex
    else:
        c["w"], c["d"] = ex, ey


def lay_rotate(c, step=90):
    """Turns a main room: the slot keeps its centre, width and depth swap."""
    ex, ey = cell_dims(c)
    cx, cy = c["x"] + ex / 2.0, c["y"] + ey / 2.0
    c["rot"] = (c["rot"] + step) % 360
    nx, ny = cell_dims(c)
    c["x"], c["y"] = cx - nx / 2.0, cy - ny / 2.0


def lay_default_rooms(lay, n=12, k=3):
    """n main rooms of which k are kitchens: per unit a kitchen, a living room, a bathroom (if there are enough rooms) and bedrooms."""
    lay["cells"] = []
    lay["next"] = 1
    n, k = max(1, int(n)), max(0, min(int(k), int(n)))
    units = max(1, k)
    plan = []
    left = n
    per = [[] for _ in range(units)]
    for u in range(units):
        if u < k:
            per[u].append("Kitchen")
            left -= 1
    order = ["Living room", "Bathroom", "Bedroom"]
    u = 0
    i = 0
    while left > 0:
        typ = order[i] if i < len(order) else "Bedroom"
        per[u % units].append(typ)
        left -= 1
        u += 1
        if u % units == 0:
            i += 1
    counts = {}
    for u in range(units):
        for typ in per[u]:
            counts[typ] = counts.get(typ, 0) + 1
            nm = "%s %d" % (typ, counts[typ]) if (k > 1 or sum(x.count(typ) for x in per) > 1) else typ
            plan.append((nm, typ))
    for nm, typ in plan:
        lay_cell(lay, nm, typ)
    return lay


# ---- room shapes: rectangle, L, T, U, free outline (1.4) --------------------------------------------------------------------
# A main room may carry   "shape": "L" | "T" | "U" | "free"   (no key / "rect" = rectangle, as in every older project).
# The outline lives in the room's own frame (0..w x 0..d, then turned by "rot" like a rectangle) and is stored in FRACTIONS of w and d
# ("sp" = [fx, fy] for L / T / U, "npts" = [[u, v], ...] for a free outline), so Arrange / Fit / typing a new width stretch the shape with the room.
#   L: a notch fx*w by fy*d is cut from the NE corner      T: stem fx*w wide, bar fy*d thick on top      U: notch fx*w wide, fy*d deep at the top
# Only 90-degree edges are allowed (the wall builder, doors and the neighbours' gaps all work on horizontal / vertical edges).
# Limits: a shaped room cannot have sub-rooms (they are carved from a rectangle's corner); the empty notch of an L / T / U is NOT a room
# and gets no walls except the room's own outline - put a small room in it by dragging, or leave it as a niche.
ROOM_SHAPES = ["rect", "L", "T", "U", "free"]
SHAPE_NAMES = {"rect": "Rectangle", "L": "L-shape", "T": "T-shape", "U": "U-shape", "free": "Free outline"}
SHAPE_DEFAULT = {"L": (0.40, 0.45), "T": (0.40, 0.35), "U": (0.40, 0.50)}
SHAPE_PARAM_LABELS = {"L": ("Notch width mm", "Notch depth mm"), "T": ("Stem width mm", "Bar depth mm"), "U": ("Notch width mm", "Notch depth mm")}
MIN_EDGE = 300.0


def cell_shape(c):
    s = c.get("shape") or "rect"
    return s if s in ROOM_SHAPES else "rect"


def shape_params(c):
    d = SHAPE_DEFAULT.get(cell_shape(c), (0.4, 0.4))
    try:
        fx, fy = float(c["sp"][0]), float(c["sp"][1])
    except (KeyError, TypeError, ValueError, IndexError):
        fx, fy = d
    return min(0.85, max(0.15, fx)), min(0.85, max(0.15, fy))


def shape_local(c):
    """The outline of a main room in its own frame (before the turn), a list of (x, y) in mm."""
    lw, ld = c["w"], c["d"]
    sh = cell_shape(c)
    if sh in ("L", "T", "U"):
        fx, fy = shape_params(c)
        if sh == "L":
            nx, ny = fx * lw, fy * ld
            return [(0.0, 0.0), (lw, 0.0), (lw, ld - ny), (lw - nx, ld - ny), (lw - nx, ld), (0.0, ld)]
        if sh == "T":
            s, b = fx * lw, fy * ld
            x0 = (lw - s) / 2.0
            return [(x0, 0.0), (x0 + s, 0.0), (x0 + s, ld - b), (lw, ld - b), (lw, ld), (0.0, ld), (0.0, ld - b), (x0, ld - b)]
        n, nd = fx * lw, fy * ld
        x0 = (lw - n) / 2.0
        return [(0.0, 0.0), (lw, 0.0), (lw, ld), (x0 + n, ld), (x0 + n, ld - nd), (x0, ld - nd), (x0, ld), (0.0, ld)]
    if sh == "free":
        try:
            pts = [(float(u) * lw, float(v) * ld) for u, v in c["npts"]]
            if len(pts) >= 4:
                return pts
        except (KeyError, TypeError, ValueError):
            pass
    return [(0.0, 0.0), (lw, 0.0), (lw, ld), (0.0, ld)]


def _unrot_local(q, k, lw, ld):
    """Inverse of _rot_local."""
    x, y = q
    if k == 0:
        return (x, y)
    if k == 1:
        return (y, ld - x)
    if k == 2:
        return (lw - x, ld - y)
    return (lw - y, x)


def _seg_touch(a, b, c, d):
    """Do two axis-parallel segments share a point (ends included)?"""
    ax0, ax1 = sorted((a[0], b[0]))
    ay0, ay1 = sorted((a[1], b[1]))
    cx0, cx1 = sorted((c[0], d[0]))
    cy0, cy1 = sorted((c[1], d[1]))
    return ax0 <= cx1 + 0.01 and cx0 <= ax1 + 0.01 and ay0 <= cy1 + 0.01 and cy0 <= ay1 + 0.01


def ortho_check(pts):
    """(clean points, '') for a usable outline with only horizontal / vertical edges, else (None, reason)."""
    p = [(round(float(x), 1), round(float(y), 1)) for x, y in pts]
    # an edge that is neither horizontal nor vertical is refused (it is not repaired silently)
    for i in range(len(p)):
        a, b = p[i], p[(i + 1) % len(p)]
        if abs(a[0] - b[0]) > 0.5 and abs(a[1] - b[1]) > 0.5:
            return None, "Corner %d to %d is slanted.  Only horizontal and vertical edges (90-degree corners) are possible." % (i + 1, (i + 1) % len(p) + 1)
    p = _clean(p)
    if len(p) < 4 or len(p) % 2:
        return None, "The outline needs at least 4 corners with 90-degree turns (an even number of corners)."
    for i in range(len(p)):
        if dist(p[i], p[(i + 1) % len(p)]) < MIN_EDGE:
            return None, "An edge is shorter than %d mm (corner %d)." % (MIN_EDGE, i + 1)
    n = len(p)
    for i in range(n):
        for j in range(i + 1, n):
            if j == i + 1 or (i == 0 and j == n - 1):
                continue
            if _seg_touch(p[i], p[(i + 1) % n], p[j], p[(j + 1) % n]):
                return None, "The outline crosses or touches itself (edges %d and %d)." % (i + 1, j + 1)
    if poly_area(p) < 1.0e6:
        return None, "The room would be smaller than 1 m2."
    return p, ""


def ortho_rects(poly):
    """An axis-parallel polygon as a list of rectangles (x0, y0, x1, y1): horizontal slabs between the corner heights."""
    p = [tuple(q) for q in poly]
    ys = sorted({round(q[1], 1) for q in p})
    out = []
    n = len(p)
    for y0, y1 in zip(ys, ys[1:]):
        ym = (y0 + y1) / 2.0
        xs = sorted(a[0] for a, b in ((p[i], p[(i + 1) % n]) for i in range(n)) if abs(a[0] - b[0]) < 0.5 and min(a[1], b[1]) < ym < max(a[1], b[1]))
        for k in range(0, len(xs) - 1, 2):
            out.append((xs[k], y0, xs[k + 1], y1))
    return out


def lay_set_world_outline(c, world):
    """Gives a main room a free outline given in house coordinates: the room's slot becomes the bounding box of the outline."""
    xs = [p[0] for p in world]
    ys = [p[1] for p in world]
    bx0, by0, bx1, by1 = min(xs), min(ys), max(xs), max(ys)
    c["x"], c["y"] = bx0, by0
    set_effective(c, bx1 - bx0, by1 - by0)
    k = (c["rot"] // 90) % 4
    lw, ld = c["w"], c["d"]
    out = []
    for p in world:
        x, y = _unrot_local((p[0] - bx0, p[1] - by0), k, lw, ld)
        out.append([round(x / lw, 9), round(y / ld, 9)])
    c["shape"], c["npts"] = "free", out
    c.pop("sp", None)


def cell_world_outline(lay, c):
    """The inner outline of a main room in house coordinates (no sub-rooms in it)."""
    k = (c["rot"] // 90) % 4
    return [(c["x"] + q[0], c["y"] + q[1]) for q in (_rot_local(p, k, c["w"], c["d"]) for p in shape_local(c))]


def lay_set_shape(lay, c, shape, a_mm=None, b_mm=None):
    """Changes the shape of a main room.  a_mm / b_mm = the two sizes of L / T / U in mm.  Returns '' or the reason it was refused."""
    if c["parent"] is not None:
        return "Only a main room can get another shape (a sub-room is a rectangle)."
    if shape not in ROOM_SHAPES:
        return "Unknown shape."
    if shape != "rect" and lay_subs(lay, c):
        return "%s has sub-rooms.  Delete them first: sub-rooms are carved from the corner of a rectangle." % c["name"]
    if shape == "rect":
        c["shape"] = "rect"
        c.pop("sp", None)
        c.pop("npts", None)
        return ""
    if shape == "free":
        if cell_shape(c) != "free":
            c["npts"] = [[round(x / c["w"], 9), round(y / c["d"], 9)] for x, y in shape_local(c)]
        c["shape"] = "free"
        c.pop("sp", None)
        return ""
    fx, fy = shape_params(dict(c, shape=shape, sp=c.get("sp") if cell_shape(c) == shape else None))
    if a_mm:
        fx = float(a_mm) / c["w"]
    if b_mm:
        fy = float(b_mm) / c["d"]
    c["shape"], c["sp"] = shape, [min(0.85, max(0.15, fx)), min(0.85, max(0.15, fy))]
    c.pop("npts", None)
    return ""


def lay_shape_mm(c):
    """(a, b) in mm of an L / T / U shape (what the form shows)."""
    fx, fy = shape_params(c)
    return fx * c["w"], fy * c["d"]


def lay_mirror(c):
    """Mirrors a main room left-right in its own frame (a free outline results)."""
    if c["parent"] is not None or cell_shape(c) == "rect":
        return                                                # a rectangle looks the same mirrored
    pts = [[round(x / c["w"], 9), round(y / c["d"], 9)] for x, y in shape_local(c)]
    c["shape"], c["npts"] = "free", [[round(1.0 - u, 9), v] for u, v in pts][::-1]
    c.pop("sp", None)


def shape_points_text(c):
    """The corners of the outline in the room's own frame as 'x, y' lines (mm, origin = lower left of its bounding box)."""
    return "\n".join("%g, %g" % (round(x, 1), round(y, 1)) for x, y in shape_local(c))


def lay_set_points_text(lay, c, text):
    """Sets a free outline from typed 'x, y' lines (mm).  The room's width / depth follow the outline.  Returns '' or the reason."""
    if c["parent"] is not None or lay_subs(lay, c):
        return "Only a main room without sub-rooms can have its own outline."
    pts = []
    for ln in str(text).splitlines():
        nums = re.findall(r"-?\d+(?:\.\d+)?", ln)                # comma / semicolon / space separate x and y; decimals use a dot
        if not nums:
            continue
        if len(nums) != 2:
            return "Each line needs two numbers: x, y  (mm, a dot for decimals).  Problem: '%s'" % ln.strip()
        pts.append((float(nums[0]), float(nums[1])))
    p, why = ortho_check(pts)
    if p is None:
        return why
    ex0, ey0 = min(q[0] for q in p), min(q[1] for q in p)
    p = [(q[0] - ex0, q[1] - ey0) for q in p]
    lw, ld = max(q[0] for q in p), max(q[1] for q in p)
    cx, cy = cell_dims(c)
    cx, cy = c["x"] + cx / 2.0, c["y"] + cy / 2.0
    c["w"], c["d"] = lw, ld
    c["shape"], c["npts"] = "free", [[round(q[0] / lw, 9), round(q[1] / ld, 9)] for q in p]
    c.pop("sp", None)
    nx, ny = cell_dims(c)
    c["x"], c["y"] = cx - nx / 2.0, cy - ny / 2.0
    return ""


def lay_drag_outline(lay, c, kind, idx, to_xy):
    """Drags a corner (kind 'v') or an edge (kind 'e') of a shaped room to the house point to_xy; the neighbouring corners follow so
    that all corners stay 90 degrees.  The room becomes a free outline.  Returns '' or the reason it was refused (nothing changes)."""
    if c["parent"] is not None or lay_subs(lay, c):
        return "Only a main room without sub-rooms."
    w = [list(p) for p in cell_world_outline(lay, c)]
    n = len(w)
    i = idx % n

    def horizontal(a, b):
        return abs(w[a][1] - w[b][1]) < 0.5

    nx, ny = float(to_xy[0]), float(to_xy[1])
    if kind == "v":
        pv, nt = (i - 1) % n, (i + 1) % n
        if horizontal(pv, i):
            w[pv][1] = w[i][1] = ny
            w[i][0] = w[nt][0] = nx
        else:
            w[pv][0] = w[i][0] = nx
            w[i][1] = w[nt][1] = ny
    else:
        j = (i + 1) % n
        if horizontal(i, j):
            w[i][1] = w[j][1] = ny
        else:
            w[i][0] = w[j][0] = nx
    p, why = ortho_check([tuple(q) for q in w])
    if p is None:
        return why
    if len(p) != n:
        return "That would merge two corners - drag a little less."
    lay_set_world_outline(c, [tuple(q) for q in w])
    return ""


# ---- the shape of a main room with its sub-units --------------------------------------------------------------------
def _rot_local(p, k, lw, ld):
    x, y = p
    if k == 0:
        return (x, y)
    if k == 1:
        return (ld - y, x)
    if k == 2:
        return (lw - x, ld - y)
    return (y, lw - x)


def _norm_rect(a, b):
    return (min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1]))


def cell_shapes(lay, c):
    """(parent polygon or None, [(sub-unit cell, (x0, y0, x1, y1))]) in house coordinates."""
    t = lay["frame"]["t_in"]
    lw, ld = c["w"], c["d"]
    subs = lay_subs(lay, c)
    k = (c["rot"] // 90) % 4
    ex, ey = cell_dims(c)

    def to_world(p):
        q = _rot_local(p, k, lw, ld)
        return (c["x"] + q[0], c["y"] + q[1])
    rect_local = [(0.0, 0.0), (lw, 0.0), (lw, ld), (0.0, ld)]
    if not subs:
        return [to_world(p) for p in (shape_local(c) if cell_shape(c) != "rect" else rect_local)], []     # sub-rooms win over a shape
    corner = c.get("corner", "auto")
    if corner not in CORNERS:
        corner = c.get("acorner", "SW")
    sx, sy = CORNERS[corner]
    ws = [max(300.0, s["w"]) for s in subs]
    strip_w = sum(ws) + t * (len(ws) - 1)
    strip_w_max = lw - 800.0 - t
    if strip_w > strip_w_max:
        f = (strip_w_max - t * (len(ws) - 1)) / max(1.0, sum(ws))
        ws = [x * f for x in ws]
        strip_w = strip_w_max
    sd = min(max(max(s["d"] for s in subs), 600.0), ld - 800.0 - t)
    # local geometry for the SW corner, then mirrored to the real corner
    rects, x0 = [], 0.0
    for wv in ws:
        rects.append((x0, 0.0, x0 + wv, sd))
        x0 += wv + t
    ex_, ey_ = strip_w + t, sd + t
    if ex_ >= lw - 1.0:
        parent = [(0.0, ey_), (lw, ey_), (lw, ld), (0.0, ld)]
    else:
        parent = [(ex_, 0.0), (lw, 0.0), (lw, ld), (0.0, ld), (0.0, ey_), (ex_, ey_)]

    def mirror(p):
        return (lw - p[0] if sx > 0 else p[0], ld - p[1] if sy > 0 else p[1])
    out_rects = []
    for s, r in zip(subs, rects):
        a, b = to_world(mirror((r[0], r[1]))), to_world(mirror((r[2], r[3])))
        out_rects.append((s, _norm_rect(a, b)))
    return [to_world(mirror(p)) for p in parent], out_rects


def lay_shapes(lay):
    """[{cell, name, type, poly, sub, parent}] - every room of the layout as an inner polygon (house coordinates)."""
    out = []
    for c in lay_mains(lay):
        poly, subs = cell_shapes(lay, c)
        out.append({"cell": c["id"], "name": c["name"], "type": c["type"], "poly": ensure_ccw(poly), "sub": False, "parent": None})
        for s, r in subs:
            out.append({"cell": s["id"], "name": s["name"], "type": s["type"],
                        "poly": [(r[0], r[1]), (r[2], r[1]), (r[2], r[3]), (r[0], r[3])], "sub": True, "parent": c["id"]})
    return out


# ---- arranging: bands along the long side of the house -------------------------------------------------------------
def _corner_name(sx, sy):
    return CORNER_OF[(1 if sx > 0 else -1, 1 if sy > 0 else -1)]


def _to_local_corner(sx, sy, rot):
    """The corner (sx, sy) of the real slot as a corner of the unrotated slot."""
    for _ in range((rot // 90) % 4):
        sx, sy = sy, -sx                           # turn the vector 90 degrees back
    return _corner_name(sx, sy)


def lay_arrange(lay, scaled=True):
    """Puts the main rooms in 1 or 2 bands along the long side (with a corridor between two bands when lay['opts']['corridor']).
    scaled=True: the rooms' sizes are only weights - they grow / shrink to fill the house exactly.
    scaled=False: the rooms keep their widths along the band; the depth is that of the deepest room of the band; the house is NOT
    changed (use lay_fit_frame afterwards).  Returns a list of notes."""
    notes = []
    t = lay["frame"]["t_in"]
    ix0, iy0, ix1, iy1 = lay_inner(lay)
    wi, di = ix1 - ix0, iy1 - iy0
    along_x = wi >= di
    ulen, vlen = (wi, di) if along_x else (di, wi)
    lay["cells"] = [c for c in lay["cells"] if not c.get("auto")]
    mains = lay_mains(lay)
    if not mains:
        return ["No rooms to arrange."]
    o = lay["opts"]
    nb = int(o.get("bands") or (1 if vlen < 7000 else 2))
    nb = 1 if len(mains) < 2 else max(1, min(2, nb))
    corridor = nb == 2 and bool(o.get("corridor", True))
    cw = float(o.get("corridor_w", 1200.0))

    def tl(c):
        ex, ey = cell_dims(c)
        return (ex, ey) if along_x else (ey, ex)
    if nb == 2:
        tband = (vlen - (cw + 2 * t if corridor else t)) / 2.0
    else:
        tband = vlen
    if scaled:
        lens = [max(1.0, c["w"] * c["d"]) / max(1.0, tband) for c in mains]
    else:
        lens = [tl(c)[0] for c in mains]
    total = sum(lens)
    k = len(mains)
    if nb == 2:
        best, acc = 1, 0.0
        bd = None
        for i in range(1, len(mains)):
            acc = sum(lens[:i])
            dd = abs(acc - total / 2.0)
            if bd is None or dd < bd:
                best, bd = i, dd
        k = best
    bands = [list(range(0, k)), list(range(k, len(mains)))] if nb == 2 else [list(range(len(mains)))]
    thick = []
    for bi, idxs in enumerate(bands):
        thick.append(tband if scaled else max(tl(mains[i])[1] for i in idxs))
    vstart = [0.0]
    if nb == 2:
        vstart.append(thick[0] + t + (cw + t if corridor else 0.0))
    for bi, idxs in enumerate(bands):
        ls = [lens[i] for i in idxs]
        if scaled:
            avail = ulen - (len(idxs) - 1) * t
            f = avail / max(1.0, sum(ls))
            ls = [x * f for x in ls]
        u = 0.0
        for i, ln in zip(idxs, ls):
            c = mains[i]
            if along_x:
                x, y, ex, ey = ix0 + u, iy0 + vstart[bi], ln, thick[bi]
            else:
                x, y, ex, ey = ix0 + vstart[bi], iy0 + u, thick[bi], ln
            if not scaled and abs(tl(c)[1] - thick[bi]) > 1.0:
                notes.append("%s: depth %d -> %d mm (the band is that deep)" % (c["name"], round(tl(c)[1]), round(thick[bi])))
            c["x"], c["y"] = x, y
            set_effective(c, ex, ey)
            # sub-units go to the corner at the start of the band on the corridor side
            if along_x:
                wsx, wsy = -1, (1 if (bi == 0 and nb == 2) else -1)
            else:
                wsx, wsy = (1 if (bi == 0 and nb == 2) else -1), -1
            c["acorner"] = _to_local_corner(wsx, wsy, c["rot"])
            u += ln + t
            if min(ex, ey) < 1500:
                notes.append("%s is only %d x %d mm" % (c["name"], round(ex), round(ey)))
            if cell_shape(c) != "rect" and not lay_subs(lay, c):
                notes.append("%s is a %s: the empty part of its box stays empty (it is not a room)." % (c["name"], SHAPE_NAMES[cell_shape(c)].lower()))
    if corridor:
        cc = lay_cell(lay, "Corridor", "Corridor", 0, 0)
        cc["auto"] = True
        if along_x:
            cc["x"], cc["y"] = ix0, iy0 + thick[0] + t
            cc["w"], cc["d"] = ulen, cw
        else:
            cc["x"], cc["y"] = ix0 + thick[0] + t, iy0
            cc["w"], cc["d"] = cw, ulen
    return notes


def _bbox(lay):
    ms = lay_mains(lay)
    if not ms:
        return None
    xs0 = [c["x"] for c in ms]
    ys0 = [c["y"] for c in ms]
    xs1 = [c["x"] + cell_dims(c)[0] for c in ms]
    ys1 = [c["y"] + cell_dims(c)[1] for c in ms]
    return (min(xs0), min(ys0), max(xs1), max(ys1))


def lay_fit_frame(lay):
    """The rooms are exact: the house grows / shrinks round them (the rooms move so that they start at the inner corner)."""
    b = _bbox(lay)
    if b is None:
        return
    t = lay["frame"]["t_out"]
    dx, dy = t - b[0], t - b[1]
    for c in lay_mains(lay):
        c["x"] += dx
        c["y"] += dy
    lay_set_inner(lay, b[2] - b[0], b[3] - b[1])


def _compact(spans, target, t_in):
    """spans = [(a, b)] of the rooms along one axis.  Returns a function old coordinate -> new coordinate such that the rooms fill
    `target` from 0, the wall gaps (<= 1.6 wall thicknesses between rooms) keep their size and everything else is scaled."""
    pts = sorted({round(v, 1) for s in spans for v in s})
    if len(pts) < 2:
        return lambda v: v
    fixed, scal = [], []
    for p, q in zip(pts, pts[1:]):
        covered = any(a <= p + 0.6 and b >= q - 0.6 for a, b in spans)
        (scal if covered or q - p > 1.6 * t_in else fixed).append((p, q))
    fsum = sum(q - p for p, q in fixed)
    ssum = sum(q - p for p, q in scal)
    f = (target - fsum) / ssum if ssum > 0 else 1.0
    f = max(0.2, f)
    new = {pts[0]: 0.0}
    cur = 0.0
    for p, q in zip(pts, pts[1:]):
        cur += (q - p) if (p, q) in fixed else (q - p) * f
        new[q] = cur

    def fn(v):
        v = round(v, 1)
        if v in new:
            return new[v]
        lo = max([p for p in pts if p <= v] or [pts[0]])
        hi = min([p for p in pts if p >= v] or [pts[-1]])
        return new[lo] if hi == lo else new[lo] + (v - lo) / (hi - lo) * (new[hi] - new[lo])
    return fn


def lay_fit_rooms(lay):
    """The house is fixed: the rooms shrink / grow (the walls between them keep their thickness) so that they fill the inner area."""
    ms = lay_mains(lay)
    if not ms:
        return
    if _overlaps(lay):                       # rooms that were made bigger collide: pack them again, their sizes are the weights
        return lay_arrange(lay, True)
    ix0, iy0, ix1, iy1 = lay_inner(lay)
    t = lay["frame"]["t_in"]
    fx = _compact([(c["x"], c["x"] + cell_dims(c)[0]) for c in ms], ix1 - ix0, t)
    fy = _compact([(c["y"], c["y"] + cell_dims(c)[1]) for c in ms], iy1 - iy0, t)
    for c in ms:
        ex, ey = cell_dims(c)
        x0, x1 = fx(c["x"]), fx(c["x"] + ex)
        y0, y1 = fy(c["y"]), fy(c["y"] + ey)
        c["x"], c["y"] = ix0 + x0, iy0 + y0
        set_effective(c, x1 - x0, y1 - y0)


def _cell_rects(lay, c):
    """The rectangles a main room occupies: its slot, or - for an L / T / U / free room - the pieces of its outline (so another room
    may sit in the empty notch of an L)."""
    ex, ey = cell_dims(c)
    if cell_shape(c) == "rect" or lay_subs(lay, c):
        return [(c["x"], c["y"], c["x"] + ex, c["y"] + ey)]
    return ortho_rects(cell_world_outline(lay, c)) or [(c["x"], c["y"], c["x"] + ex, c["y"] + ey)]


def _overlaps(lay):
    ms = lay_mains(lay)
    t = lay["frame"]["t_in"]
    tol = 5.0
    out = []
    rects = {c["id"]: _cell_rects(lay, c) for c in ms}
    for i, a in enumerate(ms):
        for c in ms[i + 1:]:
            hit = False
            for (ax0, ay0, ax1, ay1) in rects[a["id"]]:
                for (cx0, cy0, cx1, cy1) in rects[c["id"]]:
                    if ax0 < cx1 + t - tol and cx0 < ax1 + t - tol and ay0 < cy1 + t - tol and cy0 < ay1 + t - tol:
                        hit = True
                        break
                if hit:
                    break
            if hit:
                out.append((a, c))
    return out


def lay_status(lay):
    """(ok, text): do the rooms fit the house?  Says which of the two fit commands to use."""
    b = _bbox(lay)
    if b is None:
        return True, "No rooms yet."
    ix0, iy0, ix1, iy1 = lay_inner(lay)
    nw, nd = b[2] - b[0], b[3] - b[1]
    iw, idp = ix1 - ix0, iy1 - iy0
    wo, do = lay_outer(lay)
    msgs = []
    tol = 5.0
    if abs(nw - iw) > tol or abs(nd - idp) > tol:
        msgs.append("The rooms take %.2f x %.2f m inside, the house has %.2f x %.2f m inside (outside %.2f x %.2f m)." %
                    (nw / 1000, nd / 1000, iw / 1000, idp / 1000, wo / 1000, do / 1000))
    if b[0] < ix0 - tol or b[1] < iy0 - tol or b[2] > ix1 + tol or b[3] > iy1 + tol:
        msgs.append("Some rooms stick out of the house.")
    for a, c in _overlaps(lay)[:3]:
        msgs.append("%s and %s overlap (or are closer than a wall)." % (a["name"], c["name"]))
    for c in lay_mains(lay):
        if cell_shape(c) != "rect" and lay_subs(lay, c):
            msgs.append("%s has sub-rooms, so its %s shape is ignored (sub-rooms are carved from a rectangle)." % (c["name"], cell_shape(c)))
    if not msgs:
        return True, "The rooms fit the house exactly: %.2f x %.2f m inside, %.2f x %.2f m outside." % (iw / 1000, idp / 1000, wo / 1000, do / 1000)
    return False, "  ".join(msgs) + "   -> 'Fit rooms to the house' shrinks / grows the rooms, 'Fit house to the rooms' changes the house."


# ---- building the walls, rooms, doors and windows ---------------------------------------------------------------------
def _clean(poly):
    """Polygon without repeated and collinear points."""
    pts = [tuple(p) for p in poly]
    out = []
    for p in pts:
        if not out or dist(p, out[-1]) > 0.5:
            out.append(p)
    if len(out) > 1 and dist(out[0], out[-1]) <= 0.5:
        out.pop()
    changed = True
    while changed and len(out) > 3:
        changed = False
        for i in range(len(out)):
            a, b, c = out[i - 1], out[i], out[(i + 1) % len(out)]
            if abs((b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])) < 1.0:
                out.pop(i)
                changed = True
                break
    return out


def _offset_ortho(poly, h):
    """Axis-aligned polygon moved outwards by h."""
    pts = _clean(ensure_ccw(poly))
    n = len(pts)
    out = []
    for i in range(n):
        a, b, c = pts[i - 1], pts[i], pts[(i + 1) % n]
        n1 = v_perp(v_unit(v_sub(b, a)))
        n2 = v_perp(v_unit(v_sub(c, b)))
        out.append((b[0] - h * (n1[0] + n2[0]), b[1] - h * (n1[1] + n2[1])))      # v_perp points left = into a CCW polygon
    return out


def _union(intervals):
    iv = sorted(intervals)
    out = []
    for a, b in iv:
        if out and a <= out[-1][1] + 1.0:
            out[-1][1] = max(out[-1][1], b)
        else:
            out.append([a, b])
    return out


def lay_wall_segments(lay):
    """[(orient 'h' | 'v', coordinate, lo, hi)] - the centre lines of the INNER walls (merged, outer walls excluded)."""
    t = lay["frame"]["t_in"]
    to = lay["frame"]["t_out"]
    wo, do = lay_outer(lay)
    raw = {"h": [], "v": []}
    for sh in lay_shapes(lay):
        poly = _offset_ortho(sh["poly"], t / 2.0)
        for i in range(len(poly)):
            a, b = poly[i], poly[(i + 1) % len(poly)]
            if abs(a[1] - b[1]) < 0.5 and abs(a[0] - b[0]) > 1.0:
                raw["h"].append((a[1], min(a[0], b[0]), max(a[0], b[0])))
            elif abs(a[0] - b[0]) < 0.5 and abs(a[1] - b[1]) > 1.0:
                raw["v"].append((a[0], min(a[1], b[1]), max(a[1], b[1])))
    segs = []
    tol = 0.4 * t
    for o, items in raw.items():
        lim = (wo if o == "v" else do)
        items.sort()
        groups = []
        for c, lo, hi in items:                                # cluster nearby coordinates (rooms scaled a little)
            if groups and c - groups[-1][0][-1][0] <= tol:
                groups[-1][0].append((c, lo, hi))
            else:
                groups.append(([(c, lo, hi)], None))
        for g, _ in groups:
            c = sum(x[0] for x in g) / len(g)
            if c < to + 0.5 or c > lim - to - 0.5:             # lies inside an outer wall
                continue
            far = do if o == "v" else wo                       # length of the house along the segment
            for lo, hi in _union([(x[1], x[2]) for x in g]):
                lo2 = to / 2.0 if lo < to else lo
                hi2 = far - to / 2.0 if hi > far - to else hi
                if hi2 - lo2 > 50:
                    segs.append((o, c, lo2, hi2))
    return segs


def _edges(poly):
    out = []
    n = len(poly)
    for i in range(n):
        a, b = poly[i], poly[(i + 1) % n]
        if abs(a[1] - b[1]) < 0.5 and abs(a[0] - b[0]) > 1:
            out.append(("h", a[1], min(a[0], b[0]), max(a[0], b[0])))
        elif abs(a[0] - b[0]) < 0.5 and abs(a[1] - b[1]) > 1:
            out.append(("v", a[0], min(a[1], b[1]), max(a[1], b[1])))
    return out


def lay_adjacency(lay, shapes=None):
    """[(i, j, orient, wall coordinate, lo, hi)]: rooms i and j are separated by one inner wall along [lo, hi]."""
    sh = shapes or lay_shapes(lay)
    t = lay["frame"]["t_in"]
    tol = 0.45 * t + 1.0
    es = [_edges(_clean(s["poly"])) for s in sh]
    out = []
    for i in range(len(sh)):
        for j in range(i + 1, len(sh)):
            best = {}
            for o1, c1, a1, b1 in es[i]:
                for o2, c2, a2, b2 in es[j]:
                    if o1 != o2 or abs(abs(c1 - c2) - t) > tol:
                        continue
                    lo, hi = max(a1, a2), min(b1, b2)
                    if hi - lo >= 600:
                        key = (o1, round((c1 + c2) / 2.0, 0))
                        if key not in best or hi - lo > best[key][1] - best[key][0]:
                            best[key] = (lo, hi, (c1 + c2) / 2.0)
            for (o, _), (lo, hi, c) in best.items():
                out.append((i, j, o, c, lo, hi))
    return out


def lay_apply(proj, story, lay, doors=None, windows=None):
    """Replaces everything the planner made earlier in this storey by new outer walls, inner walls, rooms, doors and windows.
    Returns a short report (dict)."""
    doors = lay["opts"].get("doors", True) if doors is None else doors
    windows = lay["opts"].get("windows", True) if windows is None else windows
    story["walls"] = [w for w in story["walls"] if not w.get("gen")]
    story["rooms"] = [r for r in story["rooms"] if not r.get("gen")]
    wall_ids = {w["id"] for w in story["walls"]}
    story["openings"] = [o for o in story["openings"] if not o.get("gen") and o["wall"] in wall_ids]
    to, ti = lay["frame"]["t_out"], lay["frame"]["t_in"]
    wo, do = lay_outer(lay)
    h = to / 2.0
    frame = {}
    for side, a, b in (("S", (0 + h, h), (wo - h, h)), ("E", (wo - h, h), (wo - h, do - h)),
                       ("N", (wo - h, do - h), (h, do - h)), ("W", (h, do - h), (h, h))):
        w = add_wall(proj, story, a, b, to)
        w["gen"] = 1
        frame[side] = (w, a, b)
    rep = {"walls": 4, "rooms": 0, "doors": 0, "windows": 0}
    for o, c, lo, hi in lay_wall_segments(lay):
        w = add_wall(proj, story, (lo, c) if o == "h" else (c, lo), (hi, c) if o == "h" else (c, hi), ti)
        w["gen"] = 1
        rep["walls"] += 1
        w["_o"] = (o, c, lo, hi)
    inner_walls = [w for w in story["walls"] if w.get("gen") and "_o" in w]
    shapes = lay_shapes(lay)
    for s in shapes:
        r = add_room(proj, story, s["poly"], s["name"])
        r["gen"] = 1
        rep["rooms"] += 1

    def inner_wall_at(o, c, mid):
        for w in inner_walls:
            oo, cc, lo, hi = w["_o"]
            if oo == o and abs(cc - c) < 0.5 * ti + 1 and lo - 1 <= mid <= hi + 1:
                return w, mid - lo
        return None, 0.0

    def door(wid, pos, kind="door", w=None, **kw):
        op = add_opening(proj, story, wid, pos, kind, w, **kw)
        op["gen"] = 1
        return op
    if doors and shapes:
        adj = lay_adjacency(lay, shapes)
        names = [s["name"] for s in shapes]
        types = [s["type"] for s in shapes]
        nbr = {i: [] for i in range(len(shapes))}
        for e in adj:
            nbr[e[0]].append((e[1], e))
            nbr[e[1]].append((e[0], e))
        start = next((i for i, s in enumerate(shapes) if s["type"] == "Corridor"), None)
        if start is None:
            start = next((i for i, s in enumerate(shapes) if s["type"] == "Hall" and not s["sub"]), None)
        if start is None:
            start = max(range(len(shapes)), key=lambda i: poly_area(shapes[i]["poly"]))
        seen = {start}
        queue = [start]
        while queue:
            cur = queue.pop(0)
            for j, e in sorted(nbr[cur], key=lambda x: -(x[1][5] - x[1][4])):
                if j in seen:
                    continue
                seen.add(j)
                queue.append(j)
                _, _, o, c, lo, hi = e
                mid = (lo + hi) / 2.0
                wl, pos = inner_wall_at(o, c, mid)
                if wl is not None:
                    width = 800.0 if (types[j] in SMALL_DOOR or types[cur] in SMALL_DOOR) else 900.0
                    door(wl["id"], pos, "door", min(width, hi - lo - 300.0))
                    rep["doors"] += 1
        # the front door: on the outer wall at the start room
        ix0, iy0, ix1, iy1 = lay_inner(lay)
        best = None
        for o, c, lo, hi in _edges(_clean(shapes[start]["poly"])):
            side = None
            if o == "h" and abs(c - iy0) < 1:
                side = "S"
            elif o == "h" and abs(c - iy1) < 1:
                side = "N"
            elif o == "v" and abs(c - ix0) < 1:
                side = "W"
            elif o == "v" and abs(c - ix1) < 1:
                side = "E"
            if side and (best is None or (side == "S", hi - lo) > (best[0] == "S", best[2] - best[1])):
                best = (side, lo, hi)
        if best and best[2] - best[1] >= 900:
            side, lo, hi = best
            wl, a, b = frame[side]
            mid = (lo + hi) / 2.0
            pos = {"S": mid - a[0], "N": a[0] - mid, "E": mid - a[1], "W": a[1] - mid}[side]
            door(wl["id"], pos, "door", min(1000.0, hi - lo - 200.0))
            rep["doors"] += 1
    if windows:
        ix0, iy0, ix1, iy1 = lay_inner(lay)
        for s in shapes:
            if s["type"] in NO_WINDOW:
                continue
            best = None
            for o, c, lo, hi in _edges(_clean(s["poly"])):
                side = ("S" if o == "h" and abs(c - iy0) < 1 else "N" if o == "h" and abs(c - iy1) < 1 else
                        "W" if o == "v" and abs(c - ix0) < 1 else "E" if o == "v" and abs(c - ix1) < 1 else None)
                if side and (best is None or hi - lo > best[2] - best[1]):
                    best = (side, lo, hi)
            if not best:
                continue
            side, lo, hi = best
            ww = 600.0 if s["type"] in ("Bathroom", "WC") else (1800.0 if s["type"] == "Living room" and hi - lo >= 3000 else 1200.0)
            if hi - lo < ww + 600:
                continue
            wl, a, b = frame[side]
            mid = (lo + hi) / 2.0
            pos = {"S": mid - a[0], "N": a[0] - mid, "E": mid - a[1], "W": a[1] - mid}[side]
            door(wl["id"], pos, "window", ww, **({"h": 600.0, "sill": 1500.0} if ww == 600.0 else {}))
            rep["windows"] += 1
    for w in story["walls"]:
        w.pop("_o", None)
    story["layout"] = lay
    return rep


# *************** DEL 54 - QUANTITIES, PRICE BOOK, WHERE TO BUY, MEMOS, CRAFTSMEN (no windows here, only logic) *****************
# takeoff(proj)      what the model needs: wall / floor / roof areas, running metres, windows, doors, fixtures ...
# the BOOK           stores (with delivery cost), prices per material and unit, craftsmen: one file shared by all projects
# the PROJECT        a shopping list (from the model + your own lines) and memos: saved inside the project file
# best_plans()       cheapest way to buy the list: all at one store, at most two stores, at most N stores (delivery included)
# ToDo: prices with quantity discounts, VAT switch, price history per material, fetching prices from the stores' web pages.

import itertools

BOOK_FORMAT = "architect-book"
BASE_UNITS = ["m2", "m", "pc", "m3", "kg", "l"]                      # the unit a QUANTITY is counted in
SOLD_UNITS = ["m2", "m", "pc", "m3", "kg", "l", "sheet", "pack", "bag", "roll", "length", "bundle", "pallet", "can"]
CONTINUOUS_UNITS = ("m2", "m", "m3", "kg", "l")                       # these can be bought by exact amount (when size is 1)
TRADES = ["Builder", "Carpenter", "Electrician", "Plumber", "Painter", "Tiler", "Roofer", "Bricklayer / mason", "HVAC",
          "Floor layer", "Window / door fitter", "Excavation", "Architect / engineer", "Other"]
DELIVERY_MODES = ["auto", "pickup", "delivery"]
WASTE_DEFAULT = {"m2": 10.0}


def today_str():
    return time.strftime("%Y-%m-%d")


def norm_name(s):
    return " ".join(str(s).casefold().split())


def to_num(v, default=0.0):
    """A number from text such as '1 299,50' or '12.5 kr' (0 when it is not a number)."""
    if isinstance(v, (int, float)):
        return float(v)
    t = re.sub(r"[^0-9,.\-]", "", str(v).replace(" ", " ")).replace(",", ".")
    if t.count(".") > 1:
        head, _, tail = t.rpartition(".")
        t = head.replace(".", "") + "." + tail
    try:
        return float(t)
    except ValueError:
        return default


def fmt_money(v):
    s = "{:,.2f}".format(v).replace(",", " ")
    return s[:-3] if s.endswith(".00") else s


# ---- quantities from the model ----------------------------------------------------------------------------------
def mesh_volume(faces):
    v = 0.0
    for f in faces:
        for i in range(1, len(f) - 1):
            a, b, c = f[0], f[i], f[i + 1]
            v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
    return abs(v)


def takeoff(proj):
    """[{key, label, unit, qty, group}] - what the model needs.  Quantities are net (doors and windows taken out)."""
    out = []
    order = {}

    def add(key, label, unit, qty, group):
        if qty < 1e-6:
            return
        if key in order:
            out[order[key]]["qty"] += qty
            return
        order[key] = len(out)
        out.append({"key": key, "label": label, "unit": unit, "qty": qty, "group": group})
    sol = build_mesh(proj, with_items=False, with_stairs=False)
    wall_area = {}
    for s in sol:
        story = proj["stories"][s["sidx"]]
        if s["type"] == "wall":
            w = get_wall(story, s["ref"]) if any(x["id"] == s["ref"] for x in story["walls"]) else None
            if w is not None:
                wall_area[round(w["t"])] = wall_area.get(round(w["t"]), 0.0) + mesh_volume(s["faces"]) / max(1.0, w["t"])
            else:
                dm = next((x for x in story.get("dormers", []) if x["id"] == s["ref"]), None)
                t = dm.get("wt", DORMER_WT) if dm else 100.0
                add("dormerwall:%d" % round(t), "Dormer walls, %d mm" % round(t), "m2", mesh_volume(s["faces"]) / max(1.0, t) / 1e6, "Roof")
        elif s["type"] == "roof":
            r = next((x for x in story["roofs"] if x["id"] == s["ref"]), None)
            dm = None if r else next((x for x in story.get("dormers", []) if x["id"] == s["ref"]), None)
            t = r["t"] if r else (dm.get("rt", 120.0) if dm else 200.0)
            if r:
                add("roof", "Roof surface (slope area)", "m2", mesh_volume(s["faces"]) / max(1.0, t) / 1e6, "Roof")
            else:
                add("dormerroof", "Dormer roof surfaces", "m2", mesh_volume(s["faces"]) / max(1.0, t) / 1e6, "Roof")
    total_wall = 0.0
    for t in sorted(wall_area):
        a = wall_area[t] / 1e6
        total_wall += a
        add("wall:%d" % t, "Walls, %d mm thick (one face, net)" % t, "m2", a, "Walls")
    add("wallsurf", "Wall surfaces, both faces (paint, plaster, lining)", "m2", 2.0 * total_wall, "Walls")
    floor, perim, door_w = 0.0, 0.0, 0.0
    lens = {}
    for sidx, story in enumerate(proj["stories"]):
        for w in story["walls"]:
            if is_curtain(w):                      # rail + fabric instead of wall material
                ln = wall_length(w)
                hh = max(0.0, curtain_top(proj, sidx, w) - story_elevations(proj)[sidx] - CURTAIN_RAIL - CURTAIN_GAP)
                add("curtain_rail", "Curtain rail, ceiling mounted (with fittings)", "m", ln / 1000.0, "Curtains")
                add("curtain_fabric:%d" % round(hh), "Curtain fabric, %d mm drop, %g x fullness" % (round(hh), CURTAIN_FULLNESS), "m",
                    ln * CURTAIN_FULLNESS / 1000.0, "Curtains")
                continue
            lens[round(w["t"])] = lens.get(round(w["t"]), 0.0) + wall_length(w)
        for r in story["rooms"]:
            if len(r["pts"]) >= 3:
                pts = [tuple(p) for p in r["pts"]]
                floor += poly_area(pts)
                perim += poly_perimeter(pts)
        for o in story["openings"]:
            if o["kind"] in ("door", "door2", "slide", "passage"):
                door_w += o["w"]
            if o["kind"] == "passage":
                continue
            lab = OPENING_KINDS.get(o["kind"], (0, 0, 0, o["kind"]))[3]
            add("open:%s:%d:%d" % (o["kind"], round(o["w"]), round(o["h"])), "%s %d x %d mm" % (lab, round(o["w"]), round(o["h"])),
                "pc", 1, "Windows & doors")
        for dm in story.get("dormers", []):
            add("dormer:%s:%d" % (dm["kind"], round(dm["w"])), "Dormer (%s), %d mm wide" % (dm["kind"], round(dm["w"])), "pc", 1, "Roof")
            win = _dormer_window(story, dm)
            if win:
                add("dormwin:%d:%d" % (round(2 * win[0]), round(win[2] - win[1])), "Dormer window %d x %d mm" %
                    (round(2 * win[0]), round(win[2] - win[1])), "pc", 1, "Windows & doors")
        for rw in story.get("rwins", []):
            add("rwin:%d:%d" % (round(rw["w"]), round(rw["h"])), "Roof window %d x %d mm" % (round(rw["w"]), round(rw["h"])),
                "pc", 1, "Windows & doors")
        for st in story["stairs"]:
            add("stair:%s:%d" % (st["kind"], st["n"]), "Stair (%s, %d steps)" % (st["kind"], st["n"]), "pc", 1, "Stairs")
        for it in story["items"]:
            c = CATALOG.get(it["type"])
            add("item:%s" % it["type"], c["name"] if c else it["type"], "pc", 1, "Fixtures & furniture")
    add("floor", "Floor area (all rooms)", "m2", floor / 1e6, "Floors & ceilings")
    add("ceiling", "Ceiling area (all rooms)", "m2", floor / 1e6, "Floors & ceilings")
    add("skirting", "Skirting board (rooms' perimeter less doors, approx.)", "m", max(0.0, perim - door_w) / 1000.0, "Floors & ceilings")
    for t in sorted(lens):
        add("walllen:%d" % t, "Walls, %d mm thick - running length" % t, "m", lens[t] / 1000.0, "Walls")
    return out


# ---- the project's shopping list and memos ----------------------------------------------------------------------
def ensure_extras(proj):
    """Adds the shopping list and the memo list to a project that has none (old files)."""
    if not isinstance(proj.get("notes"), list):
        proj["notes"] = []
    if not isinstance(proj.get("shop"), dict):
        proj["shop"] = {}
    sh = proj["shop"]
    sh.setdefault("lines", [])
    sh.setdefault("mode", "auto")
    sh.setdefault("max_stores", 3)
    sh.setdefault("next", 1)
    return proj


def shop_add_line(proj, label, unit="m2", qty=0.0, material=None, waste=None, auto=False, key=""):
    sh = ensure_extras(proj)["shop"]
    ln = {"id": sh["next"], "label": label, "material": material if material is not None else label, "unit": unit,
          "qty": float(qty), "waste": WASTE_DEFAULT.get(unit, 0.0) if waste is None else float(waste), "auto": bool(auto), "key": key}
    sh["next"] += 1
    sh["lines"].append(ln)
    return ln


def shop_refresh(proj):
    """Brings the automatic lines of the shopping list up to date with the model.  Your own lines, and the material name /
    waste you typed on automatic lines, are kept.  Returns (added, updated, removed)."""
    sh = ensure_extras(proj)["shop"]
    now = takeoff(proj)
    have = {ln["key"]: ln for ln in sh["lines"] if ln.get("auto")}
    added = updated = 0
    keys = set()
    for t in now:
        keys.add(t["key"])
        ln = have.get(t["key"])
        if ln is None:
            shop_add_line(proj, t["label"], t["unit"], round(t["qty"], 2), None, None, True, t["key"])
            added += 1
        else:
            if abs(ln["qty"] - t["qty"]) > 0.005 or ln["label"] != t["label"] or ln["unit"] != t["unit"]:
                updated += 1
            ln["qty"], ln["label"], ln["unit"] = round(t["qty"], 2), t["label"], t["unit"]
    gone = [ln for ln in sh["lines"] if ln.get("auto") and ln["key"] not in keys]
    for ln in gone:
        sh["lines"].remove(ln)
    return added, updated, len(gone)


def line_need(ln):
    return max(0.0, float(ln["qty"])) * (1.0 + max(0.0, float(ln.get("waste") or 0.0)) / 100.0)


# ---- the book: stores, prices, craftsmen -----------------------------------------------------------------------
def book_new():
    b = {"format": BOOK_FORMAT, "version": 1, "next_id": 1, "stores": [], "prices": [], "contacts": []}
    book_add_store(b, "Byggmax", delivers=True, note="Home delivery for a fee - type in the real fee and the free-delivery limit.")
    book_add_store(b, "Jem & Fix")
    return b


def book_path():
    return os.path.join(PROGRAM_HF_DIR, "book.json")


def book_load(path=None):
    path = path or book_path()
    try:
        with open(path, encoding="utf-8-sig") as fh:
            b = json.load(fh)
        if not isinstance(b, dict) or b.get("format") != BOOK_FORMAT:
            raise ValueError("not a book")
    except Exception:
        return book_new()
    for k in ("stores", "prices", "contacts"):
        b.setdefault(k, [])
    mx = b.get("next_id", 1)
    for k in ("stores", "prices", "contacts"):
        for e in b[k]:
            mx = max(mx, e.get("id", 0) + 1)
    b["next_id"] = mx
    return b


def book_save(book, path=None):
    path = path or book_path()
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(book, fh, ensure_ascii=False, indent=1)
    os.replace(tmp, path)


def book_uid(book):
    n = book["next_id"]
    book["next_id"] = n + 1
    return n


def book_store(book, sid):
    return next((s for s in book["stores"] if s["id"] == sid), None)


def book_store_by_name(book, name):
    n = norm_name(name)
    return next((s for s in book["stores"] if norm_name(s["name"]) == n), None)


def book_add_store(book, name, delivers=False, delivery_fee=0.0, free_over=0.0, pickup_cost=0.0, note="", url=""):
    """delivery_fee: home delivery; free_over: order value from which delivery is free (0 = never);
    pickup_cost: what it costs YOU to fetch the goods (fuel, time) - 0 when it does not matter."""
    s = {"id": book_uid(book), "name": name.strip(), "delivers": bool(delivers), "delivery_fee": float(delivery_fee),
         "free_over": float(free_over), "pickup_cost": float(pickup_cost), "note": note, "url": url}
    book["stores"].append(s)
    return s


def book_add_price(book, store_id, material, price, base="m2", unit=None, size=1.0, note=""):
    """price = money per `unit` sold; one sold unit contains `size` of the base unit (a plasterboard sheet: unit 'sheet',
    size 2.88, base 'm2').  Same store + material + base: the price is replaced."""
    unit = unit or base
    key = norm_name(material)
    for e in book["prices"]:
        if e["store"] == store_id and norm_name(e["material"]) == key and e["base"] == base and e["unit"] == unit \
                and abs(e["size"] - size) < 1e-9:
            e["price"], e["note"], e["updated"] = float(price), note, today_str()
            return e
    e = {"id": book_uid(book), "store": store_id, "material": material.strip(), "base": base, "unit": unit, "size": float(size),
         "price": float(price), "note": note, "updated": today_str()}
    book["prices"].append(e)
    return e


def book_remove(book, kind, eid):
    """kind: 'stores' (its prices go too), 'prices', 'contacts'."""
    book[kind] = [e for e in book[kind] if e["id"] != eid]
    if kind == "stores":
        book["prices"] = [e for e in book["prices"] if e["store"] != eid]


def book_materials(book, proj=None):
    """Every material name known: from the prices and from the project's shopping list."""
    seen, out = set(), []
    names = [e["material"] for e in book["prices"]]
    if proj is not None:
        names += [ln["material"] for ln in ensure_extras(proj)["shop"]["lines"]]
    for n in names:
        if norm_name(n) not in seen:
            seen.add(norm_name(n))
            out.append(n)
    return sorted(out, key=norm_name)


def book_add_contact(book, name, trade="Other", company="", phone="", email="", address="", rate="", rating=0, note="", web=""):
    c = {"id": book_uid(book), "name": name.strip(), "trade": trade, "company": company, "phone": phone, "email": email,
         "address": address, "web": web, "rate": rate, "rating": int(rating), "note": note, "last": "", "created": today_str()}
    book["contacts"].append(c)
    return c


def find_contacts(book, text="", trade=""):
    t = norm_name(text)
    out = []
    for c in book["contacts"]:
        if trade and trade != "All" and c["trade"] != trade:
            continue
        if t and t not in norm_name(" ".join(str(c.get(k, "")) for k in ("name", "trade", "company", "phone", "email", "address", "note"))):
            continue
        out.append(c)
    return sorted(out, key=lambda c: (c["trade"], norm_name(c["name"])))


# ---- memos ------------------------------------------------------------------------------------------------------
def add_memo(proj, title, text="", due="", pinned=False):
    ensure_extras(proj)
    mx = max([n["id"] for n in proj["notes"]] + [0])
    n = {"id": mx + 1, "title": title.strip() or "Memo", "text": text, "due": due, "done": False, "pinned": bool(pinned),
         "created": today_str(), "changed": today_str()}
    proj["notes"].append(n)
    return n


def memos_sorted(proj, hide_done=False):
    """Pinned first, then open ones with a due date (soonest first), then the rest, newest first."""
    ensure_extras(proj)
    ns = sorted((n for n in proj["notes"] if not (hide_done and n.get("done"))), key=lambda n: (n["changed"], n["id"]), reverse=True)
    return sorted(ns, key=lambda n: (not n.get("pinned"), bool(n.get("done")), n.get("due") or "9999"))   # stable: newest first inside


def memos_due(proj, on=None):
    """Open memos whose due date is today or earlier."""
    on = on or today_str()
    return [n for n in ensure_extras(proj)["notes"] if n.get("due") and not n.get("done") and n["due"] <= on]


# ---- the cheapest way to buy ------------------------------------------------------------------------------------
def entry_cost(e, need):
    """(money, sold units to buy, unit) for buying `need` of the base unit with the price entry `e`."""
    size = max(1e-9, float(e.get("size") or 1.0))
    unit = e.get("unit") or e.get("base") or "pc"
    if need <= 1e-9:
        return 0.0, 0, unit
    if unit in CONTINUOUS_UNITS and abs(size - 1.0) < 1e-9:
        return need * e["price"], need, unit
    n = int(math.ceil(need / size - 1e-9))
    return n * e["price"], n, unit


def line_options(book, ln):
    """{store id: (money, sold units, unit, price entry)} - the cheapest offer of every store for this shopping line."""
    need = line_need(ln)
    key = norm_name(ln["material"])
    res = {}
    for e in book["prices"]:
        if norm_name(e["material"]) != key or e.get("base", ln["unit"]) != ln["unit"]:
            continue
        c = entry_cost(e, need)
        if e["store"] not in res or c[0] < res[e["store"]][0] - 1e-9:
            res[e["store"]] = (c[0], c[1], c[2], e)
    return res


def store_fee(st, subtotal, mode="auto"):
    """(money, 'delivery' | 'pickup') for the goods bought at one store.  mode 'auto' takes the cheaper way, 'pickup' always
    fetches the goods, 'delivery' uses home delivery wherever the store offers it."""
    pick = float(st.get("pickup_cost") or 0.0)
    dl = None
    if st.get("delivers"):
        fo = float(st.get("free_over") or 0.0)
        dl = 0.0 if fo > 0 and subtotal >= fo else float(st.get("delivery_fee") or 0.0)
    if mode == "pickup" or dl is None:
        return pick, "pickup"
    if mode == "delivery":
        return dl, "delivery"
    return (dl, "delivery") if dl < pick - 1e-9 else (pick, "pickup")


def make_plan(book, lines, opts, subset, mode="auto"):
    """Every shopping line bought where it is cheapest among the stores in `subset`; the delivery or pickup cost of every
    store that is actually used is added."""
    per, assign, missing = {}, {}, []
    for ln in lines:
        best = None
        for sid in subset:
            o = opts[ln["id"]].get(sid)
            if o is not None and (best is None or o[0] < best[1][0] - 1e-9):
                best = (sid, o)
        if best is None:
            missing.append(ln["id"])
            continue
        sid, o = best
        assign[ln["id"]] = {"store": sid, "money": o[0], "n": o[1], "unit": o[2], "entry": o[3]["id"]}
        p = per.setdefault(sid, {"goods": 0.0, "lines": []})
        p["goods"] += o[0]
        p["lines"].append(ln["id"])
    fees = 0.0
    for sid, p in per.items():
        p["fee"], p["how"] = store_fee(book_store(book, sid), p["goods"], mode)
        fees += p["fee"]
    goods = sum(p["goods"] for p in per.values())
    return {"stores": sorted(per, key=lambda s: -per[s]["goods"]), "assign": assign, "missing": missing, "per": per,
            "goods": goods, "fees": fees, "total": goods + fees}


def best_plans(book, lines, mode="auto", max_stores=3):
    """The answer to 'where should I buy this?'.  Only lines that at least one store has a price for take part (the others come
    back in 'unpriced').  Returns {'unpriced', 'priced', 'singles', 'single', 'two', 'best', 'majority'}:
    singles = a plan per store, best first (full coverage before price); single = the winner; two = best plan using at most two
    stores; best = best plan using at most max_stores stores; majority = the store that supplies most of the best plan."""
    opts = {ln["id"]: line_options(book, ln) for ln in lines}
    priced = [ln for ln in lines if opts[ln["id"]]]
    unpriced = [ln["id"] for ln in lines if not opts[ln["id"]]]
    sids = sorted({sid for ln in priced for sid in opts[ln["id"]]}, key=lambda s: -sum(1 for ln in priced if s in opts[ln["id"]]))[:12]
    res = {"unpriced": unpriced, "priced": [ln["id"] for ln in priced], "singles": [], "single": None, "two": None, "best": None,
           "majority": None, "mode": mode}
    if not priced or not sids:
        return res

    def score(plan):
        return (len(plan["missing"]), round(plan["total"], 4), len(plan["stores"]))
    for sid in sids:
        res["singles"].append(make_plan(book, priced, opts, [sid], mode))
    res["singles"].sort(key=score)
    res["single"] = res["singles"][0]
    best, two = None, None
    for n in range(1, min(max_stores, len(sids)) + 1):
        for sub in itertools.combinations(sids, n):
            pl = make_plan(book, priced, opts, list(sub), mode)
            if best is None or score(pl) < score(best):
                best = pl
            if n <= 2 and (two is None or score(pl) < score(two)):
                two = pl
    res["best"], res["two"] = best, two
    if best and best["stores"]:
        top = best["stores"][0]
        res["majority"] = {"store": top, "lines": len(best["per"][top]["lines"]), "of": len(priced),
                           "share": best["per"][top]["goods"] / best["goods"] if best["goods"] else 1.0}
    return res


def plan_text(book, lines, res):
    """The result of best_plans() as readable text."""
    by_id = {ln["id"]: ln for ln in lines}
    out = []

    def nm(sid):
        return book_store(book, sid)["name"]

    def block(title, pl):
        out.append(title)
        if pl is None:
            out.append("  (nothing to compare - type in some prices first)")
            return
        for sid in pl["stores"]:
            p = pl["per"][sid]
            out.append("  %s: %d line(s), goods %s kr%s" % (nm(sid), len(p["lines"]), fmt_money(p["goods"]),
                       "" if not p["fee"] else ", %s %s kr" % ("delivery" if p["how"] == "delivery" else "fetching", fmt_money(p["fee"]))))
            for lid in p["lines"]:
                a = pl["assign"][lid]
                ln = by_id[lid]
                out.append("      %s - %s %s%s = %s kr" % (ln["label"], ("%g" % round(a["n"], 2)), a["unit"],
                                                       "" if a["unit"] == ln["unit"] else " (for %.2f %s)" % (line_need(ln), ln["unit"]),
                                                       fmt_money(a["money"])))
        out.append("  TOTAL %s kr (goods %s + delivery / fetching %s)" % (fmt_money(pl["total"]), fmt_money(pl["goods"]), fmt_money(pl["fees"])))
        if pl["missing"]:
            out.append("  Not sold at these stores: " + ", ".join(by_id[i]["label"] for i in pl["missing"]))
    if res["best"] is None:
        return "No prices match the shopping list yet.\nType the prices in the 'Prices' tab - the material name must be the same as on the line."
    s = res["single"]
    full = not s["missing"]
    block("ALL AT ONE STORE: %s%s" % (nm(s["stores"][0]) if s["stores"] else "-", "" if full else "  (does not sell every line - %d of %d)" %
                                     (len(res["priced"]) - len(s["missing"]), len(res["priced"]))), s)
    out.append("")
    if res["two"] is not res["best"] and res["two"] and len(res["two"]["stores"]) > 1:
        block("AT MOST TWO STORES", res["two"])
        out.append("")
    block("CHEAPEST OVERALL (%s)" % ", ".join(nm(i) for i in res["best"]["stores"]), res["best"])
    out.append("")
    if len(res["best"]["stores"]) > 1:
        mj = res["majority"]
        out.append("Most of it at %s: %d of %d lines (%d%% of the money)." % (nm(mj["store"]), mj["lines"], mj["of"], round(100 * mj["share"])))
    sv = s["total"] - res["best"]["total"]
    if not s["missing"] and sv > 0.5:
        out.append("Splitting the purchase saves %s kr compared with buying everything at %s." % (fmt_money(sv), nm(s["stores"][0])))
    elif not s["missing"]:
        out.append("Buying everything at %s is also the cheapest." % nm(s["stores"][0]))
    if res["unpriced"]:
        out.append("")
        out.append("No price known for: " + ", ".join(by_id[i]["label"] for i in res["unpriced"]))
    return "\n".join(out)


# ---- CSV in and out ---------------------------------------------------------------------------------------------
def prices_csv_rows(book):
    rows = [["Store", "Material", "Base unit", "Price", "Sold per", "Contains (base units)", "Note", "Updated"]]
    for e in sorted(book["prices"], key=lambda e: (norm_name(book_store(book, e["store"])["name"]), norm_name(e["material"]))):
        rows.append([book_store(book, e["store"])["name"], e["material"], e["base"], ("%g" % e["price"]).replace(".", ","), e["unit"],
                     ("%g" % e["size"]).replace(".", ","), e["note"], e.get("updated", "")])
    return rows


def export_prices_csv(book, path):
    with open(path, "w", encoding="utf-8-sig", newline="") as fh:
        for r in prices_csv_rows(book):
            fh.write(";".join(str(c).replace(";", ",").replace("\n", " ") for c in r) + "\n")


def import_prices_csv(book, path):
    """Reads the file written by export_prices_csv() (or one made by hand in Excel: Store; Material; Base unit; Price; Sold per;
    Contains).  Unknown stores are created.  Returns the number of prices read."""
    n = 0
    with open(path, encoding="utf-8-sig") as fh:
        rows = [ln.rstrip("\r\n").split(";") for ln in fh if ln.strip()]
    for r in rows:
        r = r + [""] * (8 - len(r))
        price = to_num(r[3], -1.0)
        if price < 0 or not r[0].strip() or not r[1].strip() or r[0].strip().casefold() == "store":
            continue
        st = book_store_by_name(book, r[0]) or book_add_store(book, r[0])
        base = r[2].strip() if r[2].strip() in BASE_UNITS else "m2"
        unit = r[4].strip() or base
        book_add_price(book, st["id"], r[1], price, base, unit, max(1e-9, to_num(r[5], 1.0) or 1.0), r[6].strip())
        n += 1
    return n


def shop_csv_rows(book, lines, res):
    """The shopping list with the store chosen by the cheapest-overall plan."""
    rows = [["Line", "Material", "Quantity", "Unit", "Waste %", "Need", "Store", "Buy", "Sold per", "Money"]]
    best = res.get("best")
    for ln in lines:
        a = best["assign"].get(ln["id"]) if best else None
        rows.append([ln["label"], ln["material"], ("%.2f" % ln["qty"]).replace(".", ","), ln["unit"], "%g" % ln.get("waste", 0),
                     ("%.2f" % line_need(ln)).replace(".", ","), book_store(book, a["store"])["name"] if a else "",
                     ("%g" % round(a["n"], 2)).replace(".", ",") if a else "", a["unit"] if a else "",
                     ("%.2f" % a["money"]).replace(".", ",") if a else ""])
    if best:
        rows.append([])
        for sid in best["stores"]:
            p = best["per"][sid]
            rows.append(["", "", "", "", "", "", book_store(book, sid)["name"], "", p["how"], ("%.2f" % p["fee"]).replace(".", ",")])
        rows.append(["TOTAL", "", "", "", "", "", "", "", "", ("%.2f" % best["total"]).replace(".", ",")])
    return rows


def export_shop_csv(book, lines, res, path):
    with open(path, "w", encoding="utf-8-sig", newline="") as fh:
        for r in shop_csv_rows(book, lines, res):
            fh.write(";".join(str(c).replace(";", ",").replace("\n", " ") for c in r) + "\n")


def export_contacts_csv(book, path):
    with open(path, "w", encoding="utf-8-sig", newline="") as fh:
        fh.write(";".join(["Name", "Trade", "Company", "Phone", "Email", "Address", "Rate", "Rating", "Note"]) + "\n")
        for c in find_contacts(book):
            fh.write(";".join(str(c.get(k, "")).replace(";", ",").replace("\n", " ") for k in
                              ("name", "trade", "company", "phone", "email", "address", "rate", "rating", "note")) + "\n")


# *************** DEL 54 (cont.) - THE SHOPPING LIST AS A PDF (no windows here, only logic) *****************
# shop_pdf(book, lines, res, path, ...) writes the materials shopping list with the "where to buy" result: per store the lines,
# quantities to buy, prices, delivery / fetching cost, the totals and the alternatives.  Uses the same small PDF writer as the
# plan PDF (pdf_write_pages in DEL 50): Helvetica / Helvetica-Bold, A4 or A3, several pages, page numbers.
# ToDo: a logo / own address block, a QR code with the store links, landscape paper.
import unicodedata

_HELV = (278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,        # space ! " # $ % & ' ( ) * + , - . /
         556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,         # 0-9 : ; < = > ?
         1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,        # @ A-O
         667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,         # P-Z [ \ ] ^ _
         333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,         # ` a-o
         556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584)              # p-z { | } ~


def pdf_char_width(ch):
    """Width of one character in 1/1000 em (Helvetica; accented letters like their base letter)."""
    o = ord(ch)
    if 32 <= o <= 126:
        return _HELV[o - 32]
    base = unicodedata.normalize("NFD", ch)[:1]
    if base and 32 <= ord(base) <= 126:
        return _HELV[ord(base) - 32]
    return 556


def pdf_text_width(s, size, bold=False):
    """Width of a text in points (bold is estimated as 7% wider)."""
    return sum(pdf_char_width(c) for c in s) * size / 1000.0 * (1.07 if bold else 1.0)


def pdf_wrap(s, width, size, bold=False):
    """Breaks a text into lines that fit `width` points (at spaces; a word that is too long is cut)."""
    out = []
    for para in str(s).split("\n"):
        cur = ""
        for word in para.split(" "):
            cand = word if not cur else cur + " " + word
            if pdf_text_width(cand, size, bold) <= width:
                cur = cand
                continue
            if cur:
                out.append(cur)
            while pdf_text_width(word, size, bold) > width and len(word) > 1:
                k = len(word) - 1
                while k > 1 and pdf_text_width(word[:k], size, bold) > width:
                    k -= 1
                out.append(word[:k])
                word = word[k:]
            cur = word
        out.append(cur)
    return out or [""]


class PdfSheet(object):
    """A little page-flow writer: text, rules, shaded rows, table rows with wrapped cells, automatic page breaks, page numbers."""

    def __init__(self, paper="A4", margin_mm=16.0, footer=""):
        self.k = 72.0 / 25.4
        pw, ph = PAPERS.get(paper, PAPERS["A4"])
        self.W, self.H = min(pw, ph) * self.k, max(pw, ph) * self.k              # portrait
        self.m = margin_mm * self.k
        self.footer = footer
        self.pages = []
        self.ops = None
        self.y = 0.0
        self.header = None                                  # (cells, cols, size): repeated at the top of a page that continues a table
        self.new_page()

    def new_page(self):
        self.ops = []
        self.pages.append(self.ops)
        self.y = self.m

    @property
    def left(self):
        return self.m

    @property
    def right(self):
        return self.W - self.m

    def ensure(self, h):
        """Starts a new page when the next h points do not fit.  Returns True when it did."""
        if self.y + h > self.H - self.m - 14:
            self.new_page()
            if self.header:
                hd, self.header = self.header, None
                self.row(hd[0], hd[1], hd[2], True, True)
                self.header = hd
            return True
        return False

    def _t(self, x, y_top, s, size, bold=False, align="l", gray=0.0):
        if align == "r":
            x -= pdf_text_width(s, size, bold)
        elif align == "c":
            x -= pdf_text_width(s, size, bold) / 2.0
        self.ops.append(("%.3f g BT /%s %.2f Tf %.2f %.2f Td (" % (gray, "F2" if bold else "F1", size, x, self.H - y_top)).encode("latin-1")
                        + _pdf_esc(s) + b") Tj ET")

    def text(self, s, size=10.0, bold=False, x=None, align="l", gray=0.0, width=None, gap=0.0):
        """One paragraph, wrapped to `width` (default: the text area), at the current position."""
        x0 = self.left if x is None else x
        wd = (self.right - x0) if width is None else width
        lead = size * 1.25
        for ln in pdf_wrap(s, wd, size, bold):
            self.ensure(lead)
            ax = x0 if align == "l" else (x0 + wd if align == "r" else x0 + wd / 2.0)
            self._t(ax, self.y + size, ln, size, bold, align, gray)
            self.y += lead
        self.y += gap

    def rule(self, gray=0.6, w=0.6, gap=3.0):
        self.ensure(gap * 2 + 1)
        self.y += gap
        self.ops.append(("%.3f G %.2f w %.2f %.2f m %.2f %.2f l S" % (gray, w, self.left, self.H - self.y, self.right, self.H - self.y)).encode())
        self.y += gap

    def shade(self, h, gray=0.92):
        self.ops.append(("%.3f g %.2f %.2f %.2f %.2f re f" % (gray, self.left, self.H - self.y - h, self.right - self.left, h)).encode())

    def row(self, cells, cols, size=9.0, bold=False, shaded=False, gray=0.0):
        """cells = texts; cols = [(x offset from the left margin, width, 'l' | 'r')].  Wrapped cells make the row taller."""
        lead = size * 1.25
        wrapped = [pdf_wrap(c, wd - 4, size, bold) for c, (_, wd, _) in zip(cells, cols)]
        n = max(len(w) for w in wrapped)
        h = n * lead + 3
        self.ensure(h)
        if shaded:
            self.shade(h)
        for w, (off, wd, al) in zip(wrapped, cols):
            for i, ln in enumerate(w):
                x = self.left + off + (wd - 4 if al == "r" else 2)
                self._t(x, self.y + 1.5 + size + i * lead, ln, size, bold, al, gray)
        self.y += h

    def finish(self):
        """[(width, height, content bytes)] with the footer and the page numbers on every page."""
        n = len(self.pages)
        out = []
        for i, ops in enumerate(self.pages):
            self.ops = ops
            if self.footer:
                self._t(self.left, self.H - self.m + 8, self.footer, 7.5, False, "l", 0.4)
            self._t(self.right, self.H - self.m + 8, "Page %d of %d" % (i + 1, n), 7.5, False, "r", 0.4)
            out.append((self.W, self.H, b"\n".join(ops)))
        return out


def _money(v):
    return fmt_money(v) + " kr"


def store_fee_text(st, p):
    """One line about how the goods of a store come to the buyer and what that costs."""
    if p["how"] == "pickup":
        dl = store_fee(st, p["goods"], "delivery")[0]
        return ("You fetch the goods yourself" + (" (counted as %s)" % _money(p["fee"]) if p["fee"] else "")
                + ("" if not st.get("delivers") else "; home delivery would be free" if dl == 0 else "; home delivery would cost %s" % _money(dl)))
    fo = float(st.get("free_over") or 0.0)
    t = "Home delivery %s" % ("free" if p["fee"] == 0 else _money(p["fee"]))
    if fo > 0:
        t += " (free from %s" % _money(fo) + ("" if p["goods"] >= fo else ", %s more to get it" % _money(fo - p["goods"])) + ")"
    return t


def shop_pdf_pages(book, lines, res, project_name="", paper="A4", date=None):
    """The pages (see PdfSheet.finish) of the shopping-list PDF."""
    by_id = {ln["id"]: ln for ln in lines}
    sh = PdfSheet(paper, footer="Architect - shopping list - %s" % (project_name or "project"))
    sh.text("Shopping list", 20, True, gap=1)
    sh.text("%s    %s" % (project_name or "Project", date or today_str()), 10, False, gray=0.35, gap=2)
    sh.text("Quantities come from the drawing (waste added); prices are the ones in your price book, in kr including VAT.  "
            "Check prices and stock with the store before you buy.", 8, False, gray=0.4, gap=2)
    sh.rule()
    best = res.get("best") if res else None
    if best is None:
        sh.text("No prices match the shopping list yet.", 11, True, gap=2)
        sh.text("Type the prices in the 'Prices' tab - the material name must be the same as on the shopping list line.  "
                "The lines are listed below without prices.", 9, False, gap=6)
        tw = sh.right - sh.left
        cols = [(0, 0.46 * tw, "l"), (0.46 * tw, 0.16 * tw, "r"), (0.62 * tw, 0.1 * tw, "l"), (0.72 * tw, 0.12 * tw, "r"), (0.84 * tw, 0.16 * tw, "r")]
        hd = (["Line", "Quantity", "Unit", "Waste %", "Need"], cols, 9)
        sh.row(hd[0], cols, 9, True, True)
        sh.header = hd
        for ln in lines:
            sh.row([ln["label"], "%.2f" % ln["qty"], ln["unit"], "%g" % ln.get("waste", 0), "%.2f" % line_need(ln)], cols, 9)
        sh.header = None
        return sh.finish()
    # ---- the answer in short ------------------------------------------------------------------------------------
    names = [book_store(book, s)["name"] for s in best["stores"]]
    sh.text("Where to buy: cheapest overall", 12, True, gap=1)
    sh.text("%s  -  goods %s + delivery / fetching %s = TOTAL %s" % (" + ".join(names), _money(best["goods"]), _money(best["fees"]),
                                                                  _money(best["total"])), 10, True, gap=2)
    s1, two = res.get("single"), res.get("two")
    if s1 and s1["stores"]:
        sh.text("All at one store (%s): %s%s" % (book_store(book, s1["stores"][0])["name"], _money(s1["total"]),
                                                  "" if not s1["missing"] else "  - does not sell %d of the %d priced lines" %
                                                  (len(s1["missing"]), len(res["priced"]))), 9, False)
    if two and len(two["stores"]) > 1 and two is not best:
        sh.text("At most two stores (%s): %s" % (" + ".join(book_store(book, s)["name"] for s in two["stores"]), _money(two["total"])), 9, False)
    mj = res.get("majority")
    if mj and len(best["stores"]) > 1:
        sh.text("Most of it at %s: %d of %d lines (%d%% of the money)." % (book_store(book, mj["store"])["name"], mj["lines"], mj["of"],
                                                                         round(100 * mj["share"])), 9, False)
    if s1 and s1["stores"] and not s1["missing"]:
        sv = s1["total"] - best["total"]
        sh.text("Splitting the purchase saves %s compared with buying everything at %s." % (_money(sv), book_store(book, s1["stores"][0])["name"])
                if sv > 0.5 else "Buying everything at %s is also the cheapest." % book_store(book, s1["stores"][0])["name"], 9, False)
    sh.y += 6
    # ---- one block per store --------------------------------------------------------------------------------------
    tw = sh.right - sh.left
    cols = [(0, 0.44 * tw, "l"), (0.44 * tw, 0.22 * tw, "l"), (0.66 * tw, 0.17 * tw, "r"), (0.83 * tw, 0.17 * tw, "r")]
    for sid in best["stores"]:
        st = book_store(book, sid)
        p = best["per"][sid]
        sh.ensure(70)
        sh.rule(0.3, 0.4, 2)
        sh.text("%s  (%d line%s)" % (st["name"], len(p["lines"]), "" if len(p["lines"]) == 1 else "s"), 12, True, gap=0)
        sh.text(store_fee_text(st, p), 8.5, False, gray=0.3, gap=3)
        sh.row(["Line", "Buy", "Need", "Money"], cols, 8.5, True, True)
        sh.header = (["Line (%s, continued)" % st["name"], "Buy", "Need", "Money"], cols, 8.5)
        for lid in p["lines"]:
            a, ln = best["assign"][lid], by_id[lid]
            buy = "%g %s" % (round(a["n"], 2), a["unit"])
            sh.row([ln["label"], buy, "%.2f %s" % (line_need(ln), ln["unit"]), _money(a["money"])], cols, 8.5)
        sh.header = None
        sh.row(["Goods", "", "", _money(p["goods"])], cols, 8.5)
        sh.row(["Delivery" if p["how"] == "delivery" else "Fetching", "", "", _money(p["fee"])], cols, 8.5)
        sh.row(["Total at " + st["name"], "", "", _money(p["goods"] + p["fee"])], cols, 9, True, True)
        sh.y += 4
    # ---- what cannot be bought from this plan -------------------------------------------------------------------------
    left = [by_id[i] for i in best["missing"]] + [by_id[i] for i in res.get("unpriced", []) if i in by_id]
    if left:
        sh.ensure(40)
        sh.rule(0.3, 0.4, 2)
        sh.text("Not in this plan (no store with a price)", 11, True, gap=2)
        for ln in left:
            sh.text("- %s: %.2f %s (need %.2f)" % (ln["label"], ln["qty"], ln["unit"], line_need(ln)), 9, False)
        sh.y += 4
    sh.rule(0.2, 1.0, 3)
    sh.text("TOTAL %s" % _money(best["total"]), 14, True, align="r", gap=0)
    sh.text("goods %s + delivery / fetching %s" % (_money(best["goods"]), _money(best["fees"])), 8.5, False, align="r", gray=0.35)
    return sh.finish()


def shop_pdf(book, lines, res, path, project_name="", paper="A4"):
    """Writes the shopping list with the where-to-buy result as a PDF.  Returns the number of pages."""
    pages = shop_pdf_pages(book, lines, res, project_name, paper)
    pdf_write_pages(pages, path)
    return len(pages)


# *************** DEL 54 (cont.) - PRICES FROM A WEB PAGE (no windows here, only logic) *****************
# web_fetch(url)        reads ONE page (urllib, fixed polite User-Agent, timeout, size limit, no crawling, no log-in, no cookies kept)
# web_parse(text)       finds prices in a page's HTML or in pasted page text: schema.org JSON-LD offers first, then meta tags /
#                       microdata, then "123 kr" patterns.  Returns candidates; NOTHING is saved here - the window shows them and
#                       Lars confirms one (the price book is only changed by book_add_price from the window).
# web_guess_store()     which store of the book the address belongs to.
# Limits (said plainly in the window): pages that build the price with JavaScript or that show a robot check cannot be read - then
# open the page in a browser, select all, copy, and use the pasted-text box.  Never used on a loop; one click = one request.
# ToDo: remember a product address per price to refresh it later with one click (still one page at a time), unit-price pages.
import socket
import gzip
import html as htmllib
import urllib.request
import urllib.error
import urllib.parse

WEB_UA = "ArchitectPriceHelper/%s (one page, started by hand by the user; no crawling)" % APP_VERSION
WEB_MAX_BYTES = 2500000
_WEB_LAST = [0.0]


class WebPriceError(Exception):
    """A problem with reading a page; the text is meant for the user."""


def web_check_url(url):
    u = str(url).strip().replace(" ", "")
    if not u:
        raise WebPriceError("Type or paste the address of the product page.")
    if "://" not in u:
        if re.match(r"[A-Za-z][A-Za-z0-9+.-]*:(?!\d)", u):         # javascript:..., mailto:..., data:... are not web pages
            raise WebPriceError("The address must start with http:// or https:// (a normal web page).")
        u = "https://" + u
    p = urllib.parse.urlsplit(u)
    if p.scheme not in ("http", "https") or not p.hostname:
        raise WebPriceError("The address must start with http:// or https:// (a normal web page).")
    if p.username or p.password:
        raise WebPriceError("Addresses with a user name / password in them are not used.")
    return u


def _decode_page(raw, ctype):
    m = re.search(r"charset\s*=\s*[\"']?([\w.:-]+)", ctype or "", re.I)
    if not m:
        m = re.search(rb"<meta[^>]+charset\s*=\s*[\"']?([\w.:-]+)", raw[:6000], re.I)
        enc = m.group(1).decode("ascii", "replace") if m else ""
    else:
        enc = m.group(1)
    for e in (enc, "utf-8", "cp1252"):
        if not e:
            continue
        try:
            return raw.decode(e)
        except (LookupError, UnicodeDecodeError):
            continue
    return raw.decode("latin-1", "replace")


def web_fetch(url, timeout=12.0, max_bytes=WEB_MAX_BYTES, min_gap=3.0, opener=None):
    """Reads one web page.  Returns {'url': final address, 'text': page text (HTML), 'truncated': bool}.  Raises WebPriceError with a
    plain-language text when the site cannot be reached or does not want to be read by a program."""
    u = web_check_url(url)
    if min_gap and time.time() - _WEB_LAST[0] < min_gap:
        raise WebPriceError("Wait a few seconds: the program reads one page at a time, by hand, never in a row.")
    _WEB_LAST[0] = time.time()
    req = urllib.request.Request(u, headers={"User-Agent": WEB_UA, "Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.5",
                                              "Accept-Language": "sv-SE,sv;q=0.9,en;q=0.6"})
    try:
        with (opener.open(req, timeout=timeout) if opener is not None else urllib.request.urlopen(req, timeout=timeout)) as r:
            ctype = r.headers.get("Content-Type", "") or ""
            enc = (r.headers.get("Content-Encoding", "") or "").lower()
            final = r.geturl()
            raw = r.read(max_bytes + 1)
    except urllib.error.HTTPError as ex:
        if ex.code in (401, 403, 406, 429, 451, 503):
            raise WebPriceError("The site answered %d: it does not let programs read its pages (or asks for a log-in / robot check).  "
                                "Open the page in your browser, press Ctrl+A and Ctrl+C, and paste the text into the box below." % ex.code)
        if ex.code == 404:
            raise WebPriceError("The page was not found (404) - check the address.")
        raise WebPriceError("The site answered with an error (%d %s)." % (ex.code, ex.reason))
    except urllib.error.URLError as ex:
        raise WebPriceError("Could not reach the site (are you online? is the address right?): %s" % getattr(ex, "reason", ex))
    except (socket.timeout, TimeoutError):
        raise WebPriceError("The site took too long to answer (more than %d s)." % round(timeout))
    except (OSError, ValueError) as ex:
        raise WebPriceError("Could not read the page: %s" % ex)
    except Exception as ex:                                        # http.client errors and the like
        raise WebPriceError("Could not read the page: %s" % ex)
    if ctype and not re.search(r"html|xml|json|text/plain", ctype, re.I):
        raise WebPriceError("That address is not a web page (%s)." % ctype.split(";")[0])
    truncated = len(raw) > max_bytes
    raw = raw[:max_bytes]
    if "gzip" in enc:
        try:
            raw = gzip.decompress(raw)
        except Exception:
            raise WebPriceError("The page came in a form that could not be unpacked.")
    return {"url": final, "text": _decode_page(raw, ctype), "truncated": truncated}


# ---- numbers ------------------------------------------------------------------------------------------------------
def parse_price_text(s):
    """'1 299,50', '1,299.00', '199.00', '12.500', 199 -> float; None when it is not a usable price (<= 0 or absurd)."""
    if isinstance(s, (int, float)):
        v = float(s)
        return v if 0 < v < 1e7 else None
    if s is None or re.match(r"\s*-", str(s)):
        return None
    t = re.sub(r"[^\d,.]", "", str(s))
    if not re.search(r"\d", t):
        return None
    t = t.strip(",.")
    nd, nc = t.count("."), t.count(",")
    if nd and nc:
        dec = "." if t.rfind(".") > t.rfind(",") else ","
        thou = "," if dec == "." else "."
        t = t.replace(thou, "").replace(dec, ".")
    elif nd + nc >= 2:
        t = t.replace(".", "").replace(",", "")                    # 1.299.000 / 1,299,000
    elif nd + nc == 1:
        sep = "." if nd else ","
        head, tail = t.split(sep)
        t = head + tail if (len(tail) == 3 and 1 <= len(head) <= 3 and head != "0") else head + "." + tail
    try:
        v = float(t)
    except ValueError:
        return None
    return v if 0 < v < 1e7 else None


# ---- the page: HTML -> text, meta tags, JSON-LD -----------------------------------------------------------------------
def web_page_text(raw):
    """Readable text of an HTML page (or the text itself when it has no tags)."""
    t = str(raw)
    if "<" in t and ">" in t:
        t = re.sub(r"(?is)<(script|style|noscript|template|svg)\b.*?</\1\s*>", " ", t)
        t = re.sub(r"(?s)<!--.*?-->", " ", t)
        t = re.sub(r"(?i)<\s*(br|/p|/div|/li|/tr|/h\d|/td|/th|/section|/article)\b[^>]*>", "\n", t)
        t = re.sub(r"<[^>]*>", " ", t)
    t = htmllib.unescape(t).replace(" ", " ").replace(" ", " ").replace(" ", " ")
    t = re.sub(r"[ \t\r\f\v]+", " ", t)
    return re.sub(r"\n\s*", "\n", t).strip()


def _attrs(tag):
    return {k.lower(): htmllib.unescape(v.strip("\"'")) for k, v in
            re.findall(r"([\w:.-]+)\s*=\s*(\"[^\"]*\"|'[^']*'|[^\s>]+)", tag)}


def web_title(raw):
    t = str(raw)
    for tag in re.findall(r"(?is)<meta\b[^>]*>", t):
        a = _attrs(tag)
        if a.get("property", a.get("name", "")).lower() in ("og:title", "twitter:title") and a.get("content"):
            return a["content"].strip()
    m = re.search(r"(?is)<title[^>]*>(.*?)</title>", t)
    if m:
        return re.sub(r"\s+", " ", htmllib.unescape(m.group(1))).strip()
    m = re.search(r"(?is)<h1[^>]*>(.*?)</h1>", t)
    return re.sub(r"\s+", " ", htmllib.unescape(re.sub(r"<[^>]*>", " ", m.group(1)))).strip() if m else ""


def _lower_list(v):
    return [str(x).lower() for x in (v if isinstance(v, list) else [v]) if x is not None]


def _ld_price_of(node):
    """price, currency, note of an Offer-like dict (None when it has no usable price)."""
    cur = node.get("priceCurrency") or ""
    note = ""
    av = node.get("availability")
    if av:
        note = str(av).rsplit("/", 1)[-1]
    for key in ("price", "lowPrice"):
        if key in node:
            v = parse_price_text(node[key])
            if v is not None:
                return v, cur, note
    ps = node.get("priceSpecification")
    for spec in (ps if isinstance(ps, list) else [ps]):
        if isinstance(spec, dict) and not re.search(r"list|strike|msrp|original", str(spec.get("priceType", "")), re.I):
            v = parse_price_text(spec.get("price"))
            if v is not None:
                return v, spec.get("priceCurrency") or cur, note
    return None


def _ld_collect(node, out, name="", depth=0):
    if depth > 14:
        return
    if isinstance(node, list):
        for x in node:
            _ld_collect(x, out, name, depth + 1)
        return
    if not isinstance(node, dict):
        return
    types = _lower_list(node.get("@type"))
    if any(t in ("product", "productmodel", "individualproduct", "productgroup", "vehicle", "service") for t in types):
        name = str(node.get("name") or name)
    if any(t in ("offer", "aggregateoffer") for t in types) or ("price" in node and "priceCurrency" in node):
        r = _ld_price_of(node)
        if r:
            out.append({"price": r[0], "currency": r[1], "source": "JSON-LD offer", "label": name, "note": r[2]})
    for k, v in node.items():
        if isinstance(v, (dict, list)) and k not in ("priceSpecification",):
            _ld_collect(v, out, name, depth + 1)


def web_find_structured(raw):
    """Prices the page states in a machine-readable way: JSON-LD, meta tags, microdata.  [{price, currency, source, label, note}]"""
    t = str(raw)
    out = []
    for blk in re.findall(r"(?is)<script\b[^>]*type\s*=\s*[\"']?application/(?:ld\+json|json\+ld)[\"']?[^>]*>(.*?)</script\s*>", t):
        body = re.sub(r"^\s*(//)?\s*<!\[CDATA\[|\]\]>\s*(//)?\s*$|<!--|-->", "", blk.strip()).strip()
        try:
            _ld_collect(json.loads(body, strict=False), out)
        except ValueError:                                         # damaged JSON: look for the price by hand
            pm = re.search(r"\"price\"\s*:\s*\"?([\d][\d\s.,]*)", body)
            cm = re.search(r"\"priceCurrency\"\s*:\s*\"(\w+)\"", body)
            v = parse_price_text(pm.group(1)) if pm else None
            if v is not None:
                out.append({"price": v, "currency": cm.group(1) if cm else "", "source": "JSON-LD (damaged)", "label": "", "note": ""})
    meta = {}
    for tag in re.findall(r"(?is)<meta\b[^>]*>", t):
        a = _attrs(tag)
        key = (a.get("property") or a.get("name") or a.get("itemprop") or "").lower()
        if key and a.get("content") and key not in meta:
            meta[key] = a["content"]
    for key in ("product:price:amount", "og:price:amount", "price", "twitter:data1"):
        if key in meta:
            v = parse_price_text(meta[key]) if key != "twitter:data1" or re.search(r"\d", meta[key]) else None
            if v is not None:
                cur = meta.get("product:price:currency") or meta.get("og:price:currency") or meta.get("pricecurrency") or ""
                out.append({"price": v, "currency": cur, "source": "meta tag (%s)" % key, "label": "", "note": ""})
                break
    for m in re.finditer(r"(?is)<(\w+)\b([^>]*\bitemprop\s*=\s*[\"']price[\"'][^>]*)>([^<]*)", t):
        a = _attrs(m.group(2))
        v = parse_price_text(a.get("content") or m.group(3))
        if v is not None:
            out.append({"price": v, "currency": meta.get("pricecurrency", ""), "source": "microdata (itemprop=price)", "label": "", "note": ""})
    return out


# ---- pattern search in the text ---------------------------------------------------------------------------------------
_NUM = r"\d{1,3}(?:[ .]\d{3})+(?:[.,]\d{1,2})?|\d+(?:[.,]\d{1,2})?"
_CUR = r"kr\.?|kronor|:-|sek|€|eur|usd|\$|£|nok|dkk"
_RE_FWD = re.compile(r"(?<![\w.,])(%s)\s*(%s)(?![A-Za-zÅÄÖåäö])(?:\s*/\s*([^\s,;)<]{1,12}))?" % (_NUM, _CUR), re.I)
_RE_REV = re.compile(r"(?<![A-Za-z])(SEK|EUR|USD|NOK|DKK|kr|€|\$|£)\s*(%s)(?![\d])" % _NUM, re.I)
_BAD_CONTEXT = [(r"frakt|leverans|shipping|delivery|fraktfri", "mentions delivery - probably not the price"),
                (r"spara|rabatt|discount|you save|besparing", "mentions a saving"),
                (r"jämförpris|jmf|jämf|per kg|kr/kg|unit price", "looks like a comparison price"),
                (r"moms|vat\b|exkl|excl", "mentions VAT - check if it includes VAT"),
                (r"ordinarie|ord\.? ?pris|tidigare|før|was\b|före", "looks like an old price"),
                (r"över|ovan|fri frakt|free shipping|from \d", "looks like a limit")]
CUR_SYMBOLS = {"kr": "SEK", "kr.": "SEK", "kronor": "SEK", ":-": "SEK", "sek": "SEK", "€": "EUR", "eur": "EUR", "$": "USD", "usd": "USD",
               "£": "GBP", "nok": "NOK", "dkk": "DKK"}
UNIT_WORDS = [(r"m²|m2|kvm|sqm", ("m2", "m2")), (r"lm|lpm|löpm\w*|rm|m\b|meter", ("m", "m")), (r"st\.?|styck|pcs|pc|stk", ("pc", "pc")),
              (r"förp\w*|fp|pkt|paket|pack", ("pc", "pack")), (r"rulle|roll", ("pc", "roll")), (r"skiva|plåt|sheet", ("m2", "sheet")),
              (r"kg", ("kg", "kg")), (r"l\b|liter|ltr", ("l", "l"))]


def _unit_guess(word):
    w = (word or "").strip().lower().rstrip(".,;:)")
    if not w:
        return None
    for pat, (base, unit) in UNIT_WORDS:
        if re.fullmatch(pat, w):
            return {"base": base, "unit": unit}
    return None


def web_find_in_text(text, limit=10):
    """'123 kr', 'kr 123', '123:-', '$12.99' ... in plain text, with the words around each hit.  Candidates are NOT proof."""
    out, seen = [], set()
    pos_items = []
    for m in _RE_FWD.finditer(text):
        pos_items.append((m.start(), m.end(), m.group(1), m.group(2), m.group(3)))
    for m in _RE_REV.finditer(text):
        pos_items.append((m.start(), m.end(), m.group(2), m.group(1), None))
    for s, e, num, cur, unit in sorted(pos_items):
        v = parse_price_text(num)
        if v is None or v < 0.5:
            continue
        ls = text.rfind("\n", 0, s) + 1                            # the words around a price are the ones on its own line
        le = text.find("\n", e)
        le = len(text) if le < 0 else le
        ctx_before = text[max(ls, s - 45):s]
        ctx_after = text[e:min(le, e + 30)]
        ctx = re.sub(r"\s+", " ", ctx_before + "[" + text[s:e].strip() + "]" + ctx_after).strip()
        key = (round(v, 2), cur.lower())
        if key in seen:
            continue
        seen.add(key)
        notes = [msg for pat, msg in _BAD_CONTEXT if re.search(pat, ctx_before[-30:] + " " + ctx_after[:18], re.I)]
        near = bool(re.search(r"pris|price|nu\b|now|kampanj|ord", ctx_before[-25:], re.I))
        g = _unit_guess(unit)
        out.append({"price": v, "currency": CUR_SYMBOLS.get(cur.lower(), cur.upper()), "source": "text pattern", "label": "",
                    "note": "; ".join(notes), "context": ctx, "unit": g, "_rank": (1 if notes else 0, 0 if near else 1, len(out))})
    out.sort(key=lambda c: c["_rank"])
    for c in out:
        c.pop("_rank", None)
    return out[:limit]


def web_size_hint(text):
    """'2,88 m2 per pack' style information about what one sold unit contains: {size, base, unit, context} or None."""
    pats = [r"(\d+(?:[.,]\d+)?)\s*(m²|m2|kvm)\s*(?:/|per\s+|i\s+)?\s*(förp\w*|pkt|paket|skiva|pack|rulle)\b",
            r"(förp\w*|paket|pkt|skiva|rulle)\w*[^.\n]{0,40}?(\d+(?:[.,]\d+)?)\s*(m²|m2|kvm)\b"]
    for i, p in enumerate(pats):
        m = re.search(p, text, re.I)
        if m:
            size = parse_price_text(m.group(1 if i == 0 else 2))
            word = (m.group(3) if i == 0 else m.group(1)).lower()
            if size:
                unit = "sheet" if word.startswith("skiv") else "roll" if word.startswith("rull") else "pack"
                return {"size": size, "base": "m2", "unit": unit, "context": re.sub(r"\s+", " ", m.group(0))}
    return None


def web_parse(raw, url=""):
    """Everything useful in a page (HTML or pasted text): {'title', 'candidates': [...best first], 'size_hint', 'problem'}.
    Candidate keys: price, currency, source, label, note, context, unit ({'base', 'unit'} or None).  Nothing is saved."""
    raw = str(raw or "")
    is_html = "<" in raw and ">" in raw
    structured = web_find_structured(raw) if is_html else []
    text = web_page_text(raw)
    cands, seen = [], set()
    for c in structured:
        key = round(c["price"], 2)
        if key in seen:
            continue
        seen.add(key)
        c["context"] = (c.get("label") or "product data") + (" - %s" % c["note"] if c.get("note") else "")
        c["unit"] = None
        cands.append(c)
    # the first structured price stays first; the rest of the text hits follow (those already known are dropped)
    for c in web_find_in_text(text):
        if round(c["price"], 2) in seen:
            continue
        seen.add(round(c["price"], 2))
        cands.append(c)
    title = web_title(raw) if is_html else ""
    if not title:
        title = next((c.get("label") for c in cands if c.get("label")), "")
    problem = ""
    low = text.lower()
    if not cands:
        if re.search(r"captcha|are you a robot|access denied|just a moment|verify you are human|unusual traffic|robot|åtkomst nekad", low):
            problem = "The page looks like a robot check or an access-denied page - no price in it.  Open the product in your browser and paste the page text instead."
        elif is_html and len(text) < 400:
            problem = "The page has almost no text: the shop builds it with JavaScript.  Open the product in your browser, press Ctrl+A, Ctrl+C and paste the text instead."
        else:
            problem = "No price found.  Try the pasted-text box (open the page in your browser, Ctrl+A, Ctrl+C), or type the price by hand."
    cur = cands[0]["currency"] if cands else ""
    return {"title": title, "currency": cur, "candidates": cands, "size_hint": web_size_hint(text), "problem": problem, "url": url,
            "structured": len(structured)}


# ---- the book -----------------------------------------------------------------------------------------------------------
def web_host(url):
    try:
        h = (urllib.parse.urlsplit(url if "://" in str(url) else "https://" + str(url)).hostname or "").lower()
    except ValueError:
        return ""
    return h[4:] if h.startswith("www.") else h


def web_guess_store(book, url):
    """The store of the book that this address belongs to (by the store's own web page, else by its name inside the host name)."""
    host = web_host(url)
    if not host:
        return None
    for s in book["stores"]:
        sh = web_host(s.get("url", "")) if s.get("url") else ""
        if sh and (host == sh or host.endswith("." + sh) or sh.endswith("." + host)):
            return s
    flat = re.sub(r"[^a-z0-9]", "", host.split(":")[0])
    best = None
    for s in book["stores"]:
        nm = re.sub(r"[^a-z0-9åäö]", "", norm_name(s["name"]))
        if len(nm) >= 3 and nm in flat and (best is None or len(nm) > len(best[0])):
            best = (nm, s)
    return best[1] if best else None


def web_find_existing(book, store_id, material, base, unit, size):
    """The price entry that saving this price would replace (same store + material + units), or None."""
    key = norm_name(material)
    return next((e for e in book["prices"] if e["store"] == store_id and norm_name(e["material"]) == key and e["base"] == base
                 and e["unit"] == unit and abs(e["size"] - size) < 1e-9), None)


def web_save_price(book, store_id, material, price, base, unit, size, url="", title=""):
    """Writes the confirmed price into the book (replaces the same store + material + unit).  Returns (entry, old entry or None)."""
    old = web_find_existing(book, store_id, material, base, unit, size)
    old = dict(old) if old else None
    note = ("web: " + (title[:80] + " - " if title else "") + web_host(url)).strip(" -")
    e = book_add_price(book, store_id, material, price, base, unit, size, note)
    if url:
        e["url"] = url
    return e, old


# *************** DEL 55 - WALL SNAPPING AND THE EXAMPLE HOUSE *****************
# snap_to_wall() puts wall-bound things (toilet, bed head, outlet ...) against the nearest wall face, back to the wall.
# make_example() builds a 9 x 7 m house: ground floor, first floor, attic with a 38 degree gable roof and a kneewall.
# ToDo: example variants (flat roof, L-shaped house).


def wall_mount(story, wid, u, side, depth):
    """Centre (x, y) and rotation of an item of depth `depth` standing on the face `side` (+1 left / -1 right) of a wall
    at distance u along it, back to the wall."""
    w = get_wall(story, wid)
    A = (w["p"][0], w["p"][1])
    B = (w["p"][2], w["p"][3])
    d = v_unit(v_sub(B, A))
    n = v_perp(d)
    c = (A[0] + d[0] * u, A[1] + d[1] * u)
    off = w["t"] / 2.0 + depth / 2.0
    pos = (c[0] + n[0] * side * off, c[1] + n[1] * side * off)
    back = (-n[0] * side, -n[1] * side)
    rot = math.degrees(math.atan2(back[1], back[0])) - 90.0
    return pos[0], pos[1], rot


def snap_to_wall(story, px, py, depth, maxdist=350.0):
    """(x, y, rot, wall id) when the point is within `maxdist` of a wall face, else None."""
    story = expand_curved(story)
    best = None
    for w in story["walls"]:
        if w.get("kind") == "curtain":                # furniture does not snap to a drape
            continue
        A = (w["p"][0], w["p"][1])
        B = (w["p"][2], w["p"][3])
        dd, t = seg_point_dist((px, py), A, B)
        if dd - w["t"] / 2.0 > maxdist:
            continue
        d = v_unit(v_sub(B, A))
        n = v_perp(d)
        c = (A[0] + (B[0] - A[0]) * t, A[1] + (B[1] - A[1]) * t)
        side = 1 if v_dot(v_sub((px, py), c), n) >= 0 else -1
        if best is None or dd < best[0]:
            best = (dd, w["id"], t * dist(A, B), side)
    if best is None:
        return None
    x, y, rot = wall_mount(story, best[1], best[2], best[3], depth)
    return x, y, rot, best[1]


def _box_walls(proj, story, x0, y0, x1, y1, t):
    ws = []
    for a, b in (((x0, y0), (x1, y0)), ((x1, y0), (x1, y1)), ((x1, y1), (x0, y1)), ((x0, y1), (x0, y0))):
        ws.append(add_wall(proj, story, a, b, t))
    return ws


def make_example():
    p = new_project("Example house")
    p["settings"]["headroom"] = [1000, 1900]
    g = p["stories"][0]
    g["name"] = "Ground floor"
    f1 = new_story("First floor", 2500)
    f1["id"] = uid(p)
    at = new_story("Attic", 4000)
    at["id"] = uid(p)
    p["stories"] += [f1, at]
    X, Y = 9000.0, 7000.0
    rooms_rect = {"lb": (125, 125, 4950, 3450), "lt": (125, 3550, 4950, 6875), "rb": (5050, 125, 8875, 3450),
                  "rt": (5050, 3550, 8875, 6875)}

    def rr(story, key, name):
        x0, y0, x1, y1 = rooms_rect[key]
        return add_room(p, story, [(x0, y0), (x1, y0), (x1, y1), (x0, y1)], name)

    for s in (g, f1):
        walls = _box_walls(p, s, 0, 0, X, Y, 250)
        mid_x = add_wall(p, s, (5000, 0), (5000, Y), 100)
        mid_y = add_wall(p, s, (0, 3500), (X, 3500), 100)
        s["_w"] = walls
    # ---- ground floor
    wS, wE, wN, wW = g["_w"]
    add_opening(p, g, wS["id"], 6800, "door", 1000)
    add_opening(p, g, wS["id"], 2500, "window", 1800)
    add_opening(p, g, wW["id"], 1800, "window")
    add_opening(p, g, wW["id"], 5200, "window")
    add_opening(p, g, wN["id"], 2500, "window")
    add_opening(p, g, wN["id"], 7000, "window", 1200)
    add_opening(p, g, wE["id"], 5200, "window", 600, 600, 1200)
    mx = g["walls"][4]
    my = g["walls"][5]
    add_opening(p, g, mx["id"], 1800, "passage", 1200)
    add_opening(p, g, mx["id"], 5000, "door", 800)
    add_opening(p, g, my["id"], 6800, "door", 800)
    add_opening(p, g, my["id"], 2500, "passage", 1400)
    rr(g, "lb", "Living room")
    rr(g, "lt", "Kitchen")
    rr(g, "rb", "Hall")
    rr(g, "rt", "Bathroom")
    add_stair(p, g, 0, 5600, 250, "L", 0, 900, 250, None, "R")
    S, W_, N_, E_ = wS["id"], wW["id"], wN["id"], wE["id"]

    def on(story, typ, x, y, **kw):
        """Place an item near (x, y); wall-bound types snap back-to-wall to the nearest wall face."""
        c = CATALOG[typ]
        r = snap_to_wall(story, x, y, c["d"], 700.0) if c["snap"] else None
        if r:
            return add_item(p, story, typ, r[0], r[1], r[2], **kw)
        return add_item(p, story, typ, x, y, kw.pop("rot", 0.0), **kw)
    # living room
    on(g, "sofa3", 2500, 3300)
    on(g, "bookshelf2", 300, 700)
    on(g, "bookshelf2", 300, 3000)
    on(g, "woodstove", 4800, 700)
    add_item(p, g, "coffee", 2500, 1900, 0)
    add_item(p, g, "armchair", 3900, 1100, 150)
    on(g, "outlet", 300, 2500)
    on(g, "outlet2", 2500, 3400)
    on(g, "switch", 4900, 2600)
    add_item(p, g, "lightc", 2500, 1800)
    # kitchen
    on(g, "stove", 700, 6700)
    on(g, "ksink", 2000, 6700)
    on(g, "fridge", 3050, 6700)
    on(g, "pantry", 3700, 6700)
    on(g, "pantry", 4350, 6700)
    on(g, "outlet_hi", 1400, 6800)
    add_item(p, g, "dining", 2700, 5000, 0)
    for dx, dy, r in ((-500, 700, 180), (0, 700, 180), (500, 700, 180), (-500, -700, 0), (0, -700, 0), (500, -700, 0)):
        add_item(p, g, "chair", 2700 + dx, 5000 + dy, r)
    add_item(p, g, "lightc", 2700, 5000)
    # hall
    on(g, "shoes", 8300, 300)
    on(g, "switch", 5100, 3300)
    add_item(p, g, "lightc", 7500, 2000)
    # bathroom
    on(g, "shower", 8500, 6500)
    on(g, "wc", 7400, 6700)
    on(g, "basin", 6500, 6700)
    on(g, "washer", 5500, 6700)
    on(g, "outlet", 6000, 3650)
    add_dim(p, g, (0, 0), (X, 0), -900)
    add_dim(p, g, (0, 0), (0, Y), -900)
    add_text(p, g, 100, Y + 600, "Ground floor plan", 300)
    # ---- first floor
    wS, wE, wN, wW = f1["_w"]
    for u in (1800, 7000):
        add_opening(p, f1, wS["id"], u, "window")
    add_opening(p, f1, wW["id"], 1800, "window")
    add_opening(p, f1, wW["id"], 5200, "window")
    add_opening(p, f1, wN["id"], 2500, "window")
    add_opening(p, f1, wN["id"], 7000, "window")
    add_opening(p, f1, wE["id"], 1800, "window")
    mx = f1["walls"][4]
    my = f1["walls"][5]
    add_opening(p, f1, mx["id"], 1800, "door", 800)
    add_opening(p, f1, mx["id"], 5200, "door", 800)
    add_opening(p, f1, my["id"], 6800, "door", 800)
    add_opening(p, f1, my["id"], 2300, "door", 800)
    rr(f1, "lb", "Bedroom 1")
    rr(f1, "lt", "Bathroom")
    rr(f1, "rb", "Landing")
    rr(f1, "rt", "Study")
    add_stair(p, f1, 1, 7600, 4800, "spiral", 0, 900, 250, 16)
    f1["stairs"][0]["r"] = 1000.0
    on(f1, "bed2", 300, 1800)
    on(f1, "wardrobe2", 3500, 300)
    on(f1, "nightstand", 300, 700)
    on(f1, "nightstand", 300, 2900)
    on(f1, "outlet", 300, 3300)
    on(f1, "bath", 300, 5200)
    on(f1, "wc", 1500, 6700)
    on(f1, "basin2", 3300, 6700)
    on(f1, "shower2", 4200, 3700)
    on(f1, "desk", 6500, 6700)
    add_item(p, f1, "ochair", 6500, 6000, 0)
    on(f1, "bookshelf2", 5250, 4000)
    on(f1, "radiator", 7000, 300)
    add_item(p, f1, "lightc", 2500, 1800)
    # ---- attic: kneewall + gable roof (the roof's inner surface limits the walls and the room height)
    wS, wE, wN, wW = _box_walls(p, at, 0, 0, X, Y, 250)
    pw = add_wall(p, at, (0, 3500), (X, 3500), 100)
    add_roof(p, at, (0, 0, X, Y), "gable", 38.0, 1100.0, "x", over=500.0, t=200.0)
    add_opening(p, at, wW["id"], 1750, "window", 900, 1100, 900)
    add_opening(p, at, wW["id"], 5250, "window", 900, 1100, 900)
    add_opening(p, at, wE["id"], 1750, "window", 900, 1100, 900)
    add_opening(p, at, wE["id"], 5250, "window", 900, 1100, 900)
    add_opening(p, at, pw["id"], 2000, "door", 800)
    add_room(p, at, [(125, 125), (8875, 125), (8875, 3450), (125, 3450)], "Attic bedroom")
    add_room(p, at, [(125, 3550), (8875, 3550), (8875, 6875), (125, 6875)], "Attic study / guest")
    on(at, "bed180", 300, 1750)
    on(at, "dresser", 6000, 300)
    on(at, "bookshelf_low", 3000, 300)
    on(at, "bookshelf_low", 4000, 300)
    on(at, "sofa2", 8700, 5250)
    on(at, "bookshelf_low", 2800, 6700)
    on(at, "bookshelf_low", 4000, 6700)
    add_item(p, at, "lightc", 4500, 1800)
    # two gable dormers on the south slope, two roof windows on the north slope
    for dx in (2500.0, 6500.0):
        add_dormer(p, at, dx, 700.0, default_dormer_rot(at, dx, 700.0), "gable", 1800.0)
        add_rwin(p, at, dx, 5300.0)
    add_section(p, g, (4500, -1500), (4500, Y + 1500), "A")
    add_section(p, at, (2500, -1500), (2500, Y + 1500), "B")         # through a dormer and a roof window
    for s in (g, f1):
        s.pop("_w", None)
    return p


def add_section(proj, story, a, b, name="A"):
    sc = {"id": uid(proj), "a": [float(a[0]), float(a[1])], "b": [float(b[0]), float(b[1])], "name": name}
    story["sections"].append(sc)
    return sc


# *************** DEL 56 - EDITING HELPERS (room detection, auto roof, copy storey, walls round a room) *****************
# Window-free logic the UI calls; kept apart so it can be tested without a screen.
# ToDo: detect rooms with islands (pillars), auto-join of overlapping walls.
import copy
from collections import deque


def detect_room(story, px, py, cell=25.0, max_cells=600000):
    """The room polygon (mm) enclosed by the walls around the point (px, py), or None when the point is in a wall or the
    walls do not close.  Openings count as CLOSED (a door does not merge two rooms).  The pixel outline is snapped back
    onto the real wall faces, so a rectangular room comes out as an exact rectangle."""
    story = expand_curved(story)
    geo = wall_geometry(story)
    polys = []
    for w in story["walls"]:
        g = geo[w["id"]]
        if g["len"] > 1:
            polys.append([g["R0"], g["R1"], g["L1"], g["L0"]])
    if not polys:
        return None
    xs = [p[0] for q in polys for p in q] + [px]
    ys = [p[1] for q in polys for p in q] + [py]
    ox, oy = min(xs) - 3 * cell, min(ys) - 3 * cell
    while ((max(xs) + 3 * cell - ox) / cell) * ((max(ys) + 3 * cell - oy) / cell) > max_cells:
        cell *= 1.5
    nx = int((max(xs) + 3 * cell - ox) / cell) + 1
    ny = int((max(ys) + 3 * cell - oy) / cell) + 1
    blocked = bytearray(nx * ny)
    for q in polys:
        q = ensure_ccw(q)
        j0 = max(0, int((min(p[1] for p in q) - oy) / cell) - 1)
        j1 = min(ny - 1, int((max(p[1] for p in q) - oy) / cell) + 1)
        for j in range(j0, j1 + 1):
            yc = oy + (j + 0.5) * cell
            xl = []
            n = len(q)
            for i in range(n):
                a, b = q[i], q[(i + 1) % n]
                if (a[1] > yc) != (b[1] > yc):
                    xl.append(a[0] + (yc - a[1]) * (b[0] - a[0]) / (b[1] - a[1]))
            if len(xl) < 2:
                continue
            i0 = max(0, int(math.ceil((min(xl) - ox) / cell - 0.5)))
            i1 = min(nx - 1, int(math.floor((max(xl) - ox) / cell - 0.5)))
            if i1 >= i0:
                base = j * nx
                blocked[base + i0:base + i1 + 1] = b"\x01" * (i1 - i0 + 1)
    si, sj = int((px - ox) / cell), int((py - oy) / cell)
    if blocked[sj * nx + si]:
        return None
    region = bytearray(nx * ny)
    dq = deque([(si, sj)])
    region[sj * nx + si] = 1
    cells = [(si, sj)]
    while dq:
        i, j = dq.popleft()
        for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            a, b = i + di, j + dj
            if a < 0 or b < 0 or a >= nx or b >= ny:
                return None                       # leaked out of the house: not enclosed
            k = b * nx + a
            if not blocked[k] and not region[k]:
                region[k] = 1
                dq.append((a, b))
                cells.append((a, b))
    edges = {}

    def inreg(a, b):
        return 0 <= a < nx and 0 <= b < ny and region[b * nx + a]
    for i, j in cells:
        if not inreg(i, j - 1):
            edges.setdefault((i, j), []).append((i + 1, j))
        if not inreg(i + 1, j):
            edges.setdefault((i + 1, j), []).append((i + 1, j + 1))
        if not inreg(i, j + 1):
            edges.setdefault((i + 1, j + 1), []).append((i, j + 1))
        if not inreg(i - 1, j):
            edges.setdefault((i, j + 1), []).append((i, j))
    loops = []
    while edges:
        start = next(iter(edges))
        loop = [start]
        cur = start
        while True:
            nxt = edges[cur].pop()
            if not edges[cur]:
                del edges[cur]
            if nxt == start:
                break
            loop.append(nxt)
            cur = nxt
            if cur not in edges:
                break
        loops.append(loop)
    loop = max(loops, key=lambda l: abs(poly_area_signed(l)))
    pts = [(ox + a * cell, oy + b * cell) for a, b in loop]
    # drop collinear points, then simplify the staircase of diagonal walls
    def decollinear(P):
        out = []
        n = len(P)
        for i in range(n):
            a, b, c = P[i - 1], P[i], P[(i + 1) % n]
            if abs(v_cross(v_sub(b, a), v_sub(c, b))) > 1e-6:
                out.append(b)
        return out
    pts = decollinear(pts)
    if len(pts) > 8:
        simp = rdp(pts + [pts[0]], cell * 0.9)[:-1]
        if len(simp) >= 3:
            pts = simp
    # snap each edge onto the nearest parallel wall face line
    faces = []
    for w in story["walls"]:
        g = geo[w["id"]]
        for a, b in ((g["L0"], g["L1"]), (g["R0"], g["R1"])):
            if dist(a, b) > 1:
                faces.append((a, v_unit(v_sub(b, a))))
    n = len(pts)
    lines = []
    for i in range(n):
        p, q = pts[i], pts[(i + 1) % n]
        d = v_unit(v_sub(q, p))
        best = None
        for fa, fd in faces:
            if abs(v_cross(d, fd)) > 0.08:
                continue
            e1 = abs(v_cross(fd, v_sub(p, fa)))
            e2 = abs(v_cross(fd, v_sub(q, fa)))
            e = (e1 + e2) / 2.0
            if e <= cell * 1.6 and (best is None or e < best[0]):
                best = (e, fa, fd)
        lines.append((best[1], best[2]) if best else (p, d))
    out = []
    for i in range(n):
        (a1, d1), (a2, d2) = lines[i - 1], lines[i]
        x = line_isect(a1, d1, a2, d2)
        out.append(x if x is not None and dist(x, pts[i]) < cell * 3 else pts[i])
    if poly_area(out) < 10000:
        return None
    return [(round(x, 1), round(y, 1)) for x, y in out]


def auto_roof(proj, story, kind="gable", pitch=38.0, eave=1100.0):
    """A roof over the bounding box of all walls of the storey; the storey is made tall enough for the ridge."""
    if not story["walls"]:
        return None
    pts = story_wall_points(story)
    xs = [p[0] for p in pts]
    ys = [p[1] for p in pts]
    r = add_roof(proj, story, (min(xs), min(ys), max(xs), max(ys)), kind, pitch, eave)
    ridge = roof_ridge_height(r)
    if story["height"] < ridge:
        story["height"] = math.ceil(ridge / 100.0) * 100.0
    return r


def walls_round_rect(proj, story, x0, y0, x1, y1, t):
    """Four walls whose INNER faces lie on the rectangle (so the room inside is exactly x0..x1, y0..y1)."""
    h = t / 2.0
    return _box_walls(proj, story, x0 - h, y0 - h, x1 + h, y1 + h, t)


def clone_story(proj, story, name=None):
    """Deep copy of a storey with fresh ids (openings keep pointing at the copied walls)."""
    s = copy.deepcopy(story)
    s["id"] = uid(proj)
    if name:
        s["name"] = name
    wmap = {}
    for w in s["walls"]:
        old = w["id"]
        w["id"] = uid(proj)
        wmap[old] = w["id"]
    for kind, lst in KIND_LISTS.items():
        if kind == "wall":
            continue
        for e in s[lst]:
            e["id"] = uid(proj)
            if kind == "opening":
                e["wall"] = wmap.get(e["wall"], e["wall"])
    return s


def clone_elements(proj, story, ids, dx=300.0, dy=-300.0):
    """Copy the elements with these ids (+ openings of copied walls) into the same storey, shifted; returns new ids."""
    new = []
    wmap = {}
    for eid in ids:
        kind, e = find_element(story, eid)
        if e is None or kind == "opening":
            continue
        c = copy.deepcopy(e)
        c["id"] = uid(proj)
        _shift_element(kind, c, dx, dy)
        story[KIND_LISTS[kind]].append(c)
        new.append(c["id"])
        if kind == "wall":
            wmap[eid] = c["id"]
    for o in list(story["openings"]):
        if o["wall"] in wmap:
            c = copy.deepcopy(o)
            c["id"] = uid(proj)
            c["wall"] = wmap[o["wall"]]
            story["openings"].append(c)
    return new


def _shift_element(kind, e, dx, dy):
    if kind == "wall":
        e["p"] = [e["p"][0] + dx, e["p"][1] + dy, e["p"][2] + dx, e["p"][3] + dy]
    elif kind == "room":
        e["pts"] = [[p[0] + dx, p[1] + dy] for p in e["pts"]]
    elif kind in ("item", "stair", "text", "dormer", "rwin"):
        e["x"] += dx
        e["y"] += dy
    elif kind == "roof":
        r = e["rect"]
        e["rect"] = [r[0] + dx, r[1] + dy, r[2] + dx, r[3] + dy]
    elif kind in ("dim", "section") or (kind == "meas" and "a" in e):
        e["a"] = [e["a"][0] + dx, e["a"][1] + dy]
        e["b"] = [e["b"][0] + dx, e["b"][1] + dy]
    elif kind == "meas":                                       # outline of a room
        e["pts"] = [[p[0] + dx, p[1] + dy] for p in e["pts"]]


def element_anchor(kind, e):
    """A representative point of an element (box selection, nudging)."""
    if kind == "wall":
        return ((e["p"][0] + e["p"][2]) / 2, (e["p"][1] + e["p"][3]) / 2)
    if kind == "room":
        return poly_centroid([tuple(p) for p in e["pts"]])
    if kind in ("item", "stair", "text", "dormer", "rwin"):
        return (e["x"], e["y"])
    if kind == "roof":
        r = e["rect"]
        return ((r[0] + r[2]) / 2, (r[1] + r[3]) / 2)
    if kind in ("dim", "section"):
        return ((e["a"][0] + e["b"][0]) / 2, (e["a"][1] + e["b"][1]) / 2)
    if kind == "meas":
        return poly_centroid(meas_outline(e)) if e["kind"] != "ruler" else ((e["a"][0] + e["b"][0]) / 2, (e["a"][1] + e["b"][1]) / 2)
    return (0, 0)


def opening_anchor(story, o):
    w = get_wall(story, o["wall"])
    if w is None:
        return (0, 0)
    return wall_arc_at(w, o["pos"])[0]


def place_opening_on_wall(story, px, py, tol=400.0):
    """(wall id, position along the wall, swing side, hinge) for an opening put near (px, py), or None."""
    sx = expand_curved(story)
    best = None
    for w in sx["walls"]:
        if is_curtain(w):                             # no doors or windows in a drape
            continue
        A = (w["p"][0], w["p"][1])
        B = (w["p"][2], w["p"][3])
        dd, t = seg_point_dist((px, py), A, B)
        if dd <= w["t"] / 2.0 + tol and (best is None or dd < best[0]):
            best = (dd, w, A, B, t)
    if best is None:
        return None
    dd, w, A, B, t = best
    d = v_unit(v_sub(B, A))
    n = v_perp(d)
    c = (A[0] + (B[0] - A[0]) * t, A[1] + (B[1] - A[1]) * t)
    swing = 1 if v_dot(v_sub((px, py), c), n) >= 0 else -1
    if "src" in w:                                  # a piece of a curved wall: position along the whole arc
        real = get_wall(story, w["src"])
        pos = w["s0"] + t * (w["s1"] - w["s0"])
        return real["id"], pos, swing, (0 if pos < wall_length(real) / 2.0 else 1)
    return w["id"], t * dist(A, B), swing, (0 if t < 0.5 else 1)


# *************** DEL 60 - DRAWING ON THE SCREEN (plan, 3D view, section view) *****************
# DrawMixin belongs to the ArchApp class (DEL 63).  Plan = flat 2D with snapping; 3D = painter's algorithm on tk canvas
# polygons (orbit with the left mouse button); Section = the model cut by a vertical plane drawn in the plan.
# ToDo: shadows in 3D, section view with the visible walls behind the cut, print of the 3D view.

THEME = dict(bg="#1e1e2e", panel="#252535", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa", btn="#313244",
             btnfg="#e0e0e0", field="#2a2a3c", field_fg="#e0e0e0")
SEC_COLORS = {"wall": "#4a4a4a", "slab": "#8a8a8a", "roof": "#9a4a3a", "stair": "#a88455", "cupboard": "#c9a878"}


def _hex(r, g, b):
    return "#%02x%02x%02x" % (max(0, min(255, int(r * 255))), max(0, min(255, int(g * 255))), max(0, min(255, int(b * 255))))


class DrawMixin(object):

    # ---- plan coordinates ----------------------------------------------------------------------------------
    def w2s(self, x, y):
        v = self.view
        return (v["ox"] + x * v["sc"], v["oy"] - y * v["sc"])

    def s2w(self, px, py):
        v = self.view
        return ((px - v["ox"]) / v["sc"], (v["oy"] - py) / v["sc"])

    def fit_view(self):
        self.cv.update_idletasks()
        w, h = max(200, self.cv.winfo_width()), max(200, self.cv.winfo_height())
        if self.mode == "section":
            sec = self.current_section()
            if sec:
                L = dist(tuple(sec["a"]), tuple(sec["b"]))
                el = story_elevations(self.proj)
                top = max(el[i] + s["height"] + 1500 for i, s in enumerate(self.proj["stories"]))
                sc = min((w - 120) / max(L, 1), (h - 100) / max(top + 600, 1))
                self.sview = {"sc": sc, "ox": 60, "oy": h - 50 - 300 * sc}
            return
        x0, y0, x1, y1 = plan_bounds(self.proj, self.sidx)
        bw, bh = max(x1 - x0, 3000), max(y1 - y0, 3000)
        sc = min((w - 120) / bw, (h - 120) / bh)
        self.view = {"sc": sc, "ox": w / 2 - (x0 + x1) / 2 * sc, "oy": h / 2 + (y0 + y1) / 2 * sc}

    def reset_camera(self):
        x0, y0, x1, y1 = plan_bounds(self.proj, 0)
        el = story_elevations(self.proj)
        zt = el[-1] + self.proj["stories"][-1]["height"]
        diag = math.hypot(x1 - x0, y1 - y0)
        self.cam = {"yaw": -60.0, "pitch": 28.0, "dist": max(8000.0, diag * 1.7), "tx": (x0 + x1) / 2, "ty": (y0 + y1) / 2,
                    "tz": zt / 2.5}

    # ---- main redraw ---------------------------------------------------------------------------------------
    def redraw(self, fast=False):
        if self.mode == "3d":
            self.draw_3d(fast)
        elif self.mode == "section":
            self.draw_section()
        else:
            self.draw_plan()
        self.update_title()

    def draw_grid(self):
        cv = self.cv
        sc = self.view["sc"]
        step = float(self.proj["settings"].get("grid", 500))
        while step * sc < 14:
            step *= 2
        w, h = cv.winfo_width(), cv.winfo_height()
        x0, y1 = self.s2w(0, 0)
        x1, y0 = self.s2w(w, h)
        i0 = int(math.floor(x0 / step))
        i1 = int(math.ceil(x1 / step))
        j0 = int(math.floor(y0 / step))
        j1 = int(math.ceil(y1 / step))
        if (i1 - i0) * (j1 - j0) > 12000:
            return
        for i in range(i0, i1 + 1):
            for j in range(j0, j1 + 1):
                px, py = self.w2s(i * step, j * step)
                big = (i % 2 == 0 and j % 2 == 0)
                cv.create_line(px - 1, py, px + 1, py, fill="#9a9a9a" if big else "#c8c8c8")
                cv.create_line(px, py - 1, px, py + 1, fill="#9a9a9a" if big else "#c8c8c8")
        ax, ay = self.w2s(0, 0)
        cv.create_line(ax - 8, ay, ax + 8, ay, fill="#d08080")
        cv.create_line(ax, ay - 8, ax, ay + 8, fill="#80a080")

    def draw_prim(self, pr, sel, ghost=False):
        cv = self.cv
        sc = self.view["sc"]
        col = "#c4c4c4" if ghost else LAYERS.get(pr["layer"], (7, "#000000"))[1]
        lw = 1 if pr["lw"] < 0.3 else 2
        if sel:
            col = "#ff7a00"
            lw += 1
        kw = {"dash": (5, 3)} if pr.get("dash") else {}
        k = pr["k"]
        if k == "poly":
            pts = []
            for p in pr["pts"]:
                pts += self.w2s(p[0], p[1])
            if len(pts) < 4:
                return
            if pr["closed"] and len(pts) >= 6:
                fill = ""
                if not ghost and pr["fill"]:
                    fill = FILL_COLORS[pr["fill"]]
                cv.create_polygon(pts, fill=fill, outline=col if not (pr["fill"] == "wall" and not sel) else "#1c1c1c",
                                  width=lw, **kw)
            else:
                cv.create_line(pts, fill=col, width=lw, **kw)
        elif k == "circle":
            cx, cy = self.w2s(pr["c"][0], pr["c"][1])
            r = pr["r"] * sc
            cv.create_oval(cx - r, cy - r, cx + r, cy + r, outline=col, width=lw)
        elif k == "arc":
            pts = []
            for p in pr["pts"]:
                pts += self.w2s(p[0], p[1])
            cv.create_line(pts, fill=col, width=1 if not sel else 2)
        elif k == "text":
            if ghost:
                return
            size = int(pr["h"] * sc)
            if size < 5:
                return
            x, y = self.w2s(pr["p"][0], pr["p"][1])
            if pr.get("meas"):                         # ghost measure label: bold on a pale plate so it stays readable over the plan
                tid = cv.create_text(x, y, text=pr["s"], fill=col, font=("Segoe UI", -size, "bold"), anchor="center", angle=pr["rot"])
                if not pr["rot"]:
                    bb = cv.bbox(tid)
                    if bb:
                        rid = cv.create_rectangle(bb[0] - 3, bb[1] - 1, bb[2] + 3, bb[3] + 1, fill="#eaf6f3", outline="")
                        cv.tag_lower(rid, tid)
                return
            if pr.get("note"):                         # ghost note: italic, pale blue, with a dotted frame so it reads as "not part of the plan"
                fnt = ("Segoe UI", -size, "italic")
                tid = cv.create_text(x, y, text=pr["s"], fill=col, font=fnt, anchor="w", angle=pr["rot"])
                if not pr["rot"]:
                    bb = cv.bbox(tid)
                    if bb:
                        cv.create_rectangle(bb[0] - 4, bb[1] - 2, bb[2] + 4, bb[3] + 2, outline=col, dash=(2, 3))
                return
            cv.create_text(x, y, text=pr["s"], fill=col, font=("Segoe UI", -size),
                           anchor="center" if pr.get("anchor", "c") == "c" else "w", angle=pr["rot"])

    def draw_plan(self):
        cv = self.cv
        cv.delete("all")
        self.draw_grid()
        if self.v_ghost and self.sidx > 0:
            for pr in ghost_prims(self.proj, self.sidx):
                self.draw_prim(pr, False, True)
        opts = {"headroom": self.v_headroom, "roof": self.v_roof_lines, "area": self.v_areas,
                "dims": True, "texts": True, "below_stairs": self.v_conn, "notes": self.v_notes, "meas": self.v_meas}
        sel = set(self.sel)
        for pr in plan_prims(self.proj, self.sidx, opts):
            self.draw_prim(pr, pr.get("eid") in sel)
        self.draw_overlay()

    def draw_overlay(self):
        """Things that change with the mouse: handles of the selection, tool previews, rubber band."""
        cv = self.cv
        cv.delete("ov")
        if self.mode != "plan":
            return
        for kind, idx, (x, y) in self.handles():
            px, py = self.w2s(x, y)
            if kind in ("rot", "drot"):          # the TURN handle: an orange round knob on a stalk, easy to find
                el = find_element(self.story(), self.sel[0])[1] if self.sel else None
                if el is not None:
                    ax, ay = self.w2s(el["x"], el["y"])
                    cv.create_line(ax, ay, px, py, fill="#ff7a00", width=2, tags="ov")
                cv.create_oval(px - 7, py - 7, px + 7, py + 7, fill="#ff7a00", outline="#ffffff", width=2, tags="ov")
                cv.create_text(px + 11, py, text="turn", anchor="w", fill="#c04000", font=("Segoe UI", 8, "bold"), tags="ov")
                continue
            cv.create_rectangle(px - 4, py - 4, px + 4, py + 4, fill="#ffffff", outline="#ff7a00", width=2, tags="ov")
        self.draw_tool_preview()

    # ---- 3D --------------------------------------------------------------------------------------------------
    def get_mesh(self):
        key = (self.rev, self.v3_upto, self.v3_hide_roof, self.v3_items, self.v3_from)
        if self._mesh_key != key:
            self._mesh = build_mesh(self.proj, self.v3_upto, not self.v3_hide_roof, self.v3_items, True, first=self.v3_from)
            self._mesh_key = key
            self._tiled = None
        return self._mesh

    def view_solids(self, fast):
        """[(type, material, storey, faces)] for the 3D view.  Walls are cut into pieces of at most 1.2 m so the painter's
        algorithm puts furniture, doors and windows in front of / behind the right wall piece (skipped while orbiting)."""
        mesh = self.get_mesh()
        if fast:
            return [(s["type"], s["mat"], s["sidx"], s["faces"], s["type"] in ("wall", "slab")) for s in mesh]
        if self._tiled is None:
            self._tiled = [(s["type"], s["mat"], s["sidx"],
                            [t for f in s["faces"] for t in tile_face(f)] if s["type"] == "wall" else s["faces"],
                            s["type"] in ("wall", "slab")) for s in mesh]
        return self._tiled

    def draw_3d(self, fast=False):
        cv = self.cv
        cv.delete("all")
        w, h = max(200, cv.winfo_width()), max(200, cv.winfo_height())
        c = self.cam
        yaw, pit = math.radians(c["yaw"]), math.radians(c["pitch"])
        T = (c["tx"], c["ty"], c["tz"])
        C = (T[0] + c["dist"] * math.cos(pit) * math.cos(yaw), T[1] + c["dist"] * math.cos(pit) * math.sin(yaw),
             T[2] + c["dist"] * math.sin(pit))
        f = (T[0] - C[0], T[1] - C[1], T[2] - C[2])
        fl = math.sqrt(sum(a * a for a in f))
        f = tuple(a / fl for a in f)
        r = (f[1] * 1 - f[2] * 0, f[2] * 0 - f[0] * 1, 0.0)          # f x up(0,0,1)
        rl = math.hypot(r[0], r[1]) or 1.0
        r = (r[0] / rl, r[1] / rl, 0.0)
        u = (r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0])
        F = 0.95 * min(w, h)
        light = (-0.35, -0.55, 0.76)
        faces = []
        quick = fast and not self.v3_keep               # 'Keep objects while turning' off: orbit with a light model
        for styp, smat, ssidx, sfaces, stiled in self.view_solids(quick):
            if quick and styp in ("item", "stair", "window", "door", "cupboard", "curtain"):
                continue
            mr, mg, mb, ma = MATERIALS.get(smat, (0.8, 0.8, 0.8, 1.0))
            layer = 0 if styp == "slab" else 1          # a floor is painted before everything that stands on it
            for fc in sfaces:
                pts = []
                zsum = 0.0
                ok = True
                for p in fc:
                    vx, vy, vz = p[0] - C[0], p[1] - C[1], p[2] - C[2]
                    zc = vx * f[0] + vy * f[1] + vz * f[2]
                    if zc < 100:
                        ok = False
                        break
                    xc = vx * r[0] + vy * r[1]
                    yc = vx * u[0] + vy * u[1] + vz * u[2]
                    pts.append((w / 2 + xc / zc * F, h / 2 - yc / zc * F))
                    zsum += zc
                if not ok or len(pts) < 3:
                    continue
                p0, p1, p2 = fc[0], fc[1], fc[2]
                n = ((p1[1] - p0[1]) * (p2[2] - p0[2]) - (p1[2] - p0[2]) * (p2[1] - p0[1]),
                     (p1[2] - p0[2]) * (p2[0] - p0[0]) - (p1[0] - p0[0]) * (p2[2] - p0[2]),
                     (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p1[1] - p0[1]) * (p2[0] - p0[0]))
                nl = math.sqrt(n[0] ** 2 + n[1] ** 2 + n[2] ** 2) or 1.0
                sh = 0.45 + 0.55 * abs((n[0] * light[0] + n[1] * light[1] + n[2] * light[2]) / nl)
                if ma < 1.0:
                    col = _hex(mr * sh * 0.6 + 0.4, mg * sh * 0.6 + 0.4, mb * sh * 0.6 + 0.4)
                else:
                    col = _hex(mr * sh, mg * sh, mb * sh)
                faces.append(((ssidx, layer, -zsum / len(fc)), pts, col, stiled))
        faces.sort(key=lambda t: t[0])                  # storey by storey, floor first, then far to near
        for _, pts, col, stiled in faces:
            flat = [v for p in pts for v in p]
            # pieces of a cut wall / the triangles of a floor get no grey seams: their outline has the colour of the fill
            cv.create_polygon(flat, fill=col, outline=col if stiled else ("#6a6a6a" if not fast else ""), width=1)
        cv.create_text(10, 10, anchor="nw", fill="#555", font=("Segoe UI", 9),
                       text="3D view - drag: orbit   right/middle drag: move   wheel: zoom   (%d faces)" % len(faces))

    # ---- section ---------------------------------------------------------------------------------------------
    def current_section(self):
        for i, s in enumerate(self.proj["stories"]):
            for sc in s["sections"]:
                if sc["id"] == self.sec_id:
                    return sc
        for s in self.proj["stories"]:
            if s["sections"]:
                self.sec_id = s["sections"][0]["id"]
                return s["sections"][0]
        return None

    def all_sections(self):
        return [(sc["id"], sc["name"]) for s in self.proj["stories"] for sc in s["sections"]]

    def draw_section(self):
        cv = self.cv
        cv.delete("all")
        sec = self.current_section()
        if sec is None:
            cv.create_text(40, 40, anchor="nw", font=("Segoe UI", 11), fill="#444",
                           text="No section yet.  Use the Section tool in the plan view: click two points to cut the house.")
            return
        A, B = tuple(sec["a"]), tuple(sec["b"])
        key = (self.rev, sec["id"], tuple(sec["a"]), tuple(sec["b"]))
        if self._sec_key != key:
            self._sec = section_cut(self.proj, A, B, build_mesh(self.proj, with_items=False))
            self._sec_key = key
        v = self.sview
        S = lambda s, z: (v["ox"] + s * v["sc"], v["oy"] - z * v["sc"])
        L = dist(A, B)
        el = story_elevations(self.proj)
        for i, st in enumerate(self.proj["stories"]):
            x0, y0 = S(-300, el[i])
            x1, _ = S(L + 300, el[i])
            cv.create_line(x0, y0, x1, y0, fill="#7a7aaa", dash=(6, 4))
            cv.create_text(x0 + 4, y0 - 4, anchor="sw", fill="#5a5a8a", font=("Segoe UI", 9),
                           text="%s  +%s" % (st["name"], fmt_m(el[i])))
        # "lay": a dormer's own walls and roof are drawn over the main roof
        for cut in sorted(self._sec, key=lambda c: c.get("lay") or {"slab": 0, "roof": 1, "wall": 2, "stair": 3}.get(c["type"], 4)):
            pts = []
            for s, z in cut["poly"]:
                pts += S(s, z)
            cv.create_polygon(pts, fill=SEC_COLORS.get(cut["type"], "#666"), outline="#111", width=1)
        gx0, gy = S(-300, 0)
        gx1, _ = S(L + 300, 0)
        cv.create_text(10, 10, anchor="nw", fill="#555", font=("Segoe UI", 9),
                       text="Section %s - looking to the left of the line (A to B).  Hover to read heights; wheel: zoom; "
                            "drag: move." % sec["name"])


# *************** DEL 61 - TOOLS AND MOUSE (select, wall, room, door/window, item, stairs, roof, dimension, text, section) ******
# ToolMixin belongs to the ArchApp class (DEL 63).  The undo rule: push_undo() BEFORE every change of the project.
# ToDo: copy/paste between storeys, mirror, align, array copy.

TOOL_HINTS = {
    "select": "Click = select (Shift adds).  Drag = move.  Drag on empty space = box select.  Drag the white squares to "
              "reshape.  Del = delete, F/H = flip door, Ctrl+D = duplicate.  TURN a bed / sofa / stairs: arrow keys Left / Right "
              "(15 degrees, Shift = 1 degree), R = 90, or drag the orange round handle.  Arrow keys Up / Down (Ctrl+arrows) move it.",
    "wall": "Arc wall (tick the box): click the start, the end, then the point the arc passes through.  Straight: click to start a wall, click again for each corner.  Right click / Enter / Esc ends.  Straight is on by default (untick it for slanted walls; Shift flips it while held).  "
            "Type a length in mm + Enter.  Click the first point again to close.",
    "room": "Rect: two clicks.  Polygon: click the corners, Enter / double click ends.  In walls: click inside closed walls.",
    "opening": "Click on a wall to put the door / window there (the side you click on is the side it opens to).  F = flip.",
    "item": "Click to place.  Wall-bound things snap back-to-wall (hold Alt to switch snapping off).  Turn it before you click: "
            "arrow keys Left / Right (15 degrees) or R (90).  Afterwards select it and use the same keys.  Esc = stop.",
    "stair": "Straight stairs: click one side of the bottom (or of the top: menu 'Start at'), click the other side (= the width), "
             "then move out and click (= the length; steps, tread and slope are fitted to the space).  Lift / L / spiral: click to "
             "place.  Arrow keys Left / Right (Shift = 1 degree) or R turn the stairs, also before you click.",
    "roof": "Drag two corners of the roof (inner wall line), or press 'Roof over all walls'.  Mansard / gambrel: Pitch = the "
            "shallow upper slope; the steep lower slope is set in the panel on the right.",
    "dormer": "Click on the roof of an attic storey to put a dormer (or a roof window) there; it faces down the slope.  Drag the white square to turn it, R = turn 90.  Edit size, window and depth on the right.",
    "dim": "Click the two points to measure, then click where the dimension line should be.",
    "text": "Click where the text should go.",
    "meas": "GHOST MEASURES (plan only, never exported).  Rectangle: click two corners - no walls needed.  Room: click inside a room or "
            "closed walls.  Ruler: click two points.  A ghost note inside the outline becomes the name in front of the sizes.  "
            "'Measures list...' shows all of them as text you can copy.",
    "note": "GHOST NOTE: click where your note should go (e.g. 'Bedroom B').  Notes belong to this storey, show only in the plan, "
            "only while 'Ghost notes' is ticked, and are never exported or printed.  Select a note to move, edit or delete it.",
    "section": "Click two points to cut the house; open the Section view to see it.",
}


class ToolMixin(object):

    # ---- helpers ---------------------------------------------------------------------------------------------
    def story(self):
        return self.proj["stories"][self.sidx]

    def set_status(self, s):
        self.status_var.set(s)

    def snap_mm(self):
        try:
            return float(self.snap_var.get())
        except Exception:
            return 100.0

    def snap(self, wx, wy, base=None, shift=False):
        thr = 12.0 / self.view["sc"]
        ortho = bool(shift) != bool(self.v_ortho.get())              # Straight is on by default; Shift flips it while held
        if base is not None and ortho:
            if abs(wx - base[0]) > abs(wy - base[1]):
                wy = base[1]
            else:
                wx = base[0]
        else:
            best = None
            story = self.story()
            cand = []
            for w in story["walls"]:
                cand += [(w["p"][0], w["p"][1]), (w["p"][2], w["p"][3])]
            for r in story["rooms"]:
                cand += [tuple(p) for p in r["pts"]]
            for p in cand:
                d = math.hypot(p[0] - wx, p[1] - wy)
                if d < thr and (best is None or d < best[0]):
                    best = (d, p)
            if best:
                return best[1]
        g = self.snap_mm()
        if g > 0:
            if not (base is not None and ortho and wx == base[0]):
                wx = round(wx / g) * g
            if not (base is not None and ortho and wy == base[1]):
                wy = round(wy / g) * g
        return (wx, wy)

    def push_undo(self):
        self.undo.append(json.dumps(self.proj))
        if len(self.undo) > 80:
            self.undo.pop(0)
        self.redo = []
        self.dirty = True

    def changed(self, props=True):
        self.rev += 1
        self.dirty = True
        self.redraw()
        if props:
            self.show_props()

    def do_undo(self):
        if not self.undo:
            return
        self.redo.append(json.dumps(self.proj))
        keep = (self.proj.get("notes"), self.proj.get("shop"))      # memos and the shopping list are not part of undo
        self.proj = json.loads(self.undo.pop())
        self.proj["notes"], self.proj["shop"] = keep
        ensure_extras(self.proj)
        self.after_project_swap()

    def do_redo(self):
        if not self.redo:
            return
        self.undo.append(json.dumps(self.proj))
        keep = (self.proj.get("notes"), self.proj.get("shop"))
        self.proj = json.loads(self.redo.pop())
        self.proj["notes"], self.proj["shop"] = keep
        ensure_extras(self.proj)
        self.after_project_swap()

    def after_project_swap(self):
        self.sidx = max(0, min(self.sidx, len(self.proj["stories"]) - 1))
        self.sel = []
        self.tmp = {}
        self.rev += 1
        self.dirty = True
        self.rebuild_story_bar()
        self.redraw()
        self.show_props()

    def hidden_note(self, el):
        """A ghost note while the 'Ghost notes' box is unticked: invisible, so it must not be picked, boxed or selected."""
        return bool(el.get("ghost")) and not self.v_notes

    def hidden_layer(self, kind, el):
        """True for an element of a ghost layer (note / measure) whose layer is switched off."""
        return (kind == "text" and self.hidden_note(el)) or (kind == "meas" and not self.v_meas)

    def show_notes(self, on=True):
        self.v_notes = bool(on)
        self._bvars["v_notes"].set(bool(on))

    def show_meas(self, on=True):
        self.v_meas = bool(on)
        self._bvars["v_meas"].set(bool(on))

    def set_tool(self, name):
        if name == "note" and not self.v_notes:          # drawing a note you cannot see makes no sense: switch the layer on
            self.show_notes(True)
        if name == "meas" and not self.v_meas:
            self.show_meas(True)
        self.tool = name
        self.tool_var.set(name)
        self.tmp = {}
        self.typed = ""
        self.drag = None
        self.show_tool_options()
        self.set_status(TOOL_HINTS.get(name, ""))
        if self.mode != "plan":
            self.set_mode("plan")
        else:
            self.draw_overlay()

    # ---- hit testing -----------------------------------------------------------------------------------------
    def hit_test(self, wx, wy):
        story = self.story()
        tol = 7.0 / self.view["sc"]
        P = (wx, wy)
        sx = expand_curved(story)                 # curved walls as chains of short straight ones
        for o in sx["openings"]:
            w = get_wall(sx, o["wall"])
            if w is None:
                continue
            c = opening_anchor(sx, o)
            dd = seg_point_dist(P, (w["p"][0], w["p"][1]), (w["p"][2], w["p"][3]))[0]
            if dist(P, c) <= o["w"] / 2.0 + tol and dd <= w["t"] / 2.0 + tol + (o["w"] if o["kind"] in ("door", "door2") else 0) * 0.0:
                return o["id"]
        for it in reversed(story["items"]):
            if point_in_poly(P, item_outline(it)) or dist(P, (it["x"], it["y"])) <= max(it["w"], it["d"]) / 2.0 + tol * 0.5 \
                    and max(it["w"], it["d"]) < 300:
                return it["id"]
        for st in reversed(story["stairs"]):
            if point_in_poly(P, stair_world_outline(self.proj, self.sidx, st)):
                return st["id"]
        for sc in story["sections"]:
            if seg_point_dist(P, tuple(sc["a"]), tuple(sc["b"]))[0] <= tol * 1.5:
                return sc["id"]
        for tx in story["texts"]:
            if tx.get("ghost"):                        # a ghost note starts at its point and runs to the right; hidden = not clickable
                if self.v_notes and -tol <= wx - tx["x"] <= len(tx["s"]) * tx["h"] * 0.6 + tol and abs(wy - tx["y"]) <= tx["h"]:
                    return tx["id"]
                continue
            if abs(wx - tx["x"]) <= len(tx["s"]) * tx["h"] * 0.6 and abs(wy - tx["y"]) <= tx["h"]:
                return tx["id"]
        for dm in story["dims"]:
            a, b = tuple(dm["a"]), tuple(dm["b"])
            if dist(a, b) < 1:
                continue
            n = v_perp(v_unit(v_sub(b, a)))
            p1, p2 = v_add(a, v_mul(n, dm["off"])), v_add(b, v_mul(n, dm["off"]))
            if seg_point_dist(P, p1, p2)[0] <= tol * 1.5:
                return dm["id"]
        for w in sx["walls"]:
            if seg_point_dist(P, (w["p"][0], w["p"][1]), (w["p"][2], w["p"][3]))[0] <= w["t"] / 2.0 + tol:
                return w.get("src", w["id"])
        if self.v_meas:                                # ghost measures: a ruler's line / a measured outline's edge or its label
            for ms in reversed(story.get("meas", [])):
                pts = meas_outline(ms)
                if ms["kind"] == "ruler":
                    if seg_point_dist(P, pts[0], pts[1])[0] <= tol * 1.5 + 120:
                        return ms["id"]
                    continue
                if dist(P, poly_centroid(pts)) <= 500.0 or any(seg_point_dist(P, pts[i], pts[(i + 1) % len(pts)])[0] <= tol * 1.5
                                                                 for i in range(len(pts))):
                    return ms["id"]
        for rw in story.get("rwins", []):
            ol = rwin_outline(story, rw)
            if ol and point_in_poly(P, ol):
                return rw["id"]
        for dm in reversed(story.get("dormers", [])):
            if point_in_poly(P, dormer_poly(dm, dormer_depth(story, dm))):
                return dm["id"]
        for r in reversed(story["rooms"]):
            if len(r["pts"]) >= 3 and point_in_poly(P, [tuple(p) for p in r["pts"]]):
                return r["id"]
        for rf in story["roofs"]:
            if point_in_poly(P, roof_rect_poly(rf, rf["over"] + tol)):
                return rf["id"]
        return None

    def handles(self):
        if len(self.sel) != 1 or self.mode != "plan" or self.tool != "select":
            return []
        story = self.story()
        kind, e = find_element(story, self.sel[0])
        if e is None:
            return []
        if kind == "wall":
            hs = [("wall", 0, (e["p"][0], e["p"][1])), ("wall", 1, (e["p"][2], e["p"][3]))]
            if wall_arc(e):                       # the middle of an arc wall: drag it to change the bulge
                hs.append(("sag", 0, wall_arc_at(e, wall_length(e) / 2.0)[0]))
            return hs
        if kind == "room":
            return [("room", i, tuple(p)) for i, p in enumerate(e["pts"])]
        if kind == "roof":
            x0, y0, x1, y1 = e["rect"]
            return [("roof", 0, (x0, y0)), ("roof", 1, (x1, y0)), ("roof", 2, (x1, y1)), ("roof", 3, (x0, y1))]
        if kind == "item":
            return [("rot", 0, item_to_world(e, (0, -(e["d"] / 2.0 + 300))))]
        if kind == "stair":
            return [("rot", 0, v_add(rot_pt((0, -300), e["rot"]), (e["x"], e["y"])))]
        if kind == "dormer":
            return [("drot", 0, dormer_pt(e, 0.0, -400.0))]
        if kind in ("dim", "section"):
            return [(kind, 0, tuple(e["a"])), (kind, 1, tuple(e["b"]))]
        return []

    # ---- mouse -----------------------------------------------------------------------------------------------
    def on_press(self, e):
        self.cv.focus_set()
        if self.mode == "3d":
            self.o3d = {"x": e.x, "y": e.y, "yaw": self.cam["yaw"], "pitch": self.cam["pitch"]}
            return
        if self.mode == "section":
            self.pan = {"x": e.x, "y": e.y, "ox": self.sview["ox"], "oy": self.sview["oy"]}
            return
        wx, wy = self.s2w(e.x, e.y)
        shift = bool(e.state & 1)
        t = self.tool
        if t == "select":
            self.press_select(e, wx, wy, shift)
        elif t == "wall":
            self.press_wall(wx, wy, shift)
        elif t == "room":
            self.press_room(wx, wy, shift)
        elif t == "opening":
            self.press_opening(wx, wy)
        elif t == "item":
            self.press_item(wx, wy, bool(e.state & 0x20000))
        elif t == "stair":
            self.press_stair(wx, wy)
        elif t == "roof":
            self.press_two_points(wx, wy, "roof")
        elif t == "dormer":
            self.press_dormer(wx, wy)
        elif t in ("dim", "section"):
            self.press_dim(wx, wy, shift, t)
        elif t == "text":
            self.press_text(wx, wy)
        elif t == "note":
            self.press_text(wx, wy, ghost=True)
        elif t == "meas":
            self.press_meas(wx, wy, shift)

    def on_double(self, e):
        if self.mode != "plan":
            return
        if self.tool == "select":                       # double click on stairs: the parts window
            hit = self.hit_test(*self.s2w(e.x, e.y))
            if hit is not None and find_element(self.story(), hit)[0] == "stair":
                self.sel = [hit]
                self.open_stair_editor()
                return
        if self.tool == "room" and self.tmp.get("pts"):
            self.finish_room_poly()
        elif self.tool == "wall":
            self.tmp = {}
            self.draw_overlay()

    def on_motion(self, e):
        if self.mode == "section":
            self.section_hover(e)
            return
        if self.mode != "plan":
            return
        self.mouse_s = (e.x, e.y)
        wx, wy = self.s2w(e.x, e.y)
        self.mouse = (wx, wy)
        self.alt = bool(e.state & 0x20000)
        self.shift = bool(e.state & 1)
        self.set_coords_status(wx, wy)
        self.draw_overlay()

    def set_coords_status(self, wx, wy):
        self.coord_var.set("x %s  y %s m" % (fmt_m(wx), fmt_m(wy)))

    def on_drag(self, e):
        if self.mode == "3d" and getattr(self, "o3d", None):
            o = self.o3d
            self.cam["yaw"] = o["yaw"] - (e.x - o["x"]) * 0.4
            self.cam["pitch"] = max(-5.0, min(89.0, o["pitch"] + (e.y - o["y"]) * 0.4))
            self.schedule_fast_redraw()
            return
        if self.mode == "section" and getattr(self, "pan", None):
            p = self.pan
            self.sview["ox"] = p["ox"] + e.x - p["x"]
            self.sview["oy"] = p["oy"] + e.y - p["y"]
            self.redraw()
            return
        if self.mode != "plan":
            return
        wx, wy = self.s2w(e.x, e.y)
        self.mouse = (wx, wy)
        if self.drag:
            self.drag_move(wx, wy, bool(e.state & 1))
        else:
            self.on_motion(e)

    def on_release(self, e):
        if self.mode == "3d":
            self.o3d = None
            self.redraw()
            return
        if self.mode == "section":
            self.pan = None
            return
        d = self.drag
        self.drag = None
        if d and d["type"] == "box":
            x0, y0 = d["start"]
            x1, y1 = self.mouse
            lo = (min(x0, x1), min(y0, y1))
            hi = (max(x0, x1), max(y0, y1))
            if hi[0] - lo[0] > 20 / self.view["sc"] or hi[1] - lo[1] > 20 / self.view["sc"]:
                story = self.story()
                got = [] if not d["shift"] else list(self.sel)
                for kind, lst in KIND_LISTS.items():
                    for el in story[lst]:
                        if self.hidden_layer(kind, el):
                            continue
                        a = opening_anchor(story, el) if kind == "opening" else element_anchor(kind, el)
                        if lo[0] <= a[0] <= hi[0] and lo[1] <= a[1] <= hi[1] and el["id"] not in got:
                            got.append(el["id"])
                self.sel = got
            self.redraw()
            self.show_props()
        elif d and d.get("moved"):
            self.rev += 1
            self.show_props()
            self.redraw()

    def on_rpress(self, e):
        self.pan = {"x": e.x, "y": e.y, "moved": False}
        if self.mode == "3d":
            c = self.cam
            self.pan.update(tx=c["tx"], ty=c["ty"], tz=c["tz"])
        elif self.mode == "section":
            self.pan.update(ox=self.sview["ox"], oy=self.sview["oy"])
        else:
            self.pan.update(ox=self.view["ox"], oy=self.view["oy"])

    def on_rdrag(self, e):
        p = getattr(self, "pan", None)
        if not p:
            return
        if abs(e.x - p["x"]) + abs(e.y - p["y"]) > 3:
            p["moved"] = True
        if not p["moved"]:
            return
        if self.mode == "3d":
            c = self.cam
            yaw = math.radians(c["yaw"])
            k = c["dist"] / 900.0
            dx, dy = (e.x - p["x"]) * k, (e.y - p["y"]) * k
            c["tx"] = p["tx"] + math.sin(yaw) * dx - math.cos(yaw) * dy * 0.6
            c["ty"] = p["ty"] - math.cos(yaw) * dx - math.sin(yaw) * dy * 0.6
            c["tz"] = p["tz"]
            self.schedule_fast_redraw()
        elif self.mode == "section":
            self.sview["ox"] = p["ox"] + e.x - p["x"]
            self.sview["oy"] = p["oy"] + e.y - p["y"]
            self.redraw()
        else:
            self.view["ox"] = p["ox"] + e.x - p["x"]
            self.view["oy"] = p["oy"] + e.y - p["y"]
            self.redraw()

    def on_rrelease(self, e):
        p = getattr(self, "pan", None)
        self.pan = None
        if self.mode == "3d":
            self.redraw()
            return
        if p and not p["moved"] and self.mode == "plan":
            if self.tmp:
                self.finish_tool_op()
            elif self.tool != "select":
                self.set_tool("select")

    def on_wheel(self, e):
        f = 1.15 if e.delta > 0 else 1 / 1.15
        if self.mode == "3d":
            self.cam["dist"] = max(500.0, min(400000.0, self.cam["dist"] / f))
            self.schedule_fast_redraw()
            return
        v = self.sview if self.mode == "section" else self.view
        v["ox"] = e.x - (e.x - v["ox"]) * f
        v["oy"] = e.y - (e.y - v["oy"]) * f
        v["sc"] *= f
        self.redraw()

    def schedule_fast_redraw(self):
        if self._fast_job is None:
            self._fast_job = self.root.after(30, self._fast_redraw)

    def _fast_redraw(self):
        self._fast_job = None
        self.redraw(fast=True)
        if self._full_job:
            self.root.after_cancel(self._full_job)
        self._full_job = self.root.after(250, lambda: self.redraw())

    def section_hover(self, e):
        sec = self.current_section()
        if not sec:
            return
        v = self.sview
        s = (e.x - v["ox"]) / v["sc"]
        z = (v["oy"] - e.y) / v["sc"]
        el = story_elevations(self.proj)
        below = 0
        for i, ev in enumerate(el):
            if ev <= z:
                below = i
        self.coord_var.set("s %s m   height %s m   (%s floor %s m)" % (fmt_m(s), fmt_m(z), self.proj["stories"][below]["name"],
                                                                      fmt_m(z - el[below])))

    # ---- keys ------------------------------------------------------------------------------------------------
    def on_key(self, e):
        k = e.keysym
        if self.mode != "plan":
            if k == "Home":
                self.fit_view() if self.mode == "section" else self.reset_camera()
                self.redraw()
            return
        if self.tool == "wall" and self.tmp.get("last") is not None and (e.char.isdigit() or e.char == "."):
            self.typed += e.char
            self.draw_overlay()
            return "break"
        if k == "BackSpace" and self.typed:
            self.typed = self.typed[:-1]
            self.draw_overlay()
            return "break"
        if k in ("Return", "KP_Enter"):
            if self.typed and self.tool == "wall":
                self.wall_by_length()
            else:
                self.finish_tool_op()
            return "break"
        if k == "Escape":
            if self.tmp or self.typed:
                self.tmp = {}
                self.typed = ""
                self.draw_overlay()
            elif self.tool != "select":
                self.set_tool("select")
            else:
                self.sel = []
                self.redraw()
                self.show_props()
            return "break"
        if k == "Delete":
            self.delete_selection()
            return "break"
        if k in ("r", "R"):
            self.rotate_selection(90.0)
            return "break"
        if k in ("e", "E"):
            self.rotate_selection(15.0)
            return "break"
        if k in ("f", "F"):
            self.flip_selection("swing")
            return "break"
        if k in ("h", "H"):
            self.flip_selection("hinge")
            return "break"
        if k == "Home":
            self.fit_view()
            self.redraw()
            return "break"
        if k in ("Left", "Right", "Up", "Down"):
            ctrl = bool(e.state & 4)
            if k in ("Left", "Right") and not ctrl and self.arrows_rotate():
                deg = (1.0 if (e.state & 1) else 15.0) * (1.0 if k == "Left" else -1.0)      # Left = counter-clockwise
                self.rotate_selection(deg)
                return "break"
            if self.sel:
                g = self.snap_mm() or 50.0
                dx = {"Left": -g, "Right": g}.get(k, 0.0)
                dy = {"Up": g, "Down": -g}.get(k, 0.0)
                self.nudge(dx, dy)
                return "break"

    def finish_tool_op(self):
        if self.tool == "room" and self.tmp.get("pts"):
            self.finish_room_poly()
        else:
            self.tmp = {}
            self.typed = ""
            self.draw_overlay()

    # ---- select / move ---------------------------------------------------------------------------------------
    def press_select(self, e, wx, wy, shift):
        sc = self.view["sc"]
        for kind, idx, pos in self.handles():
            px, py = self.w2s(pos[0], pos[1])
            if abs(px - e.x) <= 8 and abs(py - e.y) <= 8:
                self.drag = {"type": "handle", "kind": kind, "idx": idx, "pushed": False, "moved": False}
                if kind == "wall":
                    self.drag["links"] = self.wall_links(self.sel[0], idx)
                return
        hit = self.hit_test(wx, wy)
        if hit is not None:
            if shift:
                if hit in self.sel:
                    self.sel.remove(hit)
                else:
                    self.sel.append(hit)
            elif hit not in self.sel:
                self.sel = [hit]
            story = self.story()
            orig = {}
            for eid in self.sel:
                kind, el = find_element(story, eid)
                if el is not None:
                    orig[eid] = (kind, copy.deepcopy(el))
            links = []
            for eid, (kind, el) in orig.items():
                if kind == "wall":
                    for idx in (0, 1):
                        links += self.wall_links(eid, idx, exclude=set(self.sel))
            self.drag = {"type": "move", "start": (wx, wy), "orig": orig, "links": links, "pushed": False, "moved": False}
            self.redraw()
            self.show_props()
        else:
            if not shift:
                self.sel = []
            self.drag = {"type": "box", "start": (wx, wy), "shift": shift}
            self.redraw()
            self.show_props()

    def wall_links(self, wid, idx, exclude=None):
        """Other walls' end points that sit exactly on this wall's end point: they move along (keeps corners joined)."""
        story = self.story()
        w = get_wall(story, wid)
        pt = (w["p"][idx * 2], w["p"][idx * 2 + 1])
        out = []
        for o in story["walls"]:
            if o["id"] == wid or (exclude and o["id"] in exclude):
                continue
            for j in (0, 1):
                if dist(pt, (o["p"][j * 2], o["p"][j * 2 + 1])) < 3.0:
                    out.append((o["id"], j, pt))
        return out

    def drag_move(self, wx, wy, shift):
        d = self.drag
        story = self.story()
        if d["type"] == "box":
            self.mouse = (wx, wy)
            self.draw_overlay()
            return
        if not d["pushed"]:
            self.push_undo()
            d["pushed"] = True
        d["moved"] = True
        if d["type"] == "move":
            g = self.snap_mm()
            dx, dy = wx - d["start"][0], wy - d["start"][1]
            if g > 0:
                dx, dy = round(dx / g) * g, round(dy / g) * g
            for eid, (kind, o) in d["orig"].items():
                k2, el = find_element(story, eid)
                if el is None:
                    continue
                if kind == "opening":
                    w = get_wall(story, el["wall"])
                    if w:
                        c0, dd = wall_arc_at(w, o["pos"])
                        L = wall_length(w)
                        el["pos"] = max(el["w"] / 2.0, min(L - el["w"] / 2.0, o["pos"] + dx * dd[0] + dy * dd[1]))
                else:
                    el.clear()
                    el.update(copy.deepcopy(o))
                    _shift_element(kind, el, dx, dy)
            for wid, j, pt in d["links"]:
                w = get_wall(story, wid)
                w["p"][j * 2] = pt[0] + dx
                w["p"][j * 2 + 1] = pt[1] + dy
            self.redraw()
            return
        kind, idx = d["kind"], d["idx"]
        el = find_element(story, self.sel[0])[1]
        if kind == "wall":
            other = (el["p"][(1 - idx) * 2], el["p"][(1 - idx) * 2 + 1])
            pt = self.snap(wx, wy, other, shift)
            for wid, j, _ in d["links"]:
                w = get_wall(story, wid)
                w["p"][j * 2], w["p"][j * 2 + 1] = pt
            el["p"][idx * 2], el["p"][idx * 2 + 1] = pt
        elif kind == "room":
            el["pts"][idx] = list(self.snap(wx, wy))
        elif kind == "roof":
            x0, y0, x1, y1 = el["rect"]
            px, py = self.snap(wx, wy)
            if idx in (0, 3):
                x0 = px
            else:
                x1 = px
            if idx in (0, 1):
                y0 = py
            else:
                y1 = py
            el["rect"] = [min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)]
        elif kind == "sag":
            A = (el["p"][0], el["p"][1])
            B = (el["p"][2], el["p"][3])
            n = v_perp(v_unit(v_sub(B, A)))
            sg = v_dot(v_sub((wx, wy), ((A[0] + B[0]) / 2.0, (A[1] + B[1]) / 2.0)), n)
            sg = round(sg / 10.0) * 10.0
            el["sag"] = 0.0 if abs(sg) < 30.0 else max(-0.9 * dist(A, B), min(0.9 * dist(A, B), sg))
        elif kind == "drot":
            ang = math.degrees(math.atan2(wx - el["x"], -(wy - el["y"])))
            el["rot"] = (round(ang / 15.0) * 15.0 if not shift else ang) % 360.0
        elif kind == "rot":
            cx, cy = (el["x"], el["y"])
            ang = math.degrees(math.atan2(wy - cy, wx - cx)) + 90.0
            el["rot"] = round(ang / 15.0) * 15.0 % 360.0 if not shift else ang % 360.0
        elif kind in ("dim", "section"):
            el["a" if idx == 0 else "b"] = list(self.snap(wx, wy))
        self.redraw()

    # ---- editing commands ------------------------------------------------------------------------------------
    def delete_selection(self):
        if not self.sel:
            return
        self.push_undo()
        story = self.story()
        for eid in list(self.sel):
            remove_element(story, eid)
        self.sel = []
        self.changed()

    def duplicate_selection(self):
        if not self.sel:
            return
        self.push_undo()
        self.sel = clone_elements(self.proj, self.story(), self.sel)
        self.changed()

    def arrows_rotate(self):
        """True when the Left / Right arrow keys turn things: everything selected can be turned (items, stairs, dormers, text),
        or an item / stairs tool is waiting to place something.  Ctrl+arrows always move."""
        if self.tool in ("item", "stair"):             # placing: the keys turn the thing that is about to be placed
            return self.mode == "plan"
        if not self.sel:
            return False
        story = self.story()
        kinds = [find_element(story, eid)[0] for eid in self.sel]
        return bool(kinds) and all(k in ("item", "stair", "dormer", "text") for k in kinds)

    def rotate_selection(self, deg):
        story = self.story()
        if self.tool in ("item", "stair") and self.mode == "plan":       # placing: turn the preview, not the last placed thing
            self.item_rot = (self.item_rot + deg) % 360.0
            self.set_status("Turned to %g degrees (it snaps to a wall when you are close to one: hold Alt to place it free).  "
                            "To turn a thing that is already placed: press Esc, select it, then use the arrow keys."
                            % round(self.item_rot, 1))
            self.draw_overlay()
            return
        if not self.sel:
            return
        self.push_undo()
        last = None
        for eid in self.sel:
            kind, el = find_element(story, eid)
            if kind in ("item", "stair", "dormer"):
                el["rot"] = (el["rot"] + deg) % 360.0
                last = el["rot"]
            elif kind == "text":
                el["rot"] = (el.get("rot", 0.0) + deg) % 360.0
                last = el["rot"]
            elif kind == "roof":
                el["ridge"] = "y" if el["ridge"] == "x" else "x"
        self.changed()
        if last is not None:
            self.set_status("Turned to %g degrees." % round(last, 1))

    def flip_selection(self, what):
        story = self.story()
        done = False
        for eid in self.sel:
            kind, el = find_element(story, eid)
            if kind == "opening":
                if not done:
                    self.push_undo()
                    done = True
                if what == "swing":
                    el["swing"] = -el.get("swing", 1)
                else:
                    el["hinge"] = 1 - el.get("hinge", 0)
        if done:
            self.changed()

    def nudge(self, dx, dy):
        self.push_undo()
        story = self.story()
        for eid in self.sel:
            kind, el = find_element(story, eid)
            if el is None:
                continue
            if kind == "opening":
                w = get_wall(story, el["wall"])
                dd = v_unit((w["p"][2] - w["p"][0], w["p"][3] - w["p"][1]))
                el["pos"] += dx * dd[0] + dy * dd[1]
            else:
                _shift_element(kind, el, dx, dy)
        self.changed(props=False)

    # ---- tools: wall -----------------------------------------------------------------------------------------
    def wall_thickness(self):
        try:
            return max(20.0, float(self.wall_t_var.get()))
        except Exception:
            return 100.0

    def wall_kind(self):
        """None for a normal wall, "curtain" when the Wall type menu says Curtain (room divider)."""
        return "curtain" if getattr(self, "wall_kind_var", None) is not None and self.wall_kind_var.get() == "curtain" else None

    def press_wall(self, wx, wy, shift):
        if self.wall_arc_mode.get():                      # arc wall: start, end, then a point on the arc
            pt = self.snap(wx, wy)
            if "arc_a" not in self.tmp:
                self.tmp = {"arc_a": pt}
            elif "arc_b" not in self.tmp:
                if dist(pt, self.tmp["arc_a"]) >= 100:
                    self.tmp["arc_b"] = pt
            else:
                a, b = self.tmp["arc_a"], self.tmp["arc_b"]
                self.push_undo()
                w = add_wall(self.proj, self.story(), a, b, self.wall_thickness())
                w["sag"] = self.arc_sag(a, b, (wx, wy))
                self.sel = [w["id"]]
                self.tmp = {}
                self.changed()
                return
            self.draw_overlay()
            return
        pt = self.snap(wx, wy, self.tmp.get("last"), shift)
        if "last" not in self.tmp:
            self.tmp = {"last": pt, "first": pt, "count": 0}
            self.draw_overlay()
            return
        self.add_wall_to(pt)

    @staticmethod
    def arc_sag(a, b, cursor):
        """The bulge (mm) of an arc wall a -> b that passes through the cursor, rounded to 10 mm; 0 when almost straight."""
        n = v_perp(v_unit(v_sub(b, a)))
        s = v_dot(v_sub(cursor, ((a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0)), n)
        s = round(s / 10.0) * 10.0
        return 0.0 if abs(s) < 30.0 else max(-0.9 * dist(a, b), min(0.9 * dist(a, b), s))

    def add_wall_to(self, pt):
        last = self.tmp["last"]
        if dist(pt, last) < 50:
            return
        self.push_undo()
        w = add_wall(self.proj, self.story(), last, pt, self.wall_thickness(), kind=self.wall_kind())
        self.tmp["count"] += 1
        self.tmp["last"] = pt
        self.typed = ""
        if dist(pt, self.tmp["first"]) < 3 and self.tmp["count"] >= 2:
            self.tmp = {}
        self.changed(props=False)

    def wall_by_length(self):
        try:
            ln = float(self.typed)
        except ValueError:
            self.typed = ""
            return
        last = self.tmp["last"]
        mx, my = self.mouse
        d = v_unit((mx - last[0], my - last[1]))
        if bool(self.v_ortho.get()) != bool(self.shift):
            d = (1.0, 0.0) if abs(d[0]) >= abs(d[1]) and d[0] >= 0 else (-1.0, 0.0) if abs(d[0]) >= abs(d[1]) else \
                (0.0, 1.0) if d[1] >= 0 else (0.0, -1.0)
        self.add_wall_to((last[0] + d[0] * ln, last[1] + d[1] * ln))

    # ---- tools: room -----------------------------------------------------------------------------------------
    def new_room(self, pts):
        self.push_undo()
        r = add_room(self.proj, self.story(), pts, self.room_name_var.get())
        self.sel = [r["id"]]
        self.tmp = {}
        self.changed()

    def press_room(self, wx, wy, shift):
        mode = self.room_mode.get()
        if mode == "In walls":
            r = detect_room(self.story(), wx, wy)
            if r is None:
                self.set_status("No closed room here - the walls must form a closed loop (doors count as closed).")
                return
            self.new_room(r)
            return
        pt = self.snap(wx, wy, self.tmp.get("a") if mode == "Rect" else None, False)
        if mode == "Rect":
            if "a" not in self.tmp:
                self.tmp = {"a": pt}
                self.draw_overlay()
                return
            a = self.tmp["a"]
            x0, x1 = sorted((a[0], pt[0]))
            y0, y1 = sorted((a[1], pt[1]))
            if x1 - x0 < 300 or y1 - y0 < 300:
                return
            if self.room_walls.get():
                self.push_undo()
                walls_round_rect(self.proj, self.story(), x0, y0, x1, y1, self.wall_thickness())
            self.new_room([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
            return
        pts = self.tmp.setdefault("pts", [])
        if len(pts) >= 3 and dist(pt, pts[0]) < 12.0 / self.view["sc"]:
            self.finish_room_poly()
            return
        pts.append(pt)
        self.draw_overlay()

    def finish_room_poly(self):
        pts = self.tmp.get("pts", [])
        if len(pts) >= 3:
            self.new_room(pts)
        else:
            self.tmp = {}
            self.draw_overlay()

    # ---- tools: openings, items, stairs ---------------------------------------------------------------------
    def opening_values(self):
        def num(v, dflt):
            try:
                return float(v.get())
            except Exception:
                return dflt
        k = self.open_kind.get()
        dw, dh, ds, _ = OPENING_KINDS[k]
        return k, num(self.open_w, dw), num(self.open_h, dh), num(self.open_sill, ds)

    def press_opening(self, wx, wy):
        res = place_opening_on_wall(self.story(), wx, wy)
        if res is None:
            self.set_status("Click ON a wall.")
            return
        wid, pos, swing, hinge = res
        k, w, h, sill = self.opening_values()
        wall = get_wall(self.story(), wid)
        L = wall_length(wall)
        pos = round(pos / 50.0) * 50.0
        pos = max(w / 2.0, min(L - w / 2.0, pos))
        self.push_undo()
        o = add_opening(self.proj, self.story(), wid, pos, k, w, h, sill, hinge, swing)
        self.sel = [o["id"]]
        self.changed()

    def item_placement(self, wx, wy, alt):
        c = CATALOG[self.item_type]
        if c["snap"] and not alt:
            r = snap_to_wall(self.story(), wx, wy, c["d"], 450.0)
            if r:
                return round(r[0], 1), round(r[1], 1), r[2] % 360.0
        x, y = self.snap(wx, wy)
        return x, y, self.item_rot

    def press_item(self, wx, wy, alt):
        x, y, rot = self.item_placement(wx, wy, alt)
        self.push_undo()
        it = add_item(self.proj, self.story(), self.item_type, x, y, rot)
        self.sel = [it["id"]]
        self.changed()

    def stair_riser_mm(self):
        """Wanted riser height in mm, or None = automatic (the number of steps is fitted to the length you pull out)."""
        try:
            return max(100.0, float(self.stair_riser.get()))
        except (TypeError, ValueError):
            return None

    def stair_from_top(self):
        return self.stair_start.get() == "top"

    def stair_tool_ok(self):
        """Stairs normally connect two storeys: not allowed from the top storey unless 'Only up to the next floor' is unticked."""
        return (not self.stair_one_floor.get()) or stair_has_floor_above(self.proj, self.sidx)

    def stair_no_floor_msg(self):
        if self.sidx == 0:
            return ("There is no floor above - add a storey first (Storey menu), or untick 'Only to next floor' in the bar "
                    "for stairs that climb a height you type in 'Own rise mm'.")
        return ("There is no floor above this storey, so stairs started here would climb to nothing.  Draw them on the storey BELOW "
                "(they show up here as the opening), or untick 'Only to next floor' for an exception.")

    def stair_tool_rise(self):
        """How high the stairs about to be drawn climb: up to the next floor, or (box unticked) the 'Own rise' typed in the bar."""
        base = stair_total_rise(self.proj, self.sidx)
        if self.stair_one_floor.get():
            return base
        try:
            r = float(self.stair_rise_var.get().replace(",", "."))
        except ValueError:
            return base
        return r if r >= 300.0 else base

    def stair_drawn_mode(self):
        return self.stair_kind.get() == "straight" and self.stair_draw.get()

    def press_stair(self, wx, wy):
        if not self.stair_tool_ok():
            self.tmp = {}
            self.set_status(self.stair_no_floor_msg())
            self.draw_overlay()
            return
        if self.stair_drawn_mode():
            self.press_stair_drawn(wx, wy)
            return
        x, y = self.snap(wx, wy)
        self.push_undo()
        rise = self.stair_tool_rise()
        s = add_stair(self.proj, self.story(), self.sidx, x, y, self.stair_kind.get(), self.item_rot,
                      n=stair_steps_for(rise, self.stair_riser_mm()), rise=rise)
        if s["kind"] == "L":
            s["turn"] = "R"
        self.sel = [s["id"]]
        self.changed()

    def press_stair_drawn(self, wx, wy):
        """Straight stairs drawn like a wall: click 1 + 2 = the width of the foot of the stairs, click 3 = how far they run
        (the side of the line you click on is the side they climb to).  Steps, tread and slope are worked out."""
        pt = self.snap(wx, wy, self.tmp.get("sa") if "sb" not in self.tmp else None, getattr(self, "shift", False))
        if "sa" not in self.tmp:
            self.tmp = {"sa": pt}
            self.set_status("Now click the other side of the %s of the stairs (the distance is the width)." %
                            ("top" if self.stair_from_top() else "foot"))
            self.draw_overlay()
            return
        if "sb" not in self.tmp:
            if dist(self.tmp["sa"], pt) < 300:
                self.set_status("The stairs must be at least 0.3 m wide - click further away.")
                return
            self.tmp["sb"] = pt
            self.set_status("Now move out to the side the stairs %s and click where they end - the number of steps adapts "
                            "to the space." % ("go down to" if self.stair_from_top() else "climb to"))
            self.draw_overlay()
            return
        rise = self.stair_tool_rise()
        res = stair_from_width_and_run(self.tmp["sa"], self.tmp["sb"], pt, rise, self.stair_riser_mm(), self.stair_from_top())
        if res is None:
            return
        if res["length"] < 400.0:
            self.set_status("That is too short even for the steepest stairs - drag further out (at least 0.4 m).")
            return
        self.push_undo()
        s = add_stair(self.proj, self.story(), self.sidx, res["x"], res["y"], "straight", res["rot"], round(res["w"], 1),
                      round(res["tread"], 1), res["n"], rise=rise)
        self.sel = [s["id"]]
        self.tmp = {}
        self.changed()
        self.set_status("Stairs: %d steps, riser %d mm, tread %d mm, slope %.0f degrees, %s m long.%s" % (
            res["n"], res["riser"], res["tread"], res["slope"], fmt_m(res["length"]),
            "" if res["ok"] else "  (Steep or shallow for the space you gave - pull out longer, or type the steps in the panel.)"))

    def preview_stair_drawn(self, mx, my, line, label):
        """Rubber band of the width + length stairs tool (drawn with the tag 'ov')."""
        cv = self.cv
        pt = self.snap(mx, my, self.tmp.get("sa") if "sb" not in self.tmp else None, getattr(self, "shift", False))
        px, py = self.w2s(pt[0], pt[1])
        cv.create_oval(px - 4, py - 4, px + 4, py + 4, outline="#ff7a00", tags="ov")
        a = self.tmp.get("sa")
        if a is None:
            label(pt, "click one side of the %s of the stairs" % ("TOP" if self.stair_from_top() else "BOTTOM"))
            return
        b = self.tmp.get("sb")
        if b is None:
            line([a, pt], "#ff7a00", 2, ())
            label(pt, "width %s m: click the other side" % fmt_m(dist(a, pt)))
            return
        line([a, b], "#ff7a00", 3, ())
        rise = self.stair_tool_rise()
        res = stair_from_width_and_run(a, b, pt, rise, self.stair_riser_mm(), self.stair_from_top())
        if res is None:
            label(pt, "move to the side the stairs %s" % ("go down to" if self.stair_from_top() else "climb to"))
            return
        tmp = {"kind": "straight", "x": res["x"], "y": res["y"], "rot": res["rot"], "w": res["w"], "tread": max(res["tread"], 1.0),
               "n": res["n"], "turn": "R", "r": 1000.0, "ang": 22.5, "cw": 0}
        lay = stair_layout(tmp, rise)
        col = "#ff7a00" if res["ok"] else "#d02020"
        poly = stair_to_world(tmp, lay["outline"])
        line(poly + [poly[0]], col, 2, ())
        for p, q in lay["lines"]:
            line(stair_to_world(tmp, [p, q]), col, 1, ())
        label(pt, "%s m long, %d steps, riser %d, tread %d mm, %.0f deg%s" % (
            fmt_m(res["length"]), res["n"], res["riser"], res["tread"], res["slope"], "" if res["ok"] else "  - check!"))

    # ---- tools: roof, dim, text, section ----------------------------------------------------------------------
    def roof_values(self):
        def num(v, dflt):
            try:
                return float(v.get())
            except Exception:
                return dflt
        return self.roof_type.get(), num(self.roof_pitch, 38.0), num(self.roof_eave, 1100.0)

    def press_two_points(self, wx, wy, what):
        pt = self.snap(wx, wy)
        if "a" not in self.tmp:
            self.tmp = {"a": pt}
            self.draw_overlay()
            return
        a = self.tmp["a"]
        if abs(a[0] - pt[0]) < 500 or abs(a[1] - pt[1]) < 500:
            return
        k, pitch, eave = self.roof_values()
        self.push_undo()
        r = add_roof(self.proj, self.story(), (a[0], a[1], pt[0], pt[1]), k, pitch, eave)
        ridge = roof_ridge_height(r)
        if self.story()["height"] < ridge:
            self.story()["height"] = math.ceil(ridge / 100.0) * 100.0
        self.sel = [r["id"]]
        self.tmp = {}
        self.changed()

    def roof_type_changed(self, v):
        """A broken roof wants a shallow upper slope and a low eave (kneewall); other roofs the usual 38 degrees / 1.1 m."""
        if v in MANSARD_TYPES and self.roof_pitch.get() == "38" and self.roof_eave.get() == "1100":
            self.roof_pitch.set("25")
            self.roof_eave.set("600")
        elif v not in MANSARD_TYPES and self.roof_pitch.get() == "25" and self.roof_eave.get() == "600":
            self.roof_pitch.set("38")
            self.roof_eave.set("1100")

    def press_dormer(self, wx, wy):
        story = self.story()
        if roof_at(story, wx, wy) is None:
            self.set_status("Click on the roof: this storey needs a roof (Roof tool) and the dormer goes on top of it.")
            return
        x, y = self.snap(wx, wy)
        if roof_at(story, x, y) is None:
            x, y = wx, wy
        self.push_undo()
        kind = self.dormer_kind.get()
        if kind == "Roof window":
            el = add_rwin(self.proj, story, x, y)
        else:
            try:
                w = max(600.0, float(self.dormer_w.get()))
            except ValueError:
                w = 1800.0
            key = {"Gable dormer": "gable", "Shed dormer": "shed", "Flat dormer": "flat"}.get(kind, "gable")
            el = add_dormer(self.proj, story, x, y, default_dormer_rot(story, x, y), key, w)
        self.sel = [el["id"]]
        self.changed()

    def roof_over_all(self):
        k, pitch, eave = self.roof_values()
        self.push_undo()
        r = auto_roof(self.proj, self.story(), k, pitch, eave)
        if r is None:
            self.set_status("Draw some walls first - the roof is fitted to them.")
            return
        self.sel = [r["id"]]
        self.changed()

    def press_dim(self, wx, wy, shift, what):
        pt = self.snap(wx, wy, self.tmp.get("a"), shift if what == "dim" else False)
        if "a" not in self.tmp:
            self.tmp = {"a": pt}
            self.draw_overlay()
            return
        if "b" not in self.tmp:
            if dist(self.tmp["a"], pt) < 50:
                return
            if what == "section":
                self.push_undo()
                name = chr(ord("A") + len(self.all_sections()) % 26)
                sc = add_section(self.proj, self.story(), self.tmp["a"], pt, name)
                self.sec_id = sc["id"]
                self.sel = [sc["id"]]
                self.tmp = {}
                self.changed()
                self.set_status("Section %s made.  Open the Section view (top right) to look at it." % name)
                return
            self.tmp["b"] = pt
            self.draw_overlay()
            return
        a, b = self.tmp["a"], self.tmp["b"]
        n = v_perp(v_unit(v_sub(b, a)))
        off = v_dot(v_sub(pt, a), n)
        self.push_undo()
        d = add_dim(self.proj, self.story(), a, b, round(off / 50.0) * 50.0)
        self.sel = [d["id"]]
        self.tmp = {}
        self.changed()

    def room_outline_at(self, wx, wy):
        """The outline of the room around a point: a room you made (smallest one), else the space inside closed walls."""
        story = self.story()
        P = (wx, wy)
        best = None
        for r in story["rooms"]:
            pts = [tuple(p) for p in r["pts"]]
            if len(pts) >= 3 and point_in_poly(P, pts):
                a = poly_area(pts)
                if best is None or a < best[0]:
                    best = (a, pts)
        if best:
            return best[1]
        return detect_room(story, wx, wy)

    def press_meas(self, wx, wy, shift):
        """Measure tool: Rectangle (two corners, no walls needed), Room (click inside) or Ruler (two points).  Ghost layer."""
        mode = self.meas_mode.get()
        story = self.story()
        if mode.startswith("Room"):
            pts = self.room_outline_at(wx, wy)
            if not pts or len(pts) < 3:
                self.set_status("No room here: click inside closed walls or a room you made - or use Rectangle (needs no walls).")
                return
            self.push_undo()
            m = add_meas(self.proj, story, "poly", pts=pts)
        else:
            pt = self.snap(wx, wy, self.tmp.get("a") if mode == "Ruler" else None, shift)      # a ruler follows 'Straight'; a rectangle is free
            if "a" not in self.tmp:
                self.tmp = {"a": pt}
                self.draw_overlay()
                return
            a = self.tmp["a"]
            if mode == "Ruler":
                if dist(a, pt) < 50:
                    return
                self.push_undo()
                m = add_meas(self.proj, story, "ruler", a, pt)
            else:
                if abs(pt[0] - a[0]) < 100 or abs(pt[1] - a[1]) < 100:
                    return
                self.push_undo()
                m = add_meas(self.proj, story, "rect", a, pt)
            self.tmp = {}
        self.sel = [m["id"]]
        self.changed()
        self.set_status(meas_label(story, m))

    def open_meas_report(self):
        """The measures as text (this storey or all), to read or copy: 'Bedroom B: 3.60 x 4.20 m  15.1 m²'."""
        top = tk.Toplevel(self.root)
        top.title("Measures list")
        top.geometry("560x420")
        top.transient(self.root)
        allv = tk.BooleanVar(value=False)
        box = tk.Frame(top)
        box.pack(fill="both", expand=True, padx=8, pady=8)
        txt = new_text(box, width=60, height=18, wrap="word", font=("Consolas", 10))
        txt.pack(fill="both", expand=True)

        def fill():
            txt.configure(state="normal")
            txt.delete("1.0", "end")
            rep = meas_report(self.proj, None if allv.get() else self.sidx)
            txt.insert("1.0", rep or "No measures yet.  Use the Measure tool: Rectangle, Room or Ruler.")
            txt.configure(state="disabled")
            self._meas_report_text = rep

        def copy():
            self.root.clipboard_clear()
            self.root.clipboard_append(self._meas_report_text or "")
            self.set_status("Measures copied.")
        bar = tk.Frame(top)
        bar.pack(fill="x", padx=8, pady=(0, 8))
        tk.Checkbutton(bar, text="All storeys", variable=allv, command=fill).pack(side="left")
        tk.Button(bar, text="Copy", width=10, command=copy).pack(side="right", padx=4)
        tk.Button(bar, text="Close", width=10, command=top.destroy).pack(side="right", padx=4)
        fill()
        make_modal(top)
        self.meas_report_top = top

    def press_text(self, wx, wy, ghost=False):
        s = self.ask_text("Ghost note (only you see it, only in the plan)" if ghost else "Text on the plan", "")
        if not s:
            return
        self.push_undo()
        if ghost and not self.v_notes:
            self.show_notes(True)
        t = add_text(self.proj, self.story(), wx, wy, s, 400 if ghost else 200, ghost=ghost)      # ghost notes are bigger: 400 mm
        self.sel = [t["id"]]
        self.changed()

    # ---- previews (drawn with the tag "ov") ----------------------------------------------------------------
    def draw_tool_preview(self):
        cv = self.cv
        t = self.tool
        if not hasattr(self, "mouse") or self.mouse is None:
            return
        mx, my = self.mouse
        story = self.story()
        W = lambda p: self.w2s(p[0], p[1])

        def line(pts, col="#ff7a00", w=1, dash=(4, 3)):
            flat = [c for p in pts for c in W(p)]
            if len(flat) >= 4:
                cv.create_line(flat, fill=col, width=w, dash=dash, tags="ov")

        def label(p, s):
            x, y = W(p)
            cv.create_text(x + 12, y - 12, text=s, anchor="w", fill="#c04000", font=("Segoe UI", 10, "bold"), tags="ov")
        if t == "box" or (self.drag and self.drag.get("type") == "box"):
            x0, y0 = self.drag["start"]
            a, b = W((x0, y0)), W((mx, my))
            cv.create_rectangle(a[0], a[1], b[0], b[1], outline="#3070d0", dash=(3, 3), tags="ov")
            return
        if t == "wall" and self.wall_arc_mode.get():
            if "arc_a" in self.tmp:
                a = self.tmp["arc_a"]
                if "arc_b" not in self.tmp:
                    pt = self.snap(mx, my)
                    line([a, pt], "#ff7a00", 2)
                    label(pt, fmt_m(dist(a, pt)) + " m: click the end")
                else:
                    b = self.tmp["arc_b"]
                    sag = self.arc_sag(a, b, (mx, my))
                    tmpw = {"p": [a[0], a[1], b[0], b[1]], "t": self.wall_thickness(), "sag": sag}
                    line(wall_arc_polyline(tmpw), "#ff7a00", 3, ())
                    line([a, b], "#ff7a00", 1)
                    label((mx, my), "bulge %s m: click to set" % fmt_m(abs(sag)))
            else:
                px, py = W(self.snap(mx, my))
                cv.create_oval(px - 4, py - 4, px + 4, py + 4, outline="#ff7a00", tags="ov")
        elif t == "wall":
            last = self.tmp.get("last")
            pt = self.snap(mx, my, last, getattr(self, "shift", False))
            if last is not None:
                th = self.wall_thickness()
                d = v_unit(v_sub(pt, last))
                n = v_mul(v_perp(d), th / 2.0)
                if dist(pt, last) > 1:
                    poly = [v_add(last, n), v_add(pt, n), v_sub(pt, n), v_sub(last, n)]
                    flat = [c for p in poly for c in W(p)]
                    cv.create_polygon(flat, fill="", outline="#ff7a00", dash=(4, 3), tags="ov")
                txt = self.typed + " mm" if self.typed else fmt_m(dist(pt, last)) + " m"
                label(pt, txt)
            px, py = W(pt)
            cv.create_oval(px - 4, py - 4, px + 4, py + 4, outline="#ff7a00", tags="ov")
        elif t == "room":
            mode = self.room_mode.get()
            if mode == "Rect" and "a" in self.tmp:
                a = self.tmp["a"]
                pt = self.snap(mx, my)
                line([a, (pt[0], a[1]), pt, (a[0], pt[1]), a])
                label(pt, "%s x %s m" % (fmt_m(abs(pt[0] - a[0])), fmt_m(abs(pt[1] - a[1]))))
            elif mode == "Polygon" and self.tmp.get("pts"):
                pts = self.tmp["pts"]
                line(pts + [self.snap(mx, my)])
            elif mode == "In walls":
                px, py = W((mx, my))
                cv.create_text(px + 12, py - 12, text="click inside a closed room", anchor="w", fill="#c04000", tags="ov")
        elif t == "meas":
            mode = self.meas_mode.get()
            if mode.startswith("Room"):
                pts = self.room_outline_at(mx, my)
                if pts and len(pts) >= 3:
                    line(list(pts) + [pts[0]], "#14907f", 2, (4, 3))
                    c = poly_centroid(list(pts))
                    label(c, "%s x %s m  %s" % (fmt_m(meas_size({"kind": "poly", "pts": [list(p) for p in pts]})["w"]),
                                                fmt_m(meas_size({"kind": "poly", "pts": [list(p) for p in pts]})["d"]),
                                                fmt_area(poly_area(list(pts)))))
                else:
                    px, py = W((mx, my))
                    cv.create_text(px + 12, py - 12, text="click inside a room", anchor="w", fill="#c04000", tags="ov")
            elif "a" in self.tmp:
                a = self.tmp["a"]
                pt = self.snap(mx, my, a if mode == "Ruler" else None, getattr(self, "shift", False))
                if mode == "Ruler":
                    line([a, pt], "#14907f", 2, (4, 3))
                    label(pt, fmt_m(dist(a, pt)) + " m")
                else:
                    line([a, (pt[0], a[1]), pt, (a[0], pt[1]), a], "#14907f", 2, (4, 3))
                    label(pt, "%s x %s m" % (fmt_m(abs(pt[0] - a[0])), fmt_m(abs(pt[1] - a[1]))))
        elif t == "opening":
            res = place_opening_on_wall(story, mx, my)
            if res:
                k, w, h, sill = self.opening_values()
                wid, pos, swing, hinge = res
                wall = get_wall(story, wid)
                pos = round(pos / 50.0) * 50.0
                pos = max(w / 2.0, min(wall_length(wall) - w / 2.0, pos))
                c, d = wall_arc_at(wall, pos)
                n = v_perp(d)
                hw, ht = w / 2.0, wall["t"] / 2.0
                poly = [v_add(v_add(c, v_mul(d, -hw)), v_mul(n, -ht)), v_add(v_add(c, v_mul(d, hw)), v_mul(n, -ht)),
                        v_add(v_add(c, v_mul(d, hw)), v_mul(n, ht)), v_add(v_add(c, v_mul(d, -hw)), v_mul(n, ht))]
                flat = [q for p in poly for q in W(p)]
                cv.create_polygon(flat, fill="", outline="#1a8f3a", width=2, tags="ov")
                tip = v_add(c, v_mul(n, swing * (ht + 300)))
                line([c, tip], "#1a8f3a", 1, ())
        elif t in ("item", "stair"):
            if t == "item":
                x, y, rot = self.item_placement(mx, my, getattr(self, "alt", False))
                it = {"x": x, "y": y, "rot": rot, "w": CATALOG[self.item_type]["w"], "d": CATALOG[self.item_type]["d"]}
                poly = item_outline(it)
                line(poly + [poly[0]], "#ff7a00", 2, ())
                b = item_to_world(it, (0, it["d"] / 2.0))
                line([(x, y), b], "#ff7a00", 1, ())
            elif not self.stair_tool_ok():
                label((mx, my), "no floor above - " + ("draw the stairs on the storey BELOW" if self.sidx else "add a storey first") + " (or untick 'Only to next floor')")
            elif self.stair_drawn_mode():
                self.preview_stair_drawn(mx, my, line, label)
            else:
                x, y = self.snap(mx, my)
                tmp = {"kind": self.stair_kind.get(), "x": x, "y": y, "rot": self.item_rot,
                       "w": LIFT_W if self.stair_kind.get() == "lift" else 900.0, "tread": 250.0,
                       "n": stair_steps_for(self.stair_tool_rise(), self.stair_riser_mm()), "turn": "R", "rise": self.stair_tool_rise(),
                       "r": 1000.0, "ang": 22.5, "cw": 0, "dep": LIFT_DEP}
                poly = stair_world_outline(self.proj, self.sidx, tmp)
                line(poly + [poly[0]], "#ff7a00", 2, ())
        elif t == "dormer":
            if roof_at(story, mx, my) is not None:
                x, y = self.snap(mx, my)
                if self.dormer_kind.get() == "Roof window":
                    ol = rwin_outline(story, {"x": x, "y": y, "w": 780.0, "h": 1180.0})
                    if ol:
                        line(ol + [ol[0]], "#1f5fd0", 2, ())
                else:
                    try:
                        w = max(600.0, float(self.dormer_w.get()))
                    except ValueError:
                        w = 1800.0
                    tmp = {"x": x, "y": y, "rot": default_dormer_rot(story, x, y), "w": w, "d": 0.0, "fh": 1300.0, "pitch": 30.0,
                           "kind": "gable", "wt": DORMER_WT}
                    poly = dormer_poly(tmp, dormer_depth(story, tmp))
                    line(poly + [poly[0]], "#7a3a8a", 2, ())
        elif t == "roof" and "a" in self.tmp:
            a = self.tmp["a"]
            pt = self.snap(mx, my)
            line([a, (pt[0], a[1]), pt, (a[0], pt[1]), a], "#8a3a2a", 2)
        elif t in ("dim", "section") and "a" in self.tmp:
            a = self.tmp["a"]
            if "b" not in self.tmp:
                pt = self.snap(mx, my, a, getattr(self, "shift", False) if t == "dim" else False)
                line([a, pt], "#ff7a00", 2)
                label(pt, fmt_m(dist(a, pt)) + " m")
            else:
                b = self.tmp["b"]
                n = v_perp(v_unit(v_sub(b, a)))
                off = v_dot(v_sub((mx, my), a), n)
                line([a, b], "#ff7a00", 1)
                line([v_add(a, v_mul(n, off)), v_add(b, v_mul(n, off))], "#ff7a00", 2, ())


# *************** DEL 62 (cont.) - THE HOUSE PLANNER WINDOW (house size, room list, arrange, fit, build) *****************
# Logic: DEL 53.  The window works on a copy of the layout; 'Build in the drawing' writes walls / rooms / doors / windows.
# ToDo: drag the sub-rooms, snap to the other rooms' walls while dragging with Shift, copy a layout to another storey.
from tkinter import ttk

CELL_COLORS = {"Kitchen": "#f6d6a8", "Living room": "#cfe8c4", "Bedroom": "#c9d8f0", "Bathroom": "#bfe6ec", "WC": "#bfe6ec", "Hall": "#e8e0c0",
               "Corridor": "#ece8e0", "Wardrobe": "#e0cfe8", "Pantry": "#f0d0d0", "Laundry": "#d8e8e0", "Office": "#e8dcc8"}


def parse_size_mm(text):
    """'10 x 29' (metres), '10x29,5 m' or '10000 x 29000' (mm) -> (w, d) in mm, or None."""
    parts = re.split(r"\s*[xX×*]\s*", str(text).strip().replace("m", " "))
    if len(parts) != 2:
        return None
    a, b = to_num(parts[0], -1.0), to_num(parts[1], -1.0)
    if a <= 0 or b <= 0:
        return None
    if a < 200 and b < 200:
        a, b = a * 1000.0, b * 1000.0
    return a, b


class HousePlanner(object):

    def __init__(self, app):
        self.app = app
        self.story = app.story()
        src = self.story.get("layout")
        self.lay = copy.deepcopy(src) if src else lay_new(10000, 29000)
        self.snap_stack = []
        self.sel = None
        self._filling = False
        self.drag = None
        self.top = tk.Toplevel(app.root)
        self.top.title("House planner - %s" % self.story["name"])
        self.top.geometry("1180x820")
        self.top.transient(app.root)
        self.build()
        self.refresh()
        make_modal(self.top, on_escape=self.close)

    # ---- window --------------------------------------------------------------------------------------------------
    def build(self):
        f = self.lay["frame"]
        top = tk.LabelFrame(self.top, text="The house", padx=8, pady=4)
        top.pack(fill="x", padx=8, pady=(8, 2))
        r1 = tk.Frame(top)
        r1.pack(fill="x")
        tk.Label(r1, text="Size (m), width x length:").pack(side="left")
        self.size_var = tk.StringVar(value="%g x %g" % (f["w"] / 1000.0, f["d"] / 1000.0))
        e = new_entry(r1, textvariable=self.size_var, width=14)
        e.pack(side="left", padx=4)
        self.dims_var = tk.StringVar(value="outside" if f["dims"] == "outer" else "inside")
        ttk.Combobox(r1, textvariable=self.dims_var, values=["outside", "inside"], width=8, state="readonly").pack(side="left", padx=4)
        tk.Label(r1, text="  Outer walls mm").pack(side="left")
        self.tout_var = tk.StringVar(value="%g" % f["t_out"])
        new_entry(r1, textvariable=self.tout_var, width=6).pack(side="left", padx=3)
        tk.Label(r1, text="Inner walls mm").pack(side="left")
        self.tin_var = tk.StringVar(value="%g" % f["t_in"])
        new_entry(r1, textvariable=self.tin_var, width=6).pack(side="left", padx=3)
        tk.Button(r1, text="Set house", command=self.set_frame).pack(side="left", padx=8)
        self.frame_info = tk.Label(r1, anchor="w", fg="#444444")
        self.frame_info.pack(side="left", padx=8)
        for w in (e,):
            w.bind("<Return>", lambda ev: self.set_frame())
        r2 = tk.Frame(top)
        r2.pack(fill="x", pady=(4, 0))
        tk.Label(r2, text="Main rooms").pack(side="left")
        self.n_var = tk.StringVar(value=str(len(lay_mains(self.lay)) or 12))
        new_entry(r2, textvariable=self.n_var, width=4).pack(side="left", padx=4)
        tk.Label(r2, text="of which kitchens").pack(side="left")
        self.k_var = tk.StringVar(value=str(sum(1 for c in lay_mains(self.lay) if c["type"] == "Kitchen") or 3))
        new_entry(r2, textvariable=self.k_var, width=4).pack(side="left", padx=4)
        tk.Button(r2, text="Make the room list", command=self.make_list).pack(side="left", padx=6)
        o = self.lay["opts"]
        self.cor_var = tk.BooleanVar(value=o.get("corridor", True))
        self.door_var = tk.BooleanVar(value=o.get("doors", True))
        self.win_var = tk.BooleanVar(value=o.get("windows", True))
        tk.Checkbutton(r2, text="Corridor between two rows", variable=self.cor_var, command=self.opts_changed).pack(side="left", padx=(16, 2))
        tk.Label(r2, text="width mm").pack(side="left")
        self.corw_var = tk.StringVar(value="%g" % o.get("corridor_w", 1200.0))
        ce = new_entry(r2, textvariable=self.corw_var, width=6)
        ce.pack(side="left", padx=3)
        ce.bind("<Return>", lambda ev: self.opts_changed())
        tk.Checkbutton(r2, text="Doors", variable=self.door_var, command=self.opts_changed).pack(side="left", padx=(16, 2))
        tk.Checkbutton(r2, text="Windows", variable=self.win_var, command=self.opts_changed).pack(side="left", padx=2)
        mid = tk.Frame(self.top)
        mid.pack(fill="both", expand=True, padx=8, pady=4)
        self.cv = tk.Canvas(mid, width=520, height=560, bg="#fbfbf7", highlightthickness=1, highlightbackground="#999999")
        self.cv.pack(side="left", fill="both", expand=True)
        self.cv.bind("<ButtonPress-1>", self.cv_press)
        self.cv.bind("<B1-Motion>", self.cv_drag)
        self.cv.bind("<ButtonRelease-1>", self.cv_release)
        self.cv.bind("<Configure>", lambda e: self.draw())
        right = tk.Frame(mid)
        right.pack(side="left", fill="y", padx=(8, 0))
        fr = tk.Frame(right)
        fr.pack(fill="both", expand=True)
        sb = tk.Scrollbar(fr)
        sb.pack(side="right", fill="y")
        self.tv = ttk.Treeview(fr, columns=("type", "size", "area"), height=9, yscrollcommand=sb.set, selectmode="browse")
        self.tv.heading("#0", text="Room")
        self.tv.column("#0", width=190)
        for c, h, w in (("type", "Type", 90), ("size", "Inside mm", 110), ("area", "m2", 55)):
            self.tv.heading(c, text=h)
            self.tv.column(c, width=w, anchor="w")
        self.tv.pack(side="left", fill="both", expand=True)
        sb.configure(command=self.tv.yview)
        self.tv.bind("<<TreeviewSelect>>", self.tree_select)
        form = tk.LabelFrame(right, text="Selected room", padx=6, pady=4)
        form.pack(fill="x", pady=(6, 0))
        self.vars = {}
        rows = [("name", "Name"), ("type", "Type"), ("w", "Width mm (along x)"), ("d", "Depth mm (along y)"), ("x", "Position x mm"),
                ("y", "Position y mm"), ("parent", "Part of"), ("corner", "Corner of its sub-rooms")]
        for i, (k, lab) in enumerate(rows):
            tk.Label(form, text=lab, anchor="w").grid(row=i, column=0, sticky="w", pady=1)
            v = tk.StringVar()
            self.vars[k] = v
            if k == "type":
                w = ttk.Combobox(form, textvariable=v, values=CELL_TYPES, width=18)
            elif k == "parent":
                w = ttk.Combobox(form, textvariable=v, values=["(main room)"], width=18, state="readonly")
                self.parent_cb = w
            elif k == "corner":
                w = ttk.Combobox(form, textvariable=v, values=["auto", "SW", "SE", "NW", "NE"], width=8, state="readonly")
            else:
                w = new_entry(form, textvariable=v, width=20)
            w.grid(row=i, column=1, sticky="w", padx=4, pady=1)
            if isinstance(w, tk.Entry):
                w.bind("<Return>", lambda ev: self.commit())
                w.bind("<FocusOut>", lambda ev: self.commit())
            else:
                w.bind("<<ComboboxSelected>>", lambda ev: self.commit())
        self.rot_label = tk.Label(form, text="", anchor="w")
        self.rot_label.grid(row=len(rows), column=0, columnspan=2, sticky="w")
        r0 = len(rows) + 1                                    # the room's SHAPE: rectangle / L / T / U / free outline (fixed rows: nothing is hidden)
        tk.Label(form, text="Shape", anchor="w").grid(row=r0, column=0, sticky="w", pady=1)
        self.shape_var = tk.StringVar(value=SHAPE_NAMES["rect"])
        self.shape_cb = ttk.Combobox(form, textvariable=self.shape_var, values=[SHAPE_NAMES[s] for s in ROOM_SHAPES], width=26, state="readonly")
        self.shape_cb.grid(row=r0, column=1, sticky="w", padx=4, pady=1)
        self.shape_cb.bind("<<ComboboxSelected>>", lambda ev: self.shape_changed())
        self.sp_vars, self.sp_labels, self.sp_entries = [], [], []
        for i in range(2):
            lab = tk.Label(form, text="", anchor="w")
            lab.grid(row=r0 + 1 + i, column=0, sticky="w", pady=1)
            v = tk.StringVar()
            e = new_entry(form, textvariable=v, width=20)
            e.grid(row=r0 + 1 + i, column=1, sticky="w", padx=4, pady=1)
            e.bind("<Return>", lambda ev: self.shape_params_changed())
            e.bind("<FocusOut>", lambda ev: self.shape_params_changed())
            self.sp_vars.append(v)
            self.sp_labels.append(lab)
            self.sp_entries.append(e)
        b1 = tk.Frame(right)
        b1.pack(fill="x", pady=4)
        tk.Button(b1, text="Rotate 90°", command=self.rotate).pack(side="left", padx=2)
        tk.Button(b1, text="Add room", command=self.add_room).pack(side="left", padx=2)
        self.sub_var = tk.StringVar(value="Hall")
        ttk.Combobox(b1, textvariable=self.sub_var, values=list(SUB_PRESETS), width=9, state="readonly").pack(side="left", padx=(8, 0))
        tk.Button(b1, text="Add as sub-room", command=self.add_sub).pack(side="left", padx=2)
        tk.Button(b1, text="Delete", command=self.delete).pack(side="left", padx=8)
        b2 = tk.Frame(right)
        b2.pack(fill="x")
        self.corners_btn = tk.Button(b2, text="Edit corners...", command=self.edit_corners)
        self.corners_btn.pack(side="left", padx=2)
        self.mirror_btn = tk.Button(b2, text="Mirror", command=self.mirror)
        self.mirror_btn.pack(side="left", padx=2)
        tk.Label(b2, fg="#555555", anchor="w", text="  L / T / U / free: drag the white squares in the picture").pack(side="left")
        bar = tk.LabelFrame(self.top, text="Fit", padx=6, pady=4)
        bar.pack(fill="x", padx=8, pady=2)
        for text, cmd in (("Arrange: rooms fill the house", lambda: self.arrange(True)), ("Arrange: keep the room sizes", lambda: self.arrange(False)),
                          ("Fit rooms to the house", self.fit_rooms), ("Fit house to the rooms", self.fit_frame), ("Undo", self.undo)):
            tk.Button(bar, text=text, command=cmd, padx=6).pack(side="left", padx=4)
        self.status = tk.Label(self.top, anchor="w", justify="left", wraplength=1140, fg="#206020")
        self.status.pack(fill="x", padx=10, pady=2)
        self.notes = tk.Label(self.top, anchor="w", justify="left", wraplength=1140, fg="#884400")
        self.notes.pack(fill="x", padx=10)
        end = tk.Frame(self.top)
        end.pack(fill="x", padx=8, pady=8)
        tk.Button(end, text="Build in the drawing", command=self.build_it, padx=10, bg="#cfe8c4").pack(side="left")
        tk.Label(end, text="  (replaces what the planner built before; your own walls, items and doors stay.  Ctrl+Z in the main window undoes it.)",
                 fg="#555555").pack(side="left")
        tk.Button(end, text="Close", command=self.close, padx=10).pack(side="right")

    # ---- state ---------------------------------------------------------------------------------------------------
    def snapshot(self):
        self.snap_stack.append(json.dumps(self.lay))
        if len(self.snap_stack) > 60:
            self.snap_stack.pop(0)

    def undo(self):
        if self.snap_stack:
            self.lay = json.loads(self.snap_stack.pop())
            self.sel = self.sel if lay_get(self.lay, self.sel) else None
            self.refresh()

    def info(self, text, notes=""):
        self.status.configure(text=text)
        self.notes.configure(text=notes)

    def refresh(self):
        f = self.lay["frame"]
        wo, do = lay_outer(self.lay)
        ix0, iy0, ix1, iy1 = lay_inner(self.lay)
        self.frame_info.configure(text="outside %.2f x %.2f m, inside %.2f x %.2f m" % (wo / 1000, do / 1000, (ix1 - ix0) / 1000, (iy1 - iy0) / 1000))
        ok, txt = lay_status(self.lay)
        self.status.configure(text=txt, fg="#206020" if ok else "#aa2222")
        self.fill_tree()
        self.fill_form()
        self.draw()

    def fill_tree(self):
        self.tv.delete(*self.tv.get_children())
        shapes = {s["cell"]: s for s in lay_shapes(self.lay)}
        for c in lay_mains(self.lay):
            sh = shapes.get(c["id"])
            area = poly_area(sh["poly"]) / 1e6 if sh else 0.0
            ex, ey = cell_dims(c)
            self.tv.insert("", "end", iid=str(c["id"]), text=c["name"] + ("  (auto)" if c.get("auto") else "") +
                           ("" if cell_shape(c) == "rect" else "  [%s]" % ("free" if cell_shape(c) == "free" else cell_shape(c))),
                           values=(c["type"], "%d x %d" % (ex, ey), "%.1f" % area), open=True)
            for s in lay_subs(self.lay, c):
                sh = shapes.get(s["id"])
                self.tv.insert(str(c["id"]), "end", iid=str(s["id"]), text=s["name"],
                               values=(s["type"], "%d x %d" % (s["w"], s["d"]), "%.1f" % (poly_area(sh["poly"]) / 1e6 if sh else 0.0)))
        if self.sel is not None and self.tv.exists(str(self.sel)):
            self.tv.selection_set(str(self.sel))

    def fill_form(self):
        c = lay_get(self.lay, self.sel) if self.sel is not None else None
        self._filling = True
        mains = [m for m in lay_mains(self.lay) if not m.get("auto")]
        self.parent_cb.configure(values=["(main room)"] + [m["name"] for m in mains if c is None or m["id"] != c["id"]])
        for k, v in self.vars.items():
            if c is None:
                v.set("")
            elif k == "parent":
                p = lay_get(self.lay, c["parent"]) if c["parent"] else None
                v.set(p["name"] if p else "(main room)")
            elif k in ("x", "y"):
                v.set("%g" % round(c[k], 1) if c["parent"] is None else "")
            elif k == "corner":
                v.set(c.get("corner", "auto"))
            elif k in ("w", "d"):
                v.set("%g" % round(c[k], 1))
            else:
                v.set(str(c.get(k, "")))
        self.rot_label.configure(text="" if c is None else ("Turned %d°" % c["rot"] if c["parent"] is None else "Sub-room"))
        main = c is not None and c["parent"] is None and not c.get("auto")
        shp = cell_shape(c) if c is not None else "rect"
        self.shape_var.set(SHAPE_NAMES[shp])
        self.shape_cb.configure(state="readonly" if main else "disabled")
        labs = SHAPE_PARAM_LABELS.get(shp, ("", ""))
        ab = lay_shape_mm(c) if (c is not None and shp in SHAPE_PARAM_LABELS) else (0, 0)
        for i in range(2):
            self.sp_labels[i].configure(text=labs[i])
            self.sp_vars[i].set("%g" % round(ab[i]) if labs[i] else "")
            self.sp_entries[i].configure(state="normal" if (main and labs[i]) else "disabled")
        self.corners_btn.configure(state="normal" if main else "disabled")
        self.mirror_btn.configure(state="normal" if main else "disabled")
        self._filling = False

    def commit(self):
        if self._filling or self.sel is None:
            return
        c = lay_get(self.lay, self.sel)
        if c is None:
            return
        before = json.dumps(self.lay)
        v = {k: x.get().strip() for k, x in self.vars.items()}
        c["name"] = v["name"] or c["name"]
        c["type"] = v["type"] or c["type"]
        for k in ("w", "d"):
            n = to_num(v[k], 0.0)
            if n >= 300:
                c[k] = n
        if c["parent"] is None:
            for k in ("x", "y"):
                if v[k] != "":
                    c[k] = to_num(v[k], c[k])
            c["corner"] = v["corner"] or "auto"
            p = next((m for m in lay_mains(self.lay) if m["name"] == v["parent"]), None)
            if p is not None and not c.get("auto") and not lay_subs(self.lay, c):     # becomes a sub-room of p
                if cell_shape(c) != "rect" or cell_shape(p) != "rect":
                    self.notes.configure(text="A room with an L / T / U / free shape cannot be a sub-room, and cannot have sub-rooms.")
                else:
                    c["parent"] = p["id"]
        else:
            p = next((m for m in lay_mains(self.lay) if m["name"] == v["parent"]), None)
            c["parent"] = p["id"] if p is not None else None
        if json.dumps(self.lay) != before:
            self.snap_stack.append(before)
            self.refresh()

    # ---- commands ----------------------------------------------------------------------------------------------
    def set_frame(self):
        sz = parse_size_mm(self.size_var.get())
        if sz is None:
            self.info("Type the size like  10 x 29  (metres, width x length).")
            return
        self.snapshot()
        f = self.lay["frame"]
        f["w"], f["d"] = sz
        f["dims"] = "outer" if self.dims_var.get() == "outside" else "inner"
        f["t_out"] = max(50.0, to_num(self.tout_var.get(), 250.0))
        f["t_in"] = max(30.0, to_num(self.tin_var.get(), 100.0))
        self.refresh()

    def opts_changed(self):
        o = self.lay["opts"]
        o["corridor"], o["doors"], o["windows"] = self.cor_var.get(), self.door_var.get(), self.win_var.get()
        o["corridor_w"] = max(800.0, to_num(self.corw_var.get(), 1200.0))

    def make_list(self):
        if lay_mains(self.lay) and not messagebox.askyesno(APP_TITLE, "Replace the room list with a new one?", parent=self.top):
            return
        self.snapshot()
        lay_default_rooms(self.lay, int(to_num(self.n_var.get(), 12)), int(to_num(self.k_var.get(), 3)))
        notes = lay_arrange(self.lay, True)
        self.sel = None
        self.refresh()
        self.notes.configure(text="  ".join(notes))

    def arrange(self, scaled):
        if not lay_mains(self.lay):
            self.info("Make the room list first.")
            return
        self.opts_changed()
        self.snapshot()
        notes = lay_arrange(self.lay, scaled)
        self.refresh()
        self.notes.configure(text="  ".join(notes))

    def fit_rooms(self):
        self.snapshot()
        notes = lay_fit_rooms(self.lay) or []
        self.refresh()
        self.notes.configure(text="  ".join(notes))

    def fit_frame(self):
        self.snapshot()
        lay_fit_frame(self.lay)
        f = self.lay["frame"]
        self.size_var.set("%g x %g" % (f["w"] / 1000.0, f["d"] / 1000.0))
        self.refresh()

    def new_name(self, base):
        names = {c["name"] for c in self.lay["cells"]}
        i = 1
        while "%s %d" % (base, i) in names:
            i += 1
        return base if base not in names else "%s %d" % (base, i)

    def add_room(self):
        self.snapshot()
        ix0, iy0, _, _ = lay_inner(self.lay)
        c = lay_cell(self.lay, self.new_name("Room"), "Room", x=ix0, y=iy0)
        self.sel = c["id"]
        self.refresh()

    def add_sub(self):
        c = lay_get(self.lay, self.sel) if self.sel is not None else None
        if c is None:
            self.info("Select the main room first, then add the hall / toilet / wardrobe to it.")
            return
        if c["parent"] is not None:
            c = lay_get(self.lay, c["parent"])
        if cell_shape(c) != "rect":
            self.info("%s has an L / T / U / free shape: sub-rooms are carved from a rectangle's corner.  Make it a rectangle first, "
                      "or add a small room next to it (the empty notch of an L is a good place)." % c["name"])
            return
        name = self.sub_var.get()
        w, d = SUB_PRESETS.get(name, (1500, 2000))
        self.snapshot()
        typ = {"Toilet": "WC"}.get(name, name)
        s = lay_cell(self.lay, self.new_name(name), typ, w, d, parent=c["id"])
        self.sel = s["id"]
        self.refresh()

    def rotate(self):
        c = lay_get(self.lay, self.sel) if self.sel is not None else None
        if c is None:
            return
        if c["parent"] is not None:
            c = lay_get(self.lay, c["parent"])
        self.snapshot()
        lay_rotate(c)
        self.refresh()

    # ---- room shapes ---------------------------------------------------------------------------------------------------
    def main_sel(self):
        """The selected main room (not a sub-room, not the automatic corridor), or None."""
        c = lay_get(self.lay, self.sel) if self.sel is not None else None
        return c if (c is not None and c["parent"] is None and not c.get("auto")) else None

    def shape_changed(self):
        if self._filling:
            return
        c = self.main_sel()
        if c is None:
            self.fill_form()
            return
        name = self.shape_var.get()
        shape = next((k for k, v in SHAPE_NAMES.items() if v == name), "rect")
        if shape == cell_shape(c):
            return
        before = json.dumps(self.lay)
        why = lay_set_shape(self.lay, c, shape)
        if why:
            self.fill_form()
            self.notes.configure(text=why)
            return
        self.snap_stack.append(before)
        self.refresh()
        self.notes.configure(text="" if shape == "rect" else
                             "%s: the empty part of its box is not a room.  Drag the white squares to reshape it, or 'Edit corners...'." % SHAPE_NAMES[shape])

    def shape_params_changed(self):
        if self._filling:
            return
        c = self.main_sel()
        if c is None or cell_shape(c) not in SHAPE_PARAM_LABELS:
            return
        a, b = to_num(self.sp_vars[0].get(), 0.0), to_num(self.sp_vars[1].get(), 0.0)
        cur = lay_shape_mm(c)
        if a < 100 or b < 100 or (abs(a - cur[0]) < 1.0 and abs(b - cur[1]) < 1.0):
            return
        before = json.dumps(self.lay)
        lay_set_shape(self.lay, c, cell_shape(c), a, b)
        if json.dumps(self.lay) != before:
            self.snap_stack.append(before)
            self.refresh()

    def edit_corners(self):
        c = self.main_sel()
        if c is None:
            self.info("Select a main room first.")
            return
        if lay_subs(self.lay, c):
            self.info("%s has sub-rooms: delete them first, then it can have its own outline." % c["name"])
            return

        def validate(vals):
            return lay_set_points_text(self.lay, copy.deepcopy(c), vals["pts"]) or None
        hint = ("One corner per line: x, y in mm, measured from the lower left of the room's box BEFORE the room is turned.  "
                "Only horizontal and vertical edges.  Example, an L:  0,0 / 5000,0 / 5000,2000 / 3000,2000 / 3000,4500 / 0,4500.  "
                "The room's width and depth follow the outline.")
        v = ask_form(self.top, "Corners of %s" % c["name"], [{"key": "pts", "label": "Corners (mm)", "kind": "text", "width": 30, "height": 10}],
                     {"pts": shape_points_text(c)}, validate, hint)
        if v:
            self.snapshot()
            lay_set_points_text(self.lay, c, v["pts"])
            self.refresh()

    def mirror(self):
        c = self.main_sel()
        if c is None:
            self.info("Select a main room first.")
            return
        if lay_subs(self.lay, c):
            self.info("%s has sub-rooms: mirroring is for rooms without them." % c["name"])
            return
        self.snapshot()
        lay_mirror(c)
        self.refresh()

    def delete(self):
        c = lay_get(self.lay, self.sel) if self.sel is not None else None
        if c is None:
            return
        self.snapshot()
        lay_remove(self.lay, c["id"])
        self.sel = None
        self.refresh()

    def tree_select(self, ev=None):
        s = self.tv.selection()
        self.sel = int(s[0]) if s else None
        self.fill_form()
        self.draw()

    def build_it(self):
        self.opts_changed()
        if not lay_mains(self.lay):
            self.info("Nothing to build: make the room list first.")
            return
        ok, txt = lay_status(self.lay)
        if not ok and not messagebox.askyesno(APP_TITLE, txt + "\n\nBuild anyway?", parent=self.top):
            return
        app = self.app
        had = any(w.get("gen") for w in self.story["walls"])
        if had and not messagebox.askyesno(APP_TITLE, "The walls, rooms, doors and windows the planner built before will be replaced.\nContinue?",
                                           parent=self.top):
            return
        app.push_undo()
        rep = lay_apply(app.proj, self.story, copy.deepcopy(self.lay))
        app.sel = []
        app.rev += 1
        app.changed()
        app.fit_view()
        app.redraw()
        self.info("Built: %(walls)d walls, %(rooms)d rooms, %(doors)d doors, %(windows)d windows.  Edit anything in the drawing as usual; "
                  "change the plan here and build again to replace it." % rep)

    def close(self):
        if lay_mains(self.lay):
            self.story["layout"] = copy.deepcopy(self.lay)
            self.app.dirty = True
        self.top.destroy()

    # ---- canvas ----------------------------------------------------------------------------------------------------
    def view(self):
        wo, do = lay_outer(self.lay)
        cw, ch = max(200, self.cv.winfo_width()), max(200, self.cv.winfo_height())
        s = min((cw - 30) / wo, (ch - 30) / do)
        return s, (cw - wo * s) / 2.0, (ch + do * s) / 2.0

    def to_cv(self, x, y):
        s, ox, oy = self.view()
        return ox + x * s, oy - y * s

    def from_cv(self, px, py):
        s, ox, oy = self.view()
        return (px - ox) / s, (oy - py) / s

    def draw(self):
        cv = self.cv
        cv.delete("all")
        wo, do = lay_outer(self.lay)
        to = self.lay["frame"]["t_out"]
        ix0, iy0, ix1, iy1 = lay_inner(self.lay)
        a, b = self.to_cv(0, do), self.to_cv(wo, 0)
        cv.create_rectangle(a[0], a[1], b[0], b[1], fill="#555555", outline="")
        a, b = self.to_cv(ix0, iy1), self.to_cv(ix1, iy0)
        cv.create_rectangle(a[0], a[1], b[0], b[1], fill="#ffffff", outline="#999999")
        for sh in lay_shapes(self.lay):
            pts = []
            for x, y in sh["poly"]:
                pts += list(self.to_cv(x, y))
            sel = sh["cell"] == self.sel or (self.sel is not None and sh["parent"] == self.sel)
            cv.create_polygon(pts, fill=CELL_COLORS.get(sh["type"], "#e8e8e8"), outline="#cc3300" if sel else "#333333", width=3 if sel else 1)
            xs = [p[0] for p in sh["poly"]]
            ys = [p[1] for p in sh["poly"]]
            lx, ly = label_point(sh["poly"])                         # inside the room even for an L / T / U
            cx, cy = self.to_cv(lx, ly)
            area = poly_area(sh["poly"]) / 1e6
            wpx = (max(xs) - min(xs)) * self.view()[0]
            if wpx > 44:
                cv.create_text(cx, cy, text="%s\n%.1f m2" % (sh["name"], area), font=("Segoe UI", 8 if wpx > 70 else 7), justify="center")
        for kind, idx, (hx, hy) in self.handles():
            px, py = self.to_cv(hx, hy)
            r = 5 if kind == "v" else 4
            cv.create_rectangle(px - r, py - r, px + r, py + r, fill="#ffffff" if kind == "v" else "#ffe9b0", outline="#cc3300", width=2)
        cv.create_text(8, 8, anchor="nw", fill="#555555", font=("Segoe UI", 8),
                       text="Drag a room to move it.  x = width (across), y = length (up).  Walls are not drawn here - 'Build in the drawing'.")

    def handles(self):
        """[(kind, index, (x, y))] - the squares of the selected L / T / U / free room: 'v' = corner, 'e' = middle of an edge."""
        c = self.main_sel()
        if c is None or cell_shape(c) == "rect" or lay_subs(self.lay, c):
            return []
        w = cell_world_outline(self.lay, c)
        out = [("v", i, p) for i, p in enumerate(w)]
        out += [("e", i, ((w[i][0] + w[(i + 1) % len(w)][0]) / 2.0, (w[i][1] + w[(i + 1) % len(w)][1]) / 2.0)) for i in range(len(w))]
        return out

    def handle_at(self, px, py):
        best = None
        for kind, idx, (hx, hy) in self.handles():
            qx, qy = self.to_cv(hx, hy)
            d = max(abs(qx - px), abs(qy - py))
            if d <= 8 and (best is None or d < best[0] or (d == best[0] and kind == "v")):
                best = (d, kind, idx)
        return best[1:] if best else None

    def cell_at(self, x, y):
        best = None
        for sh in lay_shapes(self.lay):
            xs = [p[0] for p in sh["poly"]]
            ys = [p[1] for p in sh["poly"]]
            if min(xs) <= x <= max(xs) and min(ys) <= y <= max(ys) and point_in_poly((x, y), sh["poly"]):
                if best is None or sh["sub"]:
                    best = sh
        return best

    def cv_press(self, ev):
        x, y = self.from_cv(ev.x, ev.y)
        hd = self.handle_at(ev.x, ev.y)
        if hd is not None:                                           # a white square of the selected shaped room
            self.drag = {"handle": hd, "cell": self.sel, "snap": json.dumps(self.lay), "moved": False}
            return
        sh = self.cell_at(x, y)
        self.sel = sh["cell"] if sh else None
        self.drag = None
        if sh:
            c = lay_get(self.lay, sh["parent"] if sh["sub"] else sh["cell"])
            if c is not None and not c.get("auto"):
                self.drag = {"cell": c["id"], "dx": x - c["x"], "dy": y - c["y"], "snap": json.dumps(self.lay), "moved": False}
        self.fill_tree()
        self.fill_form()
        self.draw()

    def drag_handle(self, x, y):
        """Moves the grabbed corner / edge of a shaped room to (x, y); snaps to the frame, to other rooms' edges (a wall apart) and to 50 mm."""
        c = lay_get(self.lay, self.drag["cell"])
        t = self.lay["frame"]["t_in"]
        thr = 160.0
        ix0, iy0, ix1, iy1 = lay_inner(self.lay)
        xs, ys = [ix0, ix1], [iy0, iy1]
        for o in lay_mains(self.lay):
            if o["id"] == c["id"]:
                continue
            for (rx0, ry0, rx1, ry1) in _cell_rects(self.lay, o):
                xs += [rx1 + t, rx0 - t, rx0, rx1]
                ys += [ry1 + t, ry0 - t, ry0, ry1]
        sx = min(xs, key=lambda v: abs(v - x))
        sy = min(ys, key=lambda v: abs(v - y))
        nx = sx if abs(sx - x) < thr else round(x / 50.0) * 50.0
        ny = sy if abs(sy - y) < thr else round(y / 50.0) * 50.0
        kind, idx = self.drag["handle"]
        before = json.dumps(self.lay)
        why = lay_drag_outline(self.lay, c, kind, idx, (nx, ny))
        if why:
            self.notes.configure(text=why)
        elif json.dumps(self.lay) != before:
            self.drag["moved"] = True
            self.notes.configure(text="")
            self.draw()

    def cv_drag(self, ev):
        if not self.drag:
            return
        if "handle" in self.drag:
            self.drag_handle(*self.from_cv(ev.x, ev.y))
            return
        c = lay_get(self.lay, self.drag["cell"])
        x, y = self.from_cv(ev.x, ev.y)
        nx, ny = x - self.drag["dx"], y - self.drag["dy"]
        ex, ey = cell_dims(c)
        t = self.lay["frame"]["t_in"]
        thr = 160.0
        ix0, iy0, ix1, iy1 = lay_inner(self.lay)
        xs = [ix0, ix1 - ex]
        ys = [iy0, iy1 - ey]
        for o in lay_mains(self.lay):
            if o["id"] == c["id"]:
                continue
            ox, oy = cell_dims(o)
            xs += [o["x"] + ox + t, o["x"] - t - ex, o["x"], o["x"] + ox - ex]
            ys += [o["y"] + oy + t, o["y"] - t - ey, o["y"], o["y"] + oy - ey]
        sx = min(xs, key=lambda v: abs(v - nx))
        sy = min(ys, key=lambda v: abs(v - ny))
        nx = sx if abs(sx - nx) < thr else round(nx / 50.0) * 50.0
        ny = sy if abs(sy - ny) < thr else round(ny / 50.0) * 50.0
        if (nx, ny) != (c["x"], c["y"]):
            c["x"], c["y"] = nx, ny
            self.drag["moved"] = True
            self.draw()

    def cv_release(self, ev):
        if self.drag and self.drag["moved"]:
            self.snap_stack.append(self.drag["snap"])
            self.refresh()
        self.drag = None


# *************** DEL 62 - PROPERTIES PANEL, STOREY COMMANDS, DIALOGS (help, export, report) *****************
# PropsMixin belongs to the ArchApp class (DEL 63).
# ToDo: change the type of an existing item in the panel; edit several selected items at once.

HELP_TEXT = """ARCHITECT - quick help

START HERE: THE HOUSE PLANNER (House menu > House planner)
  1. Type the size of the house, e.g. 10 x 29 (metres), choose whether that is the OUTSIDE or the INSIDE size, set the
     outer and inner wall thickness (mm) and press 'Set house'.
  2. Say how many main rooms (e.g. 12) and how many of them are kitchens (e.g. 3) and press 'Make the room list'.  You get
     a list: per unit a kitchen, a living room, a bathroom and bedrooms.  Rename, resize, add, delete as you like.
  3. Split a room into smaller units: select the room, choose Hall / Toilet / Wardrobe / Bathroom / Pantry / Laundry and
     press 'Add as sub-room'.  The small unit is cut from a corner of the room (the room becomes L-shaped).  Give it its
     size and corner in the form.  Built-in wardrobes you can also place yourself later with the Items tool.
  4. Place the rooms in the frame: 'Arrange' fills the house (room sizes are used as weights) or keeps your room sizes
     (a corridor can be put between two rows).  Drag a room in the picture to move it - it snaps to the frame and to its
     neighbours.  Rotate 90 turns the selected room.  Width, depth, X, Y, name and type can be changed any time.
  5. FIT: the rooms are INSIDE sizes and the walls take space, so rooms and frame rarely agree.  'Fit rooms to the house'
     shrinks / stretches the rooms a little so they fit inside the frame (the house stays as it is).  'Fit house to the
     rooms' does the opposite: when your room sizes are correct the OUTER size of the house changes.  The status line
     says which one you need, and Undo takes the last fit back.
  6. 'Build in the drawing' makes outer walls, inner walls, rooms, doors and windows on the current storey.  Run it again
     after changes: only what the planner made earlier is replaced - walls, doors and items you drew yourself stay.
  7. ROOM SHAPES: select a main room and pick its Shape: Rectangle, L-shape, T-shape, U-shape or Free outline.  For L / T / U
     the two sizes (notch width / depth, stem width / bar depth) are typed in mm.  White squares appear on the selected
     L / T / U / free room: drag a square at a corner to move the corner, a yellow one in the middle of an edge to push the
     edge in or out (the corners always stay 90 degrees; the room becomes a 'free outline').  'Edit corners...' lists the
     corners as x, y in mm (one per line) so you can type any outline with 90 degree corners; 'Mirror' flips a free room.
     Rotate 90 turns the whole room.  Arrange, Fit and Build keep the shapes, and the room's walls follow its outline.
  Limits: rooms have only horizontal / vertical edges (no slanted or curved room walls in the planner; draw those afterwards
  with the wall tool).  A room with an L / T / U / free shape cannot have sub-rooms (they are carved from a rectangle's
  corner).  The empty notch of an L / T / U is NOT a room: it gets only the room's own walls, so put a small room in it
  (drag it there, it may sit in the notch) or leave it as a niche.  Rotation is in 90 degree steps and the arrangement has
  one or two rows of rooms.  After building, everything is ordinary drawing and can be edited with the other tools.

DRAWING (plan view)
  Wall tool     click corners; type a length in mm + Enter; 'Straight' is on (level / plumb lines, Shift = free while held;
                 untick it for slanted walls); right click / Esc ends; click the first
                 point again to close a loop.  Corners are mitred automatically.
  Room tool      Rect (two clicks, "also build walls" makes walls round it), Polygon, or "In walls" = click inside a closed
                 set of walls and the room outline is found for you.  Area is printed in the room.
  Door / Window  click on a wall.  Kinds: single door, double door, sliding door, passage, window.  The side you click
                 on is the side the door opens to; F flips the swing, H flips the hinge.
  Items          pick one in the list on the left (toilet, shower, bath, beds, sofas, tables, wardrobes, bookshelves,
                 pantry, kitchen units, outlets, switches, lights ...), click to place.  Wall-bound things snap back-to-wall
                 (hold Alt to switch off).  TURNING: before you click, the arrow keys Left / Right turn the thing 15 degrees
                 (Shift = 1 degree) and R turns it 90.  Afterwards: Esc, select the thing, and use the same keys, the
                 'Turn left / Turn right' buttons in the bar, the round orange 'turn' knob (drag it) or the Rotation field
                 on the right.  Up / Down (or Ctrl + arrows) move the selected thing.
  Stairs         STRAIGHT: click one side of the BOTTOM of the stairs (menu 'Start at' = top: of the TOP), click the other
                 side (that is the width), then move out and click where they end.  The number of steps is fitted to the
                 space you pull out (riser 'auto'; type a riser height in mm to fix it); tread, slope and length are shown
                 while you move (red = steep / shallow).  Untick
                 'Width, then length' to place them with one click instead.  L-shaped (with landing), spiral and LIFT
                 (elevator shaft, default 1.1 x 1.4 m, glass walls in 3D, hole in the floor above) are placed with one click.
                 ONE FLOOR AT A TIME: stairs belong to the storey they start on and climb up to the next floor (a storey
                 without a floor above refuses them - draw them on the storey below).  For an exception untick 'Only to next
                 floor' in the bar and type the height in 'Own rise' (mm); the rise can also be changed in 'Edit parts...'.
                 Stairs that were drawn on the top storey get a button 'Move to storey below'.
                 The stairs and lifts that come UP from the storey below stay visible (dashed, with 'DN') even when the grey
                 floor below is switched off - tick box 'Stairs / lift from below' (on by default) - so you do not build a
                 kitchen on top of a staircase.
                 The steps are computed from the floor-to-floor height.  On the storey above the opening is cut in the
                 floor when the room outline goes round the stairs / lift.
                 EDIT PARTS: select the stairs and press 'Edit parts...' (or double-click them): number of steps, tread, run
                 length, width - and for straight stairs the SPACE UNDER THEM: closed block, open, or a CUPBOARD cut into
                 sections (shelves, wardrobe with a hanging rail, drawers, empty), each with the front closed, open or open
                 in the middle, doors on the right or left side.  Type a width (mm) for a section at the right of its row - the sections
                 without one ('auto') share the rest equally; 'Equal widths' clears them.  Every section shows its width (w), height (h) and
                 the depth is the width of the stairs.  Tick 'Bespoke' for a made-to-measure cupboard: boards, back and doors
                 follow the steps, there are NO open areas (the low foot end is a closed filler, every section has closed doors
                 or drawer fronts from the side, shelves and the rail are cut short where the steps come down).
                 Changes show at once; Cancel / Esc puts everything back.
  Dimension      two points, then the position of the line.
  Select tool    click / Shift+click / box select (a door is picked by clicking in its gap in the wall); the bar under
                 the storeys then shows what the selection can do: a door can be changed to passage / double / sliding
                 door / window, flipped (side, hinge) or deleted.  Drag to move; white squares reshape (wall ends, room corners, roof
                 corners, rotation).  Del deletes, Ctrl+D duplicates, Ctrl+Z / Ctrl+Y undo / redo.  Arrow keys move the selection
                 (walls, rooms ...); for beds, sofas, stairs, dormers and text Left / Right TURN it and Up / Down or Ctrl+arrows move.
  Mouse          wheel zooms, right or middle button drags the drawing, Home fits it to the window.

STOREYS AND THE ATTIC
  Storey menu: add a storey above, add an ATTIC storey (with a roof fitted over the walls of the storey below), copy,
  delete.  Click a storey name in the bar to work on it; the storey below is shown in light grey (tick box 'Show floor
  below' at the right end of the bar, on by default - untick it when you place things and the grey walls disturb).
  Each storey has a clear height and a floor thickness (right panel when nothing is selected).

ROOF AND SLOPED CEILINGS
  A roof belongs to a storey.  Its INNER surface is the ceiling: the walls of that storey are cut off by it, so gable
  walls become triangles and kneewalls get their height.  Gable, hip, shed, flat, MANSARD (hip roof with a steep lower
  slope) and GAMBREL (gable roof with a steep lower slope) roofs; set pitch, kneewall height (eave), ridge direction and
  overhang.  For mansard / gambrel, Pitch is the shallow upper slope; the steep lower slope (angle and how far it runs
  in, measured on the floor) is set in the panel on the right.  On the plan the area where the ceiling is lower than the two headroom limits
  (default 1.0 m and 1.9 m, change them in the storey panel) is shaded and dashed lines show where the ceiling is
  exactly that high.  Every attic room shows its area and the part of it that is at least as high as the upper limit.
  The limits are just numbers you choose - check the building rules that apply to you.

DORMERS AND ROOF WINDOWS (Dormer tool, attic storeys)
  Pick Gable dormer, Shed dormer, Flat dormer or Roof window in the tool bar and click on the roof.  A dormer is a small
  house on the roof: it gets its depth automatically (it runs back until it meets the roof) and its own ceiling, which
  adds headroom and lifts the walls inside it.  The white square turns it (it faces the direction you set); the
  panel gives width, window size, sill, eave height, pitch, overhang.  A roof window lies in the roof slope: the hole is
  cut in the roof and shown in plan, 3D, section and every export.  Duplicate, move, rotate and delete work as usual.

GHOST NOTES (your own working notes per storey)
  Tool 'Note': click where the note goes and type it ('Bedroom B', 'Guest room' ...).  Notes belong to the storey you are on and
  are shown only in the PLAN of that storey, only while 'Ghost notes' is ticked (bottom right of the plan bar, or View menu;
  OFF by default - choosing the Note tool switches it on).  They are never exported or printed and never in 3D / section.
  Select a note to move, turn, edit or delete it; in the panel 'Ghost note = Yes / No' turns a normal text into a note and back.

GHOST MEASURES (a second ghost layer: show the measurements)
  Tool 'Measure' (tick 'Ghost measures' in the plan bar or View menu; OFF by default, the tool switches it on).  Three modes:
    Rectangle           click two opposite corners - marks a space that needs NO walls (curtain, open plan ...).
    Room (click inside) click inside a room - the space enclosed by the walls (curtains and doors count as closed) is measured.
    Ruler               click two points - a ruler with ticks every 100 mm and a number every metre (follows 'Straight' in the plan bar; Shift flips it).
  A room gets a label: PREFIX, then width x depth and area.  The prefix is the name you typed in the panel ('Own name'),
  else the ghost notes standing inside the outline (several are joined with ' / ').  Corners can be edited in the panel.
  'Measures list...' (Measure tool bar, or the panel) shows all measures of the storey as text you can copy
  ('All storeys' ticked = every storey).  Like ghost notes they belong to their storey, are shown in the PLAN only and are
  never exported or printed.  Select, move, duplicate and delete work as usual.

CURTAIN (ROOM DIVIDER)
  Wall tool > Wall type > 'Curtain (room divider)', then draw it like a wall (or select any wall and set Type = Curtain in
  the panel).  It is a rail just under the ceiling with a drape on it, used instead of a wall with a door: no wall
  material, no doors or windows in it.  Panel: 'Drawn open (%)' slides the drape (0 = shut, 100 = pushed aside; the
  Open / Close buttons do the same), 'Gathers at' = Start, End or Both (two drapes that meet in the middle).  Plan: dashed
  rail, wavy cloth, boxed zig-zag where it is bunched up.  3D shows rail and cloth (with 'Show furniture').  The Materials
  list gets the rail (m) and the fabric (running metres, 2 x fullness).  A curtain cannot be curved.

CURVED WALLS
  Wall tool with 'Arc wall (3 clicks)': click the start, the end, then a point the curve passes through.  Any wall can
  be bent afterwards: select it and drag the white square in the middle of the wall (or type 'Bulge' in the panel;
  positive bulges to the left of the drawing direction, 0 = straight; 'Curve it / Straighten' in the panel).
  Doors and windows can be placed on a curved wall (they are flat in the curve).  Rooms are found inside curved walls,
  roofs follow the outermost points, and DXF writes real ARCs.

MATERIALS, PRICES, MEMOS AND CRAFTSMEN (Materials menu)
  Shopping list   'Fill from the model' counts what the drawing needs: wall areas per thickness (net of doors and
                  windows), floors, ceilings, roof, windows, doors, fixtures, running metres of walls and skirting.  Add
                  your own lines (paint, screws ...).  Waste % is added to the need.  Your own lines and the material
                  names you change are kept when you fill again.
  Prices          for every store and material: a price per m2, per running metre, per piece or per pack / sheet / length
                  ('one sold unit contains 2.88 m2').  The material name must be the same as on the shopping list line.
                  Import / export as CSV (open it in Excel, ; between the columns).  The price book is shared by all your
                  projects (Helpfiles\\Architect\\book.json).
  Price from web page   (buttons in the Prices and Shopping list tabs) paste the address of ONE product page: the program
                  reads that single page (a fixed 'Architect' user agent, one request per click, no log-in, nothing else
                  sent) and lists the prices it finds - first the shop's own product data (schema.org JSON-LD, meta tags),
                  then '123 kr' patterns in the text with the words around them.  You pick one, check store, material,
                  units and 'contains' (the program guesses from 'kr/m2', 'per pack' ...) and press Save price; nothing
                  is saved before that, and it tells you when the save replaces an older price.  If a shop blocks programs
                  (403 / robot check), is offline, or builds the price with JavaScript, open the page in your browser,
                  press Ctrl+A, Ctrl+C and paste the text into the box in the window instead.  Prices in another
                  currency than kr are flagged - type the kr price.  The address is kept with the price in the book.
  Stores          delivery fee, order value from which delivery is free, and what it costs you to fetch the goods yourself.
  Where to buy    compares everything and tells you the cheapest way: all at one store, at most two stores, or the
                  cheapest mix (delivery or fetching costs of every store you use are included), and which store gives
                  you most of it.  Save the result as CSV, or as a PDF shopping list (A4): the cheapest plan store by store with
                  quantities to buy, prices, delivery / fetching cost, how far you are from free delivery, the totals, the
                  alternatives and the lines nobody has a price for.
  Memos           notes with an optional due date, pinned and done flags; saved in the project file.  Memos that have
                  fallen due are shown in the status bar when the project opens.
  Craftsmen       name, trade, company, phone, e-mail, rate, rating and a note; search and filter by trade.
                  The list is shared by all your projects and can be exported as CSV.

VIEWS (top right)
  Plan, 3D (drag = orbit, right drag = move, wheel = zoom) and Section.  In 3D the roof is hidden by default (tick box
  'Hide roof' in the bar) so you can look into the house; 'Show furniture' shows beds, sofas, kitchen units ... and
  'View > 3D: show storeys up to' hides the storeys above.  'Keep objects when turning' (on by default) keeps furniture,
  stairs, doors and windows on screen while you orbit and zoom; untick it only if a very big house turns too slowly.  Make a section with the Section tool (two
  clicks across the house); the Section view shows the cut with floors, walls, stairs and the sloping roof, and tells
  heights when you hover.

SAVING AND EXPORT
  Projects are saved as .arch.json.  File > Export opens the export window:
    DXF   one file per storey, all storeys in one file, and a 3D DXF.  AutoCAD, BricsCAD, LibreCAD, QCAD, DraftSight,
          SketchUp (import) ...  Units are millimetres, layers have standard names (A-WALL, A-DOOR, A-GLAZ ...).
          DWG cannot be written by a program like this (closed format): open the DXF in AutoCAD and Save As DWG, or use
          the free ODA File Converter.
    IFC   IFC4 for BIM programs (Revit, ArchiCAD, Vectorworks, FreeCAD, BIMvision ...): walls, floors, roofs, doors,
          windows, stairs, furniture, rooms (IfcSpace) and storeys.  Doors, windows, dormer windows and roof windows
          are real openings (IfcOpeningElement + IfcRelVoidsElement + IfcRelFillsElement) in whole walls / roofs.
    OBJ   3D model with colours (SketchUp, Blender, ...), metres.
    SVG / PDF   scaled drawings for printing (PDF: one page per storey, A4 - A1).
    CSV   room list with areas.
"""


class PropsMixin(object):

    # ---- the panel -------------------------------------------------------------------------------------------
    def clear_props(self):
        for w in self.props_frame.winfo_children():
            w.destroy()

    def prop_title(self, text):
        tk.Label(self.props_frame, text=text, font=("Segoe UI", 10, "bold"), anchor="w", bg=THEME["panel"],
                 fg=THEME["accent"]).pack(fill="x", padx=6, pady=(6, 4))

    def prop_row(self, label, value, setter, kind="n", choices=None, rebuild=False):
        f = self.props_frame
        row = tk.Frame(f, bg=THEME["panel"])
        row.pack(fill="x", padx=6, pady=1)
        tk.Label(row, text=label, width=18, anchor="w", bg=THEME["panel"], fg=THEME["fg"],
                 font=("Segoe UI", 9)).pack(side="left")
        if kind == "ro":
            tk.Label(row, text=str(value), anchor="w", bg=THEME["panel"], fg=THEME["dim"], font=("Segoe UI", 9),
                     width=16).pack(side="left")
            return
        if kind == "c":
            var = tk.StringVar(value=str(value))

            def pick(v):
                setter(v)
                if rebuild:
                    self.show_props()
            om = tk.OptionMenu(row, var, *choices, command=pick)
            om.configure(width=13, bg=THEME["btn"], fg=THEME["btnfg"], activebackground=THEME["accent"], bd=0,
                         highlightthickness=0, font=("Segoe UI", 9))
            om.pack(side="left")
            return
        if kind == "b":
            var = tk.BooleanVar(value=bool(value))
            tk.Checkbutton(row, variable=var, bg=THEME["panel"], activebackground=THEME["panel"], selectcolor=THEME["btn"],
                           command=lambda: (setter(var.get()), self.show_props() if rebuild else None)).pack(side="left")
            return
        ent = new_entry(row, width=13, bg=THEME["field"], fg=THEME["field_fg"], insertbackground=THEME["field_fg"],
                        relief="flat", font=("Segoe UI", 9))
        txt = ("%g" % round(value, 2)) if kind == "n" and isinstance(value, (int, float)) else str(value)
        ent.insert(0, txt)
        ent.pack(side="left")

        def commit(ev=None):
            s = ent.get().strip()
            if s == txt:
                return
            try:
                v = float(s.replace(",", ".")) if kind == "n" else s
            except ValueError:
                ent.delete(0, "end")
                ent.insert(0, txt)
                return
            setter(v)
            if rebuild:
                self.show_props()
        ent.bind("<Return>", commit)
        ent.bind("<FocusOut>", commit)

    def prop_buttons(self, items):
        row = tk.Frame(self.props_frame, bg=THEME["panel"])
        row.pack(fill="x", padx=6, pady=(8, 2))
        for text, cmd in items:
            tk.Button(row, text=text, command=cmd, width=10, bg=THEME["btn"], fg=THEME["btnfg"], relief="flat",
                      activebackground=THEME["accent"], font=("Segoe UI", 9)).pack(side="left", padx=2)

    def setter(self, el, key, idx=None, rebuild_ro=False, cast=None):
        def f(v):
            self.push_undo()
            val = cast(v) if cast else v
            if idx is None:
                el[key] = val
            else:
                el[key][idx] = val
            self.changed(props=rebuild_ro)
        return f

    def show_props(self):
        if not hasattr(self, "props_frame"):
            return
        self.refresh_select_bar()
        self.clear_props()
        story = self.story()
        if not self.sel:
            self.props_story()
            return
        if len(self.sel) > 1:
            self.prop_title("%d elements selected" % len(self.sel))
            self.prop_buttons([("Duplicate", self.duplicate_selection), ("Delete", self.delete_selection)])
            return
        kind, el = find_element(story, self.sel[0])
        if el is None:
            self.props_story()
            return
        S = self.setter
        if kind == "wall":
            def set_kind(v):                      # Wall <-> Curtain (room divider: rail under the ceiling + sliding drape)
                self.push_undo()
                if v == "Curtain":
                    el["kind"] = "curtain"
                    el.setdefault("open", 0.0)
                    el.setdefault("gather", "Both")
                    el["sag"] = 0.0
                    el["t"] = CURTAIN_T if el["t"] > 80 else el["t"]
                    story["openings"] = [o for o in story["openings"] if o["wall"] != el["id"]]       # no doors in a drape
                else:
                    el.pop("kind", None)
                    if el["t"] < 70:
                        el["t"] = 100.0
                self.changed()
            curt = is_curtain(el)
            self.prop_title("Curtain (room divider)" if curt else "Wall")
            self.prop_row("Type", "Curtain" if curt else "Wall", set_kind, "c", ["Wall", "Curtain"])
            if curt:
                self.prop_row("Drawn open (%)", round(100.0 * el.get("open", 0.0)),
                              S(el, "open", cast=lambda v: min(1.0, max(0.0, float(v) / 100.0))))
                self.prop_row("Gathers at", el.get("gather", "Both"), S(el, "gather"), "c", CURTAIN_GATHER)
                self.prop_row("Colour", el.get("color", "Green"), S(el, "color"), "c", list(CURTAIN_COLORS))
                self.prop_row("Cloth thickness (mm)", el["t"], S(el, "t", cast=lambda v: max(10.0, float(v))))
                self.prop_row("Height (0 = storey)", el["h"] or 0, S(el, "h", cast=lambda v: float(v) or None))
                self.prop_row("Length (m)", fmt_m(wall_length(el)), None, "ro")
                self.prop_row("Start x (mm)", el["p"][0], S(el, "p", 0, True))
                self.prop_row("Start y (mm)", el["p"][1], S(el, "p", 1, True))
                self.prop_row("End x (mm)", el["p"][2], S(el, "p", 2, True))
                self.prop_row("End y (mm)", el["p"][3], S(el, "p", 3, True))
                self.prop_buttons([("Open", lambda: S(el, "open")(1.0)), ("Close", lambda: S(el, "open")(0.0))])
                self.prop_buttons([("Duplicate", self.duplicate_selection), ("Delete", self.delete_selection)])
                return
            self.prop_row("Thickness (mm)", el["t"], S(el, "t", rebuild_ro=True))
            self.prop_row("Height (0 = storey)", el["h"] or 0, S(el, "h", cast=lambda v: float(v) or None))
            self.prop_row("Bulge (mm, 0 = straight)", el.get("sag", 0.0), S(el, "sag", rebuild_ro=True))
            arc = wall_arc(el)
            if arc:
                self.prop_row("Arc length (m)", fmt_m(arc["length"]), None, "ro")
                self.prop_row("Radius (m)", fmt_m(arc["r"]), None, "ro")
                self.prop_row("Angle (deg)", "%.1f" % abs(math.degrees(arc["sweep"])), None, "ro")
            self.prop_row("Chord (m)", fmt_m(math.hypot(el["p"][2] - el["p"][0], el["p"][3] - el["p"][1])), None, "ro")
            self.prop_row("Start x (mm)", el["p"][0], S(el, "p", 0, True))
            self.prop_row("Start y (mm)", el["p"][1], S(el, "p", 1, True))
            self.prop_row("End x (mm)", el["p"][2], S(el, "p", 2, True))
            self.prop_row("End y (mm)", el["p"][3], S(el, "p", 3, True))
        elif kind == "opening":
            self.prop_title(OPENING_KINDS[el["kind"]][3])
            self.prop_row("Kind", el["kind"], S(el, "kind"), "c", list(OPENING_KINDS), True)
            self.prop_row("Width (mm)", el["w"], S(el, "w"))
            self.prop_row("Height (mm)", el["h"], S(el, "h"))
            self.prop_row("Sill (mm)", el["sill"], S(el, "sill"))
            self.prop_row("Position (mm)", el["pos"], S(el, "pos"))
            self.prop_row("Opens to", "Left" if el.get("swing", 1) > 0 else "Right",
                          lambda v: S(el, "swing")(1 if v == "Left" else -1), "c", ["Left", "Right"])
            self.prop_row("Hinge at", "Start" if el.get("hinge", 0) == 0 else "End",
                          lambda v: S(el, "hinge")(0 if v == "Start" else 1), "c", ["Start", "End"])
        elif kind == "room":
            pts = [tuple(p) for p in el["pts"]]
            self.prop_title("Room")
            self.prop_row("Name", el["name"], S(el, "name"), "s")
            self.prop_row("Type", "pick...", lambda v: S(el, "name")(v), "c", ROOM_TYPES)
            self.prop_row("Area", fmt_area(poly_area(pts)), None, "ro")
            self.prop_row("Perimeter (m)", fmt_m(poly_perimeter(pts)), None, "ro")
            if story["roofs"]:
                lim = self.proj["settings"]["headroom"][-1]
                self.prop_row("Area, h >= %s m" % fmt_m(lim), fmt_area(room_headroom_area(story, el, lim)), None, "ro")
        elif kind == "item":
            c = CATALOG.get(el["type"], {"name": el["type"]})
            self.prop_title(c["name"])
            self.prop_row("Label", el.get("label", ""), S(el, "label"), "s")
            self.prop_row("x (mm)", el["x"], S(el, "x"))
            self.prop_row("y (mm)", el["y"], S(el, "y"))
            self.prop_row("Rotation (deg)", el["rot"], S(el, "rot"))
            self.prop_row("Width (mm)", el["w"], S(el, "w"))
            self.prop_row("Depth (mm)", el["d"], S(el, "d"))
            self.prop_row("Height (mm)", el["h"], S(el, "h"))
            self.prop_row("Above floor (mm)", el["z"], S(el, "z"))
            if is_shaft(el):                      # chimney / flue / vent shaft
                self.prop_row("Continues up", "Yes" if el.get("up") else "No",
                              lambda v: S(el, "up")(1 if v == "Yes" else 0), "c", ["Yes", "No"])
        elif kind == "stair":
            self.prop_title("Lift" if el["kind"] == "lift" else "Stairs")
            rise = stair_rise(self.proj, self.sidx, el)
            orphan = self.stair_is_orphan(el)
            self.prop_row("Kind", el["kind"], S(el, "kind"), "c", STAIR_KINDS, True)
            self.prop_row("Width (mm)", el["w"], S(el, "w", rebuild_ro=True))
            if el["kind"] == "lift":
                self.prop_row("Depth (mm)", el.get("dep", LIFT_DEP), S(el, "dep"))
                self.prop_row("Rotation (deg)", el["rot"], S(el, "rot"))
                self.prop_row("Total rise (mm)", "%.0f" % rise, None, "ro")
                self.prop_row("Serves", "NO FLOOR ABOVE!" if orphan else "this floor up to the next", None, "ro")
                btns = [("Duplicate", self.duplicate_selection), ("Delete", self.delete_selection)]
                if orphan:
                    btns.insert(0, ("Move to storey below", self.move_stair_down))
                self.prop_buttons(btns)
                return
            if el["kind"] != "spiral":
                self.prop_row("Tread depth (mm)", el["tread"], S(el, "tread", rebuild_ro=True))
            self.prop_row("Risers", el["n"], S(el, "n", cast=lambda v: max(3, int(v))), "n", None, True)
            if el["kind"] == "L":
                self.prop_row("Turns", "Right" if el["turn"] == "R" else "Left",
                              lambda v: S(el, "turn")("R" if v == "Right" else "L"), "c", ["Right", "Left"])
            if el["kind"] == "spiral":
                self.prop_row("Radius (mm)", el["r"], S(el, "r"))
                self.prop_row("Angle per step", el["ang"], S(el, "ang"))
                self.prop_row("Clockwise up", "Yes" if el.get("cw") else "No",
                              lambda v: S(el, "cw")(1 if v == "Yes" else 0), "c", ["No", "Yes"])
            self.prop_row("Rotation (deg)", el["rot"], S(el, "rot"))
            self.prop_row("Total rise (mm)", "%.0f%s" % (rise, "  - NO FLOOR ABOVE!" if orphan else ""), None, "ro")
            self.prop_row("One riser (mm)", "%.1f" % (rise / el["n"]), None, "ro")
            if el["kind"] in ("straight", "L"):
                self.prop_row("Slope (deg)", "%.1f" % math.degrees(math.atan2(rise / el["n"], el["tread"])), None, "ro")
                if el["kind"] == "straight":
                    self.prop_row("Run length (m)", fmt_m((el["n"] - 1) * el["tread"]), None, "ro")
            self.prop_buttons([("Auto steps", lambda: S(el, "n")(max(3, int(round(rise / 175.0)))) or self.show_props()),
                               ("Edit parts...", lambda: self.open_stair_editor(el))] +
                              ([("Move to storey below", self.move_stair_down)] if orphan else []))
        elif kind == "roof":
            self.prop_title("Roof")
            self.prop_row("Type", el["type"], S(el, "type"), "c", ROOF_TYPES, True)
            broken = el["type"] in MANSARD_TYPES
            if el["type"] != "flat":
                self.prop_row("Upper pitch (deg)" if broken else "Pitch (deg)", el["pitch"], S(el, "pitch", rebuild_ro=True))
            if broken:
                self.prop_row("Lower pitch (deg)", el.get("pitch2", 70.0), S(el, "pitch2", rebuild_ro=True))
                self.prop_row("Lower slope run (mm)", el.get("run", 1200.0), S(el, "run", rebuild_ro=True))
            self.prop_row("Eave height (mm)", el["eave"], S(el, "eave", rebuild_ro=True))
            if el["type"] in ("gable", "gambrel"):
                self.prop_row("Ridge runs along", el["ridge"], S(el, "ridge"), "c", ["x", "y"])
            if el["type"] == "shed":
                self.prop_row("Low side", el["fall"], S(el, "fall"), "c", ["S", "N", "E", "W"])
            self.prop_row("Overhang (mm)", el["over"], S(el, "over"))
            self.prop_row("Thickness (mm)", el["t"], S(el, "t"))
            self.prop_row("Highest point (m)", fmt_m(roof_ridge_height(el)), None, "ro")
            for i, nm in enumerate(("West x", "South y", "East x", "North y")):
                self.prop_row(nm + " (mm)", el["rect"][i], S(el, "rect", i, True))
        elif kind == "dormer":
            self.prop_title("Dormer")
            self.prop_row("Roof shape", el["kind"], S(el, "kind"), "c", [k for k, _ in DORMER_KINDS], True)
            self.prop_row("Width (mm)", el["w"], S(el, "w", rebuild_ro=True))
            self.prop_row("Front wall height", el["fh"], S(el, "fh", rebuild_ro=True))
            if el["kind"] != "flat":
                self.prop_row("Roof pitch (deg)", el["pitch"], S(el, "pitch", rebuild_ro=True))
            self.prop_row("Depth (0 = auto)", el.get("d", 0.0), S(el, "d", rebuild_ro=True))
            self.prop_row("Depth now (mm)", "%.0f" % dormer_depth(story, el), None, "ro")
            self.prop_row("Faces (deg, 0=S)", el["rot"], S(el, "rot"))
            self.prop_row("Window width (0=none)", el.get("win_w", 0.0), S(el, "win_w"))
            self.prop_row("Window height", el.get("win_h", 0.0), S(el, "win_h"))
            self.prop_row("Window sill", el.get("sill", 200.0), S(el, "sill"))
            self.prop_row("Roof overhang", el.get("over", 150.0), S(el, "over"))
            self.prop_row("x (mm)", el["x"], S(el, "x", rebuild_ro=True))
            self.prop_row("y (mm)", el["y"], S(el, "y", rebuild_ro=True))
            zr = max(c[2] + c[0] * el["x"] + c[1] * el["y"] for c in dormer_planes(story, el))
            self.prop_row("Ridge height (m)", fmt_m(zr), None, "ro")
        elif kind == "rwin":
            self.prop_title("Roof window")
            self.prop_row("Width (mm)", el["w"], S(el, "w", rebuild_ro=True))
            self.prop_row("Length along roof", el["h"], S(el, "h", rebuild_ro=True))
            self.prop_row("x (mm)", el["x"], S(el, "x", rebuild_ro=True))
            self.prop_row("y (mm)", el["y"], S(el, "y", rebuild_ro=True))
            inf = rwin_info(story, el)
            self.prop_row("Roof slope (deg)", "%.1f" % math.degrees(math.atan(inf["grad"])) if inf else "not on a roof", None, "ro")
        elif kind == "dim":
            self.prop_title("Dimension")
            self.prop_row("Length (m)", fmt_m(dist(tuple(el["a"]), tuple(el["b"]))), None, "ro")
            self.prop_row("Line offset (mm)", el["off"], S(el, "off"))
        elif kind == "text":
            self.prop_title("Ghost note" if el.get("ghost") else "Text")
            self.prop_row("Text", el["s"], S(el, "s"), "s")
            self.prop_row("Height (mm)", el["h"], S(el, "h"))
            self.prop_row("Rotation (deg)", el.get("rot", 0), S(el, "rot"))

            def set_ghost(v):                         # a note is a text that lives on the ghost layer
                self.push_undo()
                if v == "Yes":
                    el["ghost"] = True
                    if not self.v_notes:
                        self.show_notes(True)
                else:
                    el.pop("ghost", None)
                self.changed()
            self.prop_row("Ghost note", "Yes" if el.get("ghost") else "No", set_ghost, "c", ["No", "Yes"])
        elif kind == "meas":
            sz = meas_size(el)
            self.prop_title({"ruler": "Ghost ruler", "rect": "Ghost measure (rectangle)", "poly": "Ghost measure (room)"}[el["kind"]])
            if el["kind"] != "ruler":
                self.prop_row("Own name (prefix)", el.get("name", ""), S(el, "name"), "s")
                pre = meas_prefix(story, el)
                self.prop_row("Prefix now", pre or "(none - no ghost note inside)", None, "ro")
            if el["kind"] == "ruler":
                self.prop_row("Length (m)", fmt_m(sz["len"]), None, "ro")
                self.prop_row("Start x (mm)", el["a"][0], S(el, "a", 0, True))
                self.prop_row("Start y (mm)", el["a"][1], S(el, "a", 1, True))
                self.prop_row("End x (mm)", el["b"][0], S(el, "b", 0, True))
                self.prop_row("End y (mm)", el["b"][1], S(el, "b", 1, True))
            else:
                self.prop_row("Width (m)", fmt_m(sz["w"]), None, "ro")
                self.prop_row("Depth (m)", fmt_m(sz["d"]), None, "ro")
                self.prop_row("Area", fmt_area(sz["area"]), None, "ro")
                if not sz["exact"]:
                    self.prop_row("Note", "W x D is the bounding box", None, "ro")
                if el["kind"] == "rect":
                    self.prop_row("Corner 1 x (mm)", el["a"][0], S(el, "a", 0, True))
                    self.prop_row("Corner 1 y (mm)", el["a"][1], S(el, "a", 1, True))
                    self.prop_row("Corner 2 x (mm)", el["b"][0], S(el, "b", 0, True))
                    self.prop_row("Corner 2 y (mm)", el["b"][1], S(el, "b", 1, True))
            self.prop_buttons([("Measures list...", lambda: self.open_meas_report())])
        elif kind == "section":
            self.prop_title("Section line")
            self.prop_row("Name", el["name"], S(el, "name"), "s")
            self.prop_row("Length (m)", fmt_m(dist(tuple(el["a"]), tuple(el["b"]))), None, "ro")
            self.prop_buttons([("View", lambda: (setattr(self, "sec_id", el["id"]), self.set_mode("section")))])
        btns = [("Duplicate", self.duplicate_selection), ("Delete", self.delete_selection)]
        if kind == "roof":
            btns.insert(0, ("Fit walls", self.fit_roof_to_walls))
        if kind == "wall":
            btns.insert(0, ("Straighten" if wall_arc(el) else "Curve it", lambda: self.toggle_curve(el)))
        self.prop_buttons(btns)

    def props_story(self):
        story = self.story()
        el = story_elevations(self.proj)[self.sidx]
        self.prop_title("Storey")
        self.prop_row("Name", story["name"], lambda v: (self.push_undo(), story.__setitem__("name", v), self.rebuild_story_bar(),
                                                       self.changed(False)), "s")
        self.prop_row("Clear height (mm)", story["height"], lambda v: (self.push_undo(), story.__setitem__("height", max(1000.0, v)),
                                                                      self.changed()))
        self.prop_row("Floor thickness", story["floor_t"], lambda v: (self.push_undo(), story.__setitem__("floor_t", max(50.0, v)),
                                                                     self.changed()))
        if self.sidx == 0:
            self.prop_row("Ground level (mm)", story.get("base", 0), lambda v: (self.push_undo(), story.__setitem__("base", v),
                                                                              self.changed()))
        self.prop_row("Floor level (m)", fmt_m(el), None, "ro")
        tot = sum(poly_area(r["pts"]) for r in story["rooms"] if len(r["pts"]) >= 3)
        self.prop_row("Rooms total", fmt_area(tot), None, "ro")
        if story["roofs"]:
            self.prop_row("Roof ridge (m)", fmt_m(el + max(roof_ridge_height(r) for r in story["roofs"])), None, "ro")
        self.prop_title("Project")
        self.prop_row("Name", self.proj["name"], lambda v: (setattr(self, "dirty", True), self.proj.__setitem__("name", v),
                                                           self.update_title()), "s")
        hr = self.proj["settings"]["headroom"]
        self.prop_row("Headroom low (mm)", hr[0], lambda v: (self.push_undo(), hr.__setitem__(0, min(v, hr[1])), self.changed()))
        self.prop_row("Headroom high (mm)", hr[1], lambda v: (self.push_undo(), hr.__setitem__(1, max(v, hr[0])), self.changed()))
        self.prop_row("Grid (mm)", self.proj["settings"].get("grid", 500),
                      lambda v: (self.proj["settings"].__setitem__("grid", max(50.0, v)), self.redraw()))
        warn = []
        top = self.proj["stories"][-1]
        if not top["roofs"]:
            warn.append("The top storey has no roof.")
        for i, st in enumerate(self.proj["stories"]):
            if not st["rooms"]:
                warn.append("%s has no rooms." % st["name"])
        if warn:
            tk.Label(self.props_frame, text="\n".join(warn), justify="left", anchor="w", wraplength=240, bg=THEME["panel"],
                     fg="#e0a060", font=("Segoe UI", 9)).pack(fill="x", padx=6, pady=8)

    def toggle_curve(self, el):
        self.push_undo()
        if wall_arc(el):
            el["sag"] = 0.0
        else:
            el["sag"] = round(math.hypot(el["p"][2] - el["p"][0], el["p"][3] - el["p"][1]) / 4.0 / 10.0) * 10.0
        self.changed()

    def fit_roof_to_walls(self):
        story = self.story()
        kind, el = find_element(story, self.sel[0]) if self.sel else (None, None)
        if kind != "roof" or not story["walls"]:
            return
        self.push_undo()
        pts = story_wall_points(story)
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        el["rect"] = [min(xs), min(ys), max(xs), max(ys)]
        self.changed()

    # ---- storeys ---------------------------------------------------------------------------------------------
    def select_story(self, i):
        self.sidx = max(0, min(i, len(self.proj["stories"]) - 1))
        self.sel = []
        self.tmp = {}
        self.rebuild_story_bar()
        if self.mode == "plan":
            self.fit_view() if not self.story()["walls"] and False else None
        self.redraw()
        self.show_props()

    def add_story(self, attic=False):
        self.push_undo()
        below = self.proj["stories"][-1]
        s = new_story("Attic" if attic else "Floor %d" % (len(self.proj["stories"])), 4000 if attic else below["height"])
        s["id"] = uid(self.proj)
        if attic:
            s["walls"] = copy.deepcopy([w for w in below["walls"] if w["t"] >= 150]) or []
            for w in s["walls"]:
                w["id"] = uid(self.proj)
                w["h"] = None
            self.proj["stories"].append(s)
            auto_roof(self.proj, s)
            s["name"] = "Attic"
        else:
            self.proj["stories"].append(s)
        self.sidx = len(self.proj["stories"]) - 1
        self.sel = []
        self.rev += 1
        self.dirty = True
        self.rebuild_story_bar()
        self.redraw()
        self.show_props()

    def copy_story(self):
        self.push_undo()
        s = clone_story(self.proj, self.story(), self.story()["name"] + " copy")
        self.proj["stories"].insert(self.sidx + 1, s)
        self.sidx += 1
        self.sel = []
        self.rev += 1
        self.rebuild_story_bar()
        self.redraw()
        self.show_props()

    def delete_story(self):
        if len(self.proj["stories"]) < 2:
            messagebox.showinfo(APP_TITLE, "A project needs at least one storey.", parent=self.root)
            return
        if not messagebox.askyesno(APP_TITLE, "Delete the storey '%s' with everything in it?\n(You can undo with Ctrl+Z.)" %
                                   self.story()["name"], parent=self.root):
            return
        self.push_undo()
        del self.proj["stories"][self.sidx]
        self.sidx = max(0, self.sidx - 1)
        self.sel = []
        self.rev += 1
        self.rebuild_story_bar()
        self.redraw()
        self.show_props()

    # ---- small dialogs ---------------------------------------------------------------------------------------
    def ask_text(self, title, initial=""):
        top = tk.Toplevel(self.root)
        top.title(title)
        top.resizable(False, False)
        top.transient(self.root)
        res = {"v": None}
        tk.Label(top, text=title).pack(padx=12, pady=(12, 4))
        ent = new_entry(top, width=40)
        ent.insert(0, initial)
        ent.pack(padx=12)

        def ok(e=None):
            res["v"] = ent.get().strip()
            top.destroy()
        ent.bind("<Return>", ok)
        row = tk.Frame(top)
        row.pack(pady=10)
        tk.Button(row, text="OK", width=9, command=ok).pack(side="left", padx=4)
        tk.Button(row, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
        make_modal(top)
        ent.focus_set()
        self.root.wait_window(top)
        return res["v"]

    def show_help(self):
        top = tk.Toplevel(self.root)
        top.title("Architect - Help")
        top.geometry("760x640")
        top.transient(self.root)
        frm = tk.Frame(top)
        frm.pack(fill="both", expand=True)
        sb = tk.Scrollbar(frm)
        sb.pack(side="right", fill="y")
        t = new_text(frm, wrap="word", font=("Consolas", 10), padx=10, pady=8, yscrollcommand=sb.set)
        t.pack(side="left", fill="both", expand=True)
        sb.configure(command=t.yview)
        t.insert("1.0", HELP_TEXT)
        t.configure(state="disabled")
        make_modal(top)

    def show_about_dialog(self):
        show_about(self.root, APP_TITLE, "Floor plans, storeys and attics with sloped roofs - export to CAD and BIM", "\U0001F3E0")

    def show_report(self):
        top = tk.Toplevel(self.root)
        top.title("Room list")
        top.geometry("640x460")
        top.transient(self.root)
        t = new_text(top, font=("Consolas", 10), padx=10, pady=8)
        t.pack(fill="both", expand=True)
        rows = rooms_table(self.proj)
        wd = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))]
        total = 0.0
        for k, r in enumerate(rows):
            t.insert("end", "  ".join(r[i].ljust(wd[i]) for i in range(len(r))) + "\n")
            if k == 0:
                t.insert("end", "-" * (sum(wd) + 8) + "\n")
            else:
                total += float(r[2])
        t.insert("end", "\nTotal room area: %.2f m2\n" % total)
        t.configure(state="disabled")
        make_modal(top)

    def show_export(self):
        top = tk.Toplevel(self.root)
        top.title("Export")
        top.resizable(False, False)
        top.transient(self.root)
        default = os.path.join(PROGRAM_HF_DIR, "Exports", safe_name(self.proj["name"]))
        tk.Label(top, text="Export folder", anchor="w").pack(fill="x", padx=12, pady=(12, 2))
        row = tk.Frame(top)
        row.pack(fill="x", padx=12)
        folder = tk.StringVar(value=self.settings.get("export_dir") or default)
        ent = new_entry(row, textvariable=folder, width=56)
        ent.pack(side="left")
        tk.Button(row, text="Browse...", command=lambda: folder.set(filedialog.askdirectory(parent=top, initialdir=folder.get())
                                                                    or folder.get())).pack(side="left", padx=4)
        opts = {}
        box = tk.LabelFrame(top, text="Formats", padx=8, pady=4)
        box.pack(fill="x", padx=12, pady=8)
        for key, label in (("dxf", "DXF - plan of every storey + all storeys in one file (AutoCAD & co)"),
                           ("dxf3d", "DXF - 3D model (3D faces)"), ("ifc", "IFC4 - BIM (Revit, ArchiCAD ...)"),
                           ("obj", "OBJ + MTL - 3D model with colours"), ("pdf", "PDF - scaled plans, one page per storey"),
                           ("svg", "SVG - scaled plans"), ("csv", "CSV - room list")):
            v = tk.BooleanVar(value=True)
            opts[key] = v
            tk.Checkbutton(box, text=label, variable=v, anchor="w").pack(fill="x")
        o2 = tk.LabelFrame(top, text="Drawing options", padx=8, pady=4)
        o2.pack(fill="x", padx=12)
        fill = tk.BooleanVar(value=True)
        tk.Checkbutton(o2, text="Fill walls solid (otherwise outline only)", variable=fill, anchor="w").pack(fill="x")
        r2 = tk.Frame(o2)
        r2.pack(fill="x")
        tk.Label(r2, text="Paper").pack(side="left")
        paper = tk.StringVar(value="A3")
        tk.OptionMenu(r2, paper, *PAPERS.keys()).pack(side="left", padx=4)
        tk.Label(r2, text="Scale 1:").pack(side="left")
        scale = tk.StringVar(value="auto")
        tk.OptionMenu(r2, scale, "auto", "20", "50", "100", "200").pack(side="left", padx=4)
        msg = tk.Label(top, text="", anchor="w", justify="left", wraplength=520, fg="#206020")
        msg.pack(fill="x", padx=12, pady=6)

        def go():
            out = folder.get().strip()
            if not out:
                return
            self.settings["export_dir"] = out
            self.save_settings()
            sc = None if scale.get() == "auto" else int(scale.get())
            try:
                os.makedirs(out, exist_ok=True)
                base = safe_name(self.proj["name"])
                done = []
                if opts["dxf"].get():
                    for i, s in enumerate(self.proj["stories"]):
                        p = os.path.join(out, "%s_%02d_%s.dxf" % (base, i + 1, safe_name(s["name"])))
                        export_dxf_story(self.proj, i, p, fill.get())
                        done.append(p)
                    p = os.path.join(out, base + "_all_storeys.dxf")
                    export_dxf_combined(self.proj, p, fill.get())
                    done.append(p)
                if opts["dxf3d"].get():
                    p = os.path.join(out, base + "_3D.dxf")
                    export_dxf_3d(self.proj, p)
                    done.append(p)
                if opts["ifc"].get():
                    p = os.path.join(out, base + ".ifc")
                    export_ifc(self.proj, p)
                    done.append(p)
                if opts["obj"].get():
                    p = os.path.join(out, base + ".obj")
                    export_obj(self.proj, p)
                    done += [p, os.path.join(out, base + ".mtl")]
                if opts["pdf"].get():
                    p = os.path.join(out, base + ".pdf")
                    export_pdf(self.proj, p, paper.get(), sc, fill.get())
                    done.append(p)
                if opts["svg"].get():
                    for i, s in enumerate(self.proj["stories"]):
                        p = os.path.join(out, "%s_%02d_%s.svg" % (base, i + 1, safe_name(s["name"])))
                        export_svg_story(self.proj, i, p, sc or 50, fill.get())
                        done.append(p)
                if opts["csv"].get():
                    p = os.path.join(out, base + "_rooms.csv")
                    export_csv(self.proj, p)
                    done.append(p)
                msg.configure(text="%d files written to %s" % (len(done), out), fg="#206020")
                self.set_status("Exported %d files to %s" % (len(done), out))
            except Exception as ex:
                msg.configure(text="Export failed: %s" % ex, fg="#b02020")
        b = tk.Frame(top)
        b.pack(pady=(0, 12))
        tk.Button(b, text="Export", width=12, command=go).pack(side="left", padx=4)
        tk.Button(b, text="Open folder", width=12, command=lambda: (os.makedirs(folder.get(), exist_ok=True),
                                                                   open_path(folder.get()))).pack(side="left", padx=4)
        tk.Button(b, text="Close", width=12, command=top.destroy).pack(side="left", padx=4)
        make_modal(top)


# *************** DEL 62 (cont.) - THE MATERIALS WINDOW: shopping list, prices, stores, where to buy, memos, craftsmen *****************
# One window with tabs (Materials menu).  The logic is in DEL 54; here are only windows.
# 1.4: "Price from web page..." (Prices + Shopping list tabs, class WebPriceDialog) and "Save shopping list as PDF..." (Where to buy tab).
# ToDo: memo reminders by e-mail, craftsmen linked to memos, refreshing a price from the address saved with it.
import threading
import queue
from tkinter import ttk


def ask_form(parent, title, fields, values, validate=None, hint=""):
    """A small modal form.  fields = [{key, label, kind: entry | combo | check | text, options, width}].  Returns {key: value}
    (strings, bool for check) or None when cancelled.  `validate(values)` returns an error text to keep the form open."""
    top = tk.Toplevel(parent)
    top.title(title)
    top.resizable(False, False)
    top.transient(parent)
    res = {"v": None}
    vars_, widgets = {}, {}
    body = tk.Frame(top)
    body.pack(padx=14, pady=(12, 4))
    for r, f in enumerate(fields):
        kind = f.get("kind", "entry")
        tk.Label(body, text=f["label"], anchor="w").grid(row=r, column=0, sticky="nw", padx=(0, 10), pady=3)
        if kind == "check":
            v = tk.BooleanVar(value=bool(values.get(f["key"])))
            tk.Checkbutton(body, variable=v, anchor="w").grid(row=r, column=1, sticky="w")
        elif kind == "combo":
            v = tk.StringVar(value=str(values.get(f["key"], "")))
            cb = ttk.Combobox(body, textvariable=v, values=list(f.get("options", [])), width=f.get("width", 34))
            cb.grid(row=r, column=1, sticky="w", pady=3)
            widgets[f["key"]] = cb
        elif kind == "text":
            t = new_text(body, width=f.get("width", 44), height=f.get("height", 5), wrap="word")
            t.insert("1.0", str(values.get(f["key"], "")))
            t.grid(row=r, column=1, sticky="w", pady=3)
            vars_[f["key"]] = t
            widgets[f["key"]] = t
            continue
        else:
            v = tk.StringVar(value=str(values.get(f["key"], "")))
            e = new_entry(body, textvariable=v, width=f.get("width", 36))
            e.grid(row=r, column=1, sticky="w", pady=3)
            widgets[f["key"]] = e
        vars_[f["key"]] = v
    if hint:
        tk.Label(top, text=hint, fg="#555555", justify="left", wraplength=470, anchor="w").pack(fill="x", padx=14, pady=(0, 2))
    err = tk.Label(top, text="", fg="#aa2222", justify="left", wraplength=470, anchor="w")
    err.pack(fill="x", padx=14)

    def collect():
        out = {}
        for k, v in vars_.items():
            out[k] = v.get("1.0", "end").strip() if isinstance(v, tk.Text) else (v.get() if isinstance(v, tk.BooleanVar) else v.get().strip())
        return out

    def ok(e=None):
        vals = collect()
        msg = validate(vals) if validate else None
        if msg:
            err.configure(text=msg)
            return
        res["v"] = vals
        top.destroy()
    row = tk.Frame(top)
    row.pack(pady=10)
    tk.Button(row, text="OK", width=9, command=ok).pack(side="left", padx=4)
    tk.Button(row, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
    for w in widgets.values():
        if isinstance(w, tk.Entry):
            w.bind("<Return>", ok)
    make_modal(top)
    first = next(iter(widgets.values()), None)
    if first is not None:
        first.focus_set()
    parent.wait_window(top)
    return res["v"]


class ShopWindow(object):
    TABS = ["Shopping list", "Prices", "Stores", "Where to buy", "Memos", "Craftsmen"]

    def __init__(self, app, tab=0):
        self.app = app
        self.book = book_load()
        self.last = None
        self.memo_id = None
        self.top = tk.Toplevel(app.root)
        self.top.title("Materials, prices, memos and craftsmen")
        self.top.geometry("1080x660")
        self.top.transient(app.root)
        self.nb = ttk.Notebook(self.top)
        self.nb.pack(fill="both", expand=True, padx=6, pady=6)
        self.frames = []
        for name in self.TABS:
            f = tk.Frame(self.nb)
            self.nb.add(f, text="  %s  " % name)
            self.frames.append(f)
        self.build_list(self.frames[0])
        self.build_prices(self.frames[1])
        self.build_stores(self.frames[2])
        self.build_where(self.frames[3])
        self.build_memos(self.frames[4])
        self.build_people(self.frames[5])
        self.nb.bind("<<NotebookTabChanged>>", lambda e: self.refresh_all())
        self.top.protocol("WM_DELETE_WINDOW", self.close)
        self.nb.select(tab)
        self.refresh_all()
        make_modal(self.top, on_escape=self.close)

    # ---- helpers ---------------------------------------------------------------------------------------------
    def proj(self):
        return ensure_extras(self.app.proj)

    def save_book(self):
        try:
            book_save(self.book)
        except Exception as ex:
            messagebox.showwarning(APP_TITLE, "Could not save the price book:\n%s" % ex, parent=self.top)

    def touch(self):
        """The project (shopping list / memos) changed."""
        self.app.dirty = True

    def close(self):
        self.save_book()
        self.save_memo()
        self.top.destroy()
        self.app.memo_reminder()

    def ask(self, title, fields, values, validate=None, hint=""):
        return ask_form(self.top, title, fields, values, validate, hint)

    @staticmethod
    def make_tree(parent, cols, heads, widths, height=14):
        fr = tk.Frame(parent)
        sb = tk.Scrollbar(fr)
        sb.pack(side="right", fill="y")
        tv = ttk.Treeview(fr, columns=cols, show="headings", height=height, yscrollcommand=sb.set, selectmode="browse")
        for c, h, w in zip(cols, heads, widths):
            tv.heading(c, text=h)
            tv.column(c, width=w, anchor="w")
        tv.pack(side="left", fill="both", expand=True)
        sb.configure(command=tv.yview)
        return fr, tv

    @staticmethod
    def buttons(parent, items):
        bar = tk.Frame(parent)
        bar.pack(fill="x", padx=6, pady=6)
        out = {}
        for text, cmd in items:
            b = tk.Button(bar, text=text, command=cmd, padx=8)
            b.pack(side="left", padx=(0, 6))
            out[text] = b
        return bar

    def sel_id(self, tv):
        s = tv.selection()
        return int(s[0]) if s else None

    def refresh_all(self):
        self.refresh_list()
        self.refresh_prices()
        self.refresh_stores()
        self.refresh_memos()
        self.refresh_people()

    # ---- tab 1: the shopping list ---------------------------------------------------------------------------
    def build_list(self, f):
        self.buttons(f, [("Fill from the model", self.list_from_model), ("Add line...", self.list_add), ("Edit...", self.list_edit),
                         ("Delete", self.list_delete), ("Price from web page...", self.web_price_for_line)])
        tk.Label(f, justify="left", anchor="w", fg="#555555", wraplength=1000,
                 text="Quantities come from the drawing (walls net of doors and windows, floors, roof, windows, doors, fixtures).  "
                      "'Material' is the name the prices are looked up by - change it to e.g. 'Plasterboard 13 mm' on a line and "
                      "type the stores' prices for that name in the Prices tab.  Waste % is added to the need.").pack(fill="x", padx=8)
        fr, self.lt = self.make_tree(f, ("label", "material", "qty", "unit", "waste", "need", "best"),
                                     ("Line", "Material (price name)", "Quantity", "Unit", "Waste %", "Need", "Cheapest known"),
                                     (330, 200, 80, 50, 60, 80, 230))
        fr.pack(fill="both", expand=True, padx=6, pady=4)
        self.lt.bind("<Double-1>", lambda e: self.list_edit())
        self.list_info = tk.Label(f, anchor="w")
        self.list_info.pack(fill="x", padx=8, pady=(0, 6))

    def refresh_list(self):
        sh = self.proj()["shop"]
        self.lt.delete(*self.lt.get_children())
        priced = 0
        for ln in sh["lines"]:
            o = line_options(self.book, ln)
            best = ""
            if o:
                sid = min(o, key=lambda s: o[s][0])
                best = "%s: %s kr" % (book_store(self.book, sid)["name"], fmt_money(o[sid][0]))
                priced += 1
            self.lt.insert("", "end", iid=str(ln["id"]), values=(ln["label"] + ("" if ln.get("auto") else "  *"), ln["material"],
                                                                  "%.2f" % ln["qty"], ln["unit"], "%g" % ln.get("waste", 0),
                                                                  "%.2f" % line_need(ln), best))
        self.list_info.configure(text="%d line(s), %d with a known price.   * = your own line" % (len(sh["lines"]), priced))

    def list_from_model(self):
        a, u, d = shop_refresh(self.app.proj)
        self.touch()
        self.refresh_list()
        self.list_info.configure(text="From the model: %d new, %d changed, %d removed.  (%d lines)" %
                                      (a, u, d, len(self.proj()["shop"]["lines"])))

    def line_form(self, ln):
        fields = [{"key": "label", "label": "Line"},
                  {"key": "material", "label": "Material (price name)", "kind": "combo", "options": book_materials(self.book, self.app.proj)},
                  {"key": "unit", "label": "Unit", "kind": "combo", "options": BASE_UNITS, "width": 10},
                  {"key": "qty", "label": "Quantity", "width": 12}, {"key": "waste", "label": "Waste %", "width": 8}]

        def validate(v):
            if not v["label"]:
                return "Type a name for the line."
            if v["unit"] not in BASE_UNITS:
                return "Unit must be one of: " + ", ".join(BASE_UNITS)
            if to_num(v["qty"], -1) < 0:
                return "Quantity must be a number."
            return None
        vals = {"label": ln["label"], "material": ln["material"], "unit": ln["unit"], "qty": "%g" % ln["qty"], "waste": "%g" % ln.get("waste", 0)}
        return self.ask("Shopping list line", fields, vals, validate)

    def list_add(self):
        v = self.line_form({"label": "", "material": "", "unit": "m2", "qty": 0.0, "waste": 0.0})
        if v:
            shop_add_line(self.app.proj, v["label"], v["unit"], to_num(v["qty"]), v["material"] or v["label"], to_num(v["waste"]))
            self.touch()
            self.refresh_list()

    def list_edit(self):
        lid = self.sel_id(self.lt)
        ln = next((x for x in self.proj()["shop"]["lines"] if x["id"] == lid), None)
        if ln is None:
            return
        v = self.line_form(ln)
        if v:
            ln["label"], ln["material"], ln["unit"] = v["label"], v["material"] or v["label"], v["unit"]
            ln["qty"], ln["waste"] = to_num(v["qty"]), to_num(v["waste"])
            self.touch()
            self.refresh_list()

    def list_delete(self):
        lid = self.sel_id(self.lt)
        sh = self.proj()["shop"]
        ln = next((x for x in sh["lines"] if x["id"] == lid), None)
        if ln is not None:
            sh["lines"].remove(ln)
            self.touch()
            self.refresh_list()

    # ---- tab 2: prices --------------------------------------------------------------------------------------
    def build_prices(self, f):
        self.buttons(f, [("Add price...", self.price_add), ("Edit...", self.price_edit), ("Delete", self.price_delete),
                         ("Price from web page...", self.web_price), ("Import CSV...", self.price_import), ("Export CSV...", self.price_export)])
        row = tk.Frame(f)
        row.pack(fill="x", padx=8)
        tk.Label(row, text="Find:").pack(side="left")
        self.price_find = tk.StringVar()
        e = new_entry(row, textvariable=self.price_find, width=30)
        e.pack(side="left", padx=6)
        self.price_find.trace_add("write", lambda *a: self.refresh_prices())
        tk.Label(row, fg="#555555", text="  A price is per 'sold per' unit.  A sheet of plasterboard: base unit m2, sold per sheet, contains 2.88.").pack(side="left")
        fr, self.pt = self.make_tree(f, ("store", "material", "price", "unit", "size", "base", "note", "updated"),
                                     ("Store", "Material", "Price kr", "Sold per", "Contains", "Counted in", "Note", "Updated"),
                                     (150, 280, 80, 80, 80, 80, 220, 90))
        fr.pack(fill="both", expand=True, padx=6, pady=4)
        self.pt.bind("<Double-1>", lambda e: self.price_edit())

    def refresh_prices(self):
        self.pt.delete(*self.pt.get_children())
        t = norm_name(self.price_find.get())
        rows = []
        for e in self.book["prices"]:
            s = book_store(self.book, e["store"])
            if s is None or (t and t not in norm_name(s["name"] + " " + e["material"] + " " + e["note"])):
                continue
            rows.append((norm_name(e["material"]), norm_name(s["name"]), e, s))
        for _, _, e, s in sorted(rows, key=lambda r: (r[0], r[1])):
            self.pt.insert("", "end", iid=str(e["id"]), values=(s["name"], e["material"], fmt_money(e["price"]), e["unit"], "%g" % e["size"],
                                                                e["base"], e["note"], e.get("updated", "")))

    def price_form(self, e):
        names = [s["name"] for s in self.book["stores"]]
        fields = [{"key": "store", "label": "Store", "kind": "combo", "options": names},
                  {"key": "material", "label": "Material", "kind": "combo", "options": book_materials(self.book, self.app.proj), "width": 44},
                  {"key": "base", "label": "Counted in (the shopping list's unit)", "kind": "combo", "options": BASE_UNITS, "width": 10},
                  {"key": "price", "label": "Price (kr, incl. VAT)", "width": 14},
                  {"key": "unit", "label": "Sold per", "kind": "combo", "options": SOLD_UNITS, "width": 12},
                  {"key": "size", "label": "One sold unit contains", "width": 12},
                  {"key": "note", "label": "Note"}]

        def validate(v):
            if book_store_by_name(self.book, v["store"]) is None:
                return "Pick a store from the list (add new stores in the Stores tab)."
            if not v["material"]:
                return "Type the material name."
            if v["base"] not in BASE_UNITS:
                return "'Counted in' must be one of: " + ", ".join(BASE_UNITS)
            if to_num(v["price"], -1) < 0:
                return "The price must be a number."
            if to_num(v["size"], 0) <= 0:
                return "'Contains' must be a number above 0 (1 when the price is per %s)." % v["base"]
            return None
        hint = ("Examples:  per square metre:  Counted in m2, price 33, sold per m2, contains 1.     "
                "A sheet of 2.88 m2:  Counted in m2, price 89, sold per sheet, contains 2.88.     "
                "A 4.8 m stud:  Counted in m, price 62, sold per length, contains 4.8.")
        return self.ask("Price", fields, e, validate, hint)

    def price_add(self):
        if not self.book["stores"]:
            messagebox.showinfo(APP_TITLE, "Add a store first (Stores tab).", parent=self.top)
            return
        last = getattr(self, "_last_price", {"store": self.book["stores"][0]["name"], "material": "", "base": "m2", "price": "", "unit": "m2",
                                             "size": "1", "note": ""})
        v = self.price_form(dict(last, price="", note=""))
        if v:
            self._last_price = v
            s = book_store_by_name(self.book, v["store"])
            book_add_price(self.book, s["id"], v["material"], to_num(v["price"]), v["base"], v["unit"], to_num(v["size"], 1.0), v["note"])
            self.save_book()
            self.refresh_prices()

    def price_edit(self):
        eid = self.sel_id(self.pt)
        e = next((x for x in self.book["prices"] if x["id"] == eid), None)
        if e is None:
            return
        v = self.price_form({"store": book_store(self.book, e["store"])["name"], "material": e["material"], "base": e["base"],
                             "price": "%g" % e["price"], "unit": e["unit"], "size": "%g" % e["size"], "note": e["note"]})
        if v:
            e["store"] = book_store_by_name(self.book, v["store"])["id"]
            e["material"], e["base"], e["unit"] = v["material"], v["base"], v["unit"]
            e["price"], e["size"], e["note"], e["updated"] = to_num(v["price"]), to_num(v["size"], 1.0), v["note"], today_str()
            self.save_book()
            self.refresh_prices()

    def price_delete(self):
        eid = self.sel_id(self.pt)
        if eid is not None:
            book_remove(self.book, "prices", eid)
            self.save_book()
            self.refresh_prices()

    def web_price(self, line=None, wait=True):
        """Opens the 'Price from web page' window (a product address or pasted page text -> a price you confirm)."""
        dlg = WebPriceDialog(self, line, wait)
        if wait:
            self.refresh_all()
        return dlg

    def web_price_for_line(self):
        lid = self.sel_id(self.lt)
        ln = next((x for x in self.proj()["shop"]["lines"] if x["id"] == lid), None)
        return self.web_price(ln)

    def price_import(self):
        p = filedialog.askopenfilename(parent=self.top, title="Import prices (CSV with ; between the columns)",
                                       filetypes=[("CSV", "*.csv"), ("All files", "*.*")])
        if p:
            try:
                n = import_prices_csv(self.book, p)
            except Exception as ex:
                messagebox.showwarning(APP_TITLE, "Could not read the file:\n%s" % ex, parent=self.top)
                return
            self.save_book()
            self.refresh_all()
            messagebox.showinfo(APP_TITLE, "%d price(s) read." % n, parent=self.top)

    def price_export(self):
        p = filedialog.asksaveasfilename(parent=self.top, title="Export prices", defaultextension=".csv", initialfile="prices.csv",
                                         filetypes=[("CSV", "*.csv")])
        if p:
            export_prices_csv(self.book, p)

    # ---- tab 3: stores -------------------------------------------------------------------------------------
    def build_stores(self, f):
        self.buttons(f, [("Add store...", self.store_add), ("Edit...", self.store_edit), ("Delete", self.store_delete)])
        tk.Label(f, justify="left", anchor="w", fg="#555555", wraplength=1000,
                 text="Delivery fee = what home delivery costs; free from = order value from which it is free (0 = never free).  "
                      "Fetching cost = what it costs YOU to collect the goods (fuel, time) - 0 if you do not count it.  "
                      "'Where to buy' adds one of the two for every store it uses.").pack(fill="x", padx=8)
        fr, self.st = self.make_tree(f, ("name", "delivers", "fee", "free", "pick", "note"),
                                     ("Store", "Delivers", "Delivery fee kr", "Free from kr", "Fetching cost kr", "Note"),
                                     (200, 70, 110, 100, 120, 420))
        fr.pack(fill="both", expand=True, padx=6, pady=4)
        self.st.bind("<Double-1>", lambda e: self.store_edit())

    def refresh_stores(self):
        self.st.delete(*self.st.get_children())
        for s in sorted(self.book["stores"], key=lambda s: norm_name(s["name"])):
            self.st.insert("", "end", iid=str(s["id"]), values=(s["name"], "yes" if s["delivers"] else "no", fmt_money(s["delivery_fee"]),
                                                                 fmt_money(s["free_over"]), fmt_money(s["pickup_cost"]), s["note"]))

    def store_form(self, s):
        fields = [{"key": "name", "label": "Store / company"}, {"key": "delivers", "label": "Offers home delivery", "kind": "check"},
                  {"key": "delivery_fee", "label": "Delivery fee (kr)", "width": 12},
                  {"key": "free_over", "label": "Delivery free from (kr)", "width": 12},
                  {"key": "pickup_cost", "label": "Cost of fetching it yourself (kr)", "width": 12},
                  {"key": "url", "label": "Web page"}, {"key": "note", "label": "Note"}]

        def validate(v):
            if not v["name"]:
                return "Type the name of the store."
            other = book_store_by_name(self.book, v["name"])
            if other is not None and other["id"] != s.get("id"):
                return "There is already a store with that name."
            return None
        return self.ask("Store", fields, s, validate)

    def store_add(self):
        v = self.store_form({"name": "", "delivers": False, "delivery_fee": "0", "free_over": "0", "pickup_cost": "0", "url": "", "note": ""})
        if v:
            book_add_store(self.book, v["name"], v["delivers"], to_num(v["delivery_fee"]), to_num(v["free_over"]), to_num(v["pickup_cost"]),
                           v["note"], v["url"])
            self.save_book()
            self.refresh_stores()

    def store_edit(self):
        sid = self.sel_id(self.st)
        s = book_store(self.book, sid) if sid is not None else None
        if s is None:
            return
        v = self.store_form({"id": s["id"], "name": s["name"], "delivers": s["delivers"], "delivery_fee": "%g" % s["delivery_fee"],
                             "free_over": "%g" % s["free_over"], "pickup_cost": "%g" % s["pickup_cost"], "url": s.get("url", ""), "note": s["note"]})
        if v:
            s.update({"name": v["name"], "delivers": v["delivers"], "delivery_fee": to_num(v["delivery_fee"]), "free_over": to_num(v["free_over"]),
                      "pickup_cost": to_num(v["pickup_cost"]), "url": v["url"], "note": v["note"]})
            self.save_book()
            self.refresh_stores()
            self.refresh_prices()

    def store_delete(self):
        sid = self.sel_id(self.st)
        s = book_store(self.book, sid) if sid is not None else None
        if s is None:
            return
        n = sum(1 for e in self.book["prices"] if e["store"] == sid)
        if messagebox.askyesno(APP_TITLE, "Delete the store '%s' and its %d price(s)?" % (s["name"], n), parent=self.top):
            book_remove(self.book, "stores", sid)
            self.save_book()
            self.refresh_stores()
            self.refresh_prices()

    # ---- tab 4: where to buy --------------------------------------------------------------------------------
    def build_where(self, f):
        sh = self.proj()["shop"]
        top = tk.Frame(f)
        top.pack(fill="x", padx=8, pady=6)
        self.mode_var = tk.StringVar(value=sh.get("mode", "auto"))
        tk.Label(top, text="Getting the goods:").pack(side="left")
        for val, text in (("auto", "cheaper of fetching / delivery"), ("pickup", "I fetch everything"), ("delivery", "home delivery where offered")):
            tk.Radiobutton(top, text=text, value=val, variable=self.mode_var).pack(side="left", padx=6)
        tk.Label(top, text="   Use at most").pack(side="left")
        self.max_var = tk.StringVar(value=str(sh.get("max_stores", 3)))
        tk.Spinbox(top, from_=1, to=8, width=3, textvariable=self.max_var).pack(side="left", padx=4)
        tk.Label(top, text="stores").pack(side="left")
        self.buttons(f, [("Calculate", self.where_calc), ("Copy text", self.where_copy), ("Save shopping list as CSV...", self.where_csv),
                         ("Save shopping list as PDF...", self.where_pdf)])
        fr = tk.Frame(f)
        fr.pack(fill="both", expand=True, padx=6, pady=4)
        sb = tk.Scrollbar(fr)
        sb.pack(side="right", fill="y")
        self.where_text = new_text(fr, wrap="word", font=("Consolas", 10), yscrollcommand=sb.set)
        self.where_text.pack(side="left", fill="both", expand=True)
        sb.configure(command=self.where_text.yview)
        self.where_text.insert("1.0", "Press 'Calculate'.  The lines of the shopping list are compared with the prices in the book.")
        self.where_text.configure(state="disabled")

    def where_calc(self):
        sh = self.proj()["shop"]
        sh["mode"] = self.mode_var.get()
        try:
            sh["max_stores"] = max(1, min(8, int(self.max_var.get())))
        except ValueError:
            sh["max_stores"] = 3
        self.touch()
        lines = sh["lines"]
        res = best_plans(self.book, lines, sh["mode"], sh["max_stores"])
        self.last = (lines, res)
        txt = plan_text(self.book, lines, res)
        self.where_text.configure(state="normal")
        self.where_text.delete("1.0", "end")
        self.where_text.insert("1.0", txt)
        self.where_text.configure(state="disabled")
        return txt

    def where_copy(self):
        txt = self.where_text.get("1.0", "end").strip()
        self.top.clipboard_clear()
        self.top.clipboard_append(txt)

    def where_csv(self):
        if self.last is None:
            self.where_calc()
        p = filedialog.asksaveasfilename(parent=self.top, title="Save the shopping list", defaultextension=".csv", initialfile="shopping.csv",
                                         filetypes=[("CSV", "*.csv")])
        if p:
            export_shop_csv(self.book, self.last[0], self.last[1], p)

    def where_pdf(self, path=None):
        """The shopping list with the where-to-buy result as a PDF (calculated again first, so the prices are today's)."""
        self.where_calc()
        p = path or filedialog.asksaveasfilename(parent=self.top, title="Save the shopping list as PDF", defaultextension=".pdf",
                                                 initialfile="shopping_list.pdf", filetypes=[("PDF", "*.pdf")])
        if not p:
            return None
        try:
            n = shop_pdf(self.book, self.last[0], self.last[1], p, self.app.proj.get("name", ""), "A4")
        except Exception as ex:
            messagebox.showwarning(APP_TITLE, "Could not write the PDF:\n%s" % ex, parent=self.top)
            return None
        if not path and messagebox.askyesno(APP_TITLE, "Saved %d page(s):\n%s\n\nOpen it now?" % (n, p), parent=self.top):
            open_path(p)
        return n

    # ---- tab 5: memos --------------------------------------------------------------------------------------
    def build_memos(self, f):
        self.buttons(f, [("New memo", self.memo_new), ("Delete", self.memo_delete)])
        self.memo_hide = tk.BooleanVar(value=False)
        tk.Checkbutton(f.winfo_children()[0], text="Hide finished", variable=self.memo_hide, command=self.refresh_memos).pack(side="left", padx=10)
        pane = tk.Frame(f)
        pane.pack(fill="both", expand=True, padx=6, pady=4)
        left = tk.Frame(pane)
        left.pack(side="left", fill="y")
        fr, self.mt = self.make_tree(left, ("title", "due", "flags"), ("Memo", "Due", ""), (230, 90, 50), 18)
        fr.pack(fill="y", expand=True)
        self.mt.bind("<<TreeviewSelect>>", lambda e: self.memo_show())
        right = tk.Frame(pane)
        right.pack(side="left", fill="both", expand=True, padx=(10, 0))
        grid = tk.Frame(right)
        grid.pack(fill="x")
        tk.Label(grid, text="Title").grid(row=0, column=0, sticky="w")
        self.m_title = tk.StringVar()
        new_entry(grid, textvariable=self.m_title, width=50).grid(row=0, column=1, sticky="w", padx=6, pady=2)
        tk.Label(grid, text="Due date (yyyy-mm-dd)").grid(row=1, column=0, sticky="w")
        self.m_due = tk.StringVar()
        new_entry(grid, textvariable=self.m_due, width=14).grid(row=1, column=1, sticky="w", padx=6, pady=2)
        self.m_pin, self.m_done = tk.BooleanVar(), tk.BooleanVar()
        flags = tk.Frame(grid)
        flags.grid(row=2, column=1, sticky="w")
        tk.Checkbutton(flags, text="Pinned (always on top)", variable=self.m_pin).pack(side="left")
        tk.Checkbutton(flags, text="Done", variable=self.m_done).pack(side="left", padx=10)
        self.m_text = new_text(right, wrap="word", height=14, font=("Segoe UI", 10))
        self.m_text.pack(fill="both", expand=True, pady=6)
        tk.Label(right, anchor="w", fg="#555555", text="Memos are saved inside the project file (Ctrl+S in the main window).").pack(fill="x")
        for v in (self.m_title, self.m_due, self.m_pin, self.m_done):
            v.trace_add("write", lambda *a: self.save_memo())
        self.m_text.bind("<KeyRelease>", lambda e: self.save_memo())

    def memo_by_id(self, mid):
        return next((n for n in self.proj()["notes"] if n["id"] == mid), None)

    def refresh_memos(self):
        keep = self.memo_id
        self.mt.delete(*self.mt.get_children())
        for n in memos_sorted(self.app.proj, self.memo_hide.get()):
            due = n.get("due", "")
            late = due and not n.get("done") and due <= today_str()
            self.mt.insert("", "end", iid=str(n["id"]), values=(n["title"], due + (" !" if late else ""),
                                                                 ("*" if n.get("pinned") else "") + ("ok" if n.get("done") else "")))
        if keep is not None and self.mt.exists(str(keep)):
            self.mt.selection_set(str(keep))
        elif self.mt.get_children():
            self.mt.selection_set(self.mt.get_children()[0])
        else:
            self.memo_id = None
            self.memo_fill(None)

    def memo_show(self):
        self.save_memo()
        mid = self.sel_id(self.mt)
        self.memo_id = mid
        self.memo_fill(self.memo_by_id(mid) if mid is not None else None)

    def memo_fill(self, n):
        self._filling = True
        self.m_title.set(n["title"] if n else "")
        self.m_due.set(n.get("due", "") if n else "")
        self.m_pin.set(bool(n and n.get("pinned")))
        self.m_done.set(bool(n and n.get("done")))
        self.m_text.delete("1.0", "end")
        self.m_text.insert("1.0", n["text"] if n else "")
        self._filling = False

    def save_memo(self):
        if getattr(self, "_filling", False) or self.memo_id is None:
            return
        n = self.memo_by_id(self.memo_id)
        if n is None:
            return
        new = (self.m_title.get().strip() or "Memo", self.m_due.get().strip(), self.m_pin.get(), self.m_done.get(),
               self.m_text.get("1.0", "end").rstrip("\n"))
        if new != (n["title"], n.get("due", ""), n.get("pinned", False), n.get("done", False), n["text"]):
            n["title"], n["due"], n["pinned"], n["done"], n["text"] = new
            n["changed"] = today_str()
            self.touch()
            try:
                self.mt.set(str(n["id"]), "title", n["title"])
                self.mt.set(str(n["id"]), "due", n["due"])
                self.mt.set(str(n["id"]), "flags", ("*" if n["pinned"] else "") + ("ok" if n["done"] else ""))
            except tk.TclError:
                pass

    def memo_new(self):
        self.save_memo()
        n = add_memo(self.app.proj, "New memo")
        self.memo_id = n["id"]
        self.touch()
        self.refresh_memos()
        self.mt.selection_set(str(n["id"]))

    def memo_delete(self):
        if self.memo_id is None:
            return
        n = self.memo_by_id(self.memo_id)
        if n is not None:
            self.proj()["notes"].remove(n)
            self.memo_id = None
            self.touch()
            self.refresh_memos()

    # ---- tab 6: craftsmen ----------------------------------------------------------------------------------
    def build_people(self, f):
        self.buttons(f, [("Add...", self.people_add), ("Edit...", self.people_edit), ("Delete", self.people_delete),
                         ("Copy phone", self.people_copy), ("Write e-mail", self.people_mail), ("Export CSV...", self.people_export)])
        row = tk.Frame(f)
        row.pack(fill="x", padx=8)
        tk.Label(row, text="Find:").pack(side="left")
        self.pp_find = tk.StringVar()
        new_entry(row, textvariable=self.pp_find, width=28).pack(side="left", padx=6)
        tk.Label(row, text="Trade:").pack(side="left", padx=(10, 0))
        self.pp_trade = tk.StringVar(value="All")
        ttk.Combobox(row, textvariable=self.pp_trade, values=["All"] + TRADES, width=22, state="readonly").pack(side="left", padx=6)
        self.pp_find.trace_add("write", lambda *a: self.refresh_people())
        self.pp_trade.trace_add("write", lambda *a: self.refresh_people())
        fr, self.pp = self.make_tree(f, ("name", "trade", "company", "phone", "email", "rate", "rating", "note"),
                                     ("Name", "Trade", "Company", "Phone", "E-mail", "Rate", "Rating", "Note"),
                                     (160, 130, 150, 120, 180, 90, 60, 220))
        fr.pack(fill="both", expand=True, padx=6, pady=4)
        self.pp.bind("<Double-1>", lambda e: self.people_edit())

    def refresh_people(self):
        self.pp.delete(*self.pp.get_children())
        for c in find_contacts(self.book, self.pp_find.get(), self.pp_trade.get()):
            self.pp.insert("", "end", iid=str(c["id"]), values=(c["name"], c["trade"], c["company"], c["phone"], c["email"], c["rate"],
                                                                 "*" * int(c.get("rating", 0)), c["note"]))

    def people_form(self, c):
        fields = [{"key": "name", "label": "Name"}, {"key": "trade", "label": "Trade", "kind": "combo", "options": TRADES},
                  {"key": "company", "label": "Company"}, {"key": "phone", "label": "Phone"}, {"key": "email", "label": "E-mail"},
                  {"key": "address", "label": "Address"}, {"key": "web", "label": "Web page"}, {"key": "rate", "label": "Rate / price (e.g. 650 kr/h)"},
                  {"key": "rating", "label": "Rating 0-5", "width": 5}, {"key": "note", "label": "Note", "kind": "text", "height": 4}]

        def validate(v):
            if not v["name"] and not v["company"]:
                return "Type a name or a company."
            if v["rating"] and not v["rating"].isdigit():
                return "Rating is a number 0-5."
            return None
        return self.ask("Craftsman / contact", fields, c, validate)

    def people_add(self):
        v = self.people_form({"name": "", "trade": "Carpenter", "company": "", "phone": "", "email": "", "address": "", "web": "", "rate": "",
                              "rating": "0", "note": ""})
        if v:
            book_add_contact(self.book, v["name"] or v["company"], v["trade"], v["company"], v["phone"], v["email"], v["address"], v["rate"],
                             min(5, int(v["rating"] or 0)), v["note"], v["web"])
            self.save_book()
            self.refresh_people()

    def people_edit(self):
        cid = self.sel_id(self.pp)
        c = next((x for x in self.book["contacts"] if x["id"] == cid), None)
        if c is None:
            return
        vals = {k: str(c.get(k, "")) for k in ("name", "trade", "company", "phone", "email", "address", "web", "rate", "rating", "note")}
        v = self.people_form(vals)
        if v:
            c.update({k: v[k] for k in ("name", "trade", "company", "phone", "email", "address", "web", "rate", "note")})
            c["rating"] = min(5, int(v["rating"] or 0))
            self.save_book()
            self.refresh_people()

    def people_delete(self):
        cid = self.sel_id(self.pp)
        c = next((x for x in self.book["contacts"] if x["id"] == cid), None)
        if c is not None and messagebox.askyesno(APP_TITLE, "Delete %s?" % (c["name"] or c["company"]), parent=self.top):
            book_remove(self.book, "contacts", cid)
            self.save_book()
            self.refresh_people()

    def people_copy(self):
        cid = self.sel_id(self.pp)
        c = next((x for x in self.book["contacts"] if x["id"] == cid), None)
        if c is not None:
            self.top.clipboard_clear()
            self.top.clipboard_append(c["phone"])

    def people_mail(self):
        cid = self.sel_id(self.pp)
        c = next((x for x in self.book["contacts"] if x["id"] == cid), None)
        if c is not None and c["email"]:
            webbrowser.open("mailto:" + c["email"])

    def people_export(self):
        p = filedialog.asksaveasfilename(parent=self.top, title="Export craftsmen", defaultextension=".csv", initialfile="craftsmen.csv",
                                         filetypes=[("CSV", "*.csv")])
        if p:
            export_contacts_csv(self.book, p)


# ---- the window "Price from web page" -------------------------------------------------------------------------------------------
class WebPriceDialog(object):
    """A product address (or pasted page text) -> the prices found in it -> you confirm one -> it goes into the price book.
    Nothing is saved before 'Save price'.  The address is read once per click, in the background (the window stays alive)."""

    def __init__(self, win, line=None, wait=True, fetcher=None):
        self.win = win
        self.book = win.book
        self.line = line
        self.fetcher = fetcher or web_fetch
        self.res = None
        self.page_url = ""
        self.saved = 0
        self._q = None
        self._filling = False
        top = self.top = tk.Toplevel(win.top)
        top.title("Price from a web page")
        top.geometry("920x720")
        top.transient(win.top)
        tk.Label(top, anchor="w", justify="left", fg="#555555", wraplength=880,
                 text="Paste the address of ONE product page and press 'Read the page': the program reads that single page (nothing else is sent) and "
                      "lists the prices it finds.  Pick the right one, check the fields, then 'Save price'.  Some shops block programs or build "
                      "the price with JavaScript - then open the page in your browser, press Ctrl+A, Ctrl+C and paste the text below.").pack(
            fill="x", padx=10, pady=(8, 2))
        row = tk.Frame(top)
        row.pack(fill="x", padx=10, pady=4)
        tk.Label(row, text="Product page address:").pack(side="left")
        self.url_var = tk.StringVar()
        self.url_entry = new_entry(row, textvariable=self.url_var, width=70)
        self.url_entry.pack(side="left", padx=6, fill="x", expand=True)
        self.url_entry.bind("<Return>", lambda e: self.read_url())
        self.read_btn = tk.Button(row, text="Read the page", command=self.read_url, padx=8)
        self.read_btn.pack(side="left")
        tk.Label(top, anchor="w", text="... or the text / HTML of the page, pasted here:").pack(fill="x", padx=10)
        pf = tk.Frame(top)
        pf.pack(fill="x", padx=10, pady=2)
        sb = tk.Scrollbar(pf)
        sb.pack(side="right", fill="y")
        self.paste = new_text(pf, height=4, wrap="word", yscrollcommand=sb.set)
        self.paste.pack(side="left", fill="x", expand=True)
        sb.configure(command=self.paste.yview)
        self.paste_btn = tk.Button(top, text="Read the pasted text", command=self.read_paste, padx=8)
        self.paste_btn.pack(anchor="w", padx=10, pady=4)
        self.status = tk.Label(top, anchor="nw", justify="left", wraplength=880, height=3)
        self.status.pack(fill="x", padx=10)
        fr, self.tv = ShopWindow.make_tree(top, ("price", "cur", "src", "ctx"), ("Price", "Currency", "Found in", "Words around it / note"),
                                           (80, 70, 170, 520), 7)
        fr.pack(fill="both", expand=True, padx=10, pady=4)
        self.tv.bind("<<TreeviewSelect>>", lambda e: self.pick())
        form = tk.LabelFrame(top, text="Save into the price book  (check every field)", padx=8, pady=6)
        form.pack(fill="x", padx=10, pady=4)
        self.vars = {}
        names = [s["name"] for s in self.book["stores"]]
        base0 = line["unit"] if line else "m2"
        spec = [("store", "Store", "combo", names, 30), ("material", "Material (price name)", "combo", book_materials(self.book, win.app.proj), 44),
                ("base", "Counted in (the shopping list's unit)", "combo", BASE_UNITS, 8), ("price", "Price (incl. VAT)", "entry", None, 12),
                ("unit", "Sold per", "combo", SOLD_UNITS, 10), ("size", "One sold unit contains", "entry", None, 10)]
        init = {"store": "", "material": line["material"] if line else "", "base": base0, "price": "", "unit": base0, "size": "1"}
        for r, (k, lab, kind, opts, wd) in enumerate(spec):
            tk.Label(form, text=lab, anchor="w").grid(row=r // 2, column=(r % 2) * 2, sticky="w", padx=(0, 6), pady=2)
            v = tk.StringVar(value=init[k])
            w = ttk.Combobox(form, textvariable=v, values=list(opts), width=wd) if kind == "combo" else new_entry(form, textvariable=v, width=wd)
            w.grid(row=r // 2, column=(r % 2) * 2 + 1, sticky="w", padx=(0, 18), pady=2)
            self.vars[k] = v
            v.trace_add("write", lambda *a: self.update_info())
        self.info = tk.Label(top, anchor="nw", justify="left", wraplength=880, height=3)
        self.info.pack(fill="x", padx=10)
        end = tk.Frame(top)
        end.pack(fill="x", padx=10, pady=8)
        self.save_btn = tk.Button(end, text="Save price", command=self.save, padx=12, bg="#cfe8c4")
        self.save_btn.pack(side="left")
        tk.Button(end, text="Close", command=self.close, padx=12).pack(side="right")
        top.protocol("WM_DELETE_WINDOW", self.close)
        self.set_status("Paste an address and press 'Read the page'.")
        make_modal(top, on_escape=self.close)
        self.url_entry.focus_set()
        if wait:
            win.top.wait_window(top)

    # ---- helpers -------------------------------------------------------------------------------------------------
    def close(self):
        self._q = None
        self.top.destroy()

    def set_status(self, text, bad=False):
        self.status.configure(text=text, fg="#aa2222" if bad else "#206020")

    def say(self, text, bad=False):
        self.info.configure(text=text, fg="#aa2222" if bad else "#444444")

    def cand(self):
        s = self.tv.selection()
        return self.res["candidates"][int(s[0])] if (s and self.res) else None

    # ---- reading ---------------------------------------------------------------------------------------------------
    def read_url(self):
        try:
            u = web_check_url(self.url_var.get())
        except WebPriceError as ex:
            self.set_status(str(ex), True)
            return
        self.url_var.set(u)
        self.read_btn.configure(state="disabled")
        self.set_status("Reading the page ...")
        q = self._q = queue.Queue()

        def work():
            try:
                q.put(("ok", self.fetcher(u)))
            except WebPriceError as ex:
                q.put(("err", str(ex)))
            except Exception as ex:                                      # never let a thread die silently
                q.put(("err", "Could not read the page: %s" % ex))
        threading.Thread(target=work, daemon=True).start()
        self.top.after(100, self.poll)

    def poll(self):
        try:
            if not self.top.winfo_exists() or self._q is None:
                return
            try:
                kind, val = self._q.get_nowait()
            except queue.Empty:
                self.top.after(100, self.poll)
                return
            self._q = None
            self.read_btn.configure(state="normal")
            if kind == "err":
                self.set_status(val, True)
                return
            self.page_url = val.get("url", "")
            self.show(web_parse(val["text"], self.page_url), val.get("truncated"))
        except tk.TclError:
            pass

    def read_paste(self):
        txt = self.paste.get("1.0", "end").strip()
        if not txt:
            self.set_status("Paste the text of the page first (Ctrl+V in the box).", True)
            return
        self.show(web_parse(txt, self.url_var.get().strip()), False)

    def show(self, res, truncated=False):
        """Fills the list with what was found and guesses the store, the material and the units."""
        self.res = res
        self.tv.delete(*self.tv.get_children())
        for i, c in enumerate(res["candidates"]):
            self.tv.insert("", "end", iid=str(i), values=("%s" % fmt_money(c["price"]), c["currency"] or "?", c["source"],
                                                          (c.get("context") or "") + ("   <- " + c["note"] if c.get("note") and c["source"] == "text pattern" else "")))
        st = web_guess_store(self.book, self.page_url or self.url_var.get())
        if st is not None and not self.vars["store"].get():
            self.vars["store"].set(st["name"])
        if res["title"] and not self.vars["material"].get():
            self.vars["material"].set(re.split(r"\s+[|\u2013\u2014]\s+", res["title"])[0][:70])
        n = len(res["candidates"])
        if res["problem"]:
            self.set_status(res["problem"], True)
        else:
            self.set_status("%d price(s) found%s.  %s Pick the one that is the price of the product, then check the fields below.%s" %
                            (n, " in the page's product data" if res["structured"] else "",
                             "" if res["structured"] else "These come from patterns in the text - read the words around each.",
                             "  (The page was long: only the first part was read.)" if truncated else ""))
        if n:
            self.tv.selection_set("0")
            self.pick()                                      # do not wait for the list's own select event
        else:
            self._extra = ""
            self.say("")

    def pick(self):
        c = self.cand()
        if c is None:
            return
        self._filling = True
        self.vars["price"].set("%g" % round(c["price"], 2))
        hint = self.res.get("size_hint")
        g = c.get("unit")
        msgs = []
        if g:                                                     # 'kr/m2', 'kr/st' ... right after the price
            self.vars["base"].set(g["base"])
            self.vars["unit"].set(g["unit"])
            if g["unit"] in ("pack", "roll", "sheet") and hint and hint["unit"] == g["unit"]:
                self.vars["base"].set(hint["base"])
                self.vars["size"].set("%g" % hint["size"])
                msgs.append("The page says %g %s per %s - used as 'contains'." % (hint["size"], hint["base"], hint["unit"]))
            else:
                self.vars["size"].set("1")
        elif hint and not self.line:
            self.vars["base"].set(hint["base"])
            self.vars["unit"].set(hint["unit"])
            self.vars["size"].set("%g" % hint["size"])
            msgs.append("The page says %g %s per %s - guessed from that." % (hint["size"], hint["base"], hint["unit"]))
        self._filling = False
        if c.get("note"):
            msgs.append("Note: %s." % c["note"])
        self.update_info(" ".join(msgs))

    def update_info(self, extra=None):
        if self._filling:
            return
        if extra is not None:
            self._extra = extra
        msgs = [getattr(self, "_extra", "")]
        bad = False
        c = self.cand()
        if c is not None and c["currency"] not in ("", "SEK"):
            msgs.append("The price is in %s but the book counts kr - convert it (type the kr price) before saving." % c["currency"])
            bad = True
        st = book_store_by_name(self.book, self.vars["store"].get())
        size = to_num(self.vars["size"].get(), 0.0)
        mat = self.vars["material"].get().strip()
        if st is not None and mat and size > 0:
            old = web_find_existing(self.book, st["id"], mat, self.vars["base"].get().strip(), self.vars["unit"].get().strip(), size)
            msgs.append(("Saving REPLACES the price now in the book: %s kr (%s)." % (fmt_money(old["price"]), old.get("updated", "")))
                        if old else "This is a new price for the book.")
        self.say(" ".join(m for m in msgs if m), bad)

    # ---- saving ------------------------------------------------------------------------------------------------------
    def save(self):
        v = {k: x.get().strip() for k, x in self.vars.items()}
        st = book_store_by_name(self.book, v["store"])
        if st is None:
            if not v["store"]:
                self.say("Pick or type the store.", True)
                return
            if not messagebox.askyesno(APP_TITLE, "There is no store called '%s' in the book.\nAdd it?" % v["store"], parent=self.top):
                return
            host = web_host(self.page_url or self.url_var.get())
            st = book_add_store(self.book, v["store"], url=("https://" + host) if host else "")
        price, size = to_num(v["price"], -1.0), to_num(v["size"], 0.0)
        if not v["material"]:
            self.say("Type the material name (the name on the shopping list line).", True)
        elif v["base"] not in BASE_UNITS:
            self.say("'Counted in' must be one of: " + ", ".join(BASE_UNITS), True)
        elif price <= 0:
            self.say("The price must be a number above 0 (pick a line in the list or type it).", True)
        elif size <= 0:
            self.say("'Contains' must be a number above 0 (1 when the price is per %s)." % v["base"], True)
        else:
            c = self.cand()
            if c is not None and c["currency"] not in ("", "SEK") and abs(c["price"] - price) < 1e-9 and not messagebox.askyesno(
                    APP_TITLE, "That price is in %s, not kr.  Save %s as kr anyway?" % (c["currency"], fmt_money(price)), parent=self.top):
                return
            title = (self.res or {}).get("title", "")
            e, old = web_save_price(self.book, st["id"], v["material"], price, v["base"], v["unit"] or v["base"], size,
                                    self.page_url or self.url_var.get().strip(), title)
            self.win.save_book()
            self.saved += 1
            self.set_status("Saved: %s / %s = %s kr per %s%s." % (st["name"], e["material"], fmt_money(price), e["unit"],
                                                                  "" if not old else " (replaced %s kr from %s)" % (fmt_money(old["price"]), old.get("updated", ""))))
            self.say("")
            return e
        return None

# *************** DEL 62 (cont.) - STAIR PARTS WINDOW ("Edit parts...": steps, space under the stairs) *****************
# Logic: DEL 27.  The window changes the real stair at once (plan + 3D follow); Cancel / Esc puts everything back.
# ToDo: the same window for kitchen units (shelves, drawers, doors) - build it on the same section rows.
from tkinter import ttk

UNDER_SIDES = [("right", "Right side (as you walk up)"), ("left", "Left side")]


class StairEditor(object):

    def __init__(self, app, st):
        self.app = app
        self.st = st
        self.rise = stair_rise(app.proj, app.sidx, st)
        self.orig = copy.deepcopy(st)
        self.done = False
        app.push_undo()                                      # one Ctrl+Z takes back everything done in this window
        self.top = tk.Toplevel(app.root)
        self.top.title("Stairs - parts")
        self.top.resizable(False, False)
        self.top.transient(app.root)
        try:
            self.top.geometry("+%d+%d" % (app.root.winfo_rootx() + 220, app.root.winfo_rooty() + 90))
        except Exception:
            pass
        self.top.protocol("WM_DELETE_WINDOW", self.cancel)
        self.rows = []
        self.build()
        self.refresh()
        make_modal(self.top, on_escape=self.cancel)

    # ---- window --------------------------------------------------------------------------------------------------
    def build(self):
        st = self.st
        body = tk.Frame(self.top)
        body.pack(padx=10, pady=(10, 4))
        left = tk.LabelFrame(body, text="Steps", padx=8, pady=6)
        left.grid(row=0, column=0, sticky="nw")
        self.v_n = tk.StringVar(value=str(st["n"]))
        self.v_tread = tk.StringVar(value="%g" % round(st["tread"], 1))
        self.v_w = tk.StringVar(value="%g" % round(st["w"], 1))
        self.v_run = tk.StringVar(value="%g" % round(stair_run_length(st), 1))
        self.v_rise = tk.StringVar(value="%g" % round(self.rise, 1))
        self.v_info = tk.StringVar()
        for r, (label, var, key) in enumerate((("Number of steps (risers)", self.v_n, "n"), ("Tread depth (mm)", self.v_tread, "tread"),
                                               ("Run length (mm)", self.v_run, "run"), ("Width (mm)", self.v_w, "w"),
                                               ("Total rise (mm)", self.v_rise, "rise"))):
            tk.Label(left, text=label, anchor="w", width=22).grid(row=r, column=0, sticky="w", pady=2)
            e = new_entry(left, textvariable=var, width=9)
            e.grid(row=r, column=1, pady=2)
            e.bind("<Return>", lambda ev, k=key: self.commit_numbers(k))
            e.bind("<FocusOut>", lambda ev, k=key: self.commit_numbers(k))
            if st["kind"] != "straight" and key == "run":
                e.configure(state="disabled")
        tk.Label(left, textvariable=self.v_info, anchor="w", justify="left", width=34, height=4, wraplength=250).grid(
            row=5, column=0, columnspan=2, sticky="w", pady=(6, 2))
        tk.Button(left, text="Fit the number of steps to the run length", command=self.fit_steps).grid(
            row=6, column=0, columnspan=2, sticky="we", pady=2)

        under = tk.LabelFrame(body, text="Space under the stairs", padx=8, pady=6)
        under.grid(row=1, column=0, sticky="nw", pady=(8, 0))
        u = stair_under(st)
        self.v_mode = tk.StringVar(value=dict(UNDER_MODES)[u["mode"]])
        self.cb_mode = ttk.Combobox(under, textvariable=self.v_mode, values=[v for _, v in UNDER_MODES], state="readonly", width=32)
        self.cb_mode.grid(row=0, column=0, columnspan=2, sticky="w")
        self.cb_mode.bind("<<ComboboxSelected>>", lambda ev: self.mode_changed())
        tk.Label(under, text="Front (doors) on", anchor="w").grid(row=1, column=0, sticky="w", pady=(6, 0))
        self.v_side = tk.StringVar(value=dict(UNDER_SIDES)[u.get("side", "right")])
        self.cb_side = ttk.Combobox(under, textvariable=self.v_side, values=[v for _, v in UNDER_SIDES], state="readonly", width=24)
        self.cb_side.grid(row=1, column=1, sticky="w", pady=(6, 0))
        self.cb_side.bind("<<ComboboxSelected>>", lambda ev: self.side_changed())
        tk.Label(under, text="Number of sections", anchor="w").grid(row=2, column=0, sticky="w", pady=(6, 0))
        self.v_count = tk.StringVar(value=str(max(1, len(u.get("sections") or [1]))))
        self.sp_count = tk.Spinbox(under, from_=1, to=6, width=4, textvariable=self.v_count, command=self.count_changed)
        self.sp_count.grid(row=2, column=1, sticky="w", pady=(6, 0))
        self.sp_count.bind("<Return>", lambda ev: self.count_changed())
        self.sp_count.bind("<FocusOut>", lambda ev: self.count_changed())
        pf = tk.Frame(under)
        pf.grid(row=3, column=0, columnspan=2, sticky="we", pady=(6, 0))
        tk.Button(pf, text="Preset: wardrobe + shelves + drawers", command=self.preset).pack(side="left", fill="x", expand=True)
        tk.Button(pf, text="Equal widths", command=self.equal_widths).pack(side="left", padx=(4, 0))
        self.v_bespoke = tk.BooleanVar(value=bool(u.get("bespoke")))
        tk.Checkbutton(under, text="Bespoke: made to fit the stairs (no open areas, all doors + drawers)", variable=self.v_bespoke,
                       anchor="w", command=self.bespoke_changed).grid(row=4, column=0, columnspan=2, sticky="w", pady=(6, 0))
        self.v_note = tk.StringVar()
        tk.Label(under, textvariable=self.v_note, anchor="w", justify="left", wraplength=370, width=52, height=4,
                 fg="#a04010").grid(row=5, column=0, columnspan=2, sticky="w", pady=(4, 0))

        right = tk.LabelFrame(body, text="Side view (foot on the left, top on the right)", padx=6, pady=6)
        right.grid(row=0, column=1, rowspan=2, sticky="nw", padx=(10, 0))
        self.cv = tk.Canvas(right, width=600, height=330, bg="#fbfbf8", highlightthickness=0)
        self.cv.pack()
        self.sec_frame = tk.LabelFrame(right, text="Sections (section 1 is under the top of the stairs)", padx=6, pady=4)
        self.sec_frame.pack(fill="x", pady=(6, 0))
        self.rebuild_rows()

        btns = tk.Frame(self.top)
        btns.pack(pady=(4, 10))
        tk.Button(btns, text="OK", width=10, command=self.ok).pack(side="left", padx=6)
        tk.Button(btns, text="Cancel", width=10, command=self.cancel).pack(side="left", padx=6)
        tk.Label(btns, text="Changes show in the plan and the 3D view at once.  Cancel / Esc puts everything back.",
                 fg="#666666").pack(side="left", padx=10)

    def rebuild_rows(self):
        for w in self.sec_frame.winfo_children():
            w.destroy()
        self.rows = []
        u = stair_under(self.st)
        secs = u.get("sections") or []
        on = self.st["kind"] == "straight" and u["mode"] == "cupboard"
        for i, s in enumerate(secs if on else []):
            lab = tk.Label(self.sec_frame, text="", anchor="w", width=27)
            lab.grid(row=i, column=0, sticky="w", pady=1)
            vt = tk.StringVar(value=s.get("type", "shelves"))
            ct = ttk.Combobox(self.sec_frame, textvariable=vt, values=SECTION_TYPES, state="readonly", width=9)
            ct.grid(row=i, column=1, padx=3)
            vn = tk.StringVar(value=str(s.get("n", 0)))
            en = new_entry(self.sec_frame, textvariable=vn, width=4)
            en.grid(row=i, column=2, padx=3)
            tk.Label(self.sec_frame, text="shelves / drawers", fg="#666666").grid(row=i, column=3, sticky="w")
            vf = tk.StringVar(value=s.get("front", "closed"))
            cf = ttk.Combobox(self.sec_frame, textvariable=vf, values=FRONT_TYPES, state="disabled" if stair_bespoke(self.st) else "readonly",
                              width=11)
            cf.grid(row=i, column=4, padx=3)
            for w in (ct, cf):
                w.bind("<<ComboboxSelected>>", lambda ev, i=i: self.section_changed(i))
            en.bind("<Return>", lambda ev, i=i: self.section_changed(i))
            en.bind("<FocusOut>", lambda ev, i=i: self.section_changed(i))
            ww = s.get("w")
            vw = tk.StringVar(value=("%g" % round(float(ww), 1)) if section_width_set(s) else "auto")
            ew = new_entry(self.sec_frame, textvariable=vw, width=6)
            ew.grid(row=i, column=5, padx=(8, 2))
            tk.Label(self.sec_frame, text="mm wide", fg="#666666").grid(row=i, column=6, sticky="w")
            ew.bind("<Return>", lambda ev, i=i: self.section_changed(i))
            ew.bind("<FocusOut>", lambda ev, i=i: self.section_changed(i))
            self.rows.append((lab, vt, vn, vf, vw))
        if not on:
            tk.Label(self.sec_frame, text="(choose 'Cupboard under the stairs' on the left to fit out the space)",
                     fg="#666666").grid(row=0, column=0, sticky="w")
        self.top.update_idletasks()

    # ---- commands ------------------------------------------------------------------------------------------------
    def touch(self):
        self.app.changed(props=False)
        self.refresh()

    def commit_numbers(self, key):
        st = self.st
        try:
            n = int(float(self.v_n.get().replace(",", ".")))
            tread = float(self.v_tread.get().replace(",", "."))
            w = float(self.v_w.get().replace(",", "."))
            run = float(self.v_run.get().replace(",", "."))
            rise = float(self.v_rise.get().replace(",", "."))
        except ValueError:
            self.refresh()
            return
        if key == "rise":                                     # an exception: climb another height than one floor
            rise = max(300.0, rise)
            if abs(rise - stair_total_rise(self.app.proj, self.app.sidx)) < 0.5:
                st.pop("rise", None)
            else:
                st["rise"] = rise
            self.rise = stair_rise(self.app.proj, self.app.sidx, st)
            self.touch()
            return
        n = max(3, min(80, n))
        w = max(400.0, w)
        if key == "run" and st["kind"] == "straight":
            tread = max(80.0, run / (n - 1))
        elif key == "n" and st["kind"] == "straight":
            tread = max(80.0, stair_run_length(st) / (n - 1))          # the run stays, the steps get shallower / deeper
        tread = max(80.0, tread)
        if (n, round(tread, 3), w) != (st["n"], round(st["tread"], 3), st["w"]):
            st["n"], st["tread"], st["w"] = n, tread, w
            self.touch()
        else:
            self.refresh()

    def fit_steps(self):
        st = self.st
        if st["kind"] != "straight":
            return
        run = stair_run_length(st)
        n = stair_best_steps(self.rise, run)
        st["n"], st["tread"] = n, run / (n - 1)
        self.touch()

    def mode_changed(self):
        keys = {v: k for k, v in UNDER_MODES}
        mode = keys.get(self.v_mode.get(), "solid")
        if self.st["kind"] != "straight":
            mode = "solid"
        u = stair_under(self.st)
        if mode == "cupboard" and not u.get("sections"):
            self.st["under"] = default_cupboard(3)
            self.st["under"]["bespoke"] = bool(self.v_bespoke.get())
            self.v_count.set("3")
        else:
            self.st["under"] = {"mode": mode, "side": u.get("side", "right"), "sections": list(u.get("sections") or []),
                                "bespoke": bool(u.get("bespoke"))}
        if mode == "cupboard":
            self.st["under"]["bespoke"] = bool(self.v_bespoke.get())
        self.rebuild_rows()
        self.touch()

    def bespoke_changed(self):
        u = dict(stair_under(self.st))
        u["bespoke"] = bool(self.v_bespoke.get())
        self.st["under"] = u
        self.rebuild_rows()
        self.touch()

    def side_changed(self):
        keys = {v: k for k, v in UNDER_SIDES}
        u = dict(stair_under(self.st))
        u["side"] = keys.get(self.v_side.get(), "right")
        self.st["under"] = u
        self.touch()

    def count_changed(self):
        try:
            n = max(1, min(6, int(float(self.v_count.get()))))
        except ValueError:
            n = 3
        self.v_count.set(str(n))
        u = dict(stair_under(self.st))
        secs = list(u.get("sections") or [])
        have = len(secs)
        if n == have:
            return
        extra = default_cupboard(6)["sections"]
        secs = secs[:n] + [dict(extra[k]) for k in range(have, n)]
        u["sections"] = secs
        self.st["under"] = u
        self.rebuild_rows()
        self.touch()

    def equal_widths(self):
        u = dict(stair_under(self.st))
        u["sections"] = [{k: v for k, v in dict(s).items() if k != "w"} for s in (u.get("sections") or [])]
        self.st["under"] = u
        self.rebuild_rows()
        self.touch()

    def preset(self):
        try:
            n = max(1, min(6, int(float(self.v_count.get()))))
        except ValueError:
            n = 3
        side = stair_under(self.st).get("side", "right")
        u = default_cupboard(n)
        u["side"] = side
        u["bespoke"] = bool(self.v_bespoke.get())
        self.st["under"] = u
        self.v_mode.set(dict(UNDER_MODES)["cupboard"])
        self.rebuild_rows()
        self.touch()

    def section_changed(self, i):
        u = dict(stair_under(self.st))
        secs = [dict(s) for s in (u.get("sections") or [])]
        if i >= len(secs) or i >= len(self.rows):
            return
        lab, vt, vn, vf, vw = self.rows[i]
        try:
            cnt = max(0, min(12, int(float(vn.get()))))
        except ValueError:
            cnt = secs[i].get("n", 0)
        new = {"type": vt.get(), "n": cnt, "front": vf.get()}
        try:
            wv = float(vw.get().replace(",", "."))
            if wv >= 100.0:
                new["w"] = round(wv, 1)
        except ValueError:
            pass                                                  # "auto" / empty = the equal share
        if new == secs[i]:
            return
        secs[i] = new
        u["sections"] = secs
        self.st["under"] = u
        self.touch()

    def ok(self):
        self.done = True
        self.close()
        self.app.changed()

    def cancel(self):
        if not self.done:
            self.st.clear()
            self.st.update(copy.deepcopy(self.orig))
            if self.app.undo:
                self.app.undo.pop()
        self.done = True
        self.close()
        self.app.changed()

    def close(self):
        try:
            self.top.destroy()
        except Exception:
            pass

    # ---- showing the result --------------------------------------------------------------------------------------
    def refresh(self):
        st = self.st
        if not self.top.winfo_exists():
            return
        rise = self.rise
        n = int(st["n"])
        R = rise / n
        slope = math.degrees(math.atan2(R, st["tread"]))
        txt = "Riser %.0f mm   tread %.0f mm   slope %.0f deg   2R+T = %.0f mm (comfort about 630)." % (
            R, st["tread"], slope, 2 * R + st["tread"])
        if slope > 42 or st["tread"] < 200:
            txt += "  Steep!"
        if self.app.stair_is_orphan(st):
            txt += "\nNO FLOOR ABOVE: these stairs climb the whole storey height.  Type the rise you want, or move them to the storey below."
        elif st.get("rise"):
            txt += "\nOwn rise (an exception: not the floor-to-floor height)."

        self.v_info.set(txt)
        try:
            foc = self.top.focus_get()
        except Exception:
            foc = None
        for var, val in ((self.v_n, str(n)), (self.v_tread, "%g" % round(st["tread"], 1)), (self.v_w, "%g" % round(st["w"], 1)), (self.v_rise, "%g" % round(rise, 1)),
                         (self.v_run, "%g" % round(stair_run_length(st), 1))):
            typing = isinstance(foc, tk.Entry) and str(foc.cget("textvariable")) == str(var)      # do not overwrite what is typed
            if var.get() != val and not typing:
                var.set(val)
        u = stair_under(st)
        secs = stair_sections(st, rise)
        for s in secs:
            if s["i"] < len(self.rows):
                hh = ("%.0f-%.0f" % (s["h"], s["h1"])) if stair_bespoke(st) else ("%.0f" % s["h"])
                self.rows[s["i"]][0].configure(text="%d: w %.0f  h %s mm%s" % (s["i"] + 1, s["w"], hh, "" if s["ok"] else "  (too low)"),
                                               fg="#000000" if s["ok"] else "#a04010")
        low = [s["i"] + 1 for s in secs if not s["ok"]]
        if st["kind"] != "straight":
            self.v_note.set("The space under the stairs can only be fitted out on STRAIGHT stairs.")
        elif u["mode"] == "cupboard" and not secs:
            self.v_note.set("These stairs are too short or too flat for a cupboard underneath (it needs at least %.0f mm of "
                            "height and 0.3 m of run)." % CB_MIN_H)
        elif u["mode"] == "cupboard" and stair_bespoke(st):
            self.v_note.set("Bespoke: follows the steps, all closed (doors + drawers from the %s side).  Depth across the stairs %.0f mm.  "
                            "Lower than %.0f mm at the foot = closed filler." % (u.get("side", "right"), st["w"], BESPOKE_MIN_H))
        elif low:
            self.v_note.set("Section %s is lower than %.0f mm and is not built." % (", ".join(str(i) for i in low), CB_MIN_H))
        elif u["mode"] == "cupboard":
            self.v_note.set("The part of the stairs that is lower than %.0f mm is left open (no cupboard fits there)." % CB_MIN_H)
        else:
            self.v_note.set("")
        self.draw()

    def draw(self):
        cv = self.cv
        cv.delete("all")
        st = self.st
        rise = self.rise
        W, H = 600, 330
        L = max(stair_run_length(st), 1.0) if st["kind"] == "straight" else max(st["n"] * st["tread"], 1.0)
        sc = min((W - 60) / (L + 600.0), (H - 70) / (rise + 400.0))
        ox, oy = 30, H - 30
        P = lambda y, z: (ox + y * sc, oy - z * sc)
        cv.create_line(ox - 20, oy, ox + (L + 500) * sc, oy, fill="#444444", width=2)
        x1, y1 = P(L, rise)
        cv.create_line(x1, y1, x1 + 120 * sc + 40, y1, fill="#444444", width=2)
        cv.create_text(x1 + 10, y1 - 10, text="floor above", anchor="w", fill="#666666", font=("Segoe UI", 8))
        n = int(st["n"])
        R = rise / n
        T = st["tread"]
        hollow = stair_hollow(st)
        # the steps: top profile + underside
        top, under = [], []
        for k in range(1, n):
            top += [P((k - 1) * T, k * R), P(k * T, k * R)]
        for k in range(n - 1, 0, -1):
            under += [P(k * T, k * R - STAIR_STRUCT), P((k - 1) * T, k * R - STAIR_STRUCT)]
        if hollow:
            cv.create_polygon([c for p in top + under for c in p], fill="#d9bf95", outline="#7a5a30")
        else:
            poly = [P(0, 0)] + top + [P(L, 0)]
            cv.create_polygon([c for p in poly for c in p], fill="#d9bf95", outline="#7a5a30")
        # the cupboard, far boards first
        u = stair_under(st)
        sg = 1.0 if u.get("side", "right") == "right" else -1.0
        boxes = sorted(stair_cupboard_boxes(st, rise), key=lambda b: sg * (b[0] + b[2]) / 2.0)
        for x0, ya, x1b, yb, z0, z1, mat in boxes:
            r, g, b, _a = MATERIALS.get(mat, (0.8, 0.8, 0.8, 1.0))
            col = _hex(r * 0.95, g * 0.95, b * 0.95)
            a, bb = P(ya, z1), P(yb, z0)
            cv.create_rectangle(a[0], a[1], bb[0], bb[1], fill=col, outline="#6a5a40")
        for s in stair_sections(st, rise):
            mid = P((s["y0"] + s["y1"]) / 2.0, 0)
            cv.create_text(mid[0], mid[1] + 14, text=str(s["i"] + 1), fill="#444444", font=("Segoe UI", 9, "bold"))
            cv.create_text(mid[0], mid[1] + 27, text="w %.0f" % s["w"], fill="#555555", font=("Segoe UI", 8))
        cv.create_text(P(0, 0)[0], 8, text="%d steps, run %s m, rise %s m" % (n, fmt_m(L), fmt_m(rise)), anchor="w", fill="#444444",
                       font=("Segoe UI", 9))


# *************** DEL 63 - THE APPLICATION WINDOW (menus, tool bar, panels, files, entry point) *****************
# ToDo: remember window layout per project, drag-and-drop of .arch.json, recent-files menu.

SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")
PROJECTS_DIR = os.path.join(PROGRAM_HF_DIR, "Projects")
AUTOSAVE_FILE = os.path.join(PROGRAM_HF_DIR, "autosave.arch.json")
FILE_TYPES = [("Architect project", "*.arch.json"), ("JSON", "*.json"), ("All files", "*.*")]
TOOLS = [("select", "Select"), ("wall", "Wall"), ("room", "Room"), ("opening", "Door/Window"), ("item", "Item"),
         ("stair", "Stairs"), ("roof", "Roof"), ("dormer", "Dormer"), ("dim", "Dimension"), ("text", "Text"), ("note", "Note"), ("meas", "Measure"), ("section", "Section")]


class ArchApp(DrawMixin, ToolMixin, PropsMixin):

    def open_shop(self, tab=0):
        """The Materials window: 0 shopping list, 1 prices, 2 stores, 3 where to buy, 4 memos, 5 craftsmen."""
        self.shop = ShopWindow(self, tab)
        return self.shop

    def open_stair_editor(self, st=None):
        """'Edit parts...': steps, run, width and the space under straight stairs (cupboard, wardrobe, shelves, drawers)."""
        if st is None:
            kind, st = find_element(self.story(), self.sel[0]) if len(self.sel) == 1 else (None, None)
            if kind != "stair":
                return None
        self.stair_editor = StairEditor(self, st)
        return self.stair_editor

    def stair_is_orphan(self, st):
        """Stairs on the top storey that were not given an own rise: they would climb 'to the roof' (storey height + floor)."""
        return self.sidx > 0 and not stair_has_floor_above(self.proj, self.sidx) and not st.get("rise")

    def move_stair_down(self, st=None):
        """Move stairs / a lift to the storey BELOW (where they belong: a stair is kept by the storey it starts on) and refit the steps."""
        if st is None:
            kind, st = find_element(self.story(), self.sel[0]) if len(self.sel) == 1 else (None, None)
            if kind != "stair":
                return
        if self.sidx == 0:
            return
        self.push_undo()
        lower = self.proj["stories"][self.sidx - 1]
        self.story()["stairs"] = [s for s in self.story()["stairs"] if s["id"] != st["id"]]
        st.pop("rise", None)
        rise = stair_total_rise(self.proj, self.sidx - 1)
        if st["kind"] == "straight":
            run = max(400.0, (int(st["n"]) - 1) * st["tread"])
            n = stair_best_steps(rise, run)
            st["n"], st["tread"] = n, run / (n - 1)
        elif st["kind"] != "lift":
            st["n"] = stair_steps_for(rise)
        lower["stairs"].append(st)
        self.select_story(self.sidx - 1)
        self.sel = [st["id"]]
        self.changed()
        self.set_status("Moved the stairs to '%s' (they climb %.2f m up to the next floor).  They are shown on the floor above as the opening." % (
            lower["name"], rise / 1000.0))

    def open_planner(self):
        """The house planner: size of the house, list of rooms, arrange / fit, build walls + rooms + doors + windows."""
        self.planner = HousePlanner(self)
        return self.planner

    def memo_reminder(self):
        due = memos_due(self.proj)
        if due:
            self.set_status("%d memo(s) due: %s   (Materials > Memos)" % (len(due), ", ".join(n["title"] for n in due[:3])))

    def __init__(self, root):
        self.root = root
        self.settings = self.load_settings()
        self.proj = None
        self.path = None
        self.dirty = False
        self.undo, self.redo = [], []
        self.sidx = 0
        self.sel = []
        self.tmp = {}
        self.drag = None
        self.pan = None
        self.o3d = None
        self.mouse = None
        self.typed = ""
        self.alt = self.shift = False
        self.item_rot = 0.0
        self.item_type = "sofa3"
        self.rev = 0
        self.mode = "plan"
        self.tool = "select"
        self.sec_id = None
        self.v_ghost = True
        self.v_notes = False                     # plan: the GHOST NOTES layer (your own working notes per storey); off by default
        self.v_meas = False                      # plan: the GHOST MEASURES layer (rulers + measured rooms); off by default
        self.v_conn = True                       # plan: stairs / lift that come up from the storey below stay visible even without the grey floor
        self.v_headroom = True
        self.v_roof_lines = True
        self.v_areas = True
        self.v3_hide_roof = True                 # 3D view: the roof is hidden by default so you can see into the house
        self.v3_items = True
        self.v3_keep = True                      # 3D: furniture, stairs, doors and windows stay visible while you turn the view
        self.v3_upto = None                      # 3D: highest storey shown (None = all)
        self.v3_from = None                      # 3D: lowest storey shown (None = from the ground floor)
        self._mesh = None
        self._mesh_key = None
        self._tiled = None
        self._sec = None
        self._sec_key = None
        self._fast_job = None
        self._full_job = None
        self.notes = None
        self.view = {"sc": 0.08, "ox": 100, "oy": 600}
        self.sview = {"sc": 0.08, "ox": 60, "oy": 600}
        self.cam = {"yaw": -60.0, "pitch": 28.0, "dist": 20000.0, "tx": 4500.0, "ty": 3500.0, "tz": 3000.0}
        root.title(APP_TITLE)
        root.geometry(self.settings.get("geometry") or "1360x860")
        root.minsize(1000, 640)
        self.status_var = tk.StringVar()
        self.coord_var = tk.StringVar()
        self.tool_var = tk.StringVar(value="select")
        self.mode_var = tk.StringVar(value="plan")
        self.snap_var = tk.StringVar(value=str(self.settings.get("snap", 100)))
        self.v_ortho = tk.BooleanVar(value=True)         # draw straight lines / walls (default on); Shift turns it the other way while held
        self.wall_t_var = tk.StringVar(value="100")
        self.room_mode = tk.StringVar(value="In walls")
        self.room_name_var = tk.StringVar(value="Room")
        self.room_walls = tk.BooleanVar(value=True)
        self.open_kind = tk.StringVar(value="door")
        self.open_w = tk.StringVar(value="900")
        self.open_h = tk.StringVar(value="2100")
        self.open_sill = tk.StringVar(value="0")
        self.stair_kind = tk.StringVar(value="straight")
        self.stair_draw = tk.BooleanVar(value=True)       # straight stairs: draw the width, then pull out the length
        self.stair_riser = tk.StringVar(value="auto")     # wanted riser height (mm) or "auto" = steps fitted to the length drawn
        self.stair_one_floor = tk.BooleanVar(value=True)  # stairs only climb to the NEXT floor (untick = exception, then 'Own rise' counts)
        self.stair_rise_var = tk.StringVar(value="auto")  # the rise (mm) used when 'Only up to the next floor' is unticked
        self.stair_start = tk.StringVar(value="bottom")   # drawn stairs: the two first clicks are the bottom or the top edge
        self._bvars = {}                                  # View menu + option bar check boxes share these variables
        for _n, _v in (("v_ghost", self.v_ghost), ("v_conn", self.v_conn), ("v_notes", self.v_notes), ("v_meas", self.v_meas), ("v3_hide_roof", self.v3_hide_roof), ("v3_items", self.v3_items), ("v3_keep", self.v3_keep),
                       ("v_roof_lines", self.v_roof_lines), ("v_headroom", self.v_headroom), ("v_areas", self.v_areas)):
            self._bvars[_n] = tk.BooleanVar(value=_v)
        self.roof_type = tk.StringVar(value="gable")
        self.roof_pitch = tk.StringVar(value="38")
        self.roof_eave = tk.StringVar(value="1100")
        self.wall_arc_mode = tk.BooleanVar(value=False)
        self.dormer_kind = tk.StringVar(value="Gable dormer")
        self.dormer_w = tk.StringVar(value="1800")
        self.load_start_project()
        self.build_ui()
        self.build_menus()
        self.rebuild_story_bar()
        self.show_tool_options()
        self.show_props()
        self.set_status(TOOL_HINTS["select"])
        self.memo_reminder()
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.bind("<Key>", self.root_key)
        for seq, fn in (("<Control-z>", self.do_undo), ("<Control-y>", self.do_redo), ("<Control-s>", self.save),
                        ("<Control-o>", self.open_file), ("<Control-n>", self.new_file), ("<Control-d>", self.duplicate_selection),
                        ("<Control-e>", self.show_export), ("<Control-a>", self.select_all)):
            root.bind(seq, lambda e, fn=fn: (fn(), "break")[1])
        self._first = True
        self.cv.bind("<Configure>", self.on_configure)
        root.after(60000, self.autosave)

    # ---- settings and start ----------------------------------------------------------------------------------
    def load_settings(self):
        try:
            with open(SETTINGS_FILE, encoding="utf-8") as fh:
                d = json.load(fh)
                return d if isinstance(d, dict) else {}
        except Exception:
            return {}

    def save_settings(self):
        try:
            os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
            with open(SETTINGS_FILE, "w", encoding="utf-8") as fh:
                json.dump(self.settings, fh, indent=1)
        except Exception:
            pass

    def load_start_project(self):
        p = self.settings.get("last_path")
        if p and os.path.isfile(p):
            try:
                self.proj = load_project(p)
                self.path = p
                return
            except Exception:
                pass
        self.proj = make_example()

    # ---- UI --------------------------------------------------------------------------------------------------
    def build_ui(self):
        r = self.root
        top = tk.Frame(r, bg=THEME["bg"])
        top.pack(fill="x")
        for key, label in TOOLS:
            tk.Radiobutton(top, text=label, value=key, variable=self.tool_var, indicatoron=0, width=10,
                           command=lambda k=key: self.set_tool(k), bg=THEME["btn"], fg=THEME["btnfg"],
                           selectcolor=THEME["accent"], activebackground=THEME["accent"], bd=0, relief="flat",
                           font=("Segoe UI", 9, "bold")).pack(side="left", padx=1, pady=3)
        for key, label in (("section", "Section"), ("3d", "3D"), ("plan", "Plan")):
            tk.Radiobutton(top, text=label, value=key, variable=self.mode_var, indicatoron=0, width=9,
                           command=lambda k=key: self.set_mode(k), bg=THEME["panel"], fg=THEME["btnfg"],
                           selectcolor="#3a7a5a", activebackground="#3a7a5a", bd=0, relief="flat",
                           font=("Segoe UI", 9, "bold")).pack(side="right", padx=1, pady=3)
        self.story_bar = tk.Frame(r, bg=THEME["panel"], height=30)
        self.story_bar.pack(fill="x")
        self.story_bar.pack_propagate(False)
        self.opt_bar = tk.Frame(r, bg="#2c2c3e", height=38)
        self.opt_bar.pack(fill="x")
        self.opt_bar.pack_propagate(False)
        self.build_options()
        bottom = tk.Frame(r, bg=THEME["bg"])
        bottom.pack(side="bottom", fill="x")
        tk.Label(bottom, textvariable=self.coord_var, width=44, anchor="w", bg=THEME["bg"], fg=THEME["accent"],
                 font=("Consolas", 9)).pack(side="right")
        tk.Label(bottom, textvariable=self.status_var, anchor="w", bg=THEME["bg"], fg=THEME["fg"], font=("Segoe UI", 9),
                 height=2, justify="left", wraplength=880).pack(side="left", fill="x", expand=True, padx=6)
        body = tk.Frame(r)
        body.pack(fill="both", expand=True)
        left = tk.Frame(body, width=210, bg=THEME["panel"])
        left.pack(side="left", fill="y")
        left.pack_propagate(False)
        right = tk.Frame(body, width=300, bg=THEME["panel"])
        right.pack(side="right", fill="y")
        right.pack_propagate(False)
        self.props_frame = tk.Frame(right, bg=THEME["panel"])
        self.props_frame.pack(fill="both", expand=True)
        self.cv = tk.Canvas(body, bg="#fbfbf8", highlightthickness=0, cursor="crosshair")
        self.cv.pack(side="left", fill="both", expand=True)
        self.build_catalog(left)
        cv = self.cv
        cv.bind("<ButtonPress-1>", self.on_press)
        cv.bind("<B1-Motion>", self.on_drag)
        cv.bind("<ButtonRelease-1>", self.on_release)
        cv.bind("<Double-Button-1>", self.on_double)
        cv.bind("<Motion>", self.on_motion)
        for b in ("2", "3"):
            cv.bind("<ButtonPress-%s>" % b, self.on_rpress)
            cv.bind("<B%s-Motion>" % b, self.on_rdrag)
            cv.bind("<ButtonRelease-%s>" % b, self.on_rrelease)
        cv.bind("<MouseWheel>", self.on_wheel)

    def build_catalog(self, parent):
        tk.Label(parent, text="Items", anchor="w", bg=THEME["panel"], fg=THEME["accent"],
                 font=("Segoe UI", 10, "bold")).pack(fill="x", padx=6, pady=(6, 2))
        self.cat_var = tk.StringVar(value=CATEGORIES[0])
        om = tk.OptionMenu(parent, self.cat_var, *CATEGORIES, command=lambda v: self.fill_catalog())
        om.configure(width=20, bg=THEME["btn"], fg=THEME["btnfg"], activebackground=THEME["accent"], bd=0, highlightthickness=0,
                     font=("Segoe UI", 9))
        om.pack(padx=6, pady=2)
        frm = tk.Frame(parent, bg=THEME["panel"])
        frm.pack(fill="both", expand=True, padx=6, pady=4)
        sb = tk.Scrollbar(frm)
        sb.pack(side="right", fill="y")
        self.cat_list = tk.Listbox(frm, bg=THEME["field"], fg=THEME["field_fg"], selectbackground=THEME["accent"],
                                   selectforeground="#101018", bd=0, highlightthickness=0, activestyle="none",
                                   font=("Segoe UI", 9), yscrollcommand=sb.set, exportselection=False)
        self.cat_list.pack(side="left", fill="both", expand=True)
        sb.configure(command=self.cat_list.yview)
        self.cat_list.bind("<<ListboxSelect>>", self.catalog_picked)
        self.cat_keys = []
        self.fill_catalog()

    def fill_catalog(self):
        self.cat_list.delete(0, "end")
        self.cat_keys = [k for k, c in CATALOG.items() if c["cat"] == self.cat_var.get()]
        for k in self.cat_keys:
            c = CATALOG[k]
            self.cat_list.insert("end", "%s  (%g x %g)" % (c["name"], c["w"] / 10.0, c["d"] / 10.0))

    def catalog_picked(self, e=None):
        sel = self.cat_list.curselection()
        if not sel:
            return
        self.item_type = self.cat_keys[sel[0]]
        self.item_rot = 0.0
        self.set_tool("item")
        self.item_label.configure(text=CATALOG[self.item_type]["name"])

    def build_options(self):
        bar = self.opt_bar
        mk = lambda parent: tk.Frame(parent, bg="#2c2c3e")
        self.opt_frames = {}

        def lab(p, t):
            tk.Label(p, text=t, bg="#2c2c3e", fg=THEME["fg"], font=("Segoe UI", 9)).pack(side="left", padx=(8, 2))

        def ent(p, var, w=6):
            e = new_entry(p, textvariable=var, width=w, bg=THEME["field"], fg=THEME["field_fg"], insertbackground=THEME["field_fg"],
                          relief="flat", font=("Segoe UI", 9))
            e.pack(side="left", padx=2)
            return e

        def menu(p, var, values, cmd=None, w=12):
            om = tk.OptionMenu(p, var, *values, command=cmd)
            om.configure(width=w, bg=THEME["btn"], fg=THEME["btnfg"], activebackground=THEME["accent"], bd=0,
                         highlightthickness=0, font=("Segoe UI", 9))
            om.pack(side="left", padx=2)
            return om

        def btn(p, t, cmd):
            tk.Button(p, text=t, command=cmd, bg=THEME["btn"], fg=THEME["btnfg"], relief="flat", activebackground=THEME["accent"],
                      font=("Segoe UI", 9)).pack(side="left", padx=4)

        CURTAIN_PRESET = "Curtain (room divider)"

        def wall_type_menu(p, curtain=False):
            lab(p, "Wall type")
            var = tk.StringVar(value="Inner wall")
            names = [n for n, _ in WALL_PRESETS] + ([CURTAIN_PRESET] if curtain else [])

            def picked(v):
                if v == CURTAIN_PRESET:                       # rail under the ceiling + sliding drape instead of a wall
                    self.wall_kind_var.set("curtain")
                    self.wall_t_var.set(str(int(CURTAIN_T)))
                else:
                    if curtain:                               # only the Wall tool's menu decides the kind
                        self.wall_kind_var.set("wall")
                    self.wall_t_var.set(str(dict(WALL_PRESETS)[v]))
            menu(p, var, names, picked, 20 if curtain else 14)
            lab(p, "Thickness mm")
            ent(p, self.wall_t_var, 5)
        self.wall_kind_var = tk.StringVar(value="wall")
        f = mk(bar)
        self.opt_frames["select"] = f
        self.sel_bar = f                     # filled by refresh_select_bar(): what the selection can do
        f = mk(bar)
        self.opt_frames["wall"] = f
        wall_type_menu(f, curtain=True)
        tk.Checkbutton(f, text="Arc wall (3 clicks)", variable=self.wall_arc_mode, bg="#2c2c3e", fg=THEME["fg"],
                       selectcolor=THEME["btn"], activebackground="#2c2c3e", font=("Segoe UI", 9),
                       command=lambda: (setattr(self, "tmp", {}), self.draw_overlay())).pack(side="left", padx=6)
        f = mk(bar)
        self.opt_frames["room"] = f
        lab(f, "Mode")
        menu(f, self.room_mode, ["In walls", "Rect", "Polygon"], None, 9)
        lab(f, "Name")
        menu(f, self.room_name_var, ROOM_TYPES, None, 13)
        tk.Checkbutton(f, text="Rect: also build walls", variable=self.room_walls, bg="#2c2c3e", fg=THEME["fg"],
                       selectcolor=THEME["btn"], activebackground="#2c2c3e", font=("Segoe UI", 9)).pack(side="left", padx=6)
        wall_type_menu(f)
        f = mk(bar)
        self.opt_frames["opening"] = f
        lab(f, "Kind")

        def kind_changed(v):
            w, h, s, _ = OPENING_KINDS[v]
            self.open_w.set(str(w))
            self.open_h.set(str(h))
            self.open_sill.set(str(s))
        menu(f, self.open_kind, list(OPENING_KINDS), kind_changed, 9)
        lab(f, "Width")
        ent(f, self.open_w)
        lab(f, "Height")
        ent(f, self.open_h)
        lab(f, "Sill")
        ent(f, self.open_sill)
        f = mk(bar)
        self.opt_frames["item"] = f
        lab(f, "Placing:")
        self.item_label = tk.Label(f, text=CATALOG[self.item_type]["name"], bg="#2c2c3e", fg=THEME["accent"],
                                   font=("Segoe UI", 9, "bold"), width=24, anchor="w")
        self.item_label.pack(side="left")
        btn(f, "Turn left  <-", lambda: self.rotate_selection(15.0))
        btn(f, "Turn right  ->", lambda: self.rotate_selection(-15.0))
        btn(f, "90 (R)", lambda: self.rotate_selection(90.0))
        f = mk(bar)
        self.opt_frames["stair"] = f
        lab(f, "Kind")
        menu(f, self.stair_kind, STAIR_KINDS, lambda v: (setattr(self, "tmp", {}), self.draw_overlay()), 9)
        tk.Checkbutton(f, text="Width, then length", variable=self.stair_draw, bg="#2c2c3e", fg=THEME["fg"],
                       selectcolor=THEME["btn"], activebackground="#2c2c3e", font=("Segoe UI", 9),
                       command=lambda: (setattr(self, "tmp", {}), self.draw_overlay())).pack(side="left", padx=6)
        lab(f, "Start at")
        menu(f, self.stair_start, ["bottom", "top"], lambda v: (setattr(self, "tmp", {}), self.draw_overlay()), 7)
        lab(f, "Riser mm")
        ent(f, self.stair_riser, 5)
        tk.Checkbutton(f, text="Only to next floor", variable=self.stair_one_floor, bg="#2c2c3e", fg=THEME["fg"],
                       selectcolor=THEME["btn"], activebackground="#2c2c3e", font=("Segoe UI", 9),
                       command=lambda: (setattr(self, "tmp", {}), self.draw_overlay())).pack(side="left", padx=6)
        lab(f, "Own rise")
        ent(f, self.stair_rise_var, 5)
        f = mk(bar)
        self.opt_frames["roof"] = f
        lab(f, "Type")
        menu(f, self.roof_type, ROOF_TYPES, self.roof_type_changed, 8)
        lab(f, "Pitch deg")
        ent(f, self.roof_pitch, 4)
        lab(f, "Eave height mm")
        ent(f, self.roof_eave, 5)
        btn(f, "Roof over all walls", self.roof_over_all)
        f = mk(bar)
        self.opt_frames["dormer"] = f
        lab(f, "Kind")
        menu(f, self.dormer_kind, ["Gable dormer", "Shed dormer", "Flat dormer", "Roof window"], None, 12)
        lab(f, "Dormer width mm")
        ent(f, self.dormer_w, 5)
        for k in ("dim", "text", "note", "section"):
            f = mk(bar)
            self.opt_frames[k] = f
            lab(f, {"dim": "Dimension tool", "text": "Text tool", "note": "Ghost note tool (plan only, never exported)",
                    "section": "Section tool"}[k])
        f = mk(bar)                                # the Measure tool (second ghost layer)
        self.opt_frames["meas"] = f
        lab(f, "Measure")
        self.meas_mode = tk.StringVar(value=MEAS_MODES[0])
        menu(f, self.meas_mode, MEAS_MODES, lambda v: (setattr(self, "tmp", {}), self.draw_overlay()), 18)
        btn(f, "Measures list...", self.open_meas_report)
        # always visible, right side
        common = mk(bar)
        common.pack(side="right")
        tk.Checkbutton(common, text="Straight (Shift = free)", variable=self.v_ortho, bg="#2c2c3e", fg=THEME["fg"],
                       selectcolor=THEME["btn"], activebackground="#2c2c3e", font=("Segoe UI", 9)).pack(side="left", padx=6)
        lab(common, "Snap mm")
        menu(common, self.snap_var, ["0", "10", "50", "100", "250", "500"], None, 4)
        self.sec_menu_frame = tk.Frame(common, bg="#2c2c3e")
        self.sec_menu_frame.pack(side="left")
        # view check boxes: the plan one (floor below) and the 3D ones (hide roof, furniture); shown by set_mode()
        def chk(parent, text, name):
            tk.Checkbutton(parent, text=text, variable=self._bvars[name], bg="#2c2c3e", fg=THEME["fg"], selectcolor=THEME["btn"],
                           activebackground="#2c2c3e", font=("Segoe UI", 9, "bold"),
                           command=lambda n=name: self.toggle(n)).pack(side="left", padx=6)
        self.chk_plan = tk.Frame(common, bg="#2c2c3e")
        chk(self.chk_plan, "Show floor below", "v_ghost")
        chk(self.chk_plan, "Stairs / lift from below", "v_conn")
        chk(self.chk_plan, "Ghost notes", "v_notes")
        chk(self.chk_plan, "Ghost measures", "v_meas")
        self.chk_3d = tk.Frame(common, bg="#2c2c3e")
        chk(self.chk_3d, "Hide roof", "v3_hide_roof")
        chk(self.chk_3d, "Show furniture", "v3_items")
        chk(self.chk_3d, "Keep objects when turning", "v3_keep")
        self.upto_bar = tk.Frame(self.chk_3d, bg="#2c2c3e")          # "Up to: All storeys" menu, filled by rebuild_upto_bar()
        self.upto_bar.pack(side="left")
        self.show_mode_checks()

    def show_mode_checks(self):
        """The check boxes at the right end of the option bar follow the view: plan = 'Show floor below', 3D = 'Hide roof'."""
        for f, on in ((self.chk_plan, self.mode == "plan"), (self.chk_3d, self.mode == "3d")):
            f.pack_forget()
            if on:
                f.pack(side="left", before=self.sec_menu_frame)

    def show_tool_options(self):
        for f in self.opt_frames.values():
            f.pack_forget()
        f = self.opt_frames.get(self.tool)
        if f is not None:
            f.pack(side="left")
        self.refresh_select_bar()

    def refresh_select_bar(self):
        """The option bar of the Select tool shows what you can do with the selected thing (door: kind, flip side, flip hinge,
        delete), or how to select something when nothing is selected."""
        bar = getattr(self, "sel_bar", None)
        if bar is None:
            return
        for w in bar.winfo_children():
            w.destroy()
        BG = "#2c2c3e"

        def lab(t, accent=False):
            tk.Label(bar, text=t, bg=BG, fg=THEME["accent"] if accent else THEME["fg"],
                     font=("Segoe UI", 9, "bold" if accent else "normal")).pack(side="left", padx=(8, 2))

        def btn(t, cmd):
            tk.Button(bar, text=t, command=cmd, bg=THEME["btn"], fg=THEME["btnfg"], relief="flat", activebackground=THEME["accent"],
                      font=("Segoe UI", 9)).pack(side="left", padx=3)
        sel = self.sel
        story = self.story()
        if not sel:
            lab("Select:  click a wall, room, item or DOOR (click in its gap in the wall) - what you can do with it shows here.")
            return
        if len(sel) > 1:
            lab("%d selected" % len(sel), True)
            btn("Duplicate (Ctrl+D)", self.duplicate_selection)
            btn("Delete (Del)", self.delete_selection)
            return
        kind, el = find_element(story, sel[0])
        if el is None:
            return
        if kind == "opening":
            lab("Selected: " + OPENING_KINDS[el["kind"]][3], True)
            lab("Change to")
            var = tk.StringVar(value=el["kind"])

            def kind_pick(v):
                self.setter(el, "kind")(v)
                self.root.after_idle(self.show_props)
            om = tk.OptionMenu(bar, var, *list(OPENING_KINDS), command=kind_pick)
            om.configure(width=8, bg=THEME["btn"], fg=THEME["btnfg"], activebackground=THEME["accent"], bd=0, highlightthickness=0,
                         font=("Segoe UI", 9))
            om.pack(side="left", padx=2)
            if el["kind"] not in ("window", "passage"):
                btn("Flip side (F)", lambda: self.flip_selection("swing"))
                btn("Flip hinge (H)", lambda: self.flip_selection("hinge"))
            btn("Delete (Del)", self.delete_selection)
            return
        names = {"wall": "Wall", "room": "Room", "item": "Item", "stair": "Stairs", "roof": "Roof", "dim": "Dimension",
                 "text": "Text", "section": "Section line", "dormer": "Dormer", "rwin": "Roof window",
                 "meas": "Ghost measure"}
        lab("Selected: " + ("Ghost note" if kind == "text" and el.get("ghost") else names.get(kind, kind)), True)
        if kind in ("item", "stair", "dormer", "text"):
            btn("Turn left  <-", lambda: self.rotate_selection(15.0))
            btn("Turn right  ->", lambda: self.rotate_selection(-15.0))
            btn("90 (R)", lambda: self.rotate_selection(90.0))
        if kind == "stair":
            btn("Edit parts...", self.open_stair_editor)
            if self.stair_is_orphan(el):
                btn("Move to storey below", self.move_stair_down)
        btn("Duplicate (Ctrl+D)", self.duplicate_selection)
        btn("Delete (Del)", self.delete_selection)
        if kind in ("item", "stair", "dormer", "text"):
            lab("Arrow keys Left / Right turn it (Shift = 1 degree), Up / Down or Ctrl+arrows move it.")

    def rebuild_sec_menu(self):
        for w in self.sec_menu_frame.winfo_children():
            w.destroy()
        secs = self.all_sections()
        if self.mode == "section" and secs:
            tk.Label(self.sec_menu_frame, text="Section", bg="#2c2c3e", fg=THEME["fg"], font=("Segoe UI", 9)).pack(side="left", padx=4)
            names = dict(secs)
            cur = self.current_section()
            var = tk.StringVar(value=cur["name"] if cur else secs[0][1])

            def pick(v):
                for i, n in secs:
                    if n == v:
                        self.sec_id = i
                self.fit_view()
                self.redraw()
            om = tk.OptionMenu(self.sec_menu_frame, var, *[n for _, n in secs], command=pick)
            om.configure(width=4, bg=THEME["btn"], fg=THEME["btnfg"], bd=0, highlightthickness=0, font=("Segoe UI", 9))
            om.pack(side="left")

    def rebuild_story_bar(self):
        for w in self.story_bar.winfo_children():
            w.destroy()
        tk.Label(self.story_bar, text="Storey:", bg=THEME["panel"], fg=THEME["dim"], font=("Segoe UI", 9)).pack(side="left", padx=8)
        self.story_var = tk.IntVar(value=self.sidx)
        for i, s in enumerate(self.proj["stories"]):
            tk.Radiobutton(self.story_bar, text=s["name"], value=i, variable=self.story_var, indicatoron=0, padx=10,
                           command=lambda i=i: self.select_story(i), bg=THEME["btn"], fg=THEME["btnfg"], selectcolor="#3a7a5a",
                           activebackground="#3a7a5a", bd=0, relief="flat", font=("Segoe UI", 9, "bold")).pack(side="left", padx=1,
                                                                                                               pady=3)
        tk.Button(self.story_bar, text="+ floor", command=lambda: self.add_story(False), bg=THEME["bg"], fg=THEME["fg"],
                  relief="flat", font=("Segoe UI", 9)).pack(side="left", padx=(10, 2))
        tk.Button(self.story_bar, text="+ attic", command=lambda: self.add_story(True), bg=THEME["bg"], fg=THEME["fg"],
                  relief="flat", font=("Segoe UI", 9)).pack(side="left", padx=2)
        self.rebuild_upto_menu()

    def build_menus(self):
        r = self.root
        m = tk.Menu(r)
        r.config(menu=m)
        f = tk.Menu(m, tearoff=0)
        m.add_cascade(label="File", menu=f)
        f.add_command(label="New", accelerator="Ctrl+N", command=self.new_file)
        f.add_command(label="New example house", command=self.new_example)
        f.add_command(label="Open...", accelerator="Ctrl+O", command=self.open_file)
        f.add_command(label="Save", accelerator="Ctrl+S", command=self.save)
        f.add_command(label="Save as...", command=self.save_as)
        f.add_separator()
        f.add_command(label="Export (DXF, IFC, OBJ, PDF, SVG, CSV)...", accelerator="Ctrl+E", command=self.show_export)
        f.add_command(label="Room list...", command=self.show_report)
        f.add_command(label="Open autosave", command=self.open_autosave)
        f.add_separator()
        f.add_command(label="Exit", command=self.on_close)
        e = tk.Menu(m, tearoff=0)
        m.add_cascade(label="Edit", menu=e)
        e.add_command(label="Undo", accelerator="Ctrl+Z", command=self.do_undo)
        e.add_command(label="Redo", accelerator="Ctrl+Y", command=self.do_redo)
        e.add_separator()
        e.add_command(label="Duplicate", accelerator="Ctrl+D", command=self.duplicate_selection)
        e.add_command(label="Delete", accelerator="Del", command=self.delete_selection)
        e.add_command(label="Select all", accelerator="Ctrl+A", command=self.select_all)
        hp = tk.Menu(m, tearoff=0)
        m.add_cascade(label="House", menu=hp)
        hp.add_command(label="House planner: size, rooms, fit...", command=self.open_planner)
        s = tk.Menu(m, tearoff=0)
        m.add_cascade(label="Storey", menu=s)
        s.add_command(label="Add storey above", command=lambda: self.add_story(False))
        s.add_command(label="Add attic (roof over the walls below)", command=lambda: self.add_story(True))
        s.add_command(label="Copy this storey", command=self.copy_story)
        s.add_command(label="Delete this storey...", command=self.delete_story)
        v = tk.Menu(m, tearoff=0)
        m.add_cascade(label="View", menu=v)
        v.add_command(label="Plan", command=lambda: self.set_mode("plan"))
        v.add_command(label="3D", command=lambda: self.set_mode("3d"))
        v.add_command(label="Section", command=lambda: self.set_mode("section"))
        v.add_command(label="Fit to window (Home)", command=lambda: (self.fit_view(), self.redraw()))
        v.add_separator()
        for name, label in (("v_ghost", "Show floor below (grey)"), ("v_conn", "Show stairs / lift that come up from below"), ("v_notes", "Ghost notes (plan only)"), ("v_meas", "Ghost measures (plan only)"), ("v_roof_lines", "Show roof lines"),
                            ("v_headroom", "Shade low headroom (attic)"), ("v_areas", "Room names and areas"),
                            ("v3_hide_roof", "3D: hide roof"), ("v3_items", "3D: show furniture"),
                            ("v3_keep", "3D: keep objects visible while turning")):
            v.add_checkbutton(label=label, variable=self._bvars[name], command=lambda n=name: self.toggle(n))
        self.upto_menu = tk.Menu(v, tearoff=0)
        v.add_cascade(label="3D: show storeys up to", menu=self.upto_menu)
        self.from_menu = tk.Menu(v, tearoff=0)
        v.add_cascade(label="3D: show storeys from", menu=self.from_menu)
        v.add_command(label="3D: only the storey I am on", command=self.only_this_storey)
        mm = tk.Menu(m, tearoff=0)
        m.add_cascade(label="Materials", menu=mm)
        mm.add_command(label="Shopping list and where to buy...", command=lambda: self.open_shop(0))
        mm.add_command(label="Prices and stores...", command=lambda: self.open_shop(1))
        mm.add_separator()
        mm.add_command(label="Memos...", command=lambda: self.open_shop(4))
        mm.add_command(label="Craftsmen...", command=lambda: self.open_shop(5))
        h = tk.Menu(m, tearoff=0)
        m.add_cascade(label="Help", menu=h)
        h.add_command(label="Help", command=self.show_help)
        h.add_command(label="My notes (Player text)", command=self.open_notes)
        h.add_command(label="About", command=self.show_about_dialog)

    def rebuild_upto_menu(self):
        if not hasattr(self, "upto_menu"):
            return
        self.upto_menu.delete(0, "end")
        self.from_menu.delete(0, "end")
        self.upto_var = tk.IntVar(value=-1 if self.v3_upto is None else self.v3_upto)
        self.from_var = tk.IntVar(value=-1 if self.v3_from is None else self.v3_from)
        self.upto_menu.add_radiobutton(label="All storeys", value=-1, variable=self.upto_var, command=self.upto_changed)
        self.from_menu.add_radiobutton(label="Ground floor / lowest", value=-1, variable=self.from_var, command=self.from_changed)
        for i, s in enumerate(self.proj["stories"]):
            self.upto_menu.add_radiobutton(label=s["name"], value=i, variable=self.upto_var, command=self.upto_changed)
            self.from_menu.add_radiobutton(label=s["name"], value=i, variable=self.from_var, command=self.from_changed)
        self.rebuild_upto_bar()

    def rebuild_upto_bar(self):
        """The 3D menus in the option bar: which storeys are shown - from one storey, up to another (look into the lower
        floors, or at one upper floor alone), and a button for 'only the storey I am on'."""
        bar = getattr(self, "upto_bar", None)
        if bar is None:
            return
        for w in bar.winfo_children():
            w.destroy()
        n = len(self.proj["stories"])
        if self.v3_upto is not None and self.v3_upto >= n:
            self.v3_upto = None
        if self.v3_from is not None and self.v3_from >= n:
            self.v3_from = None
        up_names = ["All storeys"] + [s["name"] for s in self.proj["stories"]]
        fr_names = ["Lowest"] + [s["name"] for s in self.proj["stories"]]
        up_var = tk.StringVar(value=up_names[0 if self.v3_upto is None else self.v3_upto + 1])
        fr_var = tk.StringVar(value=fr_names[0 if self.v3_from is None else self.v3_from + 1])

        def pick_from(v):
            self.v3_from = None if v == fr_names[0] else fr_names.index(v) - 1
            if self.v3_from is not None and self.v3_upto is not None and self.v3_upto < self.v3_from:
                self.v3_upto = self.v3_from                       # never an empty range
            self.shown_storeys_changed()

        def pick_up(v):
            self.v3_upto = None if v == up_names[0] else up_names.index(v) - 1
            if self.v3_from is not None and self.v3_upto is not None and self.v3_upto < self.v3_from:
                self.v3_from = self.v3_upto
            self.shown_storeys_changed()

        def mk_menu(var, names, cmd):
            om = tk.OptionMenu(bar, var, *names, command=cmd)
            om.configure(width=11, bg=THEME["btn"], fg=THEME["btnfg"], activebackground=THEME["accent"], bd=0,
                         highlightthickness=0, font=("Segoe UI", 9))
            om.pack(side="left", padx=2)
        tk.Label(bar, text="Show from", bg="#2c2c3e", fg=THEME["fg"], font=("Segoe UI", 9)).pack(side="left", padx=(8, 2))
        mk_menu(fr_var, fr_names, pick_from)
        tk.Label(bar, text="up to", bg="#2c2c3e", fg=THEME["fg"], font=("Segoe UI", 9)).pack(side="left", padx=(4, 2))
        mk_menu(up_var, up_names, pick_up)
        tk.Button(bar, text="Only this storey", command=self.only_this_storey, bg=THEME["btn"], fg=THEME["btnfg"], relief="flat",
                  activebackground=THEME["accent"], font=("Segoe UI", 9)).pack(side="left", padx=6)

    def shown_storeys_changed(self):
        """Refresh the menus and aim the 3D camera at the storeys now shown (an upper storey alone would float above the
        old target point)."""
        self.upto_var.set(-1 if self.v3_upto is None else self.v3_upto)
        self.from_var.set(-1 if self.v3_from is None else self.v3_from)
        self.aim_camera_at_shown()
        self.root.after_idle(self.rebuild_upto_bar)               # later: the menu that called us must not be destroyed inside its own callback
        self.redraw()

    def aim_camera_at_shown(self):
        el = story_elevations(self.proj)
        n = len(self.proj["stories"])
        lo = self.v3_from or 0
        hi = n - 1 if self.v3_upto is None else min(self.v3_upto, n - 1)
        zb, zt = el[lo], el[hi] + self.proj["stories"][hi]["height"]
        self.cam["tz"] = zb + (zt - zb) / 2.5

    def only_this_storey(self):
        """3D: show just the storey whose tab is selected (e.g. the attic alone)."""
        self.v3_from = self.v3_upto = self.sidx
        self.shown_storeys_changed()

    def upto_changed(self):
        v = self.upto_var.get()
        self.v3_upto = None if v < 0 else v
        if self.v3_from is not None and self.v3_upto is not None and self.v3_upto < self.v3_from:
            self.v3_from = self.v3_upto
        self.shown_storeys_changed()

    def from_changed(self):
        v = self.from_var.get()
        self.v3_from = None if v < 0 else v
        if self.v3_from is not None and self.v3_upto is not None and self.v3_upto < self.v3_from:
            self.v3_upto = self.v3_from
        self.shown_storeys_changed()

    def toggle(self, name):
        setattr(self, name, self._bvars[name].get())
        if name in ("v_notes", "v_meas"):                          # a ghost layer just vanished: drop its things from the selection
            kept = []
            for i in self.sel:
                kind, el = find_element(self.story(), i)
                if el is None or not self.hidden_layer(kind, el):
                    kept.append(i)
            if kept != self.sel:
                self.sel = kept
                self.show_props()
        self.redraw()

    # ---- modes -----------------------------------------------------------------------------------------------
    def set_mode(self, m):
        self.mode = m
        self.mode_var.set(m)
        self.drag = None
        self.tmp = {}
        self.cv.configure(cursor="crosshair" if m == "plan" else "arrow")
        if m == "section":
            self.fit_view()
        elif m == "3d":
            self.reset_camera()
        self.show_mode_checks()
        if m == "3d":                                   # the tool options mean nothing in 3D: room for the 3D tick boxes
            for f in self.opt_frames.values():
                f.pack_forget()
        elif m == "plan":
            self.show_tool_options()
        self.rebuild_sec_menu()
        self.redraw()

    def on_configure(self, e):
        if self._first and e.width > 300:
            self._first = False
            self.fit_view()
        self.redraw()

    def select_all(self):
        story = self.story()
        self.sel = [el["id"] for kind, lst in KIND_LISTS.items() for el in story[lst] if not self.hidden_layer(kind, el)]
        self.redraw()
        self.show_props()

    def update_title(self):
        nm = os.path.basename(self.path) if self.path else "(not saved)"
        self.root.title("%s - %s%s  [%s]" % (APP_TITLE, self.proj["name"], "*" if self.dirty else "", nm))

    # ---- files -----------------------------------------------------------------------------------------------
    def confirm_discard(self):
        if not self.dirty:
            return True
        a = messagebox.askyesnocancel(APP_TITLE, "Save the changes to '%s' first?" % self.proj["name"], parent=self.root)
        if a is None:
            return False
        if a:
            return self.save()
        return True

    def swap_project(self, proj, path):
        self.proj = proj
        self.path = path
        self.dirty = False
        self.undo, self.redo = [], []
        self.sidx = 0
        self.sel = []
        self.tmp = {}
        self.sec_id = None
        self.v3_upto = None
        self.v3_from = None
        self.rev += 1
        self.rebuild_story_bar()
        self.fit_view()
        self.redraw()
        self.show_props()
        self.memo_reminder()

    def new_file(self):
        if self.confirm_discard():
            self.swap_project(new_project("House"), None)

    def new_example(self):
        if self.confirm_discard():
            self.swap_project(make_example(), None)

    def open_file(self):
        if not self.confirm_discard():
            return
        os.makedirs(PROJECTS_DIR, exist_ok=True)
        p = filedialog.askopenfilename(parent=self.root, initialdir=PROJECTS_DIR, filetypes=FILE_TYPES, title="Open project")
        if p:
            self.open_path_file(p)

    def open_path_file(self, p):
        try:
            self.swap_project(load_project(p), p)
            self.settings["last_path"] = p
            self.save_settings()
        except Exception as ex:
            messagebox.showerror(APP_TITLE, "Could not open the file:\n%s" % ex, parent=self.root)

    def open_autosave(self):
        if os.path.isfile(AUTOSAVE_FILE) and self.confirm_discard():
            self.open_path_file(AUTOSAVE_FILE)
            self.path = None

    def save(self):
        if not self.path:
            return self.save_as()
        try:
            save_project(self.proj, self.path)
            self.dirty = False
            self.settings["last_path"] = self.path
            self.save_settings()
            self.update_title()
            self.set_status("Saved %s" % self.path)
            return True
        except Exception as ex:
            messagebox.showerror(APP_TITLE, "Could not save:\n%s" % ex, parent=self.root)
            return False

    def save_as(self):
        os.makedirs(PROJECTS_DIR, exist_ok=True)
        p = filedialog.asksaveasfilename(parent=self.root, initialdir=PROJECTS_DIR, filetypes=FILE_TYPES,
                                         initialfile=safe_name(self.proj["name"]) + ".arch.json", defaultextension=".arch.json",
                                         title="Save project")
        if not p:
            return False
        self.path = p
        return self.save()

    def autosave(self):
        try:
            if self.dirty:
                os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
                save_project(self.proj, AUTOSAVE_FILE)
        except Exception:
            pass
        self.root.after(60000, self.autosave)

    def open_notes(self):
        try:
            if self.notes is not None and self.notes.top.winfo_exists():
                self.notes.top.lift()
                return
        except Exception:
            pass
        self.settings["show_playertext"] = True
        self.notes = PlayerTextPopup(self.root, self.settings,
                                     ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel"),
                                     self.save_settings, THEME, "Notes", PROGRAM_HF_DIR, lambda: {})

    def root_key(self, e):
        w = self.root.focus_get()
        if w is not None and w.winfo_class() in ("Entry", "Text", "TEntry", "Listbox", "Spinbox"):
            return
        if w is not None and w.winfo_toplevel() is not self.root:
            return
        return self.on_key(e)

    def on_close(self):
        if not self.confirm_discard():
            return
        try:
            if self.notes is not None:
                self.notes.save_now()
        except Exception:
            pass
        try:
            self.settings["geometry"] = self.root.winfo_geometry()
            self.settings["snap"] = self.snap_mm()
        except Exception:
            pass
        self.save_settings()
        self.root.destroy()


# *************** DEL 64 - ENTRY POINT *****************
def main():
    _set_app_id()
    root = tk.Tk()
    app = ArchApp(root)
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()


if __name__ == "__main__":
    main()
