# -*- coding: utf-8 -*-
# =============================================================================
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH - code, comments, variable names,
# UI text, error messages and the hardcoded Help.  Never Swedish.
# (The BOOKS an author writes in it can of course be in any language; the
#  Swedish-aware part - the genitive "Kollega 1s" -> "Anders" - is data logic,
#  not interface text.)
# =============================================================================
"""StoryDesk - a writing desk for authors.

* Several books at once (a library; a book switcher in the top bar).
* Plan (the THEORETICAL book: parts, chapters, synopses, targets) next to the
  real chapters (the text) - a chapter with no text yet is simply "planned".
* Loose threads, notes, ideas, questions - each can belong to a chapter.
* Characters / places as PLACEHOLDERS ("Kollega 1") that are turned into real
  names ("Anders") only at the end - Swedish genitive aware: "Kollega 1s
  racerbil" becomes "Anders racerbil", not "Anderss racerbil".
* Word watch: words used too often, echoes (the same word twice within a few
  words), a watch list with limits, and "how often does X occur?" search.
* Dates: years, months and days written in the text are found, each chapter
  can be given the time it takes place, and a Time tab shows whether the story
  flows (jumps back in time, dates outside the chapter's time ...).
* Places: cities (and countries, regions) named in the text are found, each
  chapter can be given its main place, and a Places tab shows where the story
  moves.
* Snapshots: every save is a NEW time-stamped file, never an overwrite.  The
  first and the last snapshot of each day, and every manual SAVE, are marked
  as extra important.
* Phone sync (DEL 60 / 61): the books are kept the same on this PC and in the
  phone app "Issu's StoryDesk" through a relay of your own; every change is
  versioned, so one device never overwrites a change it has not seen - changes
  are merged, and words changed on both sides become a "Conflict" note.
"""

import os
import sys
import json
import base64
import copy
import difflib
import random
import secrets
import urllib.request
import urllib.error
import threading
import queue
import shutil
import subprocess
import webbrowser
import ctypes
import platform
import re
import time
import gzip
import hashlib
import bisect
import datetime
import calendar
from collections import Counter

import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, messagebox, filedialog

# *************** DEL XX - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico

# *************** DEL XX - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn

# *************** DEL XX - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass

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

MY_PROGRAM_NAME = PROGRAM_NAME

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


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

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


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


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


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

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


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

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


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


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

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

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

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


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

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

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

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

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

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

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

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

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

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


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


class ToolPopup(object):
    resizable = False

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

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

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def before_close(self):
        self.save_now()

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

# *************** DEL 10 - TEXT TOOLS (NAMES, WORDS, SEARCH) *****************
# Pure functions, no windows.  Everything here can be tested without Tk.

APP_TITLE = "StoryDesk"

# A word: letters (any language), optionally joined by - ' or ’  (no digits).
TOKEN_RE = re.compile(r"[^\W\d_]+(?:[-'’][^\W\d_]+)*", re.UNICODE)
# What counts as a "word" in a word count (digits too).
COUNT_RE = re.compile(r"\w+(?:['’-]\w+)*", re.UNICODE)

# "Common" words that are never flagged as used too often.
SV_STOP = set("""
och det att i en jag hon som han på den med var sig för så till är men ett om
har de inte du mig vi sin hade av honom varit då nu kunde ska skulle vid från
vad hur där här när eller efter också blev bli blir ut upp in över under mot
utan sedan hennes henne deras dem dess denna detta dessa man mycket andra annan
något någon några inga ingen inget alla all allt samma sådan sådant sådana
vilken vilket vilka bara ännu redan ju väl nog dock fast både varje vara vart
vem genom mellan bland ändå innan medan hos får fick få gå gick går ta tog tar
se såg ser sa sade säga säger kan kunna måste ville vill vilja skall må mitt
min mina din ditt dina vår vårt våra er ert era ni oss dig själv själva ja nej
igen lite mer mest mindre fler flest hela helt hel första två tre fyra fem sex
sju åtta nio tio sitt sina hans hennes ens ej ut av
""".split())

EN_STOP = set("""
the a an and or but if of to in on at by for with from as is are was were be
been being it its he she they them his her their we you your i me my our us
not no this that these those there here then than so too very can could will
would shall should may might must do does did done have has had having what
which who whom whose when where why how all any each some more most other
such only own same just also into over under up down out about after before
""".split())


def stop_words(lang):
    lang = (lang or "").lower()
    if lang.startswith("sv"):
        return SV_STOP
    if lang.startswith("en"):
        return EN_STOP
    return set()


def now_stamp():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def tokens(text, skip_rx=None):
    """Yield (word, start, end) for every word in text.  Words that overlap a
    skip_rx match (the placeholders) are left out."""
    skips = [m.span() for m in skip_rx.finditer(text)] if skip_rx else []
    i, n = 0, len(skips)
    for m in TOKEN_RE.finditer(text):
        s, e = m.span()
        while i < n and skips[i][1] <= s:
            i += 1
        if i < n and skips[i][0] < e:
            continue
        yield m.group(0), s, e


def count_words(text, ph_rx=None):
    """Words in text; a placeholder like "Kollega 1" counts as ONE word."""
    if ph_rx is not None:
        text = ph_rx.sub("X", text)
    return len(COUNT_RE.findall(text))


def genitive(name, override=""):
    """Swedish genitive of a name: Anna -> Annas, but Anders -> Anders,
    Max -> Max, Mats -> Mats (names ending in s, x or z take no extra s).
    `override` wins when the author has typed an own form."""
    if (override or "").strip():
        return override.strip()
    n = (name or "").strip()
    if not n:
        return n
    return n if n[-1].lower() in "sxz" else n + "s"


def build_ph_regex(chars):
    """ONE regex that finds every placeholder of `chars` in a text.

    Group 'ph'  = the placeholder, group 'gen' = a genitive ending right after
    it (Kollega 1s / Kollega 1:s / Kollega 1's).  A placeholder never matches
    inside a longer word or number (Kollega 1 is not found in Kollega 12)."""
    phs = sorted({(c.get("placeholder") or "").strip() for c in chars}
                 - {""}, key=len, reverse=True)
    if not phs:
        return None
    alt = "|".join(re.escape(p) for p in phs)
    return re.compile(
        r"(?<!\w)(?P<ph>%s)(?:(?P<gen>:s|['’]s|s)(?!\w)|(?!\w))" % alt)


def _char_map(chars):
    return {(c.get("placeholder") or "").strip(): c for c in chars
            if (c.get("placeholder") or "").strip()}


def substitute(text, chars, rx=None, only=None):
    """Replace placeholders by the real names (only those that HAVE a name).
    `only` = a single character dict to restrict the replacement to."""
    rx = rx or build_ph_regex(chars)
    if rx is None or not text:
        return text
    cmap = _char_map(chars)

    def rep(m):
        c = cmap.get(m.group("ph"))
        name = ((c or {}).get("name") or "").strip()
        if not c or not name or (only is not None and c is not only):
            return m.group(0)
        if m.group("gen"):
            return genitive(name, c.get("genitive") or "")
        return name
    return rx.sub(rep, text)


def substitute_map(text, chars, rx=None):
    """Like substitute(), but also returns a list that maps every position of
    the NEW text back to the position in the original (len(new)+1 entries), so
    a search hit in the names view can be found again in the raw text."""
    rx = rx or build_ph_regex(chars)
    if rx is None or not text:
        return text, None
    cmap = _char_map(chars)
    out, mp, pos = [], [], 0
    changed = False
    for m in rx.finditer(text):
        c = cmap.get(m.group("ph"))
        name = ((c or {}).get("name") or "").strip()
        if not c or not name:
            continue
        rep = (genitive(name, c.get("genitive") or "") if m.group("gen")
               else name)
        out.append(text[pos:m.start()])
        mp.extend(range(pos, m.start()))
        out.append(rep)
        mp.extend([m.start()] * len(rep))
        pos = m.end()
        changed = True
    if not changed:
        return text, None
    out.append(text[pos:])
    mp.extend(range(pos, len(text) + 1))
    return "".join(out), mp


def rename_placeholder(text, old, new):
    """Change a placeholder everywhere in text, keeping any genitive ending."""
    if not old or old == new:
        return text
    rx = re.compile(r"(?<!\w)%s(?P<gen>:s|['’]s|s)?(?!\w)" % re.escape(old))
    return rx.sub(lambda m: new + (m.group("gen") or ""), text)


def wild_rx(pattern, whole=True, case=False):
    """Search pattern -> regex.  * = any letters, blanks = any white space."""
    parts = []
    for tok in re.split(r"(\s+|\*)", (pattern or "").strip()):
        if not tok:
            continue
        if tok == "*":
            parts.append(r"\w*")
        elif tok.isspace():
            parts.append(r"\s+")
        else:
            parts.append(re.escape(tok))
    body = "".join(parts)
    if not body:
        return None
    if whole:
        body = r"(?<!\w)" + body + r"(?!\w)"
    return re.compile(body, 0 if case else re.IGNORECASE)


class PosIndex(object):
    """Character offset -> Tk "line.col" index, fast for thousands of tags."""

    def __init__(self, text):
        self.starts = [0] + [m.end() for m in re.finditer("\n", text)]

    def __call__(self, pos):
        i = bisect.bisect_right(self.starts, pos) - 1
        return "%d.%d" % (i + 1, pos - self.starts[i])


# *************** DEL 11 - THE BOOK (DATA, SNAPSHOTS, ANALYSIS) ***************

CHAPTER_STATUS = ["Idea", "Planned", "Drafting", "Draft done", "Revising",
                  "Final"]
NOTE_KINDS = ["Thread", "Note", "Idea", "Question", "Research", "Conflict"]
NOTE_STATUS = ["Open", "Done"]
WATCH_UNITS = ["per chapter", "per 1000 words"]
LANGUAGES = ["sv", "en", "none"]

DEFAULT_BOOK_SETTINGS = dict(
    min_len=4, min_count=5, per1000=3.0, hide_common=True,
    echo_on=True, echo_dist=40, echo_min_len=5,
    hl_over=True, hl_echo=True, hl_dates=True, use_names=True, ignore=[])


class Book(object):
    """One book = one folder:  book.json  (the live file, rewritten often)
    plus Snapshots\\ (time-stamped copies that are NEVER overwritten)."""

    def __init__(self, folder):
        self.folder = folder
        self.path = os.path.join(folder, "book.json")
        self.snap_dir = os.path.join(folder, "Snapshots")
        self.d = None
        self.dirty = False            # live file not written yet
        self.changed_since_snap = False
        self.last_snap_hash = None
        self.last_snap_time = 0.0
        self._rx_key = None
        self._rx = None
        self._date_cache = {}         # chapter id -> (text, raw date mentions)
        self._place_cache = {}        # chapter id -> (text, places named)
        self._place_key = None        # what the cache was made with
        self._place_custom = {}
        self._place_canon = {}
        self._place_excl = frozenset()

    # ---- creating / loading ---------------------------------------------------
    @staticmethod
    def new_data(title, author="", language="sv"):
        d = dict(version=1, title=title, author=author, language=language,
                 created=now_stamp(), next_id=1, chapters=[], notes=[],
                 characters=[], trash=[], watch=[], places=[],
                 places_ignore=[],
                 settings=dict(DEFAULT_BOOK_SETTINGS))
        return d

    def create(self, title, author="", language="sv"):
        os.makedirs(self.folder, exist_ok=True)
        self.d = Book.new_data(title, author, language)
        self.add_chapter(title="Chapter 1")
        self.save_live()
        return self

    def load(self):
        with open(self.path, encoding="utf-8") as fh:
            d = json.load(fh)
        base = Book.new_data(d.get("title", "Untitled"))
        for k, v in base.items():
            d.setdefault(k, v)
        st = dict(DEFAULT_BOOK_SETTINGS)
        st.update(d.get("settings") or {})
        d["settings"] = st
        self.d = d
        self.dirty = False
        return self

    # ---- ids / basic access ---------------------------------------------------
    def nid(self):
        n = self.d["next_id"]
        self.d["next_id"] = n + 1
        return n

    @property
    def title(self):
        return self.d.get("title") or "Untitled"

    @property
    def cfg(self):
        return self.d["settings"]

    def chapters(self):
        return self.d["chapters"]

    def chapter(self, cid):
        for c in self.d["chapters"]:
            if c["id"] == cid:
                return c
        return None

    def chapter_index(self, cid):
        for i, c in enumerate(self.d["chapters"]):
            if c["id"] == cid:
                return i
        return -1

    def chapter_label(self, cid):
        i = self.chapter_index(cid)
        if i < 0:
            return ""
        return "%d. %s" % (i + 1, self.d["chapters"][i]["title"])

    def add_chapter(self, after_id=None, title="New chapter"):
        ch = dict(id=self.nid(), title=title, part="", status="Planned",
                  target=0, pov="", synopsis="", text="",
                  when_from="", when_to="", place="")
        i = self.chapter_index(after_id) if after_id else -1
        if i < 0:
            self.d["chapters"].append(ch)
        else:
            self.d["chapters"].insert(i + 1, ch)
        self.touch()
        return ch

    def add_note(self, chapter=0, kind="Note", title="New note"):
        n = dict(id=self.nid(), kind=kind, title=title, text="",
                 status="Open", chapter=chapter, created=now_stamp())
        self.d["notes"].append(n)
        self.touch()
        return n

    def add_character(self, placeholder="", name=""):
        c = dict(id=self.nid(), placeholder=placeholder, name=name,
                 genitive="", notes="")
        self.d["characters"].append(c)
        self.touch()
        return c

    def trash(self, kind, item, collection):
        """Move an item to the trash (recoverable) - nothing is ever lost."""
        collection.remove(item)
        self.d["trash"].append(dict(type=kind, deleted=now_stamp(),
                                    item=item))
        self.touch()

    def touch(self):
        self.dirty = True
        self.changed_since_snap = True

    # ---- placeholders ----------------------------------------------------------
    def rx(self):
        key = tuple((c.get("placeholder") or "").strip()
                    for c in self.d["characters"])
        if key != self._rx_key:
            self._rx_key = key
            self._rx = build_ph_regex(self.d["characters"])
        return self._rx

    def names(self, text, use_names=True):
        return substitute(text, self.d["characters"], self.rx()) \
            if use_names else text

    def count(self, text):
        return count_words(text, self.rx())

    # ---- writing the live file ---------------------------------------------------
    def save_live(self):
        """Rewrite book.json (atomic: temp file + replace).  This file is the
        CURRENT state; the history lives in Snapshots\\."""
        os.makedirs(self.folder, exist_ok=True)
        tmp = self.path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(self.d, fh, ensure_ascii=False, indent=1)
        os.replace(tmp, self.path)
        self.dirty = False

    # ---- snapshots ----------------------------------------------------------------
    # File name:  YYYY-MM-DD_HH-MM-SS_<kind>[!].json.gz
    #   kind = open | auto | close | save | restore ; a trailing "!" = IMPORTANT.
    # Important are: every manual SAVE, the FIRST snapshot of each day and the
    # LAST snapshot of each day (the last is marked when the next day's first
    # one is made).  Nothing is ever overwritten or deleted by the program.
    def list_snapshots(self):
        out = []
        try:
            names = os.listdir(self.snap_dir)
        except OSError:
            return out
        for n in sorted(names):
            m = re.match(r"(\d{4}-\d\d-\d\d)_(\d\d-\d\d-\d\d)_([a-z-]+)(!?)"
                         r"(?:_(\d+))?\.json\.gz$", n)
            if not m:
                continue
            p = os.path.join(self.snap_dir, n)
            try:
                size = os.path.getsize(p)
            except OSError:
                size = 0
            out.append(dict(name=n, path=p, date=m.group(1),
                            time=m.group(2).replace("-", ":"),
                            kind=m.group(3), important=bool(m.group(4)),
                            size=size, seq=int(m.group(5) or 1)))
        out.sort(key=lambda x: (x["date"], x["time"], x["seq"]))
        return out

    def _mark_important(self, snap):
        if snap["important"]:
            return
        new = snap["name"].replace(
            "_" + snap["kind"], "_" + snap["kind"] + "!", 1)
        target = os.path.join(self.snap_dir, new)
        n = snap["seq"]
        while os.path.exists(target):          # never replace another file
            n += 1
            target = os.path.join(self.snap_dir, new.replace(
                ".json.gz", "").rsplit("_", 1)[0] + "_%d.json.gz" % n
                if re.search(r"_\d+\.json\.gz$", new) else
                new.replace(".json.gz", "_%d.json.gz" % n))
        try:
            os.rename(snap["path"], target)    # rename fails if it exists
        except OSError:
            pass

    def snapshot(self, kind, important=False, force=False):
        """Write a new snapshot.  Returns its path, or None when nothing has
        changed since the last one (unless force)."""
        data = json.dumps(self.d, ensure_ascii=False).encode("utf-8")
        digest = hashlib.md5(data).hexdigest()
        if not force and digest == self.last_snap_hash:
            if important:                   # nothing new, but the author
                snaps = self.list_snapshots()   # pressed Save: mark the last
                if snaps:                       # snapshot as important
                    self._mark_important(snaps[-1])
            return None
        os.makedirs(self.snap_dir, exist_ok=True)
        snaps = self.list_snapshots()
        today = datetime.date.today().isoformat()
        if not any(s["date"] == today for s in snaps):
            important = True                      # first snapshot of the day
            if snaps:                             # the last one of before
                self._mark_important(snaps[-1])
        stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        base = "%s_%s%s" % (stamp, kind, "!" if important else "")
        taken = [f for f in os.listdir(self.snap_dir)
                 if f.startswith("%s_%s" % (stamp, kind))]
        name, n = base + ".json.gz", 1
        while taken and (os.path.exists(os.path.join(self.snap_dir, name))
                         or n <= len(taken)):
            n += 1
            name = "%s_%d.json.gz" % (base, n)
        path = os.path.join(self.snap_dir, name)
        tmp = path + ".tmp"
        with gzip.open(tmp, "wb") as fh:
            fh.write(data)
        os.replace(tmp, path)
        self.last_snap_hash = digest
        self.last_snap_time = time.time()
        self.changed_since_snap = False
        return path

    def prime_snapshot_hash(self):
        """Remember what the newest snapshot holds, so opening an unchanged
        book does not make a needless copy."""
        self.last_snap_hash = None
        snaps = self.list_snapshots()
        if not snaps:
            return
        try:
            self.last_snap_time = os.path.getmtime(snaps[-1]["path"])
            d = self.load_snapshot_data(snaps[-1]["path"])
            self.last_snap_hash = hashlib.md5(json.dumps(
                d, ensure_ascii=False).encode("utf-8")).hexdigest()
        except Exception:
            pass

    def load_snapshot_data(self, path):
        with gzip.open(path, "rb") as fh:
            return json.loads(fh.read().decode("utf-8"))

    def restore_snapshot(self, path):
        """Make a snapshot the current book.  The state we leave is saved
        first (important), so the restore itself can be undone."""
        d = self.load_snapshot_data(path)
        self.snapshot("before-restore", important=True, force=True)
        base = Book.new_data(d.get("title", "Untitled"))
        for k, v in base.items():
            d.setdefault(k, v)
        st = dict(DEFAULT_BOOK_SETTINGS)
        st.update(d.get("settings") or {})
        d["settings"] = st
        self.d = d
        self._rx_key = None
        self.touch()
        self.save_live()

    # ---- analysis -----------------------------------------------------------------
    def stop(self):
        if not self.cfg.get("hide_common", True):
            return set()
        return stop_words(self.d.get("language"))

    def ignore(self):
        """Words never flagged: the author's ignore list + all character names
        and placeholder words."""
        ign = {w.casefold() for w in self.cfg.get("ignore", []) if w}
        for c in self.d["characters"]:
            for key in ("name", "placeholder"):
                for w, _, _ in tokens(c.get(key) or ""):
                    ign.add(w.casefold())
        return ign

    def chapter_tokens(self, ch, use_names):
        view = self.names(ch["text"], use_names)
        return [(w.casefold(), s, e) for w, s, e in tokens(view, self.rx())]

    def tally(self, chapters, use_names):
        """Count words in `chapters`.  Returns a dict:
        total (Counter), inch (word -> set of chapter ids), n (word total),
        per (chapter id -> (Counter, number of words))."""
        total, inch, per, n = Counter(), {}, {}, 0
        for ch in chapters:
            toks = self.chapter_tokens(ch, use_names)
            cnt = Counter(w for w, _, _ in toks)
            per[ch["id"]] = (cnt, len(toks))
            total.update(cnt)
            n += len(toks)
            for w in cnt:
                inch.setdefault(w, set()).add(ch["id"])
        return dict(total=total, inch=inch, per=per, n=n)

    def is_often(self, w, count, n, stop, ign):
        c = self.cfg
        if w in stop or w in ign or len(w) < c["min_len"] \
                or count < c["min_count"] or not n:
            return False
        return count * 1000.0 / n >= float(c["per1000"])

    def watch_rxs(self):
        out = []
        for e in self.d["watch"]:
            rx = wild_rx((e.get("word") or "").casefold(), whole=False,
                         case=True)
            if rx is not None:
                out.append((e, rx))
        return out

    def watch_eval(self, per, only_chapter=None):
        """Check the watch list.  per = Tally['per'].  Returns a list of dicts
        (entry, count, over: [(chapter id, count)])."""
        out = []
        for e, rx in self.watch_rxs():
            limit = float(e.get("limit") or 0)
            over, tot = [], 0
            for cid, (cnt, n) in per.items():
                if only_chapter is not None and cid != only_chapter:
                    continue
                k = sum(c for w, c in cnt.items() if rx.fullmatch(w))
                tot += k
                if e.get("unit") == WATCH_UNITS[1]:
                    bad = n > 0 and k * 1000.0 / n > limit
                else:
                    bad = k > limit
                if bad and k:
                    over.append((cid, k))
            out.append(dict(entry=e, rx=rx, count=tot, over=over))
        return out

    def echo_ranges(self, toks, stop, ign):
        """Words repeated within echo_dist words: [(start, end), ...]."""
        c = self.cfg
        dist, minlen = int(c["echo_dist"]), int(c["echo_min_len"])
        last, marks = {}, {}
        for i, (w, s, e) in enumerate(toks):
            if len(w) < minlen or w in stop or w in ign:
                continue
            if w in last and i - last[w][0] <= dist:
                marks[last[w][1]] = last[w][2]
                marks[s] = e
            last[w] = (i, s, e)
        return sorted(marks.items())

    # ---- dates ----------------------------------------------------------------------
    def _find_dates(self, ch):
        """The raw date mentions of a chapter; searched again only when the
        text has changed."""
        hit = self._date_cache.get(ch["id"])
        if hit is None or hit[0] != ch["text"]:
            hit = self._date_cache[ch["id"]] = (ch["text"],
                                                find_dates(ch["text"]))
        return hit[1]

    def date_analysis(self):
        """{chapter id: info} - see analyse_dates() in DEL 14."""
        return analyse_dates(self.chapters(), self._find_dates)

    # ---- places ---------------------------------------------------------------------
    def _place_setup(self):
        """The author's own places (My places + every chapter's main place that
        the built-in list does not know) and the words that are never places.
        Everything found earlier is forgotten when these change."""
        names, seen = [], set()
        pool = list(self.d.get("places", [])) + [
            c.get("place", "") for c in self.d["chapters"]]
        for p in pool:
            p = (p or "").strip()
            low = p.casefold()
            if len(p) >= 3 and low not in _PLACE_LOWER and low not in seen:
                seen.add(low)
                names.append(p)
        excl = frozenset(self.ignore()) | frozenset(
            w.casefold() for w in self.d.get("places_ignore", []))
        key = (tuple(names), excl)
        if key != self._place_key:
            self._place_key = key
            self._place_custom = build_custom_places(names)
            self._place_canon = {n.casefold(): n for n in names}
            self._place_excl = excl
            self._place_cache = {}

    def _find_places(self, ch):
        hit = self._place_cache.get(ch["id"])
        if hit is None or hit[0] != ch["text"]:
            hit = self._place_cache[ch["id"]] = (ch["text"], find_places(
                ch["text"], self._place_custom, self._place_excl,
                self._place_canon))
        return hit[1]

    def place_analysis(self):
        """{chapter id: info} - see analyse_places() in DEL 15."""
        self._place_setup()
        return analyse_places(self.chapters(), self._find_places)

    # ---- search -------------------------------------------------------------------
    def find_hits(self, rx, chapters, use_names, limit=5000):
        """All matches of rx.  Each hit: chapter, raw offset (where to jump),
        snippet.  Texts are searched WITH the names put in when use_names."""
        hits = []
        for ch in chapters:
            text, mp = (substitute_map(ch["text"], self.d["characters"],
                                       self.rx())
                        if use_names else (ch["text"], None))
            for m in rx.finditer(text):
                s, e = m.span()
                raw = mp[s] if mp else s
                a, b = max(0, s - 35), min(len(text), e + 35)
                snip = (text[a:s] + "[" + text[s:e] + "]" + text[e:b])
                snip = re.sub(r"\s+", " ", snip)
                hits.append(dict(cid=ch["id"], pos=raw, snip=snip,
                                 length=e - s))
                if len(hits) >= limit:
                    return hits
        return hits


# *************** DEL 12 - LIBRARY (SEVERAL BOOKS) ****************************

def safe_folder_name(title):
    bad = '<>:"/\\|?*'
    n = "".join(c for c in title if c not in bad and ord(c) >= 32)
    n = n.strip().strip(".")[:60]
    return n or "Book"


def books_dir():
    d = os.path.join(PROGRAM_HF_DIR, "Books")
    os.makedirs(d, exist_ok=True)
    return d


def list_books():
    """[(folder path, title)] of every book in the library, by title."""
    out = []
    try:
        for n in os.listdir(books_dir()):
            p = os.path.join(books_dir(), n)
            f = os.path.join(p, "book.json")
            if os.path.isfile(f):
                title = n
                try:
                    with open(f, encoding="utf-8") as fh:
                        title = json.load(fh).get("title") or n
                except Exception:
                    pass
                out.append((p, title))
    except OSError:
        pass
    return sorted(out, key=lambda x: x[1].lower())


def unique_folder(title):
    base = safe_folder_name(title)
    p, n = os.path.join(books_dir(), base), 1
    while os.path.exists(p):
        n += 1
        p = os.path.join(books_dir(), "%s (%d)" % (base, n))
    return p


# *************** DEL 13 - SETTINGS (WINDOW, POPUPS, SNAPSHOT RULES) ***********

SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")
DEFAULT_SETTINGS = dict(geometry="", last_book="", editor_size=13,
                        snap_every_edits=200, snap_min_minutes=3)


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


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

# *************** DEL 14 - DATES (YEARS, MONTHS AND DAYS FOUND IN THE TEXT) ****
# Pure functions, no windows.  Clock times (10:30) are never taken for dates.
#
#   find_dates(text)              the mentions in reading order
#   resolve_mention(m, ...)       real dates (lo, hi) + a short label
#   analyse_dates(chapters, f)    per chapter: the time the author SET, the time
#                                 the TEXT talks about, the flow against the
#                                 previous chapter, and warnings
#
# A mention is a dict: kind (day / month / year / decade / century / season),
# start, end, raw, and what was written (y, y2, m, d, d2, y_end, season ...).
# Swedish and English are both understood: "12 maj 1985", "May 12, 1985",
# "12/5 1985", "1985-05-12", "maj -85", "80-talet", "the 80s", "sommaren 1985",
# "19th century" ...  A year that is not written ("12 maj") is taken from the
# context (the last year written before it) and shown with a ~ in front.

_MONTHS = {
    "januari": 1, "january": 1, "jan": 1, "februari": 2, "february": 2,
    "feb": 2, "mars": 3, "march": 3, "mar": 3, "april": 4, "apr": 4,
    "maj": 5, "may": 5, "juni": 6, "june": 6, "jun": 6, "juli": 7,
    "july": 7, "jul": 7, "augusti": 8, "august": 8, "aug": 8,
    "september": 9, "sept": 9, "sep": 9, "oktober": 10, "october": 10,
    "okt": 10, "oct": 10, "november": 11, "nov": 11, "december": 12,
    "dec": 12}
_MON_ABBR = {"jan", "feb", "mar", "apr", "jun", "jul", "aug", "sep", "sept",
             "oct", "okt", "nov", "dec"}              # only with a number
_MON_AMBIG = {"may", "march", "mars", "august"}       # also ordinary words
_CAP_ONLY = {"may", "march"}                          # "May 12", never "may 12"
_PREP = set("""i på under till från fram sedan före efter av vid inför omkring
runt förra nästa kommande början mitten slutet tidigt sent in on during since
until by from before after of early late mid last next this through throughout
""".split())
_UNIT_AFTER = set("""kr kronor sek usd dollar dollars euro eur m meter meters
km kg g gram ord words personer people steg gånger times st stycken år years
days dagar timmar hours mil miles ton liter l procent percent pund pounds
soldater män men cm mm fot feet""".split())
_QUANT_BEFORE = {"ett", "ca", "cirka", "några", "ungefär", "omkring", "nån"}
_SEASONS = {"vår": "spring", "våren": "spring", "spring": "spring",
            "sommar": "summer", "sommaren": "summer", "summer": "summer",
            "höst": "autumn", "hösten": "autumn", "autumn": "autumn",
            "fall": "autumn", "vinter": "winter", "vintern": "winter",
            "winter": "winter"}
_SEASON_MONTHS = {"spring": (3, 5), "summer": (6, 8), "autumn": (9, 11),
                  "winter": (12, 2)}      # winter 1985 = Dec 1984 - Feb 1985
_SV_DECADES = {"noll": 0, "tio": 10, "tjugo": 20, "trettio": 30,
               "fyrtio": 40, "femtio": 50, "sextio": 60, "sjuttio": 70,
               "åttio": 80, "nittio": 90}
_SV_CENTURIES = {"sextonhundra": 1600, "sjuttonhundra": 1700,
                 "artonhundra": 1800, "nittonhundra": 1900,
                 "tjugohundra": 2000}
_EN_DECADES = {"twenties": 20, "thirties": 30, "forties": 40, "fifties": 50,
               "sixties": 60, "seventies": 70, "eighties": 80, "nineties": 90}
_FRAC_DEN = {2, 3, 4, 5, 8, 10}           # 3/4 is a fraction, not 3 April
_RANK = dict(day=0, month=1, season=1, year=2, decade=3, century=4)

_MON = "|".join(sorted(_MONTHS, key=len, reverse=True))
_ORD = r"(?::[ae]|st|nd|rd|th)"
_YTAIL = (r"(?:,?\s+(?:of\s+)?(?P<y4>(?:1\d|20)\d{2})(?!\d)"
          r"|\s*[-–'’](?P<y2>\d{2})(?!\d))")
_SUB = dict(m=_MON, o=_ORD, y=_YTAIL)


def _rx(pattern):
    return re.compile(pattern % _SUB, re.IGNORECASE)


_RX_DMY = _rx(r"(?<![\d:/.,\-–])(?P<d1>\d{1,2})%(o)s?(?:\s*[-–]\s*"
              r"(?P<d2>\d{1,2})%(o)s?)?\.?\s+(?:of\s+)?(?P<mon>%(m)s)\b\.?"
              r"%(y)s?")
_RX_MDY = _rx(r"(?<!\w)(?P<mon>%(m)s)\b\.?\s+(?P<d1>\d{1,2})%(o)s?"
              r"(?:\s*[-–]\s*(?P<d2>\d{1,2})%(o)s?)?(?![\d:])"
              r"(?:,?\s+(?P<y4>(?:1\d|20)\d{2})(?!\d))?")
_RX_MY = _rx(r"(?<!\w)(?P<mon>%(m)s)\b\.?%(y)s")
_RX_BARE = _rx(r"(?<!\w)(?P<mon>%(m)s)(?!\w)")
_RX_ISO = _rx(r"(?<![\d\-])(?P<y>(?:1\d|20)\d{2})[-/.](?P<m>\d{2})[-/.]"
              r"(?P<d>\d{2})(?!\d)")
_RX_YM = _rx(r"(?<![\d\-/.])(?P<y>(?:1\d|20)\d{2})-(?P<m>0[1-9]|1[0-2])"
             r"(?![\d\-])")
_RX_DOT = _rx(r"(?<![\d.])(?P<d>\d{1,2})\.(?P<m>\d{1,2})\."
              r"(?P<y>(?:1\d|20)\d{2})(?!\d)")
_RX_SLASH = _rx(r"(?<![\d/.,])(?P<a>\d{1,2})/(?P<b>\d{1,2})"
                r"(?:/(?P<y>\d{4}|\d{2})|\s(?P<y4>(?:1\d|20)\d{2}))?(?![\d/])")
_RX_YRANGE = _rx(r"(?<![\w.,:/§#$£€\-–])(?P<y1>(?:1\d|20)\d{2})\s*"
                 r"(?P<sep>[-–])\s*(?P<y2>\d{4}|\d{2})(?!\d)")
_RX_YEAR = _rx(r"(?<![\w.,:/§#$£€\-–])(?P<y>(?:1\d|20)\d{2})(?!\d)")
_RX_DECNUM = _rx(r"(?<![\w/.,])(?P<n>\d{4}|\d{3}|\d{2})\s?[-–‑:]?\s?"
                 r"(?P<suf>tals\w*|tal(?:ets|et|ens|en)?)(?!\w)")
_RX_DECEN = _rx(r"(?<![\w/.,])(?P<q>')?(?P<n>\d{4}|\d{2})'?s(?!\w)")
_RX_DECSV = re.compile(
    r"(?<!\w)(?P<w>%s)(?:talet|talets|talen|talens|tals\w*)(?!\w)"
    % "|".join(sorted(list(_SV_DECADES) + list(_SV_CENTURIES), key=len,
                      reverse=True)), re.IGNORECASE)
_RX_DECENW = re.compile(r"(?<!\w)the\s+(?P<w>%s)(?!\w)"
                        % "|".join(_EN_DECADES), re.IGNORECASE)
_RX_CENT = re.compile(r"(?<!\w)(?P<n>\d{1,2})(?:st|nd|rd|th)[\s-]century(?!\w)",
                      re.IGNORECASE)
_RX_SEAS = re.compile(
    r"(?<!\w)(?P<s>%s)\b(?:\s+(?:of\s+)?(?P<y4>(?:1\d|20)\d{2})(?!\d)"
    r"|\s*[-–'’](?P<y2>\d{2})(?!\d))" % "|".join(
        sorted(_SEASONS, key=len, reverse=True)), re.IGNORECASE)


def _prev_word(text, pos):
    m = re.search(r"([^\W\d_]+)\W{0,2}$", text[max(0, pos - 40):pos])
    return m.group(1).lower() if m else ""


def _ypart(mt):
    g = mt.groupdict()
    if g.get("y4"):
        return dict(y=int(g["y4"]))
    if g.get("y2"):
        return dict(y2=int(g["y2"]))
    return {}


def _h_dmy(mt, text, typed):
    d1 = int(mt.group("d1"))
    d2 = int(mt.group("d2")) if mt.group("d2") else None
    if not 1 <= d1 <= 31 or (d2 is not None and not d1 < d2 <= 31):
        return None
    return dict(kind="day", d=d1, d2=d2, m=_MONTHS[mt.group("mon").lower()],
                **_ypart(mt))


def _h_mdy(mt, text, typed):
    mon = mt.group("mon")
    if mon.lower() in _CAP_ONLY and mon[0].islower():
        return None
    d1 = int(mt.group("d1"))
    d2 = int(mt.group("d2")) if mt.group("d2") else None
    if not 1 <= d1 <= 31 or (d2 is not None and not d1 < d2 <= 31):
        return None
    return dict(kind="day", d=d1, d2=d2, m=_MONTHS[mon.lower()],
                **_ypart(mt))


def _h_my(mt, text, typed):
    mon = mt.group("mon")
    if mon.lower() in _CAP_ONLY and mon[0].islower():
        return None
    return dict(kind="month", m=_MONTHS[mon.lower()], **_ypart(mt))


def _h_bare(mt, text, typed):
    w = mt.group("mon")
    lw = w.lower()
    if typed:
        return dict(kind="month", m=_MONTHS[lw])
    if lw in _MON_ABBR:
        return None
    if (lw in _MON_AMBIG or w[0].isupper()) \
            and _prev_word(text, mt.start()) not in _PREP:
        return None
    return dict(kind="month", m=_MONTHS[lw])


def _ymd(y, mo, d):
    if 1000 <= y <= 2099 and 1 <= mo <= 12 and 1 <= d <= 31:
        return dict(kind="day", y=y, m=mo, d=d, d2=None)
    return None


def _h_iso(mt, text, typed):
    return _ymd(int(mt.group("y")), int(mt.group("m")), int(mt.group("d")))


def _h_ym(mt, text, typed):
    return dict(kind="month", y=int(mt.group("y")), m=int(mt.group("m")))


def _h_dot(mt, text, typed):
    return _ymd(int(mt.group("y")), int(mt.group("m")), int(mt.group("d")))


def _h_slash(mt, text, typed):
    a, b = int(mt.group("a")), int(mt.group("b"))
    ys = mt.group("y") or mt.group("y4")
    if ys is None and ((a < b and b in _FRAC_DEN) or (a, b) == (24, 7)):
        return None                      # 1/2, 3/4 ... 24/7: not dates
    if 1 <= a <= 31 and 1 <= b <= 12:
        d, mo = a, b                     # day first (Swedish)
    elif 1 <= b <= 31 and 1 <= a <= 12:
        d, mo = b, a                     # 12/25 can only be month first
    else:
        return None
    out = dict(kind="day", d=d, d2=None, m=mo)
    if ys is not None:
        if len(ys) == 4:
            if not 1000 <= int(ys) <= 2099:
                return None
            out["y"] = int(ys)
        else:
            out["y2"] = int(ys)
    return out


def _h_yrange(mt, text, typed):
    y1, s2 = int(mt.group("y1")), mt.group("y2")
    if len(s2) == 2:
        if mt.group("sep") == "-" and 1 <= int(s2) <= 12:
            return None                  # 1985-03 is a month, not a range
        y2 = y1 // 100 * 100 + int(s2)
    else:
        y2 = int(s2)
    if not y1 < y2 <= 2099:
        return None
    return dict(kind="year", y=y1, y_end=y2)


def _h_year(mt, text, typed):
    after = text[mt.end():mt.end() + 16]
    if re.match(r"[.,]\d", after) or after[:1] == "%":
        return None
    nxt = re.match(r"\s*([^\W\d_]+)", after)
    if nxt and nxt.group(1).lower() in _UNIT_AFTER:
        return None
    if re.search(r"[$£€]\s?$", text[max(0, mt.start() - 3):mt.start()]):
        return None
    return dict(kind="year", y=int(mt.group("y")))


def _h_decnum(mt, text, typed):
    ns, suf = mt.group("n"), mt.group("suf").lower()
    if suf == "tal" and _prev_word(text, mt.start()) in _QUANT_BEFORE:
        return None                      # "ett 20-tal personer" = about 20
    n = int(ns)
    if len(ns) == 2:
        return dict(kind="decade", y=n, two=True) if n % 10 == 0 else None
    if n % 100 == 0:
        return dict(kind="century", y=n)
    if n % 10 == 0:
        return dict(kind="decade", y=n)
    return None


def _h_decen(mt, text, typed):
    ns = mt.group("n")
    n = int(ns)
    if n % 10:
        return None
    if len(ns) == 2:
        if not (mt.group("q") or _prev_word(text, mt.start()) == "the"):
            return None                  # "60s" alone may be seconds
        return dict(kind="decade", y=n, two=True)
    return dict(kind="century" if n % 100 == 0 else "decade", y=n)


def _h_decsv(mt, text, typed):
    w = mt.group("w").lower()
    if w in _SV_CENTURIES:
        return dict(kind="century", y=_SV_CENTURIES[w])
    return dict(kind="decade", y=_SV_DECADES[w], two=True)


def _h_decenw(mt, text, typed):
    return dict(kind="decade", y=_EN_DECADES[mt.group("w").lower()], two=True)


def _h_cent(mt, text, typed):
    n = int(mt.group("n"))
    return dict(kind="century", y=(n - 1) * 100) if 1 <= n <= 21 else None


def _h_seas(mt, text, typed):
    return dict(kind="season", season=_SEASONS[mt.group("s").lower()],
                **_ypart(mt))


_DATE_PATTERNS = (
    (_RX_DMY, _h_dmy), (_RX_MDY, _h_mdy), (_RX_MY, _h_my),
    (_RX_BARE, _h_bare), (_RX_ISO, _h_iso), (_RX_YM, _h_ym),
    (_RX_DOT, _h_dot), (_RX_SLASH, _h_slash), (_RX_YRANGE, _h_yrange),
    (_RX_YEAR, _h_year), (_RX_DECNUM, _h_decnum), (_RX_DECEN, _h_decen),
    (_RX_DECSV, _h_decsv), (_RX_DECENW, _h_decenw), (_RX_CENT, _h_cent),
    (_RX_SEAS, _h_seas))


def find_dates(text, typed=False):
    """Every date mention in `text`, in reading order, none overlapping.
    typed=True: the text was typed into a date field, so a lone month name
    ("June") is accepted too."""
    cands = []
    for rx, handler in _DATE_PATTERNS:
        for mt in rx.finditer(text):
            m = handler(mt, text, typed)
            if m is None:
                continue
            s, e = mt.start(), mt.end()
            while e > s and text[e - 1] in ".,":
                e -= 1
            m.update(start=s, end=e, raw=text[s:e])
            cands.append(m)
    cands.sort(key=lambda m: (m["start"], -(m["end"] - m["start"])))
    out, last = [], -1
    for m in cands:
        if m["start"] >= last:
            out.append(m)
            last = m["end"]
    return out


def _pick_year(two, ref):
    """Full year for a two-digit number (85, or 20 in "20-talet"): the latest
    1800s/1900s/2000s candidate that is not far after `ref` (15 years)."""
    cands = [1800 + two, 1900 + two, 2000 + two]
    if ref is None:
        return 1900 + two if two >= 30 else 2000 + two
    ok = [y for y in cands if y <= ref + 15]
    return max(ok) if ok else cands[0]


def _dim(y, mo):
    return calendar.monthrange(y, mo)[1]


def _date(y, mo, d):
    return datetime.date(min(9999, max(1, y)), mo, d)


def resolve_mention(m, run_year=None, ref_year=None):
    """Fill in lo / hi (real dates), rank, short (label), inf (a ~ guess),
    bad (impossible date), year (the year used).  run_year = the last year
    written before this mention; ref_year = the book's typical year."""
    k = m["kind"]
    ref = ref_year if ref_year is not None else run_year
    y, inf, bad = m.get("y"), False, False
    if m.get("y2") is not None:
        y, inf = _pick_year(m["y2"], ref), True
    if k in ("day", "month", "season") and y is None:
        y = run_year
        inf = y is not None
    if k == "decade" and m.get("two"):
        y, inf = _pick_year(m["y"], ref), True
    lo = hi = None
    if k == "day" and y is not None:
        n = _dim(y, m["m"])
        d1, d2 = m["d"], m.get("d2") or m["d"]
        bad = d2 > n
        lo, hi = _date(y, m["m"], min(d1, n)), _date(y, m["m"], min(d2, n))
    elif k == "month" and y is not None:
        lo, hi = _date(y, m["m"], 1), _date(y, m["m"], _dim(y, m["m"]))
    elif k == "year":
        lo, hi = _date(y, 1, 1), _date(m.get("y_end") or y, 12, 31)
    elif k == "decade":
        lo, hi = _date(y, 1, 1), _date(y + 9, 12, 31)
    elif k == "century":
        lo, hi = _date(y, 1, 1), _date(y + 99, 12, 31)
    elif k == "season" and y is not None:
        a, z = _SEASON_MONTHS[m["season"]]
        if a == 12:
            lo, hi = _date(y - 1, 12, 1), _date(y, 2, _dim(y, 2))
        else:
            lo, hi = _date(y, a, 1), _date(y, z, _dim(y, z))
    ys = ("%04d" % y) if y is not None else "????"
    if k == "day":
        lab = "%s-%02d-%02d%s" % (ys, m["m"], m["d"],
                                  ("..%02d" % m["d2"]) if m.get("d2") else "")
    elif k == "month":
        lab = "%s-%02d" % (ys, m["m"])
    elif k == "year":
        lab = "%d" % y + (("-%d" % m["y_end"]) if m.get("y_end") else "")
    elif k == "decade":
        lab = "%ds" % y
    elif k == "century":
        lab = "%d-%d" % (y, y + 99)
    else:
        lab = "%s %s" % (m["season"], ys)
    m.update(lo=lo, hi=hi, rank=_RANK[k], inf=inf, bad=bad, year=y,
             short=("~" if inf else "") + lab + (" (no such day)" if bad
                                                 else ""))
    return m


def human_gap(days):
    days = abs(int(days))
    if days <= 14:
        return "%d day%s" % (days, "" if days == 1 else "s")
    if days <= 60:
        return "%d weeks" % round(days / 7.0)
    if days <= 730:
        return "%d months" % round(days / 30.44)
    return "%.1f years" % (days / 365.25)


def _span_label(a, b=None):
    return a if not b or b == a else "%s \u2013 %s" % (a, b)


def _median(vals):
    vals = sorted(vals)
    return vals[len(vals) // 2] if vals else None


def analyse_dates(chapters, finder):
    """{chapter id: info} for the chapters in book order.  `finder(ch)` gives
    the raw mentions of a chapter (a cached find_dates).  info:
      ments      the mentions, resolved, in text order ('out' = outside the
                 time set for the chapter, 'back' = earlier than the date
                 mentioned before it)
      decl       the time the author SET: dict(lo, hi, label, err) or None
      found      the time the TEXT talks about: dict(lo, hi, label) or None
      eff        decl when usable, else found: dict(lo, hi, label, src)
      flow, flow_kind   comparison with the previous dated chapter
                 ("+3 weeks" gap / "continues" / "back 2 years" / "start")
      check      warning texts"""
    chapters = list(chapters)
    raws, typed, years = {}, {}, []
    for ch in chapters:
        ms = [dict(m) for m in finder(ch)]
        raws[ch["id"]] = ms
        tm = []
        for key in ("when_from", "when_to"):
            txt = (ch.get(key) or "").strip()
            hit = find_dates(txt, True) if txt else []
            tm.append((txt, dict(hit[0]) if hit else None))
        typed[ch["id"]] = tm
        for m in ms + [t[1] for t in tm if t[1]]:
            if m["kind"] in ("day", "month", "year", "season") and m.get("y"):
                years.append(m["y"])
    ref = _median(years)
    out, ctx = {}, None
    for ch in chapters:
        cid = ch["id"]
        info = dict(cid=cid, ments=raws[cid], decl=None, found=None, eff=None,
                    flow="", flow_kind="", check=[])
        out[cid] = info
        run = ctx
        # --- the time the author set
        (ft, fm), (tt, tm) = typed[cid]
        if ft or tt:
            d = dict(lo=None, hi=None, label="", err="")
            if ft and fm is None:
                d["err"] = "'from' is not a date I understand"
            if tt and tm is None:
                d["err"] = "'to' is not a date I understand"
            if fm:
                resolve_mention(fm, run, ref)
                if fm["year"] is not None:
                    run = fm["year"]
            if tm:
                resolve_mention(tm, run, ref)
                if (fm and fm["lo"] and tm["lo"] and tm["inf"]
                        and tm["lo"] < fm["lo"] and run is not None
                        and tm.get("y2") is None):
                    resolve_mention(tm, run + 1, ref)    # Nov -> Jan
            a, b = fm or tm, tm or fm
            if a and b and a["lo"] and b["hi"]:
                d["lo"], d["hi"] = a["lo"], b["hi"]
                d["label"] = _span_label(a["short"],
                                         b["short"] if (fm and tm) else None)
                if d["lo"] > d["hi"]:
                    d["err"] = "'from' is later than 'to'"
            elif not d["err"]:
                d["err"] = "the year is missing"
            info["decl"] = d
            if d["lo"] and not d["err"]:
                run = d["lo"].year
        good = info["decl"] if (info["decl"] and not info["decl"]["err"]) \
            else None
        # --- the dates in the text
        prev = None
        for m in info["ments"]:
            resolve_mention(m, run, ref)
            if (m["kind"] in ("day", "month", "year", "season")
                    and m["year"] is not None
                    and (m.get("y") is not None or m.get("y2") is not None)):
                run = m["year"]
            if good and m["lo"] and m["rank"] <= 3 \
                    and (m["hi"] < good["lo"] or m["lo"] > good["hi"]):
                m["out"] = True
            if m["lo"] and m["rank"] <= 2:
                if prev is not None and m["hi"] < prev["lo"]:
                    m["back"] = True
                prev = m
        ctx = good["hi"].year if good else run
        # --- the time the text talks about (the finest dates it has)
        for tier in ((0, 1), (2,), (3,), (4,)):
            ms = [m for m in info["ments"] if m["lo"] and m["rank"] in tier]
            if ms:
                a = min(ms, key=lambda m: m["lo"])
                z = max(ms, key=lambda m: m["hi"])
                info["found"] = dict(
                    lo=a["lo"], hi=z["hi"],
                    label=_span_label(a["short"], z["short"]))
                break
        if good:
            info["eff"] = dict(lo=good["lo"], hi=good["hi"],
                               label=good["label"], src="set")
        elif info["found"]:
            info["eff"] = dict(info["found"], src="text")
        # --- warnings
        ck = info["check"]
        if info["decl"] and info["decl"]["err"]:
            ck.append("set time: " + info["decl"]["err"])
        n_out = sum(1 for m in info["ments"] if m.get("out"))
        n_back = sum(1 for m in info["ments"] if m.get("back"))
        n_bad = sum(1 for m in info["ments"] if m["bad"])
        n_noy = sum(1 for m in info["ments"] if m["lo"] is None)
        if n_out:
            ck.append("%d date%s outside the set time"
                      % (n_out, "" if n_out == 1 else "s"))
        if n_back:
            ck.append("%d date%s back in time"
                      % (n_back, " goes" if n_back == 1 else "s go"))
        if n_bad:
            ck.append("%d impossible date%s"
                      % (n_bad, "" if n_bad == 1 else "s"))
        if n_noy:
            ck.append("year unknown for %d date%s"
                      % (n_noy, "" if n_noy == 1 else "s"))
    # --- the flow from chapter to chapter
    prev = None
    for ch in chapters:
        info = out[ch["id"]]
        e = info["eff"]
        if not e:
            continue
        if prev is None:
            info["flow"], info["flow_kind"] = "start", "start"
        elif e["lo"] < prev["lo"]:
            info["flow"] = "back " + human_gap((prev["lo"] - e["lo"]).days)
            info["flow_kind"] = "back"
            info["check"].append("starts %s before the previous chapter"
                                 % human_gap((prev["lo"] - e["lo"]).days))
        elif e["lo"] > prev["hi"]:
            info["flow"] = "+" + human_gap((e["lo"] - prev["hi"]).days)
            info["flow_kind"] = "gap"
        else:
            info["flow"], info["flow_kind"] = "continues", "ok"
        prev = e
    return out


def when_cell(info):
    """(text, tag) for the 'When' column of a chapter list.  Tag: 'back'
    (jumps back / set time is wrong), 'guess' (taken from the text) or ''."""
    if not info:
        return "", ""
    d, e = info["decl"], info["eff"]
    if d and d["err"]:
        return "! " + (d["label"] or "?"), "back"
    if not e:
        return "", ""
    if info["flow_kind"] == "back":
        return "\u21A9 " + e["label"], "back"
    return e["label"], ("" if e["src"] == "set" else "guess")


def group_mentions(ments):
    """Identical mentions (same words, same date) become one row:
    [dict(m=first mention, spans=[(start, length), ...], out, back)]."""
    rows, idx = [], {}
    for m in ments:
        key = (re.sub(r"\s+", " ", m["raw"].lower()), m["short"])
        r = idx.get(key)
        if r is None:
            r = idx[key] = dict(m=m, spans=[], out=False, back=False)
            rows.append(r)
        r["spans"].append((m["start"], m["end"] - m["start"]))
        r["out"] = r["out"] or bool(m.get("out"))
        r["back"] = r["back"] or bool(m.get("back"))
    return rows

# *************** DEL 15 - PLACES (CITIES AND OTHER PLACES FOUND IN THE TEXT) ***
# Pure functions, no windows.
#
#   find_places(text, custom, excl)   the places named in the text, in order
#   analyse_places(chapters, f)       per chapter: main place (set by the author,
#                                     else the most named city), the places
#                                     named, and the move from the last chapter
#
# Known places come from a built-in list (Swedish and world cities, countries,
# Swedish regions - Swedish and English names, also with a genitive s:
# "Stockholms", "Paris'") plus the author's own list (Book > "My places") and
# every chapter's own main place.  Words that are also ordinary names or words
# (Nice, Lund, Paris, Mora, Split ...) count only after a place word (i, till,
# från, in, to, from ...).  A capitalised word after such a place word that is
# not known is listed as an unconfirmed name (?) - the author decides.
# A mention is a dict: start, end, raw, canon (one name per place), kind
# (city / country / area / place / ?), known.

_PLACES_DATA = """
Stockholm
Göteborg|Gothenburg
Malmö|Malmo
Uppsala
Västerås
Örebro
Linköping
Helsingborg
Jönköping
Norrköping
*Lund
Umeå
Gävle
Borås
Södertälje
Eskilstuna
Halmstad
Växjö
Karlstad
Sundsvall
Östersund
Trollhättan
Luleå
Borlänge
Falun
Kalmar
Kristianstad
Skellefteå
Kiruna
Visby
Karlskrona
Varberg
Uddevalla
Nyköping
Motala
Landskrona
Lidköping
Skövde
Hudiksvall
Härnösand
Piteå
Gällivare
Mariestad
Katrineholm
Ystad
Trelleborg
Åre
*Mora
*Nora
*Sala
Arvika
Karlshamn
Ängelholm
Båstad
Sigtuna
Strängnäs
Västervik
Oskarshamn
Ronneby
Enköping
Örnsköldsvik
Kungsbacka
Alingsås
Falkenberg
Solna
Sundbyberg
Nacka
Täby
Lidingö
Huddinge
Haparanda
Vimmerby
Simrishamn
Hässleholm
Mölndal
Kungälv
Vänersborg
Kristinehamn
Avesta
Ludvika
Sollefteå
Lycksele
Jokkmokk
Oslo
Bergen
Trondheim
Stavanger
Tromsø|Tromsö
Köpenhamn|Copenhagen|København
Århus|Aarhus
Odense
Aalborg
Helsingfors|Helsinki
Åbo|Turku
Tammerfors|Tampere
Reykjavik
Tórshavn
Nuuk
*Paris
London
Berlin
Rom|Rome
Madrid
Barcelona
Lissabon|Lisbon
Wien|Vienna
Prag|Prague
Budapest
Warszawa|Warsaw
Krakow|Kraków
Moskva|Moscow
Sankt Petersburg|Saint Petersburg|St Petersburg|S:t Petersburg|St. Petersburg
Kiev|Kyiv
Minsk
Riga
Tallinn
Vilnius
Bukarest|Bucharest
*Sofia
Belgrad|Belgrade
Zagreb
Aten|Athens
Istanbul
Ankara
Amsterdam
Rotterdam
Haag|Den Haag|The Hague
Bryssel|Brussels
Antwerpen|Antwerp
Genève|Geneva
Zürich|Zurich
Bern
Basel
München|Munich
Hamburg
Frankfurt
Köln|Cologne
Düsseldorf
Stuttgart
Dresden
Leipzig
Nürnberg|Nuremberg
Hannover
Bremen
Milano|Milan
Neapel|Naples|Napoli
Venedig|Venice|Venezia
Florens|Florence
Turin|Torino
Genua|Genoa
Bologna
Marseille
Lyon
*Nice
Nizza
Bordeaux
Toulouse
Strasbourg
Cannes
Monaco
Edinburgh
Glasgow
Dublin
Manchester
Liverpool
Birmingham
Oxford
Cambridge
Bristol
Leeds
Belfast
Cardiff
*Bath
*Reading
*York
Sevilla|Seville
Valencia
Málaga|Malaga
Granada
Porto
*Split
Dubrovnik
Sarajevo
Tirana
Valletta
Nicosia
New York
Los Angeles
Chicago
San Francisco
Boston
*Washington
Miami
Seattle
Las Vegas
Houston
*Dallas
Atlanta
Philadelphia
Detroit
Denver
New Orleans
*Austin
*Orlando
San Diego
Toronto
Montreal|Montréal
Vancouver
Ottawa
Mexico City|Mexiko City
Havanna|Havana
Rio de Janeiro
São Paulo|Sao Paulo
Buenos Aires
*Lima
Santiago
Bogotá|Bogota
Caracas
Quito
Kairo|Cairo
Casablanca
Marrakech
Nairobi
Lagos
Johannesburg
Kapstaden|Cape Town
Dubai
Abu Dhabi
Doha
Jerusalem
Tel Aviv
Beirut
Damaskus|Damascus
Bagdad|Baghdad
Teheran|Tehran
Kabul
Karachi
Delhi|New Delhi
Mumbai|Bombay
Kolkata|Calcutta
Bangkok
Singapore
Kuala Lumpur
Jakarta
Manila
Hanoi
Peking|Beijing
Shanghai
Hongkong|Hong Kong
Tokyo|Tokio
Osaka
Kyoto
Seoul
*Sydney
Melbourne
*Perth
Auckland
Wellington
@Sverige|Sweden
@Norge|Norway
@Danmark|Denmark
@Finland
@*Island|Iceland
@Tyskland|Germany
@Frankrike|France
@Spanien|Spain
@Italien|Italy
@England
@Storbritannien|Great Britain|Britain
@Skottland|Scotland
@Irland|Ireland
@Ryssland|Russia
@Polen|Poland
@USA|United States
@Kanada|Canada
@Mexiko|Mexico
@Brasilien|Brazil
@Argentina
@Kina|China
@Japan
@Indien|India
@Australien|Australia
@Egypten|Egypt
@Turkiet|*Turkey
@Grekland|Greece
@Portugal
@Nederländerna|Holland|Netherlands
@Belgien|Belgium
@Schweiz|Switzerland
@Österrike|Austria
@Estland|Estonia
@Lettland|Latvia
@Litauen|Lithuania
@Ukraina|Ukraine
@Israel
@Iran
@Irak|Iraq
@Syrien|Syria
@Sydafrika|South Africa
@Thailand
@Vietnam
@Kuba|Cuba
%Skåne
%Gotland
%Öland
%Dalarna
%Lappland|Lapland
%Norrland
%Småland
%Bohuslän
%Värmland
%Jämtland
%Härjedalen
%Halland
%Blekinge
%Uppland
%Västergötland
%Östergötland
%Närke
%Västmanland
%Hälsingland
%Medelpad
%Ångermanland
%Norrbotten
%Västerbotten
%Manhattan
%Brooklyn
%Tyrol|Tirol
%Provence
%Toscana|Tuscany
%Kalifornien|California
%Texas
%Alaska
%Sibirien|Siberia
%Balkan
%Mallorca
%Kreta|Crete
%Sicilien|Sicily
%Korsika|Corsica
%Sardinien|Sardinia
"""

_PLACE_KIND = {"@": "country", "%": "area"}
_PLACE_INFO = {}       # name as written -> (canonical name, kind, ambiguous)
_PLACE_LOWER = {}      # lower case name -> canonical name


def _load_places():
    for line in _PLACES_DATA.splitlines():
        line = line.strip()
        if not line:
            continue
        kind = "city"
        flag = line[0]
        while flag in "@%":
            kind = _PLACE_KIND[flag]
            line = line[1:]
            flag = line[0]
        names = line.split("|")
        canon = names[0].lstrip("*")
        for n in names:
            amb = n.startswith("*")
            n = n.lstrip("*")
            _PLACE_INFO[n] = (canon, kind, amb)
            _PLACE_LOWER[n.casefold()] = canon


_load_places()

_PLACE_PREP = set("""i på till från utanför nära mot vid via genom hos in to
from at near outside towards through across around""".split())
_NOT_PLACE = set("""gud god jesus jul christmas easter påsk herr fru doktor
kapitel chapter sir lady mr mrs dr ms mamma pappa farmor morfar english
swedish svenska engelska monday tuesday wednesday thursday friday saturday
sunday""".split()) | set(_MONTHS) | set(_SEASONS)

_PL_WORD = re.compile(r"[^\W\d_][\w]*")
_PL_FIRST = {}         # first word -> compiled regex of the names that start with it
_PL_SUFFIX = r"(?:s|:s|['’]s)?(?![\w])"


def _build_place_index():
    by_first = {}
    for name in _PLACE_INFO:
        first = re.match(r"[^\W\d_]+", name).group(0)
        by_first.setdefault(first, []).append(name)
    for first, names in by_first.items():
        alts = "|".join(re.escape(n).replace("\\ ", r"\s+")
                        for n in sorted(names, key=len, reverse=True))
        _PL_FIRST[first] = re.compile("(?:%s)%s" % (alts, _PL_SUFFIX))


_build_place_index()

_RX_PLACE_CAND = re.compile(
    r"(?<!\w)(?:i|till|från|på|utanför|nära|mot|vid|via|in|to|from|at|near|"
    r"outside|towards)\s+(?P<n>[A-ZÅÄÖÉÜ][\wåäöéüè]+(?:[-'’][\wåäöéü]+)*"
    r"(?:\s+[A-ZÅÄÖÉÜ][\wåäöéü]+)?)(?![\w])")


def build_custom_places(names):
    """The author's own places -> {first word (lower case): regex}."""
    by_first = {}
    for n in names:
        words = n.split()
        if not words:
            continue
        by_first.setdefault(words[0].casefold(), []).append(n)
    out = {}
    for first, ns in by_first.items():
        alts = "|".join(r"\s+".join(re.escape(w) for w in n.split())
                        for n in sorted(ns, key=len, reverse=True))
        out[first] = re.compile("(?:%s)%s" % (alts, _PL_SUFFIX),
                                re.IGNORECASE)
    return out


def place_canon(text):
    """One name for a place however it is written (Gothenburg -> Göteborg)."""
    t = (text or "").strip()
    return _PLACE_LOWER.get(t.casefold(), t)


def _place_piece(g, table, fold=False):
    """The name inside a match (the genitive ending taken off), if it is in
    `table`; else None."""
    g = re.sub(r"\s+", " ", g)
    for suf in ("", "s", ":s", "'s", "’s"):
        if suf and not g.endswith(suf):
            continue
        piece = g[:len(g) - len(suf)]
        if (piece.casefold() if fold else piece) in table:
            return piece.casefold() if fold else piece
    return None


def find_places(text, custom=None, excl=frozenset(), canon_custom=None):
    """The places named in `text`.  custom = build_custom_places(...) of the
    author's own places (canon_custom: lower case -> the name as the author
    wrote it); excl = lower case words that are never places (names of the
    characters, words the author said are not places)."""
    cands = []
    for mt in _PL_WORD.finditer(text):
        w = mt.group(0)
        s = mt.start()
        if w[0].isupper():
            for key in (w, w[:-1] if len(w) > 3 and w.endswith("s") else None):
                rx = _PL_FIRST.get(key) if key else None
                m = rx.match(text, s) if rx else None
                if m:
                    hit = _place_piece(m.group(0), _PLACE_INFO)
                    if hit:
                        canon, kind, amb = _PLACE_INFO[hit]
                        if not amb or _prev_word(text, s) in _PLACE_PREP:
                            cands.append((s, 0, m.end() - s, dict(
                                canon=canon, kind=kind, known=True,
                                start=s, end=m.end())))
                    break
        if custom:
            rx = custom.get(w.casefold())
            m = rx.match(text, s) if rx else None
            if m:
                hit = _place_piece(m.group(0), canon_custom or {}, True)
                canon = (canon_custom or {}).get(hit, hit) if hit else \
                    m.group(0)
                cands.append((s, 0, m.end() - s, dict(
                    canon=canon, kind="place", known=True, start=s,
                    end=m.end())))
    for mt in _RX_PLACE_CAND.finditer(text):
        n = mt.group("n")
        first = n.split()[0].casefold()
        if first in excl or first in _NOT_PLACE or first in SV_STOP \
                or first in EN_STOP:
            continue
        if n.casefold() in excl or any(p.casefold() in excl for p in n.split()):
            continue
        s, e = mt.start("n"), mt.end("n")
        cands.append((s, 1, e - s, dict(canon=n, kind="?", known=False,
                                        start=s, end=e)))
    cands.sort(key=lambda c: (c[0], c[1], -c[2]))
    out, last = [], -1
    for s, _, _, m in cands:
        if s >= last:
            m["raw"] = text[m["start"]:m["end"]]
            out.append(m)
            last = m["end"]
    return out


def place_cell(info):
    """Text for a 'Place' column: the main place; in ( ) when it was only read
    from the text."""
    if not info or not info["eff"]:
        return ""
    return info["eff"] if info["src"] == "set" else "(%s)" % info["eff"]


def group_places(ments):
    """One row per place: [dict(canon, kind, known, spans, order)] in the order
    the places are first named."""
    rows, idx = [], {}
    for m in ments:
        key = (m["canon"].casefold(), m["known"])
        r = idx.get(key)
        if r is None:
            r = idx[key] = dict(canon=m["canon"], kind=m["kind"],
                                known=m["known"], spans=[], order=len(rows))
            rows.append(r)
        r["spans"].append((m["start"], m["end"] - m["start"]))
    return rows


def analyse_places(chapters, finder):
    """{chapter id: info} in book order.  info:
      ments, rows   the places named (raw / grouped by place)
      set           the main place the author typed ('' if none)
      eff, src      the main place used: the set one, else the most named city
                    in the text ('set' / 'text' / '')
      flow, flow_kind   'start' / 'same' / '-> Paris' (move)
      check         warning texts"""
    out, prev = {}, ""
    for ch in chapters:
        ms = [dict(m) for m in finder(ch)]
        rows = group_places(ms)
        setp = place_canon(ch.get("place") or "")
        info = dict(cid=ch["id"], ments=ms, rows=rows,
                    set=(ch.get("place") or "").strip(), eff="", src="",
                    flow="", flow_kind="", check=[])
        if setp:
            info["eff"], info["src"] = setp, "set"
        else:
            known = [r for r in rows if r["known"]]
            pool = [r for r in known if r["kind"] != "country"] or known
            if pool:
                top = max(pool, key=lambda r: (len(r["spans"]), -r["order"]))
                info["eff"], info["src"] = top["canon"], "text"
        n_q = sum(1 for r in rows if not r["known"])
        if n_q:
            info["check"].append("%d unconfirmed place name%s (?)"
                                 % (n_q, "" if n_q == 1 else "s"))
        if info["eff"]:
            if not prev:
                info["flow"], info["flow_kind"] = "start", "start"
            elif info["eff"].casefold() == prev.casefold():
                info["flow"], info["flow_kind"] = "same", "same"
            else:
                info["flow"], info["flow_kind"] = "-> " + info["eff"], "move"
            prev = info["eff"]
        out[ch["id"]] = info
    return out

# *************** DEL 20 - UI HELPERS (THEME, WIDGET MAKERS, DIALOGS) *********

T = dict(bg="#1e1e2e", panel="#252535", fg="#e0e0e0", dim="#9090a8",
         accent="#89b4fa", btn="#34344a", btnfg="#e0e0e0",
         field="#14141f", field_fg="#e8e8f0", sep="#3a3a4e",
         warn="#f38ba8", ok="#a6e3a1", sel="#89b4fa")
FONT = ("Segoe UI", 10)
FONT_S = ("Segoe UI", 9)
FONT_B = ("Segoe UI", 10, "bold")


def mklabel(parent, text="", width=None, dim=False, anchor="w", **kw):
    opts = dict(text=text, bg=parent.cget("bg"),
                fg=T["dim"] if dim else T["fg"], font=FONT_S, anchor=anchor)
    if width:
        opts["width"] = width
    opts.update(kw)
    return tk.Label(parent, **opts)


def mkbtn(parent, text, command, w=10, **kw):
    opts = dict(text=text, command=command, width=w, bg=T["btn"],
                fg=T["btnfg"], activebackground=T["accent"],
                activeforeground="#101018", relief="flat", bd=0,
                font=FONT_S, cursor="hand2", takefocus=0, pady=3)
    opts.update(kw)
    return tk.Button(parent, **opts)


def mkentry(parent, var=None, width=20, **kw):
    e = new_entry(parent, textvariable=var, width=width, bg=T["field"],
                  fg=T["field_fg"], insertbackground=T["field_fg"],
                  relief="flat", bd=0, highlightthickness=1,
                  highlightbackground=T["sep"], highlightcolor=T["accent"],
                  font=FONT, **kw)
    return e


def mkcheck(parent, text, var, command=None):
    return tk.Checkbutton(parent, text=text, variable=var, command=command,
                          bg=parent.cget("bg"), fg=T["fg"],
                          selectcolor=T["field"], activebackground=T["bg"],
                          activeforeground=T["accent"], highlightthickness=0,
                          takefocus=0, font=FONT_S)


def mkoption(parent, var, values, command=None, width=12):
    om = tk.OptionMenu(parent, var, *values, command=command)
    om.configure(bg=T["btn"], fg=T["btnfg"], activebackground=T["accent"],
                 activeforeground="#101018", highlightthickness=0, bd=0,
                 relief="flat", takefocus=0, font=FONT_S, width=width,
                 anchor="w", cursor="hand2")
    om["menu"].configure(bg=T["btn"], fg=T["btnfg"],
                         activebackground=T["accent"],
                         activeforeground="#101018", font=FONT_S)
    return om


def reset_option(om, var, values, command=None):
    """Replace the choices of an OptionMenu."""
    m = om["menu"]
    m.delete(0, "end")
    for v in values:
        m.add_command(label=v, command=lambda v=v: (
            var.set(v), command(v) if command else None))


def mktext(parent, height=6, width=30, wrap="word", font=FONT, **kw):
    """(frame, tk.Text) with a vertical scrollbar; no blinking cursor."""
    fr = tk.Frame(parent, bg=T["sep"], bd=0)
    fr.grid_rowconfigure(0, weight=1)
    fr.grid_columnconfigure(0, weight=1)
    sb = ttk.Scrollbar(fr, orient="vertical")
    t = new_text(fr, height=height, width=width, wrap=wrap, undo=True, bd=0,
                 highlightthickness=0, padx=8, pady=6, bg=T["field"],
                 fg=T["field_fg"], insertbackground=T["field_fg"], font=font,
                 selectbackground=T["accent"], selectforeground="#101018",
                 yscrollcommand=sb.set, **kw)
    sb.configure(command=t.yview)
    t.grid(row=0, column=0, sticky="nsew", padx=(1, 0), pady=1)
    sb.grid(row=0, column=1, sticky="ns", pady=1)
    return fr, t


def mktree(parent, columns, widths, headings=None, height=10, show="headings",
           selectmode="browse"):
    """(frame, ttk.Treeview) with a vertical scrollbar."""
    fr = tk.Frame(parent, bg=T["bg"])
    fr.grid_rowconfigure(0, weight=1)
    fr.grid_columnconfigure(0, weight=1)
    tv = ttk.Treeview(fr, columns=columns, show=show, height=height,
                      selectmode=selectmode)
    sb = ttk.Scrollbar(fr, orient="vertical", command=tv.yview)
    tv.configure(yscrollcommand=sb.set)
    for i, c in enumerate(columns):
        tv.heading(c, text=(headings or columns)[i], anchor="w")
        tv.column(c, width=widths[i], anchor="w",
                  stretch=(i == len(columns) - 1 or widths[i] >= 150))
    tv.grid(row=0, column=0, sticky="nsew")
    sb.grid(row=0, column=1, sticky="ns")
    return fr, tv


def setup_styles(root):
    st = ttk.Style(root)
    try:
        st.theme_use("clam")
    except tk.TclError:
        pass
    st.configure("Treeview", background=T["field"], fieldbackground=T["field"],
                 foreground=T["fg"], rowheight=22, borderwidth=0,
                 font=FONT_S)
    st.map("Treeview", background=[("selected", T["accent"])],
           foreground=[("selected", "#101018")])
    st.configure("Treeview.Heading", background=T["btn"], foreground=T["fg"],
                 relief="flat", font=FONT_S)
    st.map("Treeview.Heading", background=[("active", T["sep"])])
    st.configure("TNotebook", background=T["bg"], borderwidth=0)
    st.configure("TNotebook.Tab", background=T["btn"], foreground=T["fg"],
                 padding=[16, 6], font=FONT_B, borderwidth=0)
    st.map("TNotebook.Tab", background=[("selected", T["accent"])],
           foreground=[("selected", "#101018")])
    st.configure("Vertical.TScrollbar", background=T["btn"],
                 troughcolor=T["panel"], bordercolor=T["panel"],
                 arrowcolor=T["fg"], relief="flat")


def center_on(top, parent, w=None, h=None):
    top.update_idletasks()
    w = w or top.winfo_reqwidth()
    h = h or top.winfo_reqheight()
    x = parent.winfo_rootx() + max(0, (parent.winfo_width() - w) // 2)
    y = parent.winfo_rooty() + max(0, (parent.winfo_height() - h) // 3)
    top.geometry("%dx%d+%d+%d" % (w, h, x, y))


def open_dialog(parent, title, w=None, h=None, resizable=False):
    """A modal Toplevel (grab_set, focus_force, Escape - 01_CORE item 3)."""
    top = tk.Toplevel(parent)
    top.title(title)
    top.configure(bg=T["bg"])
    top.transient(parent)
    top.resizable(resizable, resizable)
    return top


def finish_dialog(top, parent, w=None, h=None):
    center_on(top, parent, w, h)
    top.update()
    make_modal(top)


def ask_text(parent, title, prompt, initial="", width=38):
    """Small modal 'type a line' dialog.  Returns the text or None."""
    top = open_dialog(parent, title)
    res = [None]
    mklabel(top, prompt, wraplength=360, justify="left").pack(
        padx=16, pady=(14, 4), anchor="w")
    var = tk.StringVar(value=initial)
    e = mkentry(top, var, width)
    e.pack(padx=16, pady=4)
    row = tk.Frame(top, bg=T["bg"])
    row.pack(pady=(8, 14))

    def ok():
        res[0] = var.get()
        top.destroy()
    mkbtn(row, "OK", ok, 10).pack(side="left", padx=4)
    mkbtn(row, "Cancel", top.destroy, 10).pack(side="left", padx=4)
    e.bind("<Return>", lambda ev: ok())
    finish_dialog(top, parent)
    e.focus_set()
    e.select_range(0, "end")
    parent.wait_window(top)
    return res[0]


def info_box(parent, title, text, w=640, h=520):
    """Read-only text window (Help etc.), closes with Escape."""
    top = open_dialog(parent, title, resizable=True)
    fr, t = mktext(top, width=80, height=26)
    fr.pack(fill="both", expand=True, padx=10, pady=(10, 4))
    t.insert("1.0", text)
    t.configure(state="disabled")
    mkbtn(top, "Close", top.destroy, 10).pack(pady=(4, 10))
    finish_dialog(top, parent, w, h)
    return top

# *************** DEL 30 - TAB: PLAN (THE THEORETICAL BOOK) *******************

class PlanTab(tk.Frame):
    """Parts and chapters in order, with synopsis, status and word target -
    next to how much has really been written."""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.loading = False
        self.rebuild_job = None
        self.form_cid = None             # the chapter shown in the form
        self.iid_ch = {}                 # tree item id -> chapter id

        left = tk.Frame(self, bg=T["bg"])
        left.pack(side="left", fill="both", expand=True, padx=(10, 5),
                  pady=10)
        bar = tk.Frame(left, bg=T["bg"])
        bar.pack(fill="x", pady=(0, 6))
        mkbtn(bar, "Add chapter", self.add, 12).pack(side="left", padx=(0, 4))
        mkbtn(bar, "Move up", lambda: self.move(-1), 9).pack(side="left",
                                                           padx=4)
        mkbtn(bar, "Move down", lambda: self.move(1), 9).pack(side="left",
                                                             padx=4)
        mkbtn(bar, "Write...", self.write, 9).pack(side="left", padx=4)
        mkbtn(bar, "Note popup", lambda: self.app.open_note_popup(),
              11).pack(side="left", padx=4)
        mkbtn(bar, "Delete", self.delete, 9).pack(side="right")

        fr, self.tv = mktree(
            left, ("num", "title", "status", "when", "place", "words",
                   "target", "pct"),
            (40, 280, 100, 150, 110, 70, 70, 60),
            ("#", "Chapter", "Status", "When", "Place", "Written", "Target",
             "%"), show="tree headings")
        self.tv.column("#0", width=22, stretch=False)
        self.tv.column("num", width=44, stretch=False)
        self.tv.column("title", width=300, stretch=True)
        for c in ("status", "when", "place", "words", "target", "pct"):
            self.tv.column(c, stretch=False)
        fr.pack(fill="both", expand=True)
        self.tv.tag_configure("plan", foreground=T["dim"])
        self.tv.tag_configure("guess", foreground=T["accent"])
        self.tv.tag_configure("back", foreground=T["warn"])
        self.tv.tag_configure("part", foreground=T["accent"],
                              font=FONT_B)
        self.tv.bind("<<TreeviewSelect>>", self._selected)
        self.tv.bind("<Double-1>", lambda e: self.write())
        self.tv.bind("<Alt-Up>", lambda e: self.move(-1))
        self.tv.bind("<Alt-Down>", lambda e: self.move(1))
        self.lbl_sum = mklabel(left, "", dim=True)
        self.lbl_sum.pack(fill="x", pady=(6, 0))

        right = tk.Frame(self, bg=T["panel"], width=380)
        right.pack(side="right", fill="y", padx=(5, 10), pady=10)
        right.pack_propagate(False)
        self.v_title = tk.StringVar()
        self.v_part = tk.StringVar()
        self.v_pov = tk.StringVar()
        self.v_target = tk.StringVar()
        self.v_wfrom = tk.StringVar()
        self.v_wto = tk.StringVar()
        self.v_place = tk.StringVar()
        self.v_status = tk.StringVar(value=CHAPTER_STATUS[1])
        for lab, var in (("Title", self.v_title), ("Part", self.v_part),
                         ("Point of view / who", self.v_pov),
                         ("Target words", self.v_target),
                         ("Takes place from  (1985, March 1985, 12 May, the 80s)",
                          self.v_wfrom),
                         ("Takes place to", self.v_wto),
                         ("Main place  (a city, a region ...)",
                          self.v_place)):
            mklabel(right, lab, bg=T["panel"], dim=True).pack(
                anchor="w", padx=12, pady=(10, 0))
            mkentry(right, var, 38).pack(padx=12, fill="x")
            var.trace_add("write", lambda *a, v=var: self._field_changed())
        mklabel(right, "Status", bg=T["panel"], dim=True).pack(
            anchor="w", padx=12, pady=(10, 0))
        self.om_status = mkoption(right, self.v_status, CHAPTER_STATUS,
                                  lambda v: self._field_changed(), 14)
        self.om_status.pack(anchor="w", padx=12)
        mklabel(right, "Synopsis - what this chapter is meant to do",
                bg=T["panel"], dim=True).pack(anchor="w", padx=12,
                                              pady=(10, 0))
        fr2, self.syn = mktext(right, height=12, width=36)
        fr2.pack(fill="both", expand=True, padx=12, pady=(0, 12))
        self.syn.bind("<<Modified>>", self._syn_modified)

    # ---- filling the tree -----------------------------------------------------------
    def refresh(self):
        self.loading = True
        book = self.app.book
        self.tv.delete(*self.tv.get_children())
        self.iid_ch.clear()
        parent, last_part = "", None
        tot_w = tot_t = planned = 0
        an = book.date_analysis()
        pan = book.place_analysis()
        for i, ch in enumerate(book.chapters()):
            part = (ch.get("part") or "").strip()
            if part != last_part:
                last_part = part
                parent = ""
                if part:
                    parent = self.tv.insert(
                        "", "end", text="", open=True, tags=("part",),
                        values=("", "Part: " + part, "", "", "", "", "", ""))
            w = book.count(ch["text"])
            tgt = int(ch.get("target") or 0)
            tot_w += w
            tot_t += tgt
            if not ch["text"].strip():
                planned += 1
            pct = ("%d%%" % min(999, w * 100 // tgt)) if tgt else ""
            when, wtag = when_cell(an.get(ch["id"]))
            iid = self.tv.insert(
                parent, "end", open=True,
                values=(i + 1, ch["title"], ch["status"], when,
                        place_cell(pan.get(ch["id"])), "{:,}".format(w),
                        "{:,}".format(tgt) if tgt else "", pct),
                tags=((wtag,) if wtag else
                      (() if ch["text"].strip() else ("plan",))))
            self.iid_ch[iid] = ch["id"]
        n = len(book.chapters())
        self.lbl_sum.configure(
            text="%d chapters (%d still only planned) - written %s words%s"
                 % (n, planned, "{:,}".format(tot_w),
                    (" of a planned %s" % "{:,}".format(tot_t))
                    if tot_t else ""))
        self.loading = False
        self.select(self.app.cur_ch)

    def select(self, cid):
        for iid, c in self.iid_ch.items():
            if c == cid:
                self.loading = True
                self.tv.selection_set(iid)
                self.tv.see(iid)
                self.loading = False
                self._load_form(cid)
                return
        self._load_form(None)

    def current(self):
        sel = self.tv.selection()
        return self.iid_ch.get(sel[0]) if sel else None

    def _selected(self, e=None):
        if self.loading:
            return
        cid = self.current()
        if cid is not None and cid != self.form_cid:
            self.app.select_chapter(cid, source=self)
            self._load_form(cid)

    # ---- the form on the right ------------------------------------------------------
    def _load_form(self, cid):
        ch = self.app.book.chapter(cid) if cid else None
        self.form_cid = cid if ch else None
        self.loading = True
        self.v_title.set(ch["title"] if ch else "")
        self.v_part.set(ch.get("part", "") if ch else "")
        self.v_pov.set(ch.get("pov", "") if ch else "")
        self.v_target.set(str(ch.get("target") or "") if ch else "")
        self.v_wfrom.set(ch.get("when_from", "") if ch else "")
        self.v_wto.set(ch.get("when_to", "") if ch else "")
        self.v_place.set(ch.get("place", "") if ch else "")
        self.v_status.set(ch["status"] if ch else CHAPTER_STATUS[1])
        self.syn.delete("1.0", "end")
        if ch:
            self.syn.insert("1.0", ch.get("synopsis", ""))
        self.syn.edit_modified(False)
        self.syn.edit_reset()
        self.loading = False

    def _field_changed(self):
        if self.loading:
            return
        ch = self.app.book.chapter(self.app.cur_ch)
        if not ch:
            return
        ch["title"] = self.v_title.get()
        ch["part"] = self.v_part.get().strip()
        ch["pov"] = self.v_pov.get()
        ch["when_from"] = self.v_wfrom.get()
        ch["when_to"] = self.v_wto.get()
        ch["place"] = self.v_place.get()
        ch["status"] = self.v_status.get()
        try:
            ch["target"] = max(0, int(self.v_target.get().replace(" ", "")
                                      or 0))
        except ValueError:
            pass
        self.app.touch()
        if self.rebuild_job:
            self.after_cancel(self.rebuild_job)
        self.rebuild_job = self.after(600, self._rebuild_keep)

    def _rebuild_keep(self):
        self.rebuild_job = None
        self.app.chapters_changed(source=self)
        self.refresh()

    def _syn_modified(self, e=None):
        if not self.syn.edit_modified():
            return
        self.syn.edit_modified(False)
        if self.loading:
            return
        ch = self.app.book.chapter(self.app.cur_ch)
        if ch:
            ch["synopsis"] = self.syn.get("1.0", "end-1c")
            self.app.touch()

    # ---- buttons ----------------------------------------------------------------------
    def add(self):
        ch = self.app.book.add_chapter(after_id=self.app.cur_ch)
        self.app.cur_ch = ch["id"]
        self.app.chapters_changed(source=self)
        self.refresh()

    def move(self, d):
        cid = self.current()
        lst = self.app.book.chapters()
        i = self.app.book.chapter_index(cid) if cid else -1
        j = i + d
        if i < 0 or j < 0 or j >= len(lst):
            return
        lst[i], lst[j] = lst[j], lst[i]
        self.app.touch()
        self.app.chapters_changed(source=self)
        self.refresh()

    def delete(self):
        cid = self.current()
        ch = self.app.book.chapter(cid) if cid else None
        if not ch:
            return
        words = self.app.book.count(ch["text"])
        if not messagebox.askyesno(
                "Delete chapter",
                "Move \"%s\" (%d words) to the trash?\n\nIt can be restored "
                "from Tools > Trash." % (ch["title"], words), parent=self):
            return
        self.app.book.trash("chapter", ch, self.app.book.chapters())
        left = self.app.book.chapters()
        self.app.cur_ch = left[0]["id"] if left else None
        self.app.chapters_changed(source=self)
        self.refresh()

    def write(self):
        cid = self.current()
        if cid:
            self.app.select_chapter(cid, source=self)
            self.app.show_tab("Write")

# *************** DEL 31 - TAB: WRITE (THE REAL CHAPTERS) *********************

class WriteTab(tk.Frame):
    """Chapter list | editor | the plan (synopsis), notes and names beside it."""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.cid = None
        self.loading = False
        self.names_view = False
        self.hl_job = self.stat_job = self.when_job = self.where_job = None
        self.an = {}                    # date analysis of the whole book
        self.date_rows, self.date_pos = [], {}
        self.place_rows, self.place_pos = [], {}
        self.font = tkfont.Font(family="Georgia",
                                size=int(app.S.get("editor_size", 13)))

        pw = tk.PanedWindow(self, orient="horizontal", bg=T["bg"],
                            sashwidth=6, bd=0, sashrelief="flat")
        pw.pack(fill="both", expand=True, padx=10, pady=10)

        # --- left: chapter list (with the time each chapter takes place)
        lf = tk.Frame(pw, bg=T["bg"], width=390)
        fr, self.tv = mktree(lf, ("title", "when", "words"), (140, 170, 55),
                             ("Chapter", "When", "Words"))
        self.tv.column("title", stretch=True)
        self.tv.column("when", stretch=False)
        self.tv.column("words", stretch=False, anchor="e")
        fr.pack(fill="both", expand=True)
        self.tv.tag_configure("plan", foreground=T["dim"])
        self.tv.tag_configure("guess", foreground=T["accent"])
        self.tv.tag_configure("back", foreground=T["warn"])
        self.tv.bind("<<TreeviewSelect>>", self._list_selected)
        self.iid_ch = {}
        pw.add(lf, minsize=240, width=390)

        # --- centre: editor
        cf = tk.Frame(pw, bg=T["bg"])
        top = tk.Frame(cf, bg=T["bg"])
        top.pack(fill="x")
        self.v_title = tk.StringVar()
        mkentry(top, self.v_title, 40).pack(side="left", fill="x",
                                            expand=True)
        self.v_title.trace_add("write", lambda *a: self._title_changed())
        self.lbl_count = mklabel(top, "", width=34, anchor="e", dim=True)
        self.lbl_count.pack(side="right", padx=(8, 0))

        opt = tk.Frame(cf, bg=T["bg"])
        opt.pack(fill="x", pady=(6, 4))
        self.v_names = tk.BooleanVar(value=False)
        self.v_over = tk.BooleanVar(value=app.book.cfg["hl_over"])
        self.v_echo = tk.BooleanVar(value=app.book.cfg["hl_echo"])
        self.v_dates = tk.BooleanVar(value=app.book.cfg["hl_dates"])
        mkcheck(opt, "Show names (read-only preview)", self.v_names,
                self._toggle_names).pack(side="left")
        mkcheck(opt, "Mark words used too often", self.v_over,
                self._toggle_hl).pack(side="left", padx=(10, 0))
        mkcheck(opt, "Mark echoes", self.v_echo, self._toggle_hl).pack(
            side="left", padx=(10, 0))
        mkcheck(opt, "Mark dates & places", self.v_dates,
                self._toggle_hl).pack(side="left", padx=(10, 0))

        wr = tk.Frame(cf, bg=T["bg"])
        wr.pack(fill="x", pady=(0, 4))
        mklabel(wr, "Takes place:", dim=True).pack(side="left")
        self.v_wfrom, self.v_wto = tk.StringVar(), tk.StringVar()
        mkentry(wr, self.v_wfrom, 15).pack(side="left", padx=(6, 0))
        mklabel(wr, "to", dim=True).pack(side="left", padx=5)
        mkentry(wr, self.v_wto, 15).pack(side="left")
        self.lbl_when = mklabel(wr, "", width=46, dim=True)
        self.lbl_when.pack(side="left", padx=10)
        self.v_wfrom.trace_add("write", lambda *a: self._when_changed())
        self.v_wto.trace_add("write", lambda *a: self._when_changed())

        pr = tk.Frame(cf, bg=T["bg"])
        pr.pack(fill="x", pady=(0, 4))
        mklabel(pr, "Main place:", dim=True).pack(side="left")
        self.v_place = tk.StringVar()
        mkentry(pr, self.v_place, 26).pack(side="left", padx=(14, 0))
        self.lbl_where = mklabel(pr, "", width=46, dim=True)
        self.lbl_where.pack(side="left", padx=10)
        self.v_place.trace_add("write", lambda *a: self._where_changed())

        find = tk.Frame(cf, bg=T["bg"])
        find.pack(fill="x", pady=(0, 6))
        mklabel(find, "Find:", dim=True).pack(side="left")
        self.v_find = tk.StringVar()
        self.e_find = mkentry(find, self.v_find, 22)
        self.e_find.pack(side="left", padx=4)
        self.e_find.bind("<Return>", lambda e: self.find_next(1))
        self.e_find.bind("<Shift-Return>", lambda e: self.find_next(-1))
        mkbtn(find, "Prev", lambda: self.find_next(-1), 6).pack(side="left")
        mkbtn(find, "Next", lambda: self.find_next(1), 6).pack(
            side="left", padx=4)
        # (packed on the right first, so it is always visible)
        mkbtn(find, "Fewer blank lines", self.squeeze_blank_lines, 16).pack(
            side="right")
        mkbtn(find, "Pop out", lambda: self.app.open_chapter_popup(self.cid),
              8).pack(side="right", padx=4)
        self.lbl_found = mklabel(find, "", width=22, dim=True)
        self.lbl_found.pack(side="left", padx=6)

        fr2, self.txt = mktext(cf, height=20, width=70, font=self.font)
        fr2.pack(fill="both", expand=True)
        self.txt.configure(spacing2=3, spacing3=8)
        self.txt.tag_configure("ph", foreground=T["accent"])
        self.txt.tag_configure("echo", background="#2f4c5c")
        self.txt.tag_configure("over", background="#5a4a1a")
        self.txt.tag_configure("watch", background="#6a2a3a")
        self.txt.tag_configure("date", foreground="#94e2d5", underline=True)
        self.txt.tag_configure("place", foreground="#f9e2af", underline=True)
        self.txt.tag_raise("sel")
        self.txt.bind("<<Modified>>", self._modified)
        self.txt.bind("<Control-MouseWheel>", self._zoom)
        self.txt.bind("<Control-f>", lambda e: (self.e_find.focus_set(),
                                                "break")[1])
        pw.add(cf, minsize=380)

        # --- right: plan, notes, names
        rf = tk.Frame(pw, bg=T["panel"], width=300)
        mklabel(rf, "The plan for this chapter", bg=T["panel"], dim=True
                ).pack(anchor="w", padx=10, pady=(10, 2))
        fr3, self.syn = mktext(rf, height=5, width=30)
        fr3.pack(fill="x", padx=10)
        self.syn.bind("<<Modified>>", self._syn_modified)
        row = tk.Frame(rf, bg=T["panel"])
        row.pack(fill="x", padx=10, pady=(10, 2))
        mklabel(row, "Notes for this chapter", bg=T["panel"], dim=True
                ).pack(side="left")
        mkbtn(row, "New", self._new_note, 5).pack(side="right")
        mkbtn(row, "Pop out", self._pop_note, 7).pack(side="right", padx=4)
        self.lb_notes = self._listbox(rf, 5, expand=False)
        self.lb_notes.bind("<Double-1>", self._open_note)
        mklabel(rf, "Names - double-click to insert", bg=T["panel"],
                dim=True).pack(anchor="w", padx=10, pady=(10, 2))
        self.lb_names = self._listbox(rf, 3)
        self.lb_names.bind("<Double-1>", self._insert_name)
        mklabel(rf, "Dates in this chapter - double-click to show",
                bg=T["panel"], dim=True).pack(anchor="w", padx=10,
                                              pady=(6, 2))
        self.lb_dates = self._listbox(rf, 3)
        self.lb_dates.bind("<Double-1>", self._date_open)
        mklabel(rf, "Places in this chapter - double-click to show",
                bg=T["panel"], dim=True).pack(anchor="w", padx=10,
                                              pady=(6, 2))
        self.lb_places = self._listbox(rf, 3)
        self.lb_places.bind("<Double-1>", self._place_open)
        self.lb_places.bind("<Button-3>", self._place_menu)
        self.note_ids, self.name_phs = [], []
        pw.add(rf, minsize=260, width=340)

    def _listbox(self, parent, height, expand=True):
        lb = tk.Listbox(parent, height=height, bg=T["field"], fg=T["fg"],
                        selectbackground=T["accent"],
                        selectforeground="#101018", bd=0,
                        highlightthickness=0, font=FONT_S,
                        activestyle="none", exportselection=False)
        lb.pack(fill="both", expand=expand, padx=10, pady=(0, 6))
        return lb

    # ---- list of chapters ---------------------------------------------------------
    def refresh(self):
        b = self.app.book
        self.loading = True
        self.tv.delete(*self.tv.get_children())
        self.iid_ch.clear()
        self._analyse()
        for i, ch in enumerate(b.chapters()):
            when, tag = when_cell(self.an.get(ch["id"]))
            iid = self.tv.insert(
                "", "end", values=("%d. %s" % (i + 1, ch["title"]), when,
                                   "{:,}".format(b.count(ch["text"]))),
                tags=self._row_tags(ch, tag))
            self.iid_ch[iid] = ch["id"]
        self.loading = False
        self.v_over.set(b.cfg["hl_over"])
        self.v_echo.set(b.cfg["hl_echo"])
        self.v_dates.set(b.cfg["hl_dates"])
        cid = self.app.cur_ch
        if b.chapter(cid) is None:
            cid = b.chapters()[0]["id"] if b.chapters() else None
            self.app.cur_ch = cid
        self.load(cid)

    def _list_selected(self, e=None):
        if self.loading:
            return
        sel = self.tv.selection()
        if sel and self.iid_ch.get(sel[0]) != self.cid:
            # (the equality test also ends the select-event ping-pong that
            #  the programmatic selection in _mark_in_list would cause)
            self.app.select_chapter(self.iid_ch[sel[0]], source=self)
            self.load(self.iid_ch[sel[0]])

    def _mark_in_list(self, cid):
        for iid, c in self.iid_ch.items():
            if c == cid:
                self.loading = True
                self.tv.selection_set(iid)
                self.tv.see(iid)
                self.loading = False

    # ---- loading a chapter ----------------------------------------------------------
    def load(self, cid):
        b = self.app.book
        ch = b.chapter(cid) if cid else None
        self.cid = cid if ch else None
        self.loading = True
        self.v_title.set(ch["title"] if ch else "")
        self.v_wfrom.set(ch.get("when_from", "") if ch else "")
        self.v_wto.set(ch.get("when_to", "") if ch else "")
        self.v_place.set(ch.get("place", "") if ch else "")
        self.names_view = False
        self.v_names.set(False)
        self.txt.configure(state="normal")
        self.txt.delete("1.0", "end")
        self.syn.delete("1.0", "end")
        if ch:
            self.txt.insert("1.0", ch["text"])
            self.syn.insert("1.0", ch.get("synopsis", ""))
        else:
            self.txt.configure(state="disabled")
        self.txt.edit_modified(False)
        self.txt.edit_reset()
        self.syn.edit_modified(False)
        self.loading = False
        self._mark_in_list(cid)
        self._fill_side()
        self._update_stats()
        self._highlight()

    def _fill_side(self):
        b = self.app.book
        self.lb_notes.delete(0, "end")
        self.note_ids = []
        for n in b.d["notes"]:
            if n.get("chapter") == self.cid and self.cid:
                self.lb_notes.insert("end", "[%s] %s" % (n["kind"],
                                                         n["title"]))
                self.note_ids.append(n["id"])
        self.lb_names.delete(0, "end")
        self.name_phs = []
        for c in b.d["characters"]:
            ph = (c.get("placeholder") or "").strip()
            if ph:
                nm = (c.get("name") or "").strip()
                self.lb_names.insert("end", ph + ("  ->  " + nm if nm else ""))
                self.name_phs.append(ph)

    # ---- editing ---------------------------------------------------------------------
    def _title_changed(self):
        if self.loading:
            return
        ch = self.app.book.chapter(self.cid)
        if not ch:
            return
        ch["title"] = self.v_title.get()
        self.app.touch()
        for iid, c in self.iid_ch.items():
            if c == self.cid:
                i = self.app.book.chapter_index(c)
                self.tv.set(iid, "title", "%d. %s" % (i + 1, ch["title"]))

    def _modified(self, e=None):
        if not self.txt.edit_modified():
            return
        self.txt.edit_modified(False)
        if self.loading or self.names_view:
            return
        ch = self.app.book.chapter(self.cid)
        if not ch:
            return
        ch["text"] = self.txt.get("1.0", "end-1c")
        if ch["status"] in ("Idea", "Planned") and ch["text"].strip():
            ch["status"] = "Drafting"          # text exists: no longer a plan
        self.app.touch()
        if self.stat_job:
            self.after_cancel(self.stat_job)
        self.stat_job = self.after(350, self._update_stats)
        if self.hl_job:
            self.after_cancel(self.hl_job)
        self.hl_job = self.after(900, self._highlight)

    def _syn_modified(self, e=None):
        if not self.syn.edit_modified():
            return
        self.syn.edit_modified(False)
        ch = self.app.book.chapter(self.cid)
        if ch and not self.loading:
            ch["synopsis"] = self.syn.get("1.0", "end-1c")
            self.app.touch()

    def _update_stats(self):
        self.stat_job = None
        b = self.app.book
        ch = b.chapter(self.cid)
        if not ch:
            self.lbl_count.configure(text="")
            return
        w = b.count(ch["text"])
        tgt = int(ch.get("target") or 0)
        s = "{:,} words".format(w)
        if tgt:
            s += "  /  target {:,}  ({}%)".format(tgt, w * 100 // tgt)
        self.lbl_count.configure(text=s)
        for iid, c in self.iid_ch.items():
            if c == self.cid:
                self.tv.set(iid, "words", "{:,}".format(w))
                self.tv.item(iid, tags=self._row_tags(
                    ch, when_cell(self.an.get(c))[1]))

    def _row_tags(self, ch, when_tag):
        """Row colour: red = time problem, blue = time taken from the text,
        grey = no text yet."""
        if when_tag:
            return (when_tag,)
        return () if ch["text"].strip() else ("plan",)

    def _zoom(self, e):
        size = int(self.font.cget("size")) + (1 if e.delta > 0 else -1)
        size = max(8, min(30, size))
        self.font.configure(size=size)
        self.app.S["editor_size"] = size
        return "break"

    # ---- names preview ------------------------------------------------------------------
    def _toggle_names(self):
        ch = self.app.book.chapter(self.cid)
        if not ch:
            return
        self.loading = True
        pos = self.txt.yview()[0]
        if self.v_names.get():
            self.names_view = True
            self.txt.configure(state="normal")
            self.txt.delete("1.0", "end")
            self.txt.insert("1.0", self.app.book.names(ch["text"], True))
            self.txt.configure(state="disabled")
        else:
            self.names_view = False
            self.txt.configure(state="normal")
            self.txt.delete("1.0", "end")
            self.txt.insert("1.0", ch["text"])
        self.txt.edit_modified(False)
        self.txt.yview_moveto(pos)
        self.loading = False
        self._highlight()

    def _toggle_hl(self):
        c = self.app.book.cfg
        c["hl_over"] = bool(self.v_over.get())
        c["hl_echo"] = bool(self.v_echo.get())
        c["hl_dates"] = bool(self.v_dates.get())
        self.app.touch()
        self._highlight()

    # ---- dates: the time of the chapter, the dates in its text --------------------------
    def _analyse(self):
        self.an = self.app.book.date_analysis()
        return self.an

    def _when_changed(self):
        """The author typed a 'takes place from / to'."""
        if self.loading:
            return
        ch = self.app.book.chapter(self.cid)
        if not ch:
            return
        ch["when_from"] = self.v_wfrom.get()
        ch["when_to"] = self.v_wto.get()
        self.app.touch()
        if self.when_job:
            self.after_cancel(self.when_job)
        self.when_job = self.after(300, self._dates_refresh)

    def _dates_refresh(self):
        """Analyse the whole book again (cheap: the dates of unchanged chapters
        are remembered) and show it: the dates list, the marks in the text, the
        When column and the line under the chapter title."""
        self.when_job = None
        info = self._analyse().get(self.cid)
        self._fill_dates(info)
        self._mark_dates(info)
        self._list_when()
        self._when_label(info)

    def _list_when(self):
        b = self.app.book
        for iid, cid in self.iid_ch.items():
            ch = b.chapter(cid)
            if ch is None:
                continue
            when, tag = when_cell(self.an.get(cid))
            self.tv.set(iid, "when", when)
            self.tv.item(iid, tags=self._row_tags(ch, tag))

    def _when_label(self, info):
        lab = self.lbl_when
        if not info:
            lab.configure(text="", fg=T["dim"])
            return
        d, e = info["decl"], info["eff"]
        if d and d["err"]:
            lab.configure(text="! " + d["err"], fg=T["warn"])
            return
        if not e:
            lab.configure(text="no date found in the text yet", fg=T["dim"])
            return
        flow = info["flow"] if info["flow_kind"] in ("gap", "back", "ok") \
            else ""
        txt = ("" if e["src"] == "set" else "from the text: ") + e["label"]
        if flow:
            txt += "   (" + flow + ")"
        lab.configure(text=txt,
                      fg=T["warn"] if info["flow_kind"] == "back" else T["fg"])

    def _fill_dates(self, info):
        lb = self.lb_dates
        lb.delete(0, "end")
        self.date_rows, self.date_pos = [], {}
        if not info:
            return
        for i, r in enumerate(group_mentions(info["ments"])):
            m, n = r["m"], len(r["spans"])
            lb.insert("end", "%s  >  %s%s%s" % (
                re.sub(r"\s+", " ", m["raw"]), m["short"],
                "  x%d" % n if n > 1 else "",
                "  !" if r["out"] else ("  <" if r["back"] else "")))
            if r["out"]:
                lb.itemconfig(i, fg=T["warn"])
            elif r["back"]:
                lb.itemconfig(i, fg="#fab387")
            elif m["lo"] is None:
                lb.itemconfig(i, fg=T["dim"])
            self.date_rows.append(r)

    def _mark_dates(self, info):
        txt = self.txt
        txt.tag_remove("date", "1.0", "end")
        if not info or self.names_view or not self.app.book.cfg["hl_dates"]:
            return
        ch = self.app.book.chapter(self.cid)
        text = ch["text"] if ch else ""
        if len(text) > 800000:
            return
        idx = PosIndex(text)
        for m in info["ments"]:
            txt.tag_add("date", idx(m["start"]), idx(m["end"]))
        txt.tag_raise("sel")

    def _date_open(self, e=None):
        """Double-click a date: select it in the text (again = the next time
        the same date is written)."""
        sel = self.lb_dates.curselection()
        if not sel or sel[0] >= len(self.date_rows):
            return
        spans = self.date_rows[sel[0]]["spans"]
        k = self.date_pos.get(sel[0], 0) % len(spans)
        self.date_pos[sel[0]] = k + 1
        self.jump(self.cid, spans[k][0], spans[k][1])

    # ---- places: the main place of the chapter, the places named in its text ---------------
    def _where_changed(self):
        """The author typed the main place of the chapter."""
        if self.loading:
            return
        ch = self.app.book.chapter(self.cid)
        if not ch:
            return
        ch["place"] = self.v_place.get()
        self.app.touch()
        if self.where_job:
            self.after_cancel(self.where_job)
        self.where_job = self.after(300, self._places_refresh)

    def _places_refresh(self):
        self.where_job = None
        info = self.app.book.place_analysis().get(self.cid)
        self._fill_places(info)
        self._mark_places(info)
        lab = self.lbl_where
        if not info or not info["eff"]:
            lab.configure(text="no place found in the text yet" if info
                          else "", fg=T["dim"])
            return
        txt = ("" if info["src"] == "set" else "from the text: ") + info["eff"]
        if info["flow_kind"] in ("move", "same"):
            txt += "   (%s)" % info["flow"]
        lab.configure(text=txt, fg=T["fg"])

    def _fill_places(self, info):
        lb = self.lb_places
        lb.delete(0, "end")
        self.place_rows, self.place_pos = [], {}
        if not info:
            return
        tags = dict(country="  [country]", area="  [area]", place="  [mine]")
        for i, r in enumerate(info["rows"]):
            n = len(r["spans"])
            lb.insert("end", "%s%s%s%s" % ("? " if not r["known"] else "",
                                           r["canon"], tags.get(r["kind"], ""),
                                           "  x%d" % n if n > 1 else ""))
            if not r["known"]:
                lb.itemconfig(i, fg=T["dim"])
            self.place_rows.append(r)

    def _mark_places(self, info):
        txt = self.txt
        txt.tag_remove("place", "1.0", "end")
        if not info or self.names_view or not self.app.book.cfg["hl_dates"]:
            return
        ch = self.app.book.chapter(self.cid)
        text = ch["text"] if ch else ""
        if len(text) > 800000:
            return
        idx = PosIndex(text)
        for m in info["ments"]:
            if m["known"]:
                txt.tag_add("place", idx(m["start"]), idx(m["end"]))
        txt.tag_raise("sel")

    def _place_open(self, e=None):
        """Double-click a place: select it in the text (again = the next time
        it is named).  An unconfirmed name (?) is added to My places."""
        sel = self.lb_places.curselection()
        if not sel or sel[0] >= len(self.place_rows):
            return
        r = self.place_rows[sel[0]]
        if not r["known"]:
            self._place_add(r["canon"])
            return
        k = self.place_pos.get(sel[0], 0) % len(r["spans"])
        self.place_pos[sel[0]] = k + 1
        self.jump(self.cid, r["spans"][k][0], r["spans"][k][1])

    def _place_menu(self, e):
        i = self.lb_places.nearest(e.y)
        if i < 0 or i >= len(self.place_rows):
            return
        self.lb_places.selection_clear(0, "end")
        self.lb_places.selection_set(i)
        r = self.place_rows[i]
        menu = tk.Menu(self, tearoff=0, bg=T["btn"], fg=T["btnfg"],
                       activebackground=T["accent"],
                       activeforeground="#101018", font=FONT_S)
        if not r["known"]:
            menu.add_command(label="Add \"%s\" as a place" % r["canon"],
                             command=lambda: self._place_add(r["canon"]))
            menu.add_command(label="\"%s\" is not a place" % r["canon"],
                             command=lambda: self._place_never(r["canon"]))
        elif r["kind"] == "place":
            menu.add_command(label="Remove \"%s\" from My places" % r["canon"],
                             command=lambda: self._place_remove(r["canon"]))
        else:
            return
        menu.tk_popup(e.x_root, e.y_root)

    def _place_add(self, name):
        d = self.app.book.d
        if name.casefold() not in [p.casefold() for p in d.setdefault("places", [])]:
            d["places"].append(name)
            self.app.touch()
        self._places_refresh()

    def _place_never(self, name):
        d = self.app.book.d
        d.setdefault("places_ignore", []).append(name)
        self.app.touch()
        self._places_refresh()

    def _place_remove(self, name):
        d = self.app.book.d
        d["places"] = [p for p in d.get("places", [])
                       if p.casefold() != name.casefold()]
        self.app.touch()
        self._places_refresh()

    # ---- marking words -------------------------------------------------------------------
    def _highlight(self):
        self.hl_job = None
        b = self.app.book
        cfg = b.cfg
        txt = self.txt
        for t in ("ph", "over", "watch", "echo"):
            txt.tag_remove(t, "1.0", "end")
        self._dates_refresh()
        self._places_refresh()
        text = txt.get("1.0", "end-1c")
        if not text or len(text) > 800000:
            return
        idx = PosIndex(text)
        rx = b.rx()
        if rx is not None and not self.names_view:
            for m in rx.finditer(text):
                txt.tag_add("ph", idx(m.start()), idx(m.end()))
        toks = [(w.casefold(), s, e) for w, s, e in tokens(text, rx)]
        if not toks:
            return
        stop, ign = b.stop(), b.ignore()
        if cfg["hl_over"]:
            n = len(toks)
            cnt = Counter(w for w, _, _ in toks)
            often = {w for w, c in cnt.items()
                     if b.is_often(w, c, n, stop, ign)}
            bad = set()
            for r in b.watch_eval({self.cid: (cnt, n)}):
                if r["over"]:
                    bad.update(w for w in cnt if r["rx"].fullmatch(w))
            for w, s, e in toks:
                if w in bad:
                    txt.tag_add("watch", idx(s), idx(e))
                elif w in often:
                    txt.tag_add("over", idx(s), idx(e))
        if cfg["hl_echo"]:
            for s, e in b.echo_ranges(toks, stop, ign):
                txt.tag_add("echo", idx(s), idx(e))
        txt.tag_raise("sel")

    # ---- find in this chapter ---------------------------------------------------------------
    def find_next(self, direction=1):
        pat = self.v_find.get()
        txt = self.txt
        if not pat:
            self.lbl_found.configure(text="")
            return
        total = len(re.findall(re.escape(pat), txt.get("1.0", "end-1c"),
                               re.IGNORECASE))
        self.lbl_found.configure(text="%d in this chapter" % total)
        if not total:
            return
        try:
            cur = txt.index("sel.last" if direction > 0 else "sel.first")
        except tk.TclError:
            cur = txt.index("insert")
        if direction > 0:
            pos = txt.search(pat, cur, "end", nocase=True)
            if not pos:
                pos = txt.search(pat, "1.0", "end", nocase=True)
        else:
            pos = txt.search(pat, cur, "1.0", nocase=True, backwards=True)
            if not pos:
                pos = txt.search(pat, "end", "1.0", nocase=True,
                                 backwards=True)
        if pos:
            end = "%s+%dc" % (pos, len(pat))
            txt.tag_remove("sel", "1.0", "end")
            txt.tag_add("sel", pos, end)
            txt.mark_set("insert", end if direction > 0 else pos)
            txt.see(pos)

    # ---- tidy: several blank lines in a row -> one blank line ---------------------------------
    # ToDo (2026-11-09): "Fewer blank lines" button on the Find row.  Works on the
    # selected lines, or on the whole chapter when nothing is selected.  A line
    # with only spaces counts as blank.  One undo (Ctrl+Z) brings everything back.
    def squeeze_blank_lines(self):
        txt = self.txt
        if not self.cid or self.names_view:
            self.lbl_found.configure(text="Not in the names preview")
            return
        try:
            a = txt.index("sel.first linestart")
            b = txt.index("sel.last lineend")
            what = "in the selection"
        except tk.TclError:
            a, b = "1.0", txt.index("end-1c")
            what = "in this chapter"
        first = int(a.split(".")[0])
        lines = txt.get(a, b).split("\n")
        runs, i = [], 0                      # runs = [(first_line, last_line)]
        while i < len(lines):
            if lines[i].strip():
                i += 1
                continue
            j = i
            while j + 1 < len(lines) and not lines[j + 1].strip():
                j += 1
            if j > i:
                runs.append((first + i, first + j))
            i = j + 1
        removed = sum(e - s for s, e in runs)
        if not removed:
            self.lbl_found.configure(text="No double blank lines " + what)
            return
        txt.edit_separator()
        for s, e in reversed(runs):          # from the bottom, so line numbers stay true
            txt.delete("%d.end" % s, "%d.end" % e)
        txt.edit_separator()
        self.lbl_found.configure(text="Removed %d blank line%s" % (
            removed, "" if removed == 1 else "s"))

    def jump(self, cid, pos, length, use_names=False):
        """Open chapter `cid` and select the text at raw offset `pos`."""
        if cid != self.cid or self.names_view:
            self.app.select_chapter(cid, source=None)
            self.load(cid)
        txt = self.txt
        a = "1.0+%dc" % pos
        txt.tag_remove("sel", "1.0", "end")
        txt.tag_add("sel", a, "%s+%dc" % (a, max(1, length)))
        txt.mark_set("insert", a)
        txt.see(a)
        txt.focus_set()

    # ---- the side panel -------------------------------------------------------------------
    def _insert_name(self, e=None):
        sel = self.lb_names.curselection()
        if sel and not self.names_view and self.cid:
            self.txt.insert("insert", self.name_phs[sel[0]])
            self.txt.focus_set()

    def _new_note(self):
        if not self.cid:
            return
        n = self.app.book.add_note(chapter=self.cid, kind="Thread",
                                   title="New thread")
        self.app.open_note(n["id"])

    def _pop_note(self):
        sel = self.lb_notes.curselection()
        self.app.open_note_popup(self.note_ids[sel[0]] if sel else None)

    def _open_note(self, e=None):
        sel = self.lb_notes.curselection()
        if sel:
            self.app.open_note(self.note_ids[sel[0]])

    def flush(self):
        """Nothing is buffered: every keystroke already went into the book."""
        pass

# *************** DEL 32 - TAB: NOTES & LOOSE THREADS **************************

class NotesTab(tk.Frame):
    """Loose threads, notes, ideas, questions - each may belong to a chapter."""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.loading = False
        self.nid = None
        self.iid_note = {}
        self.chap_labels = {}            # label -> chapter id

        left = tk.Frame(self, bg=T["bg"])
        left.pack(side="left", fill="both", expand=True, padx=(10, 5),
                  pady=10)
        bar = tk.Frame(left, bg=T["bg"])
        bar.pack(fill="x", pady=(0, 6))
        self.v_kind = tk.StringVar(value="All kinds")
        self.v_stat = tk.StringVar(value="All")
        self.v_search = tk.StringVar()
        mkoption(bar, self.v_kind, ["All kinds"] + NOTE_KINDS,
                 lambda v: self.refresh(), 11).pack(side="left")
        mkoption(bar, self.v_stat, ["All"] + NOTE_STATUS,
                 lambda v: self.refresh(), 7).pack(side="left", padx=4)
        e = mkentry(bar, self.v_search, 18)
        e.pack(side="left", padx=4)
        self.v_search.trace_add("write", lambda *a: self.refresh())
        mkbtn(bar, "Delete", self.delete, 8).pack(side="right")
        mkbtn(bar, "Add", self.add, 8).pack(side="right", padx=4)
        mkbtn(bar, "Pop out", self.pop_out, 8).pack(side="right")

        fr, self.tv = mktree(left, ("kind", "status", "title", "chapter"),
                             (80, 60, 260, 160),
                             ("Kind", "Status", "Title", "Chapter"))
        fr.pack(fill="both", expand=True)
        self.tv.tag_configure("done", foreground=T["dim"])
        self.tv.bind("<<TreeviewSelect>>", self._selected)
        self.tv.bind("<Double-1>", lambda e: self.pop_out())
        self.lbl_sum = mklabel(left, "", dim=True)
        self.lbl_sum.pack(fill="x", pady=(6, 0))

        right = tk.Frame(self, bg=T["panel"], width=440)
        right.pack(side="right", fill="y", padx=(5, 10), pady=10)
        right.pack_propagate(False)
        self.f_title = tk.StringVar()
        self.f_kind = tk.StringVar(value=NOTE_KINDS[0])
        self.f_stat = tk.StringVar(value=NOTE_STATUS[0])
        self.f_chap = tk.StringVar(value="-")
        mklabel(right, "Title", bg=T["panel"], dim=True).pack(
            anchor="w", padx=12, pady=(10, 0))
        mkentry(right, self.f_title, 44).pack(padx=12, fill="x")
        self.f_title.trace_add("write", lambda *a: self._changed())
        row = tk.Frame(right, bg=T["panel"])
        row.pack(fill="x", padx=12, pady=(10, 0))
        mkoption(row, self.f_kind, NOTE_KINDS, lambda v: self._changed(),
                 10).pack(side="left")
        mkoption(row, self.f_stat, NOTE_STATUS, lambda v: self._changed(),
                 7).pack(side="left", padx=6)
        self.om_chap = mkoption(row, self.f_chap, ["-"],
                                lambda v: self._changed(), 22)
        self.om_chap.pack(side="left")
        mklabel(right, "Text (use placeholders like Kollega 1 here too)",
                bg=T["panel"], dim=True).pack(anchor="w", padx=12,
                                              pady=(10, 0))
        fr2, self.txt = mktext(right, height=14, width=40)
        fr2.pack(fill="both", expand=True, padx=12, pady=(0, 6))
        self.txt.bind("<<Modified>>", self._text_modified)
        self.lbl_made = mklabel(right, "", bg=T["panel"], dim=True)
        self.lbl_made.pack(anchor="w", padx=12, pady=(0, 10))

    def refresh(self):
        b = self.app.book
        self.loading = True
        self.chap_labels = {"-": 0}
        for ch in b.chapters():
            self.chap_labels[b.chapter_label(ch["id"])] = ch["id"]
        reset_option(self.om_chap, self.f_chap, list(self.chap_labels),
                     lambda v: self._changed())
        self.tv.delete(*self.tv.get_children())
        self.iid_note.clear()
        q = self.v_search.get().strip().casefold()
        n_open = 0
        for n in b.d["notes"]:
            if n["status"] == "Open":
                n_open += 1
            if self.v_kind.get() not in ("All kinds", n["kind"]):
                continue
            if self.v_stat.get() not in ("All", n["status"]):
                continue
            if q and q not in (n["title"] + " " + n["text"]).casefold():
                continue
            iid = self.tv.insert(
                "", "end", values=(n["kind"], n["status"], n["title"],
                                   b.chapter_label(n.get("chapter")) or "-"),
                tags=(("done",) if n["status"] == "Done" else ()))
            self.iid_note[iid] = n["id"]
        self.lbl_sum.configure(text="%d notes - %d open" % (
            len(b.d["notes"]), n_open))
        self.loading = False
        self.select(self.nid)

    def note(self, nid=None):
        nid = nid or self.nid
        for n in self.app.book.d["notes"]:
            if n["id"] == nid:
                return n
        return None

    def select(self, nid):
        for iid, i in self.iid_note.items():
            if i == nid:
                self.loading = True
                self.tv.selection_set(iid)
                self.tv.see(iid)
                self.loading = False
                break
        self._load(self.note(nid))

    def _selected(self, e=None):
        if self.loading:
            return
        sel = self.tv.selection()
        nid = self.iid_note[sel[0]] if sel else None
        if nid != self.nid:
            self.nid = nid
            self._load(self.note())

    def _load(self, n):
        self.loading = True
        self.nid = n["id"] if n else None
        self.f_title.set(n["title"] if n else "")
        self.f_kind.set(n["kind"] if n else NOTE_KINDS[0])
        self.f_stat.set(n["status"] if n else NOTE_STATUS[0])
        label = (self.app.book.chapter_label(n.get("chapter")) if n else "")
        self.f_chap.set(label or "-")
        self.txt.delete("1.0", "end")
        if n:
            self.txt.insert("1.0", n["text"])
        self.txt.edit_modified(False)
        self.txt.edit_reset()
        self.lbl_made.configure(text=("Written " + n["created"]) if n else "")
        self.loading = False

    def _changed(self):
        if self.loading:
            return
        n = self.note()
        if not n:
            return
        n["title"] = self.f_title.get()
        n["kind"] = self.f_kind.get()
        n["status"] = self.f_stat.get()
        n["chapter"] = self.chap_labels.get(self.f_chap.get(), 0)
        self.app.touch()
        for iid, i in self.iid_note.items():
            if i == n["id"]:
                self.tv.item(iid, values=(
                    n["kind"], n["status"], n["title"],
                    self.app.book.chapter_label(n["chapter"]) or "-"),
                    tags=(("done",) if n["status"] == "Done" else ()))

    def _text_modified(self, e=None):
        if not self.txt.edit_modified():
            return
        self.txt.edit_modified(False)
        n = self.note()
        if n and not self.loading:
            n["text"] = self.txt.get("1.0", "end-1c")
            self.app.touch()

    def pop_out(self):
        """The selected note in its own window, to keep beside the plan."""
        if self.nid:
            self.app.open_note_popup(self.nid)

    def add(self):
        cid = self.app.cur_ch or 0
        n = self.app.book.add_note(chapter=cid, kind="Thread",
                                   title="New thread")
        self.nid = n["id"]
        self.refresh()

    def delete(self):
        n = self.note()
        if not n:
            return
        if messagebox.askyesno("Delete note", "Move \"%s\" to the trash?\n\n"
                               "It can be restored from Tools > Trash."
                               % n["title"], parent=self):
            self.app.book.trash("note", n, self.app.book.d["notes"])
            self.nid = None
            self.refresh()


# *************** DEL 33 - TAB: NAMES (PLACEHOLDERS -> REAL NAMES) *************

class NamesTab(tk.Frame):
    """Call a person "Kollega 1" while writing; give the real name here and
    every "Kollega 1" (also "Kollega 1s" and "Kollega 1:s") follows."""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.loading = False
        self.cid_sel = None
        self.ph_loaded = ""
        self.iid_char = {}

        left = tk.Frame(self, bg=T["bg"])
        left.pack(side="left", fill="both", expand=True, padx=(10, 5),
                  pady=10)
        bar = tk.Frame(left, bg=T["bg"])
        bar.pack(fill="x", pady=(0, 6))
        mkbtn(bar, "Add", self.add, 8).pack(side="left", padx=(0, 4))
        mkbtn(bar, "Add series...", self.add_series, 12).pack(side="left")
        mkbtn(bar, "Delete", self.delete, 8).pack(side="right")
        fr, self.tv = mktree(left, ("ph", "name", "uses"), (200, 200, 60),
                             ("Placeholder (in the text)", "Real name",
                              "Uses"))
        fr.pack(fill="both", expand=True)
        self.tv.tag_configure("open", foreground=T["dim"])
        self.tv.bind("<<TreeviewSelect>>", self._selected)
        self.lbl_sum = mklabel(
            left, "Write a person as e.g. \"Kollega 1\" in your chapters and "
                  "notes. Give the real name here - when you decide.",
            dim=True, wraplength=520, justify="left")
        self.lbl_sum.pack(fill="x", pady=(6, 0))

        right = tk.Frame(self, bg=T["panel"], width=440)
        right.pack(side="right", fill="y", padx=(5, 10), pady=10)
        right.pack_propagate(False)
        self.f_ph = tk.StringVar()
        self.f_name = tk.StringVar()
        self.f_gen = tk.StringVar()
        for lab, var in (("Placeholder - exactly as typed in the text",
                          self.f_ph),
                         ("Real name (empty = not decided yet)", self.f_name),
                         ("Genitive form - leave empty for automatic",
                          self.f_gen)):
            mklabel(right, lab, bg=T["panel"], dim=True).pack(
                anchor="w", padx=12, pady=(10, 0))
            ent = mkentry(right, var, 40)
            ent.pack(padx=12, fill="x")
            if var is self.f_ph:
                ent.bind("<FocusOut>", lambda e: self._ph_done())
            var.trace_add("write", lambda *a: self._changed())
        mklabel(right, "Notes about this person / place", bg=T["panel"],
                dim=True).pack(anchor="w", padx=12, pady=(10, 0))
        fr2, self.notes = mktext(right, height=7, width=40)
        fr2.pack(fill="x", padx=12)
        self.notes.bind("<<Modified>>", self._notes_modified)
        mklabel(right, "How it reads in the book", bg=T["panel"],
                dim=True).pack(anchor="w", padx=12, pady=(10, 0))
        self.lbl_prev = mklabel(right, "", bg=T["panel"], justify="left",
                                wraplength=400, height=6, anchor="nw")
        self.lbl_prev.configure(fg=T["accent"], font=FONT)
        self.lbl_prev.pack(fill="x", padx=12)
        mkbtn(right, "Use this name for good...", self.apply_permanently,
              24).pack(anchor="w", padx=12, pady=(4, 12))

    # ---- list ----------------------------------------------------------------------
    def _uses(self):
        b = self.app.book
        rx = b.rx()
        uses = Counter()
        if rx is not None:
            texts = [c["text"] + "\n" + c.get("synopsis", "")
                     for c in b.chapters()] + [n["text"] + " " + n["title"]
                                               for n in b.d["notes"]]
            for t in texts:
                for m in rx.finditer(t):
                    uses[m.group("ph")] += 1
        return uses

    def refresh(self):
        b = self.app.book
        self.loading = True
        self.tv.delete(*self.tv.get_children())
        self.iid_char.clear()
        uses = self._uses()
        for c in b.d["characters"]:
            ph = (c.get("placeholder") or "").strip()
            iid = self.tv.insert(
                "", "end", values=(ph or "(applied)", c.get("name", ""),
                                   uses.get(ph, 0) if ph else ""),
                tags=(() if (c.get("name") or "").strip() else ("open",)))
            self.iid_char[iid] = c["id"]
        self.loading = False
        if self.cid_sel is None and b.d["characters"]:
            self.cid_sel = b.d["characters"][0]["id"]
        self.select(self.cid_sel)

    def char(self, cid=None):
        cid = cid or self.cid_sel
        for c in self.app.book.d["characters"]:
            if c["id"] == cid:
                return c
        return None

    def select(self, cid):
        for iid, i in self.iid_char.items():
            if i == cid:
                self.loading = True
                self.tv.selection_set(iid)
                self.loading = False
                break
        self._load(self.char(cid))

    def _selected(self, e=None):
        if self.loading:
            return
        sel = self.tv.selection()
        cid = self.iid_char[sel[0]] if sel else None
        if cid != self.cid_sel:
            self._ph_done()          # leaving a row: settle a renamed placeholder
            self.cid_sel = cid
            self._load(self.char())

    def _load(self, c):
        self.loading = True
        self.cid_sel = c["id"] if c else None
        self.f_ph.set(c.get("placeholder", "") if c else "")
        self.ph_loaded = (c.get("placeholder") or "").strip() if c else ""
        self.f_name.set(c.get("name", "") if c else "")
        self.f_gen.set(c.get("genitive", "") if c else "")
        self.notes.delete("1.0", "end")
        if c:
            self.notes.insert("1.0", c.get("notes", ""))
        self.notes.edit_modified(False)
        self.loading = False
        self._preview()

    def _preview(self):
        c = self.char()
        if not c or not (c.get("placeholder") or "").strip():
            self.lbl_prev.configure(text="")
            return
        ph = c["placeholder"].strip()
        samples = ["%s gick hem." % ph, "%ss racerbil" % ph,
                   "%s:s racerbil" % ph, "Det var %s som ringde." % ph]
        lines = []
        for s in samples:
            lines.append("%s   ->   %s" % (
                s, substitute(s, [c], only=c)))
        if not (c.get("name") or "").strip():
            lines.append("(no real name yet - the placeholder stays as it is)")
        self.lbl_prev.configure(text="\n".join(lines))

    def _changed(self):
        if self.loading:
            return
        c = self.char()
        if not c:
            return
        new = self.f_ph.get().strip()
        c["placeholder"] = new
        c["name"] = self.f_name.get().strip()
        c["genitive"] = self.f_gen.get().strip()
        self.app.touch()
        for iid, i in self.iid_char.items():
            if i == c["id"]:
                self.tv.item(iid, values=(new or "(applied)", c["name"],
                                          self.tv.set(iid, "uses")),
                             tags=(() if c["name"] else ("open",)))
        self._preview()
        self._check_duplicate(c)

    def _ph_done(self):
        """The placeholder was edited: offer to rename it in the texts too."""
        c = self.char()
        old, new = self.ph_loaded, (self.f_ph.get().strip() if c else "")
        if not c or not old or old == new:
            return
        self.ph_loaded = new
        b = self.app.book
        pat = re.compile(r"(?<!\w)%s(?!\w)" % re.escape(old))
        n_old = (sum(len(pat.findall(ch["text"] + " " + ch.get("synopsis", "")))
                     for ch in b.chapters()) +
                 sum(len(pat.findall(n["text"] + " " + n["title"]))
                     for n in b.d["notes"]))
        if not n_old or not new:
            return
        if messagebox.askyesno(
                "Rename in the text",
                "\"%s\" is used in your text. Change it to \"%s\" there "
                "too?" % (old, new), parent=self):
            for ch in b.chapters():
                ch["text"] = rename_placeholder(ch["text"], old, new)
                ch["synopsis"] = rename_placeholder(ch.get("synopsis", ""),
                                                    old, new)
            for n in b.d["notes"]:
                n["text"] = rename_placeholder(n["text"], old, new)
                n["title"] = rename_placeholder(n["title"], old, new)
            b.touch()
            self.refresh()

    def _check_duplicate(self, c):
        ph = (c.get("placeholder") or "").strip()
        dup = [o for o in self.app.book.d["characters"]
               if o is not c and (o.get("placeholder") or "").strip() == ph
               and ph]
        if dup:
            self.lbl_sum.configure(
                text="Warning: another entry uses the placeholder \"%s\"." %
                     ph, fg=T["warn"])
        else:
            self.lbl_sum.configure(text="", fg=T["dim"])

    def _notes_modified(self, e=None):
        if not self.notes.edit_modified():
            return
        self.notes.edit_modified(False)
        c = self.char()
        if c and not self.loading:
            c["notes"] = self.notes.get("1.0", "end-1c")
            self.app.touch()

    # ---- buttons -------------------------------------------------------------------------
    def add(self):
        c = self.app.book.add_character(placeholder="Person %d" % (
            len(self.app.book.d["characters"]) + 1))
        self.cid_sel = c["id"]
        self.refresh()

    def add_series(self):
        s = ask_text(self, "Add a series",
                     "Make several placeholders at once.\nType the word and "
                     "how many, e.g.  Kollega 5  (gives Kollega 1 ... "
                     "Kollega 5).", "Kollega 5")
        if not s:
            return
        m = re.match(r"^\s*(.+?)\s+(\d{1,3})\s*$", s)
        if not m:
            messagebox.showinfo("Add a series", "Type a word, a blank and a "
                                "number - for example: Kollega 5", parent=self)
            return
        have = {(c.get("placeholder") or "").strip()
                for c in self.app.book.d["characters"]}
        for i in range(1, int(m.group(2)) + 1):
            ph = "%s %d" % (m.group(1), i)
            if ph not in have:
                self.app.book.add_character(placeholder=ph)
        self.refresh()

    def delete(self):
        c = self.char()
        if not c:
            return
        if messagebox.askyesno(
                "Delete", "Move \"%s\" to the trash?\n\nText that uses the "
                "placeholder is NOT changed." % (c.get("placeholder")
                                                or c.get("name")),
                parent=self):
            self.app.book.trash("character", c, self.app.book.d["characters"])
            self.cid_sel = None
            self.refresh()

    def apply_permanently(self):
        """Write the name INTO the text for good (the placeholder is gone)."""
        c = self.char()
        b = self.app.book
        if not c or not (c.get("placeholder") or "").strip() \
                or not (c.get("name") or "").strip():
            messagebox.showinfo(
                "Use this name for good",
                "Give both a placeholder and a real name first.", parent=self)
            return
        if not messagebox.askyesno(
                "Use this name for good",
                "Replace every \"%s\" (also %ss and %s:s) by \"%s\" in ALL "
                "chapters, plans and notes?\n\nA snapshot of the book is "
                "saved first, so you can go back via Tools > Snapshots.\n\n"
                "You do NOT need this to export with names - the export "
                "puts the names in anyway. This is only for when the "
                "placeholder should disappear from the text."
                % (c["placeholder"], c["placeholder"], c["placeholder"],
                   c["name"]), parent=self):
            return
        self.app.snapshot("before-names", important=True, force=True)
        chars = b.d["characters"]
        for ch in b.chapters():
            for k in ("text", "synopsis"):
                ch[k] = substitute(ch.get(k, ""), chars, only=c)
        for n in b.d["notes"]:
            for k in ("text", "title"):
                n[k] = substitute(n.get(k, ""), chars, only=c)
        c["placeholder"] = ""
        b.touch()
        self.refresh()

# *************** DEL 34 - TAB: WORDS (WATCH, COUNT, SEARCH, ECHOES) ***********

class WordsTab(tk.Frame):
    """Which words are used too often?  How often does X occur, and where?"""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.loading = False
        self.rows = []
        self.sort_col, self.sort_rev = "count", True
        self.hits = []
        self.hit_filter = None
        self.scope_labels = ["Whole book", "This chapter"]
        self.v_scope = tk.StringVar(value=self.scope_labels[0])

        pw = tk.PanedWindow(self, orient="horizontal", bg=T["bg"],
                            sashwidth=6, bd=0, sashrelief="flat")
        pw.pack(fill="both", expand=True, padx=10, pady=10)

        # ---- left: the settings and the watch list
        lf = tk.Frame(pw, bg=T["panel"], width=330)
        lf.pack_propagate(False)
        pw.add(lf, minsize=300, width=330)
        mklabel(lf, "Look at", bg=T["panel"], dim=True).pack(
            anchor="w", padx=12, pady=(10, 0))
        mkoption(lf, self.v_scope, self.scope_labels,
                 lambda v: self.refresh(), 14).pack(anchor="w", padx=12)
        self.v_names = tk.BooleanVar(value=True)
        self.v_common = tk.BooleanVar(value=True)
        self.v_only = tk.BooleanVar(value=False)
        for text, var in (("Count the real names (not the placeholders)",
                           self.v_names),
                          ("Hide common words (och, att, det ...)",
                           self.v_common),
                          ("Show only words that are flagged", self.v_only)):
            c = mkcheck(lf, text, var, self._settings_changed)
            c.configure(bg=T["panel"], activebackground=T["panel"])
            c.pack(anchor="w", padx=12, pady=(4, 0))

        self.sv = {}
        grid = tk.Frame(lf, bg=T["panel"])
        grid.pack(fill="x", padx=12, pady=(10, 0))
        specs = (("min_len", "Flag only words of at least (letters)"),
                 ("min_count", "... and used at least (times)"),
                 ("per1000", "... and at least (times per 1000 words)"),
                 ("echo_dist", "Echo: same word within (words)"),
                 ("echo_min_len", "Echo: words of at least (letters)"))
        for r, (key, lab) in enumerate(specs):
            mklabel(grid, lab, bg=T["panel"], width=36).grid(
                row=r, column=0, sticky="w", pady=2)
            v = tk.StringVar()
            self.sv[key] = v
            e = mkentry(grid, v, 6)
            e.grid(row=r, column=1, padx=(6, 0), pady=2)
            e.bind("<Return>", lambda ev: self._settings_changed())
            e.bind("<FocusOut>", lambda ev: self._settings_changed())
        mklabel(lf, "Never flag these words (separate with commas)",
                bg=T["panel"], dim=True).pack(anchor="w", padx=12,
                                              pady=(10, 0))
        self.v_ignore = tk.StringVar()
        e = mkentry(lf, self.v_ignore, 36)
        e.pack(padx=12, fill="x")
        e.bind("<Return>", lambda ev: self._settings_changed())
        e.bind("<FocusOut>", lambda ev: self._settings_changed())

        mklabel(lf, "Watch list - words I know I overuse", bg=T["panel"],
                dim=True).pack(anchor="w", padx=12, pady=(12, 0))
        fr, self.wtv = mktree(lf, ("word", "limit", "unit", "now"),
                              (80, 40, 95, 90),
                              ("Word", "Max", "Per", "Now"), height=6)
        fr.pack(fill="both", expand=True, padx=12, pady=(0, 4))
        self.wtv.tag_configure("over", foreground=T["warn"])
        add = tk.Frame(lf, bg=T["panel"])
        add.pack(fill="x", padx=12, pady=(0, 12))
        self.w_word = tk.StringVar()
        self.w_limit = tk.StringVar(value="3")
        self.w_unit = tk.StringVar(value=WATCH_UNITS[0])
        mkentry(add, self.w_word, 10).pack(side="left")
        mkentry(add, self.w_limit, 4).pack(side="left", padx=4)
        mkoption(add, self.w_unit, WATCH_UNITS, None, 11).pack(side="left")
        mkbtn(add, "Add", self.watch_add, 5).pack(side="left", padx=4)
        mkbtn(add, "Remove", self.watch_remove, 7).pack(side="left")

        # ---- middle: the frequency table
        mf = tk.Frame(pw, bg=T["bg"])
        pw.add(mf, minsize=360)
        bar = tk.Frame(mf, bg=T["bg"])
        bar.pack(fill="x", pady=(0, 6))
        mklabel(bar, "Word list - click a word to find it", dim=True).pack(
            side="left")
        mkbtn(bar, "Refresh", self.refresh, 8).pack(side="right")
        self.v_filter = tk.StringVar()
        mkentry(bar, self.v_filter, 14).pack(side="right", padx=6)
        mklabel(bar, "Filter:", dim=True).pack(side="right")
        self.v_filter.trace_add("write", lambda *a: self._fill_table())
        fr, self.tv = mktree(mf, ("word", "count", "per", "chs", "flag"),
                             (170, 60, 70, 80, 90),
                             ("Word", "Times", "Per 1000", "In chapters",
                              "Flag"))
        fr.pack(fill="both", expand=True)
        for c in ("count", "per", "chs"):
            self.tv.column(c, anchor="e", stretch=False)
        self.tv.column("flag", stretch=False)
        for c in ("word", "count", "per", "chs", "flag"):
            self.tv.heading(c, command=lambda c=c: self._sort(c))
        self.tv.tag_configure("often", foreground="#f9c97c")
        self.tv.tag_configure("watch", foreground=T["warn"])
        self.tv.bind("<<TreeviewSelect>>", self._row_selected)
        self.lbl_tot = mklabel(mf, "", dim=True)
        self.lbl_tot.pack(fill="x", pady=(6, 0))

        # ---- right: search
        rf = tk.Frame(pw, bg=T["bg"], width=470)
        pw.add(rf, minsize=380, width=470)
        mklabel(rf, "How often does it occur, and where?", dim=True).pack(
            anchor="w")
        srow = tk.Frame(rf, bg=T["bg"])
        srow.pack(fill="x", pady=(4, 2))
        self.v_q = tk.StringVar()
        e = mkentry(srow, self.v_q, 24)
        e.pack(side="left", fill="x", expand=True)
        e.bind("<Return>", lambda ev: self.search())
        mkbtn(srow, "Search", self.search, 8).pack(side="left", padx=(6, 0))
        orow = tk.Frame(rf, bg=T["bg"])
        orow.pack(fill="x")
        self.v_whole = tk.BooleanVar(value=True)
        self.v_case = tk.BooleanVar(value=False)
        mkcheck(orow, "Whole word", self.v_whole).pack(side="left")
        mkcheck(orow, "Match case", self.v_case).pack(side="left", padx=8)
        mklabel(rf, "Tip: kall*  finds kall, kalla, kallt ... ", dim=True
                ).pack(anchor="w")
        self.lbl_res = mklabel(rf, "", wraplength=440, justify="left",
                               height=2, anchor="nw")
        self.lbl_res.configure(fg=T["accent"], font=FONT)
        self.lbl_res.pack(fill="x", pady=(6, 4))
        fr2, self.ctv = mktree(rf, ("chapter", "n"), (300, 60),
                               ("Chapter", "Times"), height=5)
        self.ctv.column("n", anchor="e", stretch=False)
        fr2.pack(fill="x")
        self.ctv.bind("<<TreeviewSelect>>", self._chap_selected)
        hrow = tk.Frame(rf, bg=T["bg"])
        hrow.pack(fill="x", pady=(8, 2))
        mklabel(hrow, "Hits - double-click to open in the text",
                dim=True).pack(side="left")
        mkbtn(hrow, "Show echoes", self.show_echoes, 11).pack(side="right")
        fr3, self.htv = mktree(rf, ("ch", "snip"), (110, 330),
                               ("Chapter", "Context"), height=10)
        fr3.pack(fill="both", expand=True)
        self.htv.bind("<Double-1>", self._hit_open)
        self.iid_chap, self.iid_hit = {}, {}

    # ---- settings -----------------------------------------------------------------------
    def _load_settings(self):
        c = self.app.book.cfg
        self.loading = True
        self.v_names.set(bool(c.get("use_names", True)))
        self.v_common.set(bool(c.get("hide_common", True)))
        for k, v in self.sv.items():
            v.set(str(c.get(k, "")))
        self.v_ignore.set(", ".join(c.get("ignore", [])))
        self.loading = False

    def _settings_changed(self):
        if self.loading:
            return
        c = self.app.book.cfg
        before = json.dumps(c, sort_keys=True)
        c["use_names"] = bool(self.v_names.get())
        c["hide_common"] = bool(self.v_common.get())
        for k, v in self.sv.items():
            try:
                c[k] = float(v.get().replace(",", ".")) if k == "per1000" \
                    else max(0, int(v.get()))
            except ValueError:
                pass
        c["ignore"] = [w.strip() for w in self.v_ignore.get().split(",")
                       if w.strip()]
        if json.dumps(c, sort_keys=True) == before:
            self._fill_table()                  # only the table filter changed
            return
        self.app.touch()
        self.refresh()

    def chapters_in_scope(self):
        b = self.app.book
        if self.v_scope.get() == self.scope_labels[1]:
            ch = b.chapter(self.app.cur_ch)
            return [ch] if ch else []
        return b.chapters()

    # ---- the table -------------------------------------------------------------------------
    def refresh(self):
        b = self.app.book
        self._load_settings()
        scope = self.chapters_in_scope()
        use_names = bool(b.cfg.get("use_names", True))
        t = b.tally(scope, use_names)
        self.tally = t
        stop, ign = b.stop(), b.ignore()
        wev = b.watch_eval(t["per"])
        watch_words = set()
        for r in wev:
            if r["over"]:
                watch_words.update(w for w in t["total"] if r["rx"].fullmatch(w))
        self.rows = []
        for w, c in t["total"].items():
            if w in stop:
                continue
            per = c * 1000.0 / t["n"] if t["n"] else 0.0
            flag = ("WATCH" if w in watch_words else
                    "often" if b.is_often(w, c, t["n"], stop, ign) else "")
            self.rows.append(dict(word=w, count=c, per=per,
                                  chs=len(t["inch"][w]), flag=flag))
        self.n_words = t["n"]
        self.lbl_tot.configure(text="%s words in %d chapter%s - %d different "
                               "words" % ("{:,}".format(t["n"]), len(scope),
                                          "" if len(scope) == 1 else "s",
                                          len(t["total"])))
        self._fill_table()
        # watch list with current numbers
        self.wtv.delete(*self.wtv.get_children())
        for i, r in enumerate(wev):
            e = r["entry"]
            n_over = len(r["over"])
            now = ("OVER in %d" % n_over) if n_over else "%d" % r["count"]
            self.wtv.insert("", "end", iid=str(i), values=(
                e["word"], e["limit"], e["unit"], now),
                tags=(("over",) if n_over else ()))

    def _sort(self, col):
        if self.sort_col == col:
            self.sort_rev = not self.sort_rev
        else:
            self.sort_col, self.sort_rev = col, col != "word"
        self._fill_table()

    def _fill_table(self):
        self.tv.delete(*self.tv.get_children())
        q = self.v_filter.get().strip().casefold()
        rows = [r for r in self.rows
                if (not q or q in r["word"])
                and (not self.v_only.get() or r["flag"])]
        key = self.sort_col
        rows.sort(key=lambda r: (r[key] if key != "flag"
                                 else (r["flag"] != "WATCH",
                                       r["flag"] != "often")),
                  reverse=self.sort_rev and key != "flag")
        for r in rows[:600]:
            self.tv.insert("", "end", values=(
                r["word"], r["count"], "%.1f" % r["per"], r["chs"],
                r["flag"]),
                tags=((r["flag"].lower(),) if r["flag"] else ()))

    def _row_selected(self, e=None):
        sel = self.tv.selection()
        if sel:
            self.v_q.set(self.tv.set(sel[0], "word"))
            self.v_whole.set(True)
            self.search()

    # ---- the watch list ----------------------------------------------------------------------
    def watch_add(self):
        w = self.w_word.get().strip()
        try:
            lim = float(self.w_limit.get().replace(",", "."))
        except ValueError:
            return
        if not w:
            return
        lim = int(lim) if lim == int(lim) else lim
        self.app.book.d["watch"].append(
            dict(word=w, limit=lim, unit=self.w_unit.get()))
        self.app.touch()
        self.w_word.set("")
        self.refresh()

    def watch_remove(self):
        sel = self.wtv.selection()
        if sel:
            del self.app.book.d["watch"][int(sel[0])]
            self.app.touch()
            self.refresh()

    # ---- search ---------------------------------------------------------------------------------
    def search(self):
        b = self.app.book
        rx = wild_rx(self.v_q.get(), self.v_whole.get(), self.v_case.get())
        if rx is None:
            self.lbl_res.configure(text="")
            return
        scope = self.chapters_in_scope()
        use_names = bool(b.cfg.get("use_names", True))
        self.hits = b.find_hits(rx, scope, use_names)
        per = Counter(h["cid"] for h in self.hits)
        words = sum(b.count(c["text"]) for c in scope) or 1
        n = len(self.hits)
        self.lbl_res.configure(
            text="\"%s\": %d time%s in %d of %d chapter%s  -  %.1f per 1000 "
                 "words%s" % (self.v_q.get().strip(), n, "" if n == 1 else "s",
                              len(per), len(scope),
                              "" if len(scope) == 1 else "s",
                              n * 1000.0 / words,
                              "  (list cut at 5000)" if n >= 5000 else ""))
        self.ctv.delete(*self.ctv.get_children())
        self.iid_chap.clear()
        for ch in scope:
            if per.get(ch["id"]):
                iid = self.ctv.insert("", "end", values=(
                    b.chapter_label(ch["id"]), per[ch["id"]]))
                self.iid_chap[iid] = ch["id"]
        self.hit_filter = None
        self._fill_hits()

    def _chap_selected(self, e=None):
        sel = self.ctv.selection()
        self.hit_filter = self.iid_chap.get(sel[0]) if sel else None
        self._fill_hits()

    def _fill_hits(self):
        b = self.app.book
        self.htv.delete(*self.htv.get_children())
        self.iid_hit.clear()
        for h in self.hits:
            if self.hit_filter and h["cid"] != self.hit_filter:
                continue
            lab = b.chapter_label(h["cid"])
            iid = self.htv.insert("", "end", values=(lab[:22], h["snip"]))
            self.iid_hit[iid] = h
            if len(self.iid_hit) >= 800:
                break

    def _hit_open(self, e=None):
        sel = self.htv.selection()
        if sel:
            h = self.iid_hit[sel[0]]
            self.app.show_tab("Write")
            self.app.write.jump(h["cid"], h["pos"], h["length"])

    def show_echoes(self):
        """List every echo (same word twice within a few words)."""
        b = self.app.book
        stop, ign = b.stop(), b.ignore()
        hits = []
        for ch in self.chapters_in_scope():
            text = ch["text"]
            toks = b.chapter_tokens(ch, False)
            marks = b.echo_ranges(toks, stop, ign)
            # a pair is marked as two consecutive ranges; show the second one
            seen = set()
            for s, e in marks:
                if s in seen:
                    continue
                seen.add(s)
                a, z = max(0, s - 35), min(len(text), e + 35)
                snip = re.sub(r"\s+", " ", text[a:s] + "[" + text[s:e] + "]"
                              + text[e:z])
                hits.append(dict(cid=ch["id"], pos=s, snip=snip,
                                 length=e - s))
        self.hits = hits
        self.hit_filter = None
        self.ctv.delete(*self.ctv.get_children())
        self.iid_chap.clear()
        self.lbl_res.configure(
            text="%d echo marks (the same word within %d words)" % (
                len(hits), int(b.cfg["echo_dist"])))
        self._fill_hits()

# *************** DEL 35 - NOTE POPUP (A NOTE BESIDE THE MAIN WINDOW) **********

class NotePopup(object):
    """A note in its own movable window that stays open beside the main window
    while you work (e.g. writing chapter plans).  NOT modal: nothing grabs
    input.  Several can be open at once, one per note.  Edits go straight into
    the book; the position is remembered per note.  Escape closes it."""

    def __init__(self, app, nid):
        self.app = app
        self.nid = nid
        self.loading = False
        self.hl_job = self.menu_job = None
        self.labels = {}
        top = self.top = tk.Toplevel(app.root)
        top.configure(bg=T["bg"])
        top.transient(app.root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<FocusIn>", self._focus_in)
        top.minsize(300, 220)

        bar = tk.Frame(top, bg=T["panel"])
        bar.pack(fill="x")
        self.v_pick = tk.StringVar()
        self.om = mkoption(bar, self.v_pick, ["-"], self._picked, 30)
        self.om.pack(side="left", padx=6, pady=4)
        mkbtn(bar, "New", self._new, 6).pack(side="left")
        self.v_done = tk.BooleanVar()
        c = mkcheck(bar, "Done", self.v_done, self._done_changed)
        c.configure(bg=T["panel"], activebackground=T["panel"])
        c.pack(side="left", padx=8)
        mkbtn(bar, "Close", self.close, 7).pack(side="right", padx=6)

        self.v_title = tk.StringVar()
        e = mkentry(top, self.v_title, 40)
        e.pack(fill="x", padx=8, pady=(8, 4))
        self.v_title.trace_add("write", lambda *a: self._title_changed())
        self.font = tkfont.Font(family="Segoe UI",
                                size=int(app.S.get("note_popup_size", 11)))
        fr, self.txt = mktext(top, height=14, width=44, font=self.font)
        fr.pack(fill="both", expand=True, padx=8, pady=(0, 4))
        self.txt.tag_configure("ph", foreground=T["accent"])
        self.txt.bind("<<Modified>>", self._modified)
        self.txt.bind("<Control-MouseWheel>", self._zoom)
        self.lbl = mklabel(top, "", dim=True)
        self.lbl.pack(fill="x", padx=8, pady=(0, 6))
        top.bind("<Configure>", self._configured)
        self.move_job = None

        self._rebuild_menu()
        self._load()
        self._place()
        self.txt.focus_set()

    # ---- the note --------------------------------------------------------------------
    def note(self):
        for n in self.app.book.d["notes"]:
            if n["id"] == self.nid:
                return n
        return None

    def _rebuild_menu(self):
        b = self.app.book
        self.labels = {}
        for n in b.d["notes"]:
            lab = "[%s] %s" % (n["kind"], n["title"] or "(no title)")
            while lab in self.labels:
                lab += " "
            self.labels[lab] = n["id"]
        reset_option(self.om, self.v_pick, list(self.labels) or ["-"],
                     self._picked)

    def _label_of(self, nid):
        for lab, i in self.labels.items():
            if i == nid:
                return lab
        return "-"

    def _load(self):
        n = self.note()
        self.loading = True
        self.v_pick.set(self._label_of(self.nid))
        self.v_title.set(n["title"] if n else "")
        self.v_done.set(bool(n and n["status"] == "Done"))
        self.txt.delete("1.0", "end")
        if n:
            self.txt.insert("1.0", n["text"])
            chap = self.app.book.chapter_label(n.get("chapter"))
            self.lbl.configure(text=("Belongs to: " + chap) if chap
                               else "Not tied to a chapter")
        else:
            self.lbl.configure(text="This note no longer exists")
        self.txt.edit_modified(False)
        self.txt.edit_reset()
        self.loading = False
        self.top.title("Note - " + (n["title"] if n else "?"))
        self._highlight()

    def _picked(self, label):
        nid = self.labels.get(label)
        other = self.app.note_popups.get(nid)
        if other is not None and other is not self:
            self.v_pick.set(self._label_of(self.nid))
            other.top.lift()                      # that note is open already
            return
        if nid and nid != self.nid:
            self.app.note_popups.pop(self.nid, None)
            self.app.note_popups[nid] = self
            self.nid = nid
            self._load()

    def _new(self):
        n = self.app.book.add_note(chapter=self.app.cur_ch or 0,
                                   kind="Note", title="New note")
        self._rebuild_menu()
        self._picked(self._label_of(n["id"]))
        self.app.touch()

    def refresh(self):
        """The book changed (restore, another tab edited): show it again."""
        self._rebuild_menu()
        self._load()

    # ---- editing ------------------------------------------------------------------------
    def _modified(self, e=None):
        if not self.txt.edit_modified():
            return
        self.txt.edit_modified(False)
        n = self.note()
        if self.loading or not n:
            return
        n["text"] = self.txt.get("1.0", "end-1c")
        self.app.touch()
        if self.hl_job:
            self.top.after_cancel(self.hl_job)
        self.hl_job = self.top.after(700, self._highlight)

    def _title_changed(self):
        n = self.note()
        if self.loading or not n:
            return
        n["title"] = self.v_title.get()
        self.top.title("Note - " + n["title"])
        self.app.touch()
        if self.menu_job:
            self.top.after_cancel(self.menu_job)
        self.menu_job = self.top.after(900, self._menu_again)

    def _menu_again(self):
        self.menu_job = None
        self.loading = True
        self._rebuild_menu()
        self.v_pick.set(self._label_of(self.nid))
        self.loading = False

    def _done_changed(self):
        n = self.note()
        if n and not self.loading:
            n["status"] = "Done" if self.v_done.get() else "Open"
            self.app.touch()

    def _highlight(self):
        self.hl_job = None
        self.txt.tag_remove("ph", "1.0", "end")
        rx = self.app.book.rx()
        text = self.txt.get("1.0", "end-1c")
        if rx is None or not text:
            return
        idx = PosIndex(text)
        for m in rx.finditer(text):
            self.txt.tag_add("ph", idx(m.start()), idx(m.end()))

    def _zoom(self, e):
        size = max(8, min(28, int(self.font.cget("size")
                                  ) + (1 if e.delta > 0 else -1)))
        self.font.configure(size=size)
        self.app.S["note_popup_size"] = size
        return "break"

    def _focus_in(self, e=None):
        """Another tab may have changed this note meanwhile: pick it up."""
        if e is not None and e.widget is not self.top:
            return
        n = self.note()
        if n is None:
            self.lbl.configure(text="This note no longer exists")
            return
        if (n["text"] != self.txt.get("1.0", "end-1c")
                or n["title"] != self.v_title.get()):
            self._load()

    # ---- position -----------------------------------------------------------------------------
    def _key(self):
        return "%s|%s" % (os.path.basename(self.app.book.folder), self.nid)

    def _place(self):
        top, root = self.top, self.app.root
        pos = self.app.S.get("note_popup_geo", {}).get(self._key())
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        if isinstance(pos, str) and re.match(
                r"^\d+x\d+[+-]-?\d+[+-]-?\d+$", pos):
            m = re.match(r"(\d+)x(\d+)[+-](-?\d+)[+-](-?\d+)", pos)
            w, h, x, y = (int(v) for v in m.groups())
            if -w + 60 < x < sw - 60 and 0 <= y < sh - 60:
                top.geometry(pos)
                return
        root.update_idletasks()
        w, h = 420, 460
        x = root.winfo_x() + root.winfo_width() + 8     # beside the program
        if x + w > sw:                    # no room: hug the right screen edge
            x = sw - w
        y = max(0, min(root.winfo_y() + 40, sh - h - 60))
        top.geometry("%dx%d+%d+%d" % (w, h, max(0, x), y))

    def _configured(self, e):
        if e.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(500, self._remember)

    def _remember(self):
        self.move_job = None
        try:
            self.app.S.setdefault("note_popup_geo", {})[self._key()] = \
                self.top.geometry()
            save_settings(self.app.S)
        except Exception:
            pass

    def close(self):
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
            self._remember()
        self.app.note_popups.pop(self.nid, None)
        try:
            self.top.destroy()
        except Exception:
            pass

# *************** DEL 36 - TAB: TIME (DOES THE STORY FLOW IN TIME?) ***********

class TimelineTab(tk.Frame):
    """Every chapter in book order: the time it takes place (set by the author
    or read from the text), how far that is from the previous chapter, what to
    check - and, under each chapter, the dates written in it."""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.rows = {}                  # tree item id -> ("ch", cid) | ("date", cid, (pos, length))
        self.opened = set()             # chapters that were opened

        bar = tk.Frame(self, bg=T["bg"])
        bar.pack(fill="x", padx=10, pady=(10, 6))
        mkbtn(bar, "Expand all", lambda: self._open_all(True), 11).pack(
            side="left", padx=(0, 4))
        mkbtn(bar, "Collapse all", lambda: self._open_all(False), 11).pack(
            side="left", padx=4)
        self.v_only = tk.BooleanVar(value=False)
        mkcheck(bar, "Only chapters with something to check", self.v_only,
                self.refresh).pack(side="left", padx=(12, 0))
        self.lbl_sum = mklabel(bar, "", width=70, anchor="e", dim=True)
        self.lbl_sum.pack(side="right")

        fr, self.tv = mktree(
            self, ("title", "set", "found", "flow", "check"),
            (300, 150, 210, 150, 260),
            ("Chapter  /  date written in it", "Set by you", "In the text",
             "From previous chapter", "Check"), show="tree headings")
        self.tv.column("#0", width=22, stretch=False)
        for c in ("set", "found", "flow"):
            self.tv.column(c, stretch=False)
        self.tv.column("title", stretch=False)
        self.tv.column("check", stretch=True)
        fr.pack(fill="both", expand=True, padx=10)
        self.tv.tag_configure("plan", foreground=T["dim"])
        self.tv.tag_configure("back", foreground=T["warn"])
        self.tv.tag_configure("out", foreground=T["warn"])
        self.tv.tag_configure("bk", foreground="#fab387")
        self.tv.tag_configure("noyear", foreground=T["dim"])
        self.tv.bind("<Double-1>", self._open_row)
        mklabel(self, "Red = a problem (the chapter jumps back in time, or a "
                "date lies outside the time you set).  Orange = a date earlier "
                "than the one before it.  Double-click = show it in the Write "
                "tab.", dim=True).pack(fill="x", padx=10, pady=(6, 8))

    def refresh(self):
        b = self.app.book
        an = b.date_analysis()
        for iid, row in self.rows.items():
            if row[0] != "ch":
                continue
            if str(self.tv.item(iid, "open")).lower() in ("1", "true"):
                self.opened.add(row[1])
            else:
                self.opened.discard(row[1])
        self.tv.delete(*self.tv.get_children())
        self.rows.clear()
        only = self.v_only.get()
        n_dated = n_back = n_check = 0
        for i, ch in enumerate(b.chapters()):
            info = an[ch["id"]]
            n_dated += 1 if info["eff"] else 0
            n_back += 1 if info["flow_kind"] == "back" else 0
            n_check += 1 if info["check"] else 0
            if only and not info["check"]:
                continue
            d = info["decl"]
            set_txt = ("" if not d else ("! " + d["err"]) if d["err"]
                       else d["label"])
            tag = ("back" if info["flow_kind"] == "back"
                   or (d and d["err"]) else
                   "plan" if not info["eff"] else "")
            iid = self.tv.insert(
                "", "end", open=ch["id"] in self.opened,
                values=("%d. %s" % (i + 1, ch["title"]), set_txt,
                        info["found"]["label"] if info["found"] else "",
                        "" if info["flow_kind"] == "start" else info["flow"],
                        "; ".join(info["check"])),
                tags=(tag,) if tag else ())
            self.rows[iid] = ("ch", ch["id"])
            for r in group_mentions(info["ments"]):
                m, n = r["m"], len(r["spans"])
                note = []
                if r["out"]:
                    note.append("outside the time you set")
                if r["back"]:
                    note.append("earlier than the date before it")
                if m["bad"]:
                    note.append("impossible date")
                if m["lo"] is None:
                    note.append("year unknown")
                dtag = ("out" if (r["out"] or m["bad"]) else
                        "bk" if r["back"] else
                        "noyear" if m["lo"] is None else "")
                civ = self.tv.insert(
                    iid, "end",
                    values=("%s%s" % (re.sub(r"\s+", " ", m["raw"]),
                                      "   x%d" % n if n > 1 else ""),
                            "", m["short"], "", "; ".join(note)),
                    tags=(dtag,) if dtag else ())
                self.rows[civ] = ("date", ch["id"], r["spans"][0])
        self.lbl_sum.configure(
            text="%d chapters  -  %d with a time  -  %d jump back in time  "
                 "-  %d to check" % (len(b.chapters()), n_dated, n_back,
                                     n_check))

    def _open_all(self, flag):
        for iid, row in self.rows.items():
            if row[0] == "ch":
                self.tv.item(iid, open=flag)

    def _open_row(self, e):
        iid = self.tv.identify_row(e.y)
        row = self.rows.get(iid)
        if not row:
            return
        self.app.select_chapter(row[1], source=self)
        self.app.show_tab("Write")
        if row[0] == "date":
            # the tab change is handled a moment later (and reloads the
            # chapter), so the date is selected after that
            self.after(80, lambda: self.app.write.jump(row[1], row[2][0],
                                                       row[2][1]))

    def flush(self):
        pass

# *************** DEL 37 - TAB: PLACES (WHERE DOES THE STORY HAPPEN?) *********

def places_dialog(app):
    """My places (the author's own names) and the words that are not places."""
    b = app.book
    top = open_dialog(app.root, "My places", resizable=False)
    mklabel(top, "My places - one per line (a town, a street, an invented "
            "place ...). They are found in the text like the built-in ones.",
            wraplength=420, justify="left").pack(padx=14, pady=(12, 2),
                                                 anchor="w")
    fr1, t1 = mktext(top, height=9, width=50)
    fr1.pack(padx=14, fill="x")
    t1.insert("1.0", "\n".join(b.d.get("places", [])))
    mklabel(top, "Not places - one per line (words that are listed as "
            "unconfirmed place names by mistake).", wraplength=420,
            justify="left").pack(padx=14, pady=(10, 2), anchor="w")
    fr2, t2 = mktext(top, height=5, width=50)
    fr2.pack(padx=14, fill="x")
    t2.insert("1.0", "\n".join(b.d.get("places_ignore", [])))

    def lines(t):
        return [x.strip() for x in t.get("1.0", "end-1c").splitlines()
                if x.strip()]

    def save():
        b.d["places"] = lines(t1)
        b.d["places_ignore"] = lines(t2)
        app.touch()
        top.destroy()
        app.refresh_current()
    row = tk.Frame(top, bg=T["bg"])
    row.pack(pady=(10, 12))
    mkbtn(row, "Save", save, 10).pack(side="left", padx=4)
    mkbtn(row, "Cancel", top.destroy, 10).pack(side="left", padx=4)
    finish_dialog(top, app.root)
    t1.focus_set()


class PlacesTab(tk.Frame):
    """Every chapter in book order: its main place (set by the author or the
    most named city), the places named in it, and where the story moves from
    chapter to chapter."""

    def __init__(self, app, parent):
        tk.Frame.__init__(self, parent, bg=T["bg"])
        self.app = app
        self.rows = {}                  # tree item id -> (chapter id, (pos, length)) or (chapter id, None)
        self.opened = set()

        bar = tk.Frame(self, bg=T["bg"])
        bar.pack(fill="x", padx=10, pady=(10, 6))
        mkbtn(bar, "Expand all", lambda: self._open_all(True), 11).pack(
            side="left", padx=(0, 4))
        mkbtn(bar, "Collapse all", lambda: self._open_all(False), 11).pack(
            side="left", padx=4)
        mkbtn(bar, "My places...", lambda: places_dialog(self.app), 12).pack(
            side="left", padx=(12, 0))
        self.lbl_sum = mklabel(bar, "", width=70, anchor="e", dim=True)
        self.lbl_sum.pack(side="right")

        fr, self.tv = mktree(
            self, ("title", "set", "main", "named", "flow", "check"),
            (260, 130, 140, 260, 130, 220),
            ("Chapter  /  place named in it", "Set by you", "Main place",
             "Places named", "From previous chapter", "Check"),
            show="tree headings")
        self.tv.column("#0", width=22, stretch=False)
        for c in ("title", "set", "main", "named", "flow"):
            self.tv.column(c, stretch=False)
        self.tv.column("check", stretch=True)
        fr.pack(fill="both", expand=True, padx=10)
        self.tv.tag_configure("plan", foreground=T["dim"])
        self.tv.tag_configure("move", foreground=T["accent"])
        self.tv.tag_configure("unk", foreground=T["dim"])
        self.tv.bind("<Double-1>", self._open_row)
        mklabel(self, "Blue = the story moves to another place.  (Name) = the "
                "main place was read from the text.  ? = a name after "
                "'in / to / från ...' that is not known as a place: add it in "
                "the Write tab (double-click) or under My places.  "
                "Double-click = show it in the Write tab.", dim=True,
                wraplength=1200, justify="left").pack(fill="x", padx=10,
                                                      pady=(6, 8))

    def refresh(self):
        b = self.app.book
        an = b.place_analysis()
        for iid, row in self.rows.items():
            if row[1] is not None:
                continue
            if str(self.tv.item(iid, "open")).lower() in ("1", "true"):
                self.opened.add(row[0])
            else:
                self.opened.discard(row[0])
        self.tv.delete(*self.tv.get_children())
        self.rows.clear()
        n_main = n_move = 0
        kinds = dict(country="  [country]", area="  [area]", place="  [mine]")
        for i, ch in enumerate(b.chapters()):
            info = an[ch["id"]]
            n_main += 1 if info["eff"] else 0
            n_move += 1 if info["flow_kind"] == "move" else 0
            named = [r for r in info["rows"] if r["known"]]
            named_txt = ", ".join(
                "%s%s" % (r["canon"],
                          " x%d" % len(r["spans"]) if len(r["spans"]) > 1
                          else "") for r in named[:5])
            if len(named) > 5:
                named_txt += ", ... (%d)" % len(named)
            tag = ("move" if info["flow_kind"] == "move" else
                   "plan" if not info["eff"] else "")
            iid = self.tv.insert(
                "", "end", open=ch["id"] in self.opened,
                values=("%d. %s" % (i + 1, ch["title"]), info["set"],
                        place_cell(info), named_txt,
                        "" if info["flow_kind"] in ("start", "") else
                        info["flow"], "; ".join(info["check"])),
                tags=(tag,) if tag else ())
            self.rows[iid] = (ch["id"], None)
            for r in info["rows"]:
                n = len(r["spans"])
                civ = self.tv.insert(
                    iid, "end",
                    values=("%s%s%s%s" % ("? " if not r["known"] else "",
                                          r["canon"], kinds.get(r["kind"], ""),
                                          "   x%d" % n if n > 1 else ""),
                            "", "", "", "",
                            "" if r["known"] else "not known as a place"),
                    tags=(() if r["known"] else ("unk",)))
                self.rows[civ] = (ch["id"], r["spans"][0])
        self.lbl_sum.configure(
            text="%d chapters  -  %d with a place  -  %d moves to another "
                 "place" % (len(b.chapters()), n_main, n_move))

    def _open_all(self, flag):
        for iid, row in self.rows.items():
            if row[1] is None:
                self.tv.item(iid, open=flag)

    def _open_row(self, e):
        row = self.rows.get(self.tv.identify_row(e.y))
        if not row:
            return
        self.app.select_chapter(row[0], source=self)
        self.app.show_tab("Write")
        if row[1] is not None:
            # the tab change is handled a moment later (and reloads the
            # chapter), so the place is selected after that
            self.after(80, lambda: self.app.write.jump(row[0], row[1][0],
                                                       row[1][1]))

    def flush(self):
        pass

# *************** DEL 38 - CHAPTER POPUP (READ A CHAPTER BESIDE THE MAIN WINDOW) ***

class ChapterPopup(object):
    """A chapter in its own movable window (drag it to a second screen) so it
    can be read while another chapter is written in the main window.
    READ-ONLY on purpose (you can select and copy): only one place edits a
    chapter, so nothing can get out of step.  NOT modal.  It follows the book
    by itself (checked every second): text written in the main window shows
    up here, a renamed chapter changes its name in the pick list.  Pick any
    chapter from the list; the position is remembered per book.  Escape
    closes it.
    ToDo: no find box in the popup (use Ctrl+F in the main window)."""

    POLL_MS = 1000

    def __init__(self, app, cid):
        self.app = app
        self.cid = cid
        self.labels = {}
        self.shown = None                  # what the window shows now
        self.move_job = self.poll_job = None
        self.closed = False
        top = self.top = tk.Toplevel(app.root)
        top.configure(bg=T["bg"])
        top.transient(app.root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.minsize(320, 240)

        bar = tk.Frame(top, bg=T["panel"])
        bar.pack(fill="x")
        self.v_pick = tk.StringVar()
        self.om = mkoption(bar, self.v_pick, ["-"], self._picked, 34)
        self.om.pack(side="left", padx=6, pady=4)
        self.v_names = tk.BooleanVar(value=False)
        c = mkcheck(bar, "Show names", self.v_names, self._load)
        c.configure(bg=T["panel"], activebackground=T["panel"])
        c.pack(side="left", padx=8)
        mkbtn(bar, "Close", self.close, 7).pack(side="right", padx=6)

        self.font = tkfont.Font(family="Georgia",
                                size=int(app.S.get("chapter_popup_size", 12)))
        fr, self.txt = mktext(top, height=20, width=60, font=self.font)
        fr.pack(fill="both", expand=True, padx=8, pady=(8, 4))
        self.txt.configure(spacing2=3, spacing3=8)
        self.txt.tag_configure("ph", foreground=T["accent"])
        self.txt.bind("<Control-MouseWheel>", self._zoom)
        self.lbl = mklabel(top, "", dim=True)
        self.lbl.pack(fill="x", padx=8, pady=(0, 6))
        top.bind("<Configure>", self._configured)

        self._rebuild_menu()
        self._load(top_of_text=True)
        self._place()
        self.poll_job = top.after(self.POLL_MS, self._poll)

    # ---- the chapter ---------------------------------------------------------------------
    def chapter(self):
        return self.app.book.chapter(self.cid) if self.cid else None

    def _labels_now(self):
        out = {}
        for i, ch in enumerate(self.app.book.chapters()):
            lab = "%d. %s" % (i + 1, ch["title"] or "(no title)")
            while lab in out:
                lab += " "
            out[lab] = ch["id"]
        return out

    def _label_of(self, cid):
        for lab, i in self.labels.items():
            if i == cid:
                return lab
        return "-"

    def _rebuild_menu(self):
        self.labels = self._labels_now()
        reset_option(self.om, self.v_pick, list(self.labels) or ["-"],
                     self._picked)
        self.v_pick.set(self._label_of(self.cid))

    def _picked(self, label):
        cid = self.labels.get(label)
        other = self.app.chapter_popups.get(cid)
        if other is not None and other is not self:
            self.v_pick.set(self._label_of(self.cid))
            other.top.lift()                   # that chapter is open already
            return
        if cid and cid != self.cid:
            self.app.chapter_popups.pop(self.cid, None)
            self.app.chapter_popups[cid] = self
            self.cid = cid
            self._load(top_of_text=True)

    def _load(self, top_of_text=False):
        ch = self.chapter()
        raw = ch["text"] if ch else ""
        names = bool(self.v_names.get())
        pos = 0.0 if top_of_text else self.txt.yview()[0]
        text = self.app.book.names(raw, True) if (ch and names) else raw
        self.txt.configure(state="normal")
        self.txt.delete("1.0", "end")
        self.txt.insert("1.0", text)
        self.txt.configure(state="disabled")
        self.txt.yview_moveto(pos)
        self.shown = (self.cid, raw, names, ch["title"] if ch else None)
        self.top.title("Chapter - " + (ch["title"] if ch else "?"))
        if ch:
            self.lbl.configure(text="{:,} words   (read-only - write in the "
                               "main window)".format(self.app.book.count(raw)))
        else:
            self.lbl.configure(text="This chapter no longer exists")
        self._highlight(text)

    def _highlight(self, text):
        self.txt.tag_remove("ph", "1.0", "end")
        rx = self.app.book.rx()
        if rx is None or not text or self.v_names.get() \
                or len(text) > 800000:
            return
        idx = PosIndex(text)
        for m in rx.finditer(text):
            self.txt.tag_add("ph", idx(m.start()), idx(m.end()))

    def _poll(self):
        """Once a second: has the book changed under us?"""
        self.poll_job = None
        if self.closed:
            return
        try:
            ch = self.chapter()
            now = (self.cid, ch["text"] if ch else "",
                   bool(self.v_names.get()), ch["title"] if ch else None)
            if now != self.shown:
                self._load()
            if self._labels_now() != self.labels:
                self._rebuild_menu()
        except Exception:
            pass
        if not self.closed:
            self.poll_job = self.top.after(self.POLL_MS, self._poll)

    def _zoom(self, e):
        size = max(8, min(30, int(self.font.cget("size")
                                  ) + (1 if e.delta > 0 else -1)))
        self.font.configure(size=size)
        self.app.S["chapter_popup_size"] = size
        return "break"

    # ---- position -----------------------------------------------------------------------------
    def _key(self):
        return os.path.basename(self.app.book.folder)

    def _place(self):
        top, root = self.top, self.app.root
        pos = self.app.S.get("chapter_popup_geo", {}).get(self._key())
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        n = len(self.app.chapter_popups)  # others already open (we are not in yet)
        if isinstance(pos, str) and re.match(
                r"^\d+x\d+[+-]-?\d+[+-]-?\d+$", pos):
            m = re.match(r"(\d+)x(\d+)[+-](-?\d+)[+-](-?\d+)", pos)
            w, h, x, y = (int(v) for v in m.groups())
            if -w + 60 < x < sw - 60 and 0 <= y < sh - 60:
                top.geometry("%dx%d+%d+%d" % (w, h, x + 30 * n, y + 30 * n))
                return
        root.update_idletasks()
        w, h = 560, 640
        x = root.winfo_x() + root.winfo_width() + 8     # beside the program
        if x + w > sw:                    # no room: hug the right screen edge
            x = sw - w
        y = max(0, min(root.winfo_y() + 40, sh - h - 60))
        top.geometry("%dx%d+%d+%d" % (w, h, max(0, x) + 30 * n, y + 30 * n))

    def _configured(self, e):
        if e.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(500, self._remember)

    def _remember(self):
        self.move_job = None
        try:
            self.app.S.setdefault("chapter_popup_geo", {})[self._key()] = \
                self.top.geometry()
            save_settings(self.app.S)
        except Exception:
            pass

    def close(self):
        self.closed = True
        for job in (self.poll_job, self.move_job):
            if job:
                try:
                    self.top.after_cancel(job)
                except Exception:
                    pass
        if self.move_job:
            self._remember()
        if self.app.chapter_popups.get(self.cid) is self:
            self.app.chapter_popups.pop(self.cid, None)
        try:
            self.top.destroy()
        except Exception:
            pass


# *************** DEL 40 - EXPORT *********************************************

EXPORT_FORMATS = {"Word (.docx)": ".docx", "Markdown (.md)": ".md",
                  "Plain text (.txt)": ".txt"}


def export_book(book, path, use_names=True, with_parts=True,
                skip_empty=True):
    """Write the book to path (.docx / .md / .txt).  Returns (chapters, words).
    The names are put in at this moment; the book itself is not changed."""
    ext = os.path.splitext(path)[1].lower()
    chapters = [c for c in book.chapters()
                if not (skip_empty and not c["text"].strip())]

    def nm(t):
        return book.names(t, use_names)
    words = sum(book.count(c["text"]) for c in chapters)
    title, author = nm(book.title), nm(book.d.get("author", ""))
    if ext == ".docx":
        import docx
        doc = docx.Document()
        doc.add_heading(title, 0)
        if author:
            doc.add_paragraph(author)
        last = None
        for ch in chapters:
            part = (ch.get("part") or "").strip()
            if with_parts and part and part != last:
                doc.add_heading(nm(part), 1)
            last = part
            doc.add_heading(nm(ch["title"]), 2 if with_parts else 1)
            for line in nm(ch["text"]).split("\n"):
                if line.strip():
                    doc.add_paragraph(line)
        doc.save(path)
        return len(chapters), words
    md = ext == ".md"
    out = [("# " if md else "") + title, ""]
    if author:
        out += [("*%s*" % author) if md else author, ""]
    last = None
    for ch in chapters:
        part = (ch.get("part") or "").strip()
        if with_parts and part and part != last:
            out += [("## " if md else "") + nm(part).upper(), ""]
        last = part
        out += [("### " if md and with_parts else "## " if md else "")
                + nm(ch["title"]), ""]
        out += [nm(ch["text"]).strip("\n"), "", ""]
    with open(path, "w", encoding="utf-8", newline="\n") as fh:
        fh.write("\n".join(out))
    return len(chapters), words


# *************** DEL 41 - HELP TEXT ******************************************

HELP_TEXT = """\
STORYDESK - a writing desk for authors

THE TABS
Plan    The theoretical book: parts, chapters, a synopsis, a status and a
        word target for each. A grey chapter has no text yet - it is only a
        plan. Move chapters with Move up / Move down (or Alt+Up / Alt+Down).
        Give chapters the same "Part" to group them. Double-click = write.
Write   The real chapters. The plan for the chapter is shown beside the text.
        Ctrl+mouse wheel = bigger/smaller letters. Ctrl+F = find.
        "Fewer blank lines" (Find row) turns several empty lines in a row
        into one - in the selection, or in the whole chapter. Ctrl+Z undoes.
        "Pop out" (Find row) shows the chapter in its own window (drag it to
        another screen) so you can read it while writing another chapter. It
        is read-only, follows what you write, and has a list to pick any
        other chapter. Zoom with Ctrl+mouse wheel. Escape closes it.
Time    Does the story flow in time? See "DATES AND TIME" below.
Places  Where does the story happen? See "PLACES" below.
Notes   Loose threads, notes, ideas, questions, research. Each can belong to
        a chapter. Mark a thread Done when it is tied up.
Names   Write "Kollega 1" in the text. Give the real name here (Anders) -
        every "Kollega 1" becomes Anders when you export or press "Show
        names" in the Write tab. The text itself keeps "Kollega 1", so you can
        change your mind as often as you like.
Words   Which words do I use too often? How often does X occur, and where?

DATES AND TIME
StoryDesk reads the years and dates you write and keeps track of the time, so
you do not end up in the wrong year.
- Found automatically (Swedish and English): 1985, 1985-86, 12 maj 1985, May
  12 1985, 3rd of March, 10-12 maj, juni (i juni, in June), 12/5 1985,
  1985-05-12, 12.5.1985, maj -85, sommaren 1985, 80-talet, 1980-talet,
  sextiotalet, the 80s, '90s, the sixties, 1800-talet, 19th century.
  Clock times (10:30) and numbers such as 1500 kronor or 3/4 are not dates.
- A date without a year ("12 maj") takes the year of the last year written
  before it in the book; it is shown with a ~ (a guess). A two-digit decade
  ("80-talet") is placed in the century that fits the book.
- Write tab, "Takes place": type when the chapter happens - from and to, in
  any of the forms above (1985 / March 1985 / 12 May 1985 / the 80s). One of
  the two is enough. The time is shown in the When column of the chapter list.
  A chapter with nothing set gets its time from the dates in its text (blue).
- Red in the When column (with an arrow) = the chapter starts earlier than the
  previous chapter did: a jump back in time (fine for a flashback - but now
  you can see it). A set time with from later than to, or not understood, is
  red too.
- Right side of the Write tab, under Names: every date written in the
  chapter, in reading order, with the date it means. Double-click one to find it
  in the text (again = the next place where it is written). Red ! = the date
  is outside the time you set for the chapter. Orange < = earlier than the
  date written before it. "Mark dates" underlines them in the text.
- Time tab: all chapters in order with the set time, the time found in the
  text, the distance from the previous chapter (+3 weeks, continues, back 2
  months) and what to check. Open a chapter to see its dates. Double-click
  = show it in the Write tab.
- Winter 1985 means December 1984 - February 1985. A chapter whose text
  mentions an old year in passing (1950) gets a wide time from the text -
  set the time yourself to make the checks exact.

PLACES
- The cities, countries and regions named in a chapter are found
  automatically (a built-in list of Swedish and world cities, Swedish and
  English names: Köpenhamn = Copenhagen, also "Stockholms" / "Paris'").
  Names that are also ordinary words or first names (Nice, Lund, Paris, Mora,
  Split ...) count only after a place word (i, till, från, in, to, from ...).
- Write tab, "Main place": type where the chapter mainly happens (a city, a
  region, an invented place ...). One place - not from/to. Without it the
  most named city of the chapter is used (shown in the Place column of the
  Plan tab inside ( ) ). A place you type is also found in the text from then
  on.
- Right side of the Write tab, under Dates: the places named in the chapter.
  Double-click = find it in the text (again = the next one). A grey ? is a
  capitalised name after "i / till / från / in / to ..." that is not known as a
  place - double-click it to add it to My places, or right-click: "is not a
  place". Right-click one of your own places to remove it. "Mark dates & places"
  underlines places in yellow and dates in green.
- Places tab: every chapter with its main place, the places named, where the
  story moves ( -> Paris ) and what to check. Blue = the story moves.
  My places... (also under Tools) lists your own places and the words that are
  not places.

NOTE AS A POPUP
Select a note in the Notes tab and press "Pop out" (or double-click it). The
note opens in its own window that stays beside the program while you write your
chapter plans. Also in the Plan tab ("Note popup") and the Write tab ("Pop
out"). The window has a drop-down to switch to another note, a New button
and a Done box; typing is saved with the book. Move and resize it - the place
is remembered. Ctrl+mouse wheel = bigger letters. Escape closes it.

NAMES AND SWEDISH GENITIVE
"Kollega 1s racerbil" and "Kollega 1:s racerbil" become "Anders racerbil"
(names ending in s, x or z get no extra s) and "Annas racerbil" for Anna.
If a name needs another form, type it in the Genitive field.
"Use this name for good..." writes the name INTO the text for good (a
snapshot is saved first).

WORDS
- Orange mark in the text = a word used too often. Red = a word from your
  watch list over its limit. Blue = an echo (same word twice within a few
  words). Switch the marks on/off above the text.
- Settings on the Words tab decide what is "too often": minimum word length,
  minimum count and how many times per 1000 words.
- Search: type a word, kall* finds kall, kalla, kallt. The result says how many
  times, in how many chapters and per 1000 words. Double-click a hit to jump
  to it in the text.
- "Show echoes" lists every echo in the chapter or the book.

SEVERAL BOOKS
Book > Library, or the book switcher at the top. Every book is a folder in
Helpfiles\\StoryDesk\\Books. Each keeps its own chapters, notes, names, word
settings and snapshots.

SAVING - NOTHING IS EVER OVERWRITTEN
- Your book is saved to book.json a moment after every change.
- Besides that, a SNAPSHOT (a complete copy with date and time in its name)
  is made when you open a book, every N edits (Tools > Autosave settings),
  when you close, and when you press Save (Ctrl+S).
- IMPORTANT snapshots (marked with a star in Tools > Snapshots): every Save you
  press yourself, the FIRST snapshot of each day and the LAST snapshot of each
  day.
- Tools > Snapshots lets you restore an old state or open it as a separate
  book. Restoring first saves the state you leave.
- Deleted chapters, notes and names go to Tools > Trash, where they can be
  restored. The program never deletes anything for good.

PHONE SYNC (Tools > Phone sync...)
- Keeps your books the same on this PC and in the phone app "Issu's StoryDesk" (and on another PC), through a small server of
  your own (the relay). Set it up once: Use relay.json (or Server... and paste a code), tick the books to share with
  "Share this book", then "Copy code for the phone" and paste it in the phone app (Settings > Paste code).
- It works by itself: a few seconds after you stop writing the book is sent, and every 30 seconds the server is asked what the
  phone did. The bar at the bottom says "in step", "changes waiting" or why it could not connect. Offline is fine: everything
  is sent when the connection is back.
- Nobody overwrites anybody. Every chapter, note and name carries a version number; a device may only replace the version it
  has seen. If the phone changed a chapter while you changed it too, the two are MERGED: changes in different places are all
  kept (paragraph by paragraph, and inside a paragraph word by word).
- If you both rewrote the SAME words, the words that reached the server first stay in the chapter and the other words are put
  into a new note of kind Conflict (tied to the chapter, shown in the Notes tab). Read it, put back what you want, set it to
  Done. Nothing is lost.
- A chapter deleted on one device but written on the other comes back (the writing wins). A deleted chapter, note or name
  goes to the trash of the other device too, never away.
- A book made on the phone shows under "On the server, not on this PC": press Get this book.
- Shared: title / author / language, chapter order, chapters (plan fields and text), notes, names, word watch, places.
  Not shared: snapshots, trash, window settings.
- Before your own changes are merged with the phone's, a snapshot "sync" of the book is made (Tools > Snapshots).

EXPORT
Book > Export makes a Word, Markdown or text file with the real names put in.

Escape closes this window.
"""


# *************** DEL 42 - DIALOGS (BOOK, LIBRARY, SNAPSHOTS, TRASH ...) *******

def book_dialog(parent, heading, title="", author="", language="sv"):
    """Ask for title, author and language of a book.  Returns a dict/None."""
    top = open_dialog(parent, heading)
    res = [None]
    v_t, v_a = tk.StringVar(value=title), tk.StringVar(value=author)
    v_l = tk.StringVar(value=language if language in LANGUAGES else "sv")
    for lab, var in (("Title of the book", v_t), ("Author", v_a)):
        mklabel(top, lab, dim=True).pack(anchor="w", padx=16, pady=(12, 0))
        mkentry(top, var, 42).pack(padx=16)
    mklabel(top, "Language of the book (decides which words count as common)",
            dim=True).pack(anchor="w", padx=16, pady=(12, 0))
    mkoption(top, v_l, LANGUAGES, None, 8).pack(anchor="w", padx=16)

    def ok():
        if v_t.get().strip():
            res[0] = dict(title=v_t.get().strip(), author=v_a.get().strip(),
                          language=v_l.get())
            top.destroy()
    row = tk.Frame(top, bg=T["bg"])
    row.pack(pady=14)
    mkbtn(row, "OK", ok, 10).pack(side="left", padx=4)
    mkbtn(row, "Cancel", top.destroy, 10).pack(side="left", padx=4)
    finish_dialog(top, parent)
    parent.wait_window(top)
    return res[0]


class LibraryDialog(object):
    def __init__(self, app):
        self.app = app
        top = self.top = open_dialog(app.root, "Library - my books",
                                     resizable=True)
        fr, self.tv = mktree(top, ("title", "folder"), (260, 260),
                             ("Book", "Folder"), height=10)
        fr.pack(fill="both", expand=True, padx=12, pady=(12, 6))
        self.tv.bind("<Double-1>", lambda e: self.open())
        row = tk.Frame(top, bg=T["bg"])
        row.pack(pady=(0, 12))
        for text, cmd, w in (("Open", self.open, 9), ("New book...", self.new,
                                                      11),
                             ("Rename...", self.rename, 10),
                             ("Duplicate", self.duplicate, 10),
                             ("Show folder", self.show, 11),
                             ("Close", top.destroy, 8)):
            mkbtn(row, text, cmd, w).pack(side="left", padx=3)
        self.fill()
        finish_dialog(top, app.root, 640, 380)

    def fill(self):
        self.tv.delete(*self.tv.get_children())
        self.paths = {}
        for p, title in list_books():
            iid = self.tv.insert("", "end", values=(title,
                                                    os.path.basename(p)))
            self.paths[iid] = p
            if self.app.book and os.path.samefile(p, self.app.book.folder):
                self.tv.selection_set(iid)

    def sel(self):
        s = self.tv.selection()
        return self.paths[s[0]] if s else None

    def open(self):
        p = self.sel()
        if p:
            self.top.destroy()
            self.app.open_book(p)

    def new(self):
        self.top.destroy()
        self.app.new_book()

    def rename(self):
        p = self.sel()
        if not p:
            return
        other = Book(p).load()
        r = book_dialog(self.top, "Rename the book", other.title,
                        other.d.get("author", ""),
                        other.d.get("language", "sv"))
        if r:
            if self.app.book and os.path.samefile(p, self.app.book.folder):
                other = self.app.book
            other.d.update(r)
            other.touch()
            other.save_live()
            self.fill()
            self.app.refresh_books_menu()

    def duplicate(self):
        p = self.sel()
        if not p:
            return
        if self.app.book and os.path.samefile(p, self.app.book.folder):
            self.app.book.save_live()
        src = Book(p).load()
        dst = Book(unique_folder(src.title + " (copy)"))
        dst.d = src.d
        dst.d["title"] = src.title + " (copy)"
        os.makedirs(dst.folder, exist_ok=True)
        dst.save_live()
        self.fill()
        self.app.refresh_books_menu()

    def show(self):
        p = self.sel()
        if p:
            open_path(p)


class SnapshotDialog(object):
    """Every snapshot of the book, newest first.  Restore or open as a copy."""

    def __init__(self, app):
        self.app = app
        top = self.top = open_dialog(app.root, "Snapshots - " + app.book.title,
                                     resizable=True)
        mklabel(top, "Every snapshot is a complete copy, kept for good. "
                     "★ = important (your own Save, and the first and "
                     "last of each day).", dim=True, wraplength=620,
                justify="left").pack(anchor="w", padx=12, pady=(10, 4))
        self.v_imp = tk.BooleanVar(value=False)
        mkcheck(top, "Show only the important ones", self.v_imp,
                self.fill).pack(anchor="w", padx=12)
        fr, self.tv = mktree(top, ("star", "date", "time", "kind", "size"),
                             (30, 100, 80, 120, 80),
                             ("", "Date", "Time", "Kind", "Size"), height=14)
        self.tv.column("star", stretch=False)
        self.tv.column("kind", stretch=True)
        fr.pack(fill="both", expand=True, padx=12, pady=6)
        self.tv.tag_configure("imp", foreground="#f9c97c")
        row = tk.Frame(top, bg=T["bg"])
        row.pack(pady=(0, 12))
        mkbtn(row, "Restore this", self.restore, 12).pack(side="left", padx=3)
        mkbtn(row, "Open as new book", self.as_copy, 16).pack(side="left",
                                                              padx=3)
        mkbtn(row, "Show folder", lambda: open_path(app.book.snap_dir),
              11).pack(side="left", padx=3)
        mkbtn(row, "Close", top.destroy, 8).pack(side="left", padx=3)
        self.fill()
        finish_dialog(top, app.root, 640, 520)

    def fill(self):
        self.tv.delete(*self.tv.get_children())
        self.snaps = {}
        for s in reversed(self.app.book.list_snapshots()):
            if self.v_imp.get() and not s["important"]:
                continue
            iid = self.tv.insert("", "end", values=(
                "★" if s["important"] else "", s["date"], s["time"],
                s["kind"], "%d KB" % max(1, s["size"] // 1024)),
                tags=(("imp",) if s["important"] else ()))
            self.snaps[iid] = s

    def sel(self):
        s = self.tv.selection()
        return self.snaps[s[0]] if s else None

    def restore(self):
        s = self.sel()
        if not s:
            return
        if not messagebox.askyesno(
                "Restore", "Make the book look as it did on %s %s?\n\nThe "
                "state you have now is saved as a snapshot first, so you can "
                "come back." % (s["date"], s["time"]), parent=self.top):
            return
        self.app.restore_snapshot(s["path"])
        self.top.destroy()

    def as_copy(self):
        s = self.sel()
        if not s:
            return
        d = self.app.book.load_snapshot_data(s["path"])
        d["title"] = "%s (from %s %s)" % (d.get("title", "Book"), s["date"],
                                          s["time"])
        nb = Book(unique_folder(d["title"]))
        nb.d = d
        os.makedirs(nb.folder, exist_ok=True)
        nb.save_live()
        self.app.refresh_books_menu()
        self.top.destroy()
        if messagebox.askyesno("Open as new book",
                               "Saved as the book \"%s\". Open it now?"
                               % d["title"], parent=self.app.root):
            self.app.open_book(nb.folder)


class TrashDialog(object):
    def __init__(self, app):
        self.app = app
        top = self.top = open_dialog(app.root, "Trash", resizable=True)
        mklabel(top, "Deleted chapters, notes and names. Nothing here is lost "
                     "- restore what you want back.", dim=True).pack(
            anchor="w", padx=12, pady=(10, 4))
        fr, self.tv = mktree(top, ("kind", "title", "when"), (90, 300, 150),
                             ("Kind", "Title", "Deleted"), height=12)
        fr.pack(fill="both", expand=True, padx=12, pady=6)
        row = tk.Frame(top, bg=T["bg"])
        row.pack(pady=(0, 12))
        mkbtn(row, "Restore", self.restore, 10).pack(side="left", padx=3)
        mkbtn(row, "Close", top.destroy, 8).pack(side="left", padx=3)
        self.fill()
        finish_dialog(top, app.root, 600, 420)

    def fill(self):
        self.tv.delete(*self.tv.get_children())
        self.map = {}
        for i, t in enumerate(self.app.book.d["trash"]):
            it = t["item"]
            title = it.get("title") or it.get("placeholder") or it.get(
                "name") or "?"
            iid = self.tv.insert("", "end", values=(t["type"], title,
                                                    t["deleted"]))
            self.map[iid] = t

    def restore(self):
        s = self.tv.selection()
        if not s:
            return
        t = self.map[s[0]]
        b = self.app.book
        coll = {"chapter": b.d["chapters"], "note": b.d["notes"],
                "character": b.d["characters"]}.get(t["type"])
        if coll is None:
            return
        coll.append(t["item"])
        b.d["trash"].remove(t)
        b.touch()
        self.fill()
        self.app.status("Restored \"%s\"" % (t["item"].get("title")
                                             or t["item"].get("name") or ""))


def autosave_dialog(app):
    top = open_dialog(app.root, "Autosave settings")
    v1 = tk.StringVar(value=str(app.S["snap_every_edits"]))
    v2 = tk.StringVar(value=str(app.S["snap_min_minutes"]))
    mklabel(top, "A snapshot is made after this many edits (each key press "
                 "counts as one):", dim=True, wraplength=380,
            justify="left").pack(anchor="w", padx=16, pady=(14, 0))
    mkentry(top, v1, 8).pack(anchor="w", padx=16)
    mklabel(top, "... but never more often than every (minutes):",
            dim=True).pack(anchor="w", padx=16, pady=(10, 0))
    mkentry(top, v2, 8).pack(anchor="w", padx=16)
    mklabel(top, "Besides this: a snapshot when a book is opened, when the "
                 "program closes, and when you press Save (Ctrl+S).",
            dim=True, wraplength=380, justify="left").pack(
        anchor="w", padx=16, pady=(10, 0))

    def ok():
        try:
            app.S["snap_every_edits"] = max(10, int(v1.get()))
            app.S["snap_min_minutes"] = max(0, int(v2.get()))
        except ValueError:
            return
        save_settings(app.S)
        top.destroy()
    row = tk.Frame(top, bg=T["bg"])
    row.pack(pady=14)
    mkbtn(row, "OK", ok, 9).pack(side="left", padx=4)
    mkbtn(row, "Cancel", top.destroy, 9).pack(side="left", padx=4)
    finish_dialog(top, app.root)


def export_dialog(app):
    top = open_dialog(app.root, "Export - " + app.book.title)
    v_fmt = tk.StringVar(value=list(EXPORT_FORMATS)[0])
    v_names = tk.BooleanVar(value=True)
    v_parts = tk.BooleanVar(value=True)
    v_skip = tk.BooleanVar(value=True)
    mklabel(top, "Format", dim=True).pack(anchor="w", padx=16, pady=(14, 0))
    mkoption(top, v_fmt, list(EXPORT_FORMATS), None, 18).pack(
        anchor="w", padx=16)
    for text, var in (("Put in the real names (Kollega 1 -> Anders)", v_names),
                      ("Include part headings", v_parts),
                      ("Leave out chapters that are only planned (no text)",
                       v_skip)):
        mkcheck(top, text, var).pack(anchor="w", padx=16, pady=(6, 0))

    def go():
        ext = EXPORT_FORMATS[v_fmt.get()]
        folder = os.path.join(app.book.folder, "Export")
        os.makedirs(folder, exist_ok=True)
        path = filedialog.asksaveasfilename(
            parent=top, initialdir=folder, defaultextension=ext,
            initialfile=safe_folder_name(app.book.title) + ext,
            filetypes=[(v_fmt.get(), "*" + ext)])
        if not path:
            return
        try:
            n, w = export_book(app.book, path, v_names.get(), v_parts.get(),
                               v_skip.get())
        except Exception as ex:
            messagebox.showerror("Export", "Could not export:\n%s" % ex,
                                 parent=top)
            return
        top.destroy()
        messagebox.showinfo("Export", "Exported %d chapters, %s words, to:\n%s"
                            % (n, "{:,}".format(w), path), parent=app.root)
    row = tk.Frame(top, bg=T["bg"])
    row.pack(pady=16)
    mkbtn(row, "Export...", go, 11).pack(side="left", padx=4)
    mkbtn(row, "Cancel", top.destroy, 9).pack(side="left", padx=4)
    finish_dialog(top, app.root)


# *************** DEL 60 - PHONE SYNC: THE CORE (merging, records, the relay client; no windows, tested alone) *****************
# ToDo (2026-11-29): how a book travels between this PC and the phone app "Issu's StoryDesk" (and any other PC).
#   A book is cut into RECORDS: the book's title/author/language ("b"), the chapter order ("o"), word-watch/places/settings ("x"),
#   every chapter ("c<id>"), note ("n<id>") and character ("h<id>").  A relay (relay\storydesk_relay.py, a small server of your own)
#   keeps the newest accepted version of each record and a version number "rev".  Both sides keep COMPLETE copies and work offline.
#   NOBODY OVERWRITES ANYBODY: a device writes "I changed version N"; the relay accepts that only while N is still the newest.  If not,
#   the newest version comes back and THIS side merges it with its own change:
#       - a record only one side changed: that side's version simply wins,
#       - a text changed on both sides: a three-way merge against the version both started from, line by line, and inside a line
#         changed on both sides word by word - changes in different places are all kept,
#       - the same words changed on both sides: the OTHER device's words stay in the book and YOUR words are put into a new note of
#         kind "Conflict" (tied to the chapter), so nothing is ever lost and both sides end up with the same book,
#       - deleted on one side, edited on the other: the edit wins (the deleted item comes back); a deleted item goes to this
#         side's trash, never away.
#   The version both sides started from is kept per record in <book folder>\sync_base.json (sync.json holds the small state).
#   New ids: the device that first shares a book keeps its normal ids; a device that joins later takes ids from its own range
#   (dev * 1,000,000,000 + n) so two devices never make the same id.  Phone-made books appear in the Phone sync window as
#   "available on the server" and are fetched with one click.  Not shared: trash, snapshots, window settings.
SYNC_CODE_PREFIX = "ISSUSYNC1:"
SYNC_APP_ID = "storydesk"
SYNC_MAX_ROUNDS = 6


def sync_code_make(url, key, app=SYNC_APP_ID):
    """The text that is copied to the phone: prefix + base64url of {"a": app, "u": address, "k": key}. It contains the key."""
    raw = json.dumps({"a": app, "u": url, "k": key}, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return SYNC_CODE_PREFIX + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def sync_code_parse(text):
    """The reverse of sync_code_make; spaces / line breaks inside the code are ignored, text around it too. None when it is not a code."""
    t = re.sub(r"\s+", "", text or "")
    i = t.find(SYNC_CODE_PREFIX)
    if i < 0:
        return None
    m = re.match(r"[A-Za-z0-9_\-]+", t[i + len(SYNC_CODE_PREFIX):])
    if not m:
        return None
    body, d = m.group(0), None
    # text that follows the code (with its spaces removed) sticks to the end of it: shorten until what is left decodes to the JSON object
    for n in range(len(body), max(len(body) - 400, 15), -1):
        try:
            d = json.loads(base64.urlsafe_b64decode(body[:n] + "=" * (-n % 4)).decode("utf-8"))
            break
        except Exception:
            d = None
    if not isinstance(d, dict):
        return None
    url, key = str(d.get("u") or ""), str(d.get("k") or "")
    if not re.match(r"^https?://[^\s]+$", url) or len(key) < 8:
        return None
    return {"app": str(d.get("a") or ""), "url": url, "key": key}


# ---- three-way merge --------------------------------------------------------------------------------------------------
def _hunks(base, other):
    """What `other` did to `base`: [(start, end, replacement list)] - base[start:end] became the replacement."""
    sm = difflib.SequenceMatcher(None, base, other, autojunk=False)
    return [(i1, i2, list(other[j1:j2])) for tag, i1, i2, j1, j2 in sm.get_opcodes() if tag != "equal"]


def _overlap(x, y):
    return (x[0] < y[1] and y[0] < x[1]) or (x[0] == x[1] == y[0] == y[1])


def merge3(base, a, b, resolve=None, keep_both=True):
    """Merge two changed copies (a = mine, b = the other one's) of the list `base`.  Returns (merged list, conflicts).
    Changes in different places are all kept.  Where both changed the same part differently: `resolve(base part, a part, b part)`
    may return a merged list; else, when both only INSERTED at the same point and keep_both is on, both insertions stay (b's first);
    else b's version stays and (a part, b part) is added to the conflicts."""
    ha, hb = _hunks(base, a), _hunks(base, b)
    out, conflicts, pos, i, j = [], [], 0, 0, 0
    while i < len(ha) or j < len(hb):
        x = ha[i] if i < len(ha) else None
        y = hb[j] if j < len(hb) else None
        if x is not None and (y is None or (not _overlap(x, y) and (x[0], x[1]) <= (y[0], y[1]))):
            out += base[pos:x[0]] + x[2]
            pos = x[1]
            i += 1
            continue
        if y is not None and (x is None or (not _overlap(x, y) and (y[0], y[1]) < (x[0], x[1]))):
            out += base[pos:y[0]] + y[2]
            pos = y[1]
            j += 1
            continue
        s, e, ai, bj = min(x[0], y[0]), max(x[1], y[1]), i, j      # a cluster of overlapping changes from both sides
        i += 1
        j += 1
        grew = True
        while grew:
            grew = False
            while i < len(ha) and ha[i][0] < e:
                e = max(e, ha[i][1])
                i += 1
                grew = True
            while j < len(hb) and hb[j][0] < e:
                e = max(e, hb[j][1])
                j += 1
                grew = True

        def apply(hs):
            res, p = [], s
            for hs_, he_, rep in hs:
                res += base[p:hs_] + rep
                p = he_
            return res + base[p:e]

        ta, tb = apply(ha[ai:i]), apply(hb[bj:j])
        out += base[pos:s]
        pos = e
        if ta == tb:
            out += ta
            continue
        res = resolve(base[s:e], ta, tb) if resolve else None
        if res is not None:
            out += res
        elif s == e and keep_both:
            out += tb + ta
        else:
            out += tb
            conflicts.append((ta, tb))
    out += base[pos:]
    return out, conflicts


_TOKEN_RX = re.compile(r"\s+|\w+|[^\w\s]")


def _word_resolve(rb, ra, rr):
    """Two lines (paragraphs) changed on both sides: try again word by word.  Returns the merged lines or None."""
    if not (rb and ra and rr):
        return None
    tb = _TOKEN_RX.findall("\n".join(rb))
    ta = _TOKEN_RX.findall("\n".join(ra))
    tr = _TOKEN_RX.findall("\n".join(rr))
    merged, conf = merge3(tb, ta, tr, keep_both=False)
    if conf:
        return None
    return "".join(merged).split("\n")


def merge_text(base, local, remote):
    """Three-way merge of a text.  Returns (text, conflicts) where conflicts = [(my words, the other one's words kept)]."""
    if local == remote:
        return local, []
    if local == base:
        return remote, []
    if remote == base:
        return local, []
    res, conf = merge3(base.split("\n"), local.split("\n"), remote.split("\n"), resolve=_word_resolve, keep_both=True)
    return "\n".join(res), [("\n".join(a), "\n".join(b)) for a, b in conf]


def merge_fields(base, local, remote):
    """Three-way merge of the fields of ONE record (dicts).  Returns (merged dict, conflicts [(field, my words, kept words)]).
    Where both changed the same words the REMOTE value stays."""
    out, conflicts = {}, []
    for k in list(remote) + [k for k in local if k not in remote]:
        hb, hl, hr = k in base, k in local, k in remote
        bv, lv, rv = base.get(k), local.get(k), remote.get(k)
        if hl and hr:
            if lv == rv:
                out[k] = lv
            elif hb and lv == bv:
                out[k] = rv
            elif hb and rv == bv:
                out[k] = lv
            elif isinstance(lv, str) and isinstance(rv, str) and (not hb or isinstance(bv, str)):
                t, cs = merge_text(bv if hb else "", lv, rv)
                out[k] = t
                conflicts += [(k, p, q) for p, q in cs]
            else:
                out[k] = rv
                conflicts.append((k, json.dumps(lv, ensure_ascii=False), json.dumps(rv, ensure_ascii=False)))
        elif hl:
            if not (hb and lv == bv):          # the other side removed a field we did not touch: it goes
                out[k] = lv
        elif not (hb and rv == bv):            # we removed a field the other side did not touch: it stays removed
            out[k] = rv
    return out, conflicts


def merge_order(base, local, remote):
    """The chapter order: ids merged like lines; an id appears once."""
    res, _ = merge3(list(base), list(local), list(remote), keep_both=True)
    seen, out = set(), []
    for x in res:
        if x not in seen:
            seen.add(x)
            out.append(x)
    return out


# ---- the book as records ----------------------------------------------------------------------------------------------
REC_B_KEYS = ("title", "author", "language")
REC_X_KEYS = ("watch", "places", "places_ignore", "settings")
_KIND_LIST = {"c": "chapters", "n": "notes", "h": "characters"}
_KIND_TRASH = {"c": "chapter", "n": "note", "h": "character"}
_CH_DEFAULT = dict(title="", part="", status="Planned", target=0, pov="", synopsis="", text="", when_from="", when_to="", place="")
_NOTE_DEFAULT = dict(kind="Note", title="", text="", status="Open", chapter=0, created="")
_CHAR_DEFAULT = dict(placeholder="", name="", genitive="", notes="")
_KIND_DEFAULT = {"c": _CH_DEFAULT, "n": _NOTE_DEFAULT, "h": _CHAR_DEFAULT}


def book_records(d):
    """{record id (without the book id): fields} - what is shared of the book data `d`."""
    recs = {"b": {k: d.get(k, "") for k in REC_B_KEYS},
            "o": {"order": [c["id"] for c in d["chapters"]]},
            "x": {k: d[k] for k in REC_X_KEYS if k in d}}
    for kind, name in _KIND_LIST.items():
        for it in d[name]:
            recs["%s%d" % (kind, it["id"])] = {k: v for k, v in it.items() if k != "id"}
    return recs


def record_fields(d, rid):
    """The fields of one record, or None when this side has no such record."""
    k = rid[0]
    if k == "b":
        return {x: d.get(x, "") for x in REC_B_KEYS}
    if k == "o":
        return {"order": [c["id"] for c in d["chapters"]]}
    if k == "x":
        return {x: d[x] for x in REC_X_KEYS if x in d}
    iid = int(rid[1:])
    for it in d[_KIND_LIST[k]]:
        if it["id"] == iid:
            return {x: v for x, v in it.items() if x != "id"}
    return None


def apply_order(d, order):
    """Puts the chapters in the given order; chapters not named stay behind in their old relative order."""
    by_id = {c["id"]: c for c in d["chapters"]}
    first = [by_id[i] for i in order if i in by_id]
    named = {c["id"] for c in first}
    d["chapters"][:] = first + [c for c in d["chapters"] if c["id"] not in named]


def apply_record(book, rid, f):
    """Puts the shared fields `f` of record `rid` into the book (f None = deleted).  An item that is deleted goes to the trash."""
    d, k = book.d, rid[0]
    if k == "b":
        for x in REC_B_KEYS:
            if f and x in f:
                d[x] = f[x]
    elif k == "x":
        for x in REC_X_KEYS:
            if f and x in f:
                d[x] = copy.deepcopy(f[x])
    elif k == "o":
        if f:
            apply_order(d, [i for i in f.get("order", []) if isinstance(i, int)])
    else:
        lst, iid = d[_KIND_LIST[k]], int(rid[1:])
        item = next((it for it in lst if it["id"] == iid), None)
        if f is None:
            if item is not None:
                book.trash(_KIND_TRASH[k], item, lst)
            return
        if item is None:
            d["trash"] = [t for t in d.get("trash", [])
                          if not (t.get("type") == _KIND_TRASH[k] and (t.get("item") or {}).get("id") == iid)]
            item = {"id": iid}
            lst.append(item)
        for x in [x for x in item if x != "id" and x not in f]:
            del item[x]
        item.update(copy.deepcopy(f))
        for x, v in _KIND_DEFAULT[k].items():
            item.setdefault(x, v)


def record_label(d, rid):
    k = rid[0]
    if k in _KIND_LIST:
        f = record_fields(d, rid) or {}
        if k == "c":
            ids = [c["id"] for c in d["chapters"]]
            i = ids.index(int(rid[1:])) + 1 if int(rid[1:]) in ids else 0
            return "chapter %s%s" % ("%d. " % i if i else "", f.get("title", ""))
        if k == "n":
            return "note \"%s\"" % f.get("title", "")
        return "character \"%s\"" % (f.get("placeholder") or f.get("name") or "")
    return {"b": "the book's title", "o": "the chapter order", "x": "the word watch and places"}.get(k, rid)


# ---- the sync state of one book ----------------------------------------------------------------------------------------
def _atomic_json(path, obj):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(obj, fh, ensure_ascii=False, separators=(",", ":"))
    os.replace(tmp, path)


class SyncReport(object):
    """What one answer of the relay did to a book."""

    def __init__(self):
        self.changed = set()       # record ids of the book that the other side changed here
        self.merged = 0            # records where both sides had changed something and the changes were combined
        self.conflicts = 0         # conflict notes made
        self.deleted = 0
        self.errors = []

    def add(self, other):
        self.changed |= other.changed
        self.merged += other.merged
        self.conflicts += other.conflicts
        self.deleted += other.deleted
        self.errors += other.errors


class BookSync(object):
    """The sync state of ONE book folder: sync.json (book id, since, in-flight pushes) and sync_base.json (per record: the
    version number and the fields both sides last agreed on)."""

    def __init__(self, folder):
        self.folder = folder
        self.p_state = os.path.join(folder, "sync.json")
        self.p_base = os.path.join(folder, "sync_base.json")
        self.s = None
        self._base = None
        self._state_dirty = False
        self._base_dirty = False
        self.pending = 0                  # records that differ from what the relay has (set by collect)
        self.scans = 0

    @staticmethod
    def exists(folder):
        return os.path.isfile(os.path.join(folder, "sync.json"))

    @staticmethod
    def bid_of(folder):
        try:
            with open(os.path.join(folder, "sync.json"), encoding="utf-8") as fh:
                return json.load(fh).get("bid") or ""
        except Exception:
            return ""

    def load(self):
        with open(self.p_state, encoding="utf-8") as fh:
            s = json.load(fh)
        for k, v in (("since", 0), ("dev", 0), ("inflight", {}), ("last", 0)):
            s.setdefault(k, v)
        self.s = s
        return self

    def create(self, bid, dev=0):
        self.s = dict(v=1, bid=bid, dev=dev, since=0, inflight={}, last=0)
        self._base = {}
        self._state_dirty = self._base_dirty = True
        self.save()
        return self

    @property
    def bid(self):
        return self.s["bid"]

    @property
    def base(self):
        if self._base is None:
            try:
                with open(self.p_base, encoding="utf-8") as fh:
                    self._base = json.load(fh)
            except (OSError, ValueError):
                self._base = {}
        return self._base

    def save(self):
        if self._base_dirty:
            _atomic_json(self.p_base, self._base)
            self._base_dirty = False
        if self._state_dirty:
            _atomic_json(self.p_state, self.s)
            self._state_dirty = False

    def set_since(self, n):
        if self.s["since"] != n:
            self.s["since"] = n
            self._state_dirty = True

    # ---- what has to be sent -------------------------------------------------------------------------------------------
    def collect(self, book):
        """The records that differ from the common base, as pushes for the relay.  Remembers a push id per record so a push whose
        answer got lost is recognised later."""
        pushes, cur = [], book_records(book.d)
        for rid, f in cur.items():
            st = self.base.get(rid)
            if st is not None and st["f"] is not None and st["f"] == f:
                continue
            pushes.append(dict(id=rid, base=st["rev"] if st else 0, d=0, f=copy.deepcopy(f)))
        for rid, st in self.base.items():
            if rid not in cur and st["f"] is not None:
                pushes.append(dict(id=rid, base=st["rev"], d=1))
        for p in pushes:
            p["pid"] = secrets.token_urlsafe(8)
            self.s["inflight"][p["id"]] = (self.s["inflight"].get(p["id"], []) + [p["pid"]])[-4:]
        if pushes:
            self._state_dirty = True
        self.pending = len(pushes)
        return pushes

    # ---- what came back ------------------------------------------------------------------------------------------------------
    def process(self, book, pushes, answer, before_merge=None):
        """Applies one answer of the relay to the book.  Returns a SyncReport.  The caller saves the book and calls save()."""
        rep = SyncReport()
        ok = answer.get("ok") or {}
        for p in pushes:
            got = ok.get(p["id"])
            if got:
                self.base[p["id"]] = {"rev": int(got["rev"]), "f": None if p.get("d") else p["f"]}
                self._base_dirty = True
                if self.s["inflight"].pop(p["id"], None) is not None:
                    self._state_dirty = True
        theirs = {}
        for src in (answer.get("recs") or {}, answer.get("conflicts") or {}):
            for rid, rec in src.items():
                if rid.startswith(self.bid + ":"):
                    theirs[rid[len(self.bid) + 1:]] = rec
        once = [before_merge]

        def snap_once():
            f, once[0] = once[0], None
            if f:
                f()
        order_last = sorted(theirs, key=lambda r: r == "o")      # the chapter order after the chapters it names
        for rid in order_last:
            try:
                self._take(book, rid, theirs[rid], rep, snap_once)
            except Exception as ex:                            # one bad record must not stop the others
                rep.errors.append("%s: %s" % (rid, ex))
        return rep

    def _take(self, book, rid, R, rep, before_merge):
        st = self.base.get(rid)
        if R["rev"] <= (st["rev"] if st else 0):
            return
        rf = None if R.get("d") else copy.deepcopy(R.get("f") or {})
        pid = R.get("pid")
        if pid and pid in self.s["inflight"].get(rid, []):       # our own earlier push whose answer never arrived
            self.base[rid] = {"rev": R["rev"], "f": rf}
            self.s["inflight"].pop(rid, None)
            self._base_dirty = self._state_dirty = True
            return
        d = book.d
        local = record_fields(d, rid)
        bf = st["f"] if st else None
        new = {"rev": R["rev"], "f": rf}
        self._base_dirty = True
        if rf is None:                                           # deleted on the other side
            if local is not None and bf is not None and local == bf:
                apply_record(book, rid, None)
                rep.changed.add(rid)
                rep.deleted += 1
            self.base[rid] = new                                  # (edited here: it stays and is sent again as a new version)
            return
        if local is None:                                         # new here - or deleted here but changed there: it comes back
            apply_record(book, rid, rf)
            rep.changed.add(rid)
        elif local == rf:
            pass
        elif bf is not None and local == bf:                      # nothing changed here: take theirs
            apply_record(book, rid, rf)
            rep.changed.add(rid)
        else:                                                     # both changed: merge
            before_merge()
            if rid == "o":
                merged, conf = {"order": merge_order((bf or {}).get("order", []), local["order"], rf.get("order", []))}, []
            elif rid == "x":
                merged, conf = merge_fields(bf or {}, local, rf)
                conf = []                                         # lists of word-watch entries: the other side's stay, no note
            else:
                merged, conf = merge_fields(bf or {}, local, rf)
            if merged != local:
                apply_record(book, rid, merged)
            rep.changed.add(rid)
            rep.merged += 1
            if conf:
                self._conflict_note(book, rid, conf, R)
                rep.conflicts += 1
        self.base[rid] = new

    def _conflict_note(self, book, rid, conf, R):
        who = {"PC": "the PC", "Phone": "the phone"}.get(R.get("by") or "", "the other device")
        label = record_label(book.d, rid)
        parts = ["Both devices changed the same words in %s. The words from %s were kept in the book; YOUR words are below, "
                 "so you can put them back where they belong. Then set this note to Done." % (label, who)]
        for field, mine, kept in conf:
            parts.append("\n===== %s: YOUR words =====\n%s\n===== %s: the words that were kept (from %s) =====\n%s"
                         % (field, mine, field, who, kept))
        cid = int(rid[1:]) if rid[0] == "c" else ((record_fields(book.d, rid) or {}).get("chapter", 0) if rid[0] == "n" else 0)
        n = book.add_note(chapter=cid or 0, kind="Conflict", title="Sync conflict: " + label[:60])
        n["text"] = "\n".join(parts)

    def mark_synced(self, ts=None):
        self.s["last"] = int(ts or time.time())
        self._state_dirty = True


# ---- the relay client ------------------------------------------------------------------------------------------------------
def relay_post(url, key, body, timeout=40):
    """One call of the relay (body = bytes).  Raises RuntimeError with a plain sentence on every problem."""
    req = urllib.request.Request(
        url.rstrip("/") + "/sync", data=body, method="POST",
        headers={"X-Sync-Key": key, "Content-Type": "application/json", "User-Agent": "StoryDesk-sync/1"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            ans = json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        raise RuntimeError({401: "the server says the key is wrong", 429: "the server says too many requests",
                            413: "too much data for the server"}.get(e.code, "the server answered HTTP %d" % e.code))
    except urllib.error.URLError as e:
        raise RuntimeError("could not reach the server (%s)" % (getattr(e, "reason", e),))
    except (OSError, ValueError) as e:
        raise RuntimeError("the server's answer was not understood (%s)" % e)
    if not isinstance(ans, dict) or "seq" not in ans:
        raise RuntimeError("the server's answer was not understood")
    return ans


def _new_token(n):
    return "".join(secrets.choice("abcdefghijklmnopqrstuvwxyz0123456789") for _ in range(n))


class SyncJob(object):
    """One request of a round: made on the main thread, sent from any thread, answered on the main thread."""

    def __init__(self):
        self.body = b""
        self.pushes = {}          # bid -> pushes
        self.asked = []           # bids in the request
        self.n_push = 0
        self.folder = None        # the folder of the book that was open when the request was made
        self.opened = {}          # bid -> Book loaded for a shared book that is not open but was never sent


class SyncHub(object):
    """All the sync state of this PC: the server (address + key), which books are shared, the list of books on the server.
    cfg file = phone_sync.json (PRIVATE: holds the key)."""

    def __init__(self, cfg_path, books_root, device="PC", post=None):
        self.cfg_path = cfg_path
        self.books_root = books_root
        self.device = device
        self.post = post or relay_post
        self.cfg = dict(url="", key="", auto=True, meta_since=0, server_books={}, last_ok=0, last_error="", full_scan=0)
        self.engines = {}               # bid -> BookSync
        self.folders = {}               # bid -> folder
        self.last_report = SyncReport()
        try:
            with open(cfg_path, encoding="utf-8") as fh:
                self.cfg.update(json.load(fh))
        except (OSError, ValueError):
            pass
        self.scan()

    # ---- settings ------------------------------------------------------------------------------------------------------
    def save_cfg(self):
        try:
            os.makedirs(os.path.dirname(self.cfg_path), exist_ok=True)
            _atomic_json(self.cfg_path, self.cfg)
        except OSError:
            pass

    def configured(self):
        return bool(self.cfg.get("url") and self.cfg.get("key"))

    def set_server(self, url, key):
        self.cfg["url"] = url.strip().rstrip("/") + "/"
        self.cfg["key"] = key.strip()
        self.cfg["meta_since"] = 0
        self.save_cfg()

    def code(self):
        return sync_code_make(self.cfg["url"], self.cfg["key"])

    def scan(self):
        """Which book folders take part (they hold a sync.json)."""
        self.folders = {}
        try:
            names = os.listdir(self.books_root)
        except OSError:
            names = []
        for n in names:
            p = os.path.join(self.books_root, n)
            if BookSync.exists(p):
                bid = BookSync.bid_of(p)
                if bid:
                    self.folders[bid] = p
        for bid in list(self.engines):
            if bid not in self.folders:
                del self.engines[bid]

    def engine(self, bid):
        e = self.engines.get(bid)
        if e is None and bid in self.folders:
            e = self.engines[bid] = BookSync(self.folders[bid]).load()
        return e

    def bid_of_folder(self, folder):
        for bid, p in self.folders.items():
            if os.path.normcase(os.path.abspath(p)) == os.path.normcase(os.path.abspath(folder)):
                return bid
        return None

    # ---- sharing -------------------------------------------------------------------------------------------------------
    def share(self, folder):
        """Starts sharing a book of this PC.  The first round sends everything."""
        bid = self.bid_of_folder(folder)
        if bid:
            return bid
        while True:
            bid = _new_token(8)
            if bid not in self.cfg["server_books"] and bid not in self.folders:
                break
        BookSync(folder).create(bid, dev=0)
        self.scan()
        return bid

    def unshare(self, folder):
        """Stops sharing (the book stays here and on the server; nothing is deleted)."""
        for n in ("sync.json", "sync_base.json"):
            try:
                os.remove(os.path.join(folder, n))
            except OSError:
                pass
        self.scan()

    # ---- one round -----------------------------------------------------------------------------------------------------
    def prepare(self, open_folder=None, open_book=None, extra_asked=None):
        """Main thread.  Builds the request: pushes of the open book, a pull for every shared book."""
        job = SyncJob()
        books = {}
        for bid in self.folders:
            e = self.engine(bid)
            books[bid] = e.s["since"]
            book = None
            if open_book is not None and open_folder and os.path.normcase(os.path.abspath(self.folders[bid])) == \
                    os.path.normcase(os.path.abspath(open_folder)):
                book = open_book
            elif not e.s.get("last"):                         # shared a moment ago, never sent, not the open book
                try:
                    book = job.opened[bid] = Book(self.folders[bid]).load()
                except Exception:
                    book = None
            if book is not None:
                p = e.collect(book)
                if p:
                    job.pushes[bid] = p
                    job.n_push += len(p)
                    e.save()
        for bid in (extra_asked or []):
            books.setdefault(bid, 0)
        job.asked = list(books)
        body = {"books": books, "meta_since": self.cfg["meta_since"], "dev": self.device, "push": []}
        for bid, ps in job.pushes.items():
            for p in ps:
                q = dict(p)
                q["id"] = bid + ":" + p["id"]
                body["push"].append(q)
        job.body = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        return job

    def exchange(self, job):
        """Any thread.  Only the network."""
        return self.post(self.cfg["url"], self.cfg["key"], job.body)

    def process(self, job, answer, open_folder=None, open_book=None, snapshot=None):
        """Main thread.  Applies the answer.  Returns a SyncReport about the OPEN book (other books are saved here)."""
        rep = SyncReport()
        for rid, rec in (answer.get("recs") or {}).items():          # the list of books on the server
            if rid.endswith(":b"):
                bid = rid[:-2]
                if rec.get("d"):
                    self.cfg["server_books"].pop(bid, None)
                else:
                    self.cfg["server_books"][bid] = str((rec.get("f") or {}).get("title") or "Untitled")
        for bid in job.asked:
            e = self.engine(bid)
            if e is None:
                continue
            pre = bid + ":"
            ans = {"ok": {k[len(pre):]: v for k, v in (answer.get("ok") or {}).items() if k.startswith(pre)},
                   "recs": {k: v for k, v in (answer.get("recs") or {}).items() if k.startswith(pre)},
                   "conflicts": {k: v for k, v in (answer.get("conflicts") or {}).items() if k.startswith(pre)}}
            is_open = open_book is not None and open_folder is not None and os.path.normcase(os.path.abspath(
                self.folders[bid])) == os.path.normcase(os.path.abspath(open_folder))
            book = open_book if is_open else job.opened.get(bid)
            if book is None and (ans["recs"] or ans["conflicts"]):
                try:
                    book = Book(self.folders[bid]).load()
                except Exception as ex:
                    rep.errors.append("%s: %s" % (bid, ex))
                    continue
            if book is None:                                        # a closed book with nothing new: only the counter moves
                e.set_since(answer["seq"])
                e.save()
                continue
            snap = snapshot if is_open else (lambda b=book: b.snapshot("sync"))
            r = e.process(book, job.pushes.get(bid, []), ans, before_merge=snap)
            if not r.errors:
                e.set_since(answer["seq"])
            e.mark_synced()
            if not is_open and (r.changed or r.conflicts):
                try:
                    book.save_live()
                except Exception as ex:
                    r.errors.append("could not save %s: %s" % (bid, ex))
            e.save()
            if is_open:
                rep.add(r)
            else:
                self.last_report.errors += r.errors
        self.cfg["meta_since"] = answer["seq"]
        self.cfg["last_ok"] = int(time.time())
        self.cfg["last_error"] = ""
        self.save_cfg()
        return rep

    def sync_now(self, open_folder=None, open_book=None, snapshot=None, max_rounds=SYNC_MAX_ROUNDS):
        """A whole sync, one thread (tests, the Sync now button's worker uses prepare/exchange/process itself).  Returns a SyncReport."""
        total = SyncReport()
        for _ in range(max_rounds):
            job = self.prepare(open_folder, open_book)
            ans = self.exchange(job)
            rep = self.process(job, ans, open_folder, open_book, snapshot)
            total.add(rep)
            if not self.more_to_send(open_folder, open_book):
                break
        self.last_report = total
        return total

    def more_to_send(self, open_folder, open_book):
        """True when the open book still differs from what the relay has (a merge made a new version, or the user wrote meanwhile)."""
        if open_book is None or not open_folder:
            return False
        bid = self.bid_of_folder(open_folder)
        if not bid:
            return False
        e = self.engine(bid)
        cur = book_records(open_book.d)
        for rid, f in cur.items():
            st = e.base.get(rid)
            if st is None or st["f"] != f:
                return True
        return any(rid not in cur and st["f"] is not None for rid, st in e.base.items())

    # ---- books that exist only on the server ---------------------------------------------------------------------------
    def available(self):
        """[(bid, title)] of books on the server that are not shared from this PC."""
        return sorted(((b, t) for b, t in self.cfg["server_books"].items() if b not in self.folders), key=lambda x: x[1].lower())

    def download(self, bid):
        """Fetches a book that is only on the server and makes it a normal book of this PC.  Returns its folder."""
        job = SyncJob()
        job.asked = [bid]
        job.body = json.dumps({"books": {bid: 0}, "meta_since": self.cfg["meta_since"], "dev": self.device, "push": []}).encode("utf-8")
        ans = self.exchange(job)
        recs = {k[len(bid) + 1:]: v for k, v in (ans.get("recs") or {}).items() if k.startswith(bid + ":")}
        meta = recs.get("b")
        if not meta or meta.get("d"):
            raise RuntimeError("that book is no longer on the server")
        title = str((meta.get("f") or {}).get("title") or "Untitled")
        folder = unique_folder(title)
        book = Book(folder)
        book.d = Book.new_data(title)
        dev = random.randint(1, 8999)
        book.d["next_id"] = dev * 1000000000 + 1
        os.makedirs(folder, exist_ok=True)
        st = BookSync(folder).create(bid, dev=dev)
        for rid in sorted(recs, key=lambda r: r == "o"):
            rec = recs[rid]
            f = None if rec.get("d") else copy.deepcopy(rec.get("f") or {})
            if f is not None:
                apply_record(book, rid, f)
            st.base[rid] = {"rev": rec["rev"], "f": f}
        st._base_dirty = True
        st.set_since(ans["seq"])
        book.save_live()
        st.save()
        self.scan()
        return folder

    # ---- what the window shows -----------------------------------------------------------------------------------------
    def status_text(self, pending=0):
        if not self.configured():
            return "Phone sync: not set up"
        if not self.folders:
            return "Phone sync: no book shared"
        if self.cfg.get("last_error"):
            return "Phone sync: " + self.cfg["last_error"][:40]
        t = time.strftime("%H:%M", time.localtime(self.cfg["last_ok"])) if self.cfg.get("last_ok") else "-"
        if pending:
            return "Phone sync: %d to send  (last %s)" % (pending, t)
        return "Phone sync: in step  (%s)" % t


# *************** DEL 61 - PHONE SYNC: THE WINDOWS (controller with automatic sync, the "Phone sync" dialog) *****************
# ToDo (2026-11-29): when it syncs by itself.  A few seconds after the last change (and at the latest 30 s after the first one of a
#   burst) the open book is sent; every 30 s the relay is asked what the phone (or another PC) did.  Only the network call runs in
#   a thread - reading and changing the book always happens on the main thread, so a keystroke can never meet a merge half way.
#   What the other side changed is merged in under the cursor: the Write tab keeps its cursor and scroll position.
#   Not done: sync of snapshots / trash / window settings, "remove a book from the server", a marker per chapter in the lists
#   (the bar at the bottom says "changes waiting" for the whole book).
SYNC_TICK_MS = 30000          # how often the relay is asked when nothing was written
SYNC_DEBOUNCE_S = 4           # quiet time after the last change before it is sent
SYNC_BURST_S = 30             # ... but never later than this after the first change of a burst


class PhoneSyncController(object):
    """Runs the rounds for the App: the timer, the thread for the network call, applying the answer, the bar at the bottom."""

    def __init__(self, app):
        self.app = app
        self.hub = SyncHub(os.path.join(PROGRAM_HF_DIR, "phone_sync.json"), books_dir())
        self.busy = False
        self.q = queue.Queue()
        self.kick_at = 0.0
        self.kick_first = 0.0
        self.waiting = False          # the open book has changes that were not sent yet
        self.error = ""
        self.rounds_in_a_row = 0
        self.lbl = None
        self.last_tick = 0.0
        self.changed_since = 0.0

    # ---- the bar at the bottom ------------------------------------------------------------------------------------------
    def build_bar(self, parent):
        bar = tk.Frame(parent, bg=T["bg"])
        bar.pack(side="bottom", fill="x", padx=10, pady=(0, 4))
        self.lbl = mklabel(bar, "", width=60, anchor="w", dim=True, cursor="hand2")
        self.lbl.pack(side="left")
        self.lbl.bind("<Button-1>", lambda e: PhoneSyncDialog(self.app))
        self.update_label()

    def book_opened(self):
        """Another book was opened: show its state and ask the relay soon."""
        self.waiting = False
        self.error = ""
        self.update_label()
        if self.hub.configured():
            self.app.root.after(800, self.start)

    def update_label(self):
        if self.lbl is None:
            return
        h, a = self.hub, self.app
        if not h.configured():
            s = "Phone sync: not set up  (click here)"
        elif a.book is None or h.bid_of_folder(a.book.folder) is None:
            s = "Phone sync: this book is not shared  (click here)"
        elif self.busy:
            s = "Phone sync: syncing ..."
        elif self.error:
            s = "Phone sync: %s - will try again" % self.error[:36]
        elif self.waiting:
            s = "Phone sync: changes waiting"
        else:
            s = h.status_text(0)
        self.lbl.configure(text=s, fg=T["warn"] if self.error else T["dim"])

    # ---- when to sync ------------------------------------------------------------------------------------------------------
    def kick(self):
        """Called after every change of the book."""
        if not self.hub.configured() or self.app.book is None or self.hub.bid_of_folder(self.app.book.folder) is None:
            return
        now = time.time()
        if not self.waiting:
            self.kick_first = now
        self.waiting = True
        self.kick_at = now + SYNC_DEBOUNCE_S
        if self.lbl is not None and not self.busy and not self.error:
            self.update_label()

    def start_loop(self):
        self.app.root.after(2500, self._first)
        self.app.root.after(400, self._pump)

    def _first(self):
        self.start(force=True)

    def _pump(self):
        """Every 400 ms: take results of the thread, start rounds that are due."""
        try:
            while True:
                item = self.q.get_nowait()
                self._finish(*item)
        except queue.Empty:
            pass
        except Exception as ex:                                    # never let the timer die
            self.busy = False
            self.error = str(ex)[:60]
            self.update_label()
        now = time.time()
        if not self.busy and self.hub.configured():
            if self.waiting and (now >= self.kick_at or now - self.kick_first >= SYNC_BURST_S):
                self.start()
            elif self.hub.cfg.get("auto", True) and now - self.last_tick >= SYNC_TICK_MS / 1000.0:
                self.start()
        self.app.root.after(400, self._pump)

    # ---- one round -------------------------------------------------------------------------------------------------------------
    def start(self, force=False, manual=False):
        h, a = self.hub, self.app
        if self.busy or not h.configured() or (not h.cfg.get("auto", True) and not (force or manual)):
            return False
        h.scan()
        if not h.folders:
            self.update_label()
            return False
        self.last_tick = time.time()
        self._flush_widgets()
        folder = a.book.folder if a.book is not None else None
        try:
            job = h.prepare(folder, a.book)
        except Exception as ex:
            self.error = "prepare: %s" % ex
            self.update_label()
            return False
        self.busy = True
        self.waiting = False
        self.update_label()
        job.folder = folder

        def work():
            try:
                self.q.put(("ok", job, h.exchange(job), None))
            except Exception as ex:
                self.q.put(("err", job, None, str(ex)))
        threading.Thread(target=work, daemon=True).start()
        return True

    def _finish(self, kind, job, answer, err):
        h, a = self.hub, self.app
        self.busy = False
        if kind == "err":
            self.error = err or "failed"
            h.cfg["last_error"] = self.error
            self.waiting = self.waiting or job.n_push > 0
            self.update_label()
            return
        self.error = ""
        same_book = a.book is not None and job.folder is not None and os.path.normcase(os.path.abspath(a.book.folder)) == \
            os.path.normcase(os.path.abspath(job.folder))
        self._flush_widgets()
        keep = self._cursor_state() if same_book else None
        rep = h.process(job, answer, job.folder if same_book else None, a.book if same_book else None,
                        snapshot=lambda: self._snap())
        for e in rep.errors:
            self.error = e[:60]
        if same_book and (rep.changed or rep.conflicts or rep.deleted):
            self._applied(rep, keep)
        if rep.conflicts:
            a.status("Sync: %d conflict note%s made - see the Notes tab" % (rep.conflicts, "" if rep.conflicts == 1 else "s"))
        elif rep.merged:
            a.status("Sync: changes from the other device were merged in")
        again = same_book and h.more_to_send(job.folder, a.book)
        self.waiting = bool(again)
        if again and self.rounds_in_a_row < SYNC_MAX_ROUNDS:
            self.rounds_in_a_row += 1
            self.kick_at = time.time() + 0.5
            self.waiting = True
        else:
            self.rounds_in_a_row = 0
        self.update_label()

    def _snap(self):
        try:
            self.app.book.save_live()
            self.app.book.snapshot("sync")
        except Exception:
            pass

    # ---- the editors: what is typed is already in the book, the cursor must survive a merge --------------------------------
    def _flush_widgets(self):
        """A keystroke whose <<Modified>> event is still queued must be in the book before a merge looks at it."""
        a = self.app
        try:
            tab = a.current_tab()
            if tab == "Write" and a.write.cid and not a.write.loading and not a.write.names_view:
                ch = a.book.chapter(a.write.cid)
                if ch is not None:
                    t = a.write.txt.get("1.0", "end-1c")
                    if t != ch["text"]:
                        ch["text"] = t
                    s = a.write.syn.get("1.0", "end-1c")
                    if s != ch.get("synopsis", ""):
                        ch["synopsis"] = s
            elif tab == "Notes" and a.notes.nid and not a.notes.loading:
                n = a.notes.note()
                if n is not None:
                    t = a.notes.txt.get("1.0", "end-1c")
                    if t != n["text"]:
                        n["text"] = t
            elif tab == "Plan" and a.plan.form_cid and not a.plan.loading:
                ch = a.book.chapter(a.plan.form_cid)
                if ch is not None:
                    s = a.plan.syn.get("1.0", "end-1c")
                    if s != ch.get("synopsis", ""):
                        ch["synopsis"] = s
        except Exception:
            pass

    def _cursor_state(self):
        a = self.app
        try:
            tab = a.current_tab()
            if tab == "Write" and a.write.cid:
                return ("Write", a.write.cid, a.write.txt.index("insert"), a.write.txt.yview()[0])
            if tab == "Notes" and a.notes.nid:
                return ("Notes", a.notes.nid, a.notes.txt.index("insert"), a.notes.txt.yview()[0])
        except Exception:
            pass
        return None

    def _applied(self, rep, keep):
        """The other side changed the book: show it, and put the cursor back where it was."""
        a = self.app
        a.book.touch()
        if a.live_job:
            a.root.after_cancel(a.live_job)
        a.live_job = a.root.after(1500, a._live_save)
        if a.book.chapter(a.cur_ch) is None:
            chs = a.book.chapters()
            a.cur_ch = chs[0]["id"] if chs else None
        a.refresh_books_menu()
        a.refresh_current()
        a.refresh_note_popups()
        try:
            if keep and keep[0] == "Write" and a.current_tab() == "Write" and a.write.cid == keep[1]:
                a.write.txt.mark_set("insert", keep[2])
                a.write.txt.yview_moveto(keep[3])
            elif keep and keep[0] == "Notes" and a.current_tab() == "Notes" and a.notes.nid == keep[1]:
                a.notes.txt.mark_set("insert", keep[2])
                a.notes.txt.yview_moveto(keep[3])
        except Exception:
            pass


class PhoneSyncDialog(object):
    """Phone sync: the server, which books are shared, books that are only on the server, the code for the phone."""

    def __init__(self, app):
        self.app = app
        self.ctl = app.psync
        self.hub = self.ctl.hub
        top = self.top = open_dialog(app.root, "Phone sync", resizable=False)
        self.v_server = tk.StringVar()
        self.v_auto = tk.BooleanVar(value=bool(self.hub.cfg.get("auto", True)))
        mklabel(top, "How it works: your books are kept the same on this PC and on your phone (and other PCs) through a "
                     "small server of your own.\nChanges are sent a few seconds after you stop writing, and fetched every 30 "
                     "seconds. Nobody overwrites anybody: changes in different places are merged;\nif both of you changed "
                     "the same words, the other device's words stay and yours go into a note of kind Conflict.",
                dim=True, justify="left", wraplength=640).pack(anchor="w", padx=14, pady=(12, 6))
        row = tk.Frame(top, bg=T["bg"])
        row.pack(fill="x", padx=14, pady=(2, 2))
        mklabel(row, "Server:", dim=True).pack(side="left")
        mklabel(row, "", textvariable=self.v_server, width=52).pack(side="left", padx=6)
        mkbtn(row, "Use relay.json", self.use_relay_json, 14).pack(side="left", padx=2)
        mkbtn(row, "Server...", self.server_dialog, 10).pack(side="left", padx=2)
        mklabel(top, "My books  (tick = share with the phone)", dim=True).pack(anchor="w", padx=14, pady=(10, 0))
        fr, self.tv = mktree(top, ("book", "shared", "state"), (300, 80, 240), ("Book", "Shared", "State"), height=7)
        fr.pack(fill="x", padx=14, pady=(2, 4))
        row2 = tk.Frame(top, bg=T["bg"])
        row2.pack(fill="x", padx=14)
        mkbtn(row2, "Share this book", self.share, 15).pack(side="left", padx=(0, 4))
        mkbtn(row2, "Stop sharing", self.unshare, 13).pack(side="left", padx=4)
        mklabel(top, "On the server, not on this PC  (made on a phone or another PC)", dim=True).pack(anchor="w", padx=14, pady=(10, 0))
        fr2, self.tv2 = mktree(top, ("book",), (560,), ("Book",), height=3)
        fr2.pack(fill="x", padx=14, pady=(2, 4))
        row3 = tk.Frame(top, bg=T["bg"])
        row3.pack(fill="x", padx=14)
        mkbtn(row3, "Get this book", self.get_book, 14).pack(side="left", padx=(0, 4))
        mkbtn(row3, "Look again", self.look_again, 11).pack(side="left", padx=4)
        row4 = tk.Frame(top, bg=T["bg"])
        row4.pack(fill="x", padx=14, pady=(12, 4))
        mkbtn(row4, "Copy code for the phone", self.copy_code, 22).pack(side="left", padx=(0, 4))
        mkbtn(row4, "Sync now", self.sync_now, 10).pack(side="left", padx=4)
        mkcheck(row4, "Sync by itself", self.v_auto, self.auto_changed).pack(side="left", padx=10)
        self.lbl_msg = mklabel(top, "", width=86, dim=True)
        self.lbl_msg.pack(anchor="w", padx=14, pady=(2, 0))
        row5 = tk.Frame(top, bg=T["bg"])
        row5.pack(pady=(6, 12))
        mkbtn(row5, "Close", top.destroy, 10).pack()
        self.paths = {}
        self.fill()
        finish_dialog(top, app.root, 700, None)
        self._poll()

    def msg(self, text):
        self.lbl_msg.configure(text=text)

    def _poll(self):
        try:
            if not self.top.winfo_exists():
                return
            self.fill()
            self.top.after(1500, self._poll)
        except tk.TclError:
            pass

    def fill(self):
        h = self.hub
        h.scan()
        self.v_server.set((h.cfg.get("url") or "not set") + ("   (key saved)" if h.cfg.get("key") else ""))
        sel_p = self.sel()
        self.tv.delete(*self.tv.get_children())
        self.paths = {}
        for p, title in list_books():
            bid = h.bid_of_folder(p)
            state = "-"
            if bid:
                e = h.engine(bid)
                state = ("in step  " + time.strftime("%H:%M", time.localtime(e.s["last"]))) if e.s.get("last") else "not sent yet"
                if self.app.book is not None and os.path.samefile(p, self.app.book.folder) and self.ctl.waiting:
                    state = "changes waiting"
            iid = self.tv.insert("", "end", values=(title, "yes" if bid else "", state))
            self.paths[iid] = p
            if (sel_p and p == sel_p) or (not sel_p and self.app.book and os.path.samefile(p, self.app.book.folder)):
                self.tv.selection_set(iid)
        sel2 = self.sel2()
        self.tv2.delete(*self.tv2.get_children())
        self.avail = {}
        for bid, title in h.available():
            iid = self.tv2.insert("", "end", values=(title,))
            self.avail[iid] = bid
            if bid == sel2:
                self.tv2.selection_set(iid)

    def sel(self):
        s = self.tv.selection()
        return self.paths.get(s[0]) if s else None

    def sel2(self):
        s = self.tv2.selection()
        return getattr(self, "avail", {}).get(s[0]) if s else None

    # ---- the server ------------------------------------------------------------------------------------------------------------
    def use_relay_json(self):
        p = os.path.join(PROGRAM_HF_DIR, "relay.json")
        try:
            with open(p, encoding="utf-8") as fh:
                d = json.load(fh)
            url, key = str(d.get("url") or ""), str(d.get("key") or "")
            if not re.match(r"^https?://\S+$", url) or len(key) < 8:
                raise ValueError("no address or key in it")
        except (OSError, ValueError) as ex:
            self.msg("relay.json could not be used (%s). It belongs in %s" % (ex, PROGRAM_HF_DIR))
            return
        self.hub.set_server(url, key)
        self.fill()
        self.msg("Server set from relay.json.")

    def server_dialog(self):
        top = open_dialog(self.top, "Server")
        v_u, v_k = tk.StringVar(value=self.hub.cfg.get("url", "")), tk.StringVar(value=self.hub.cfg.get("key", ""))
        mklabel(top, "Paste the code you got from the relay installer or from another device - or type the address and key.",
                dim=True, wraplength=420, justify="left").pack(anchor="w", padx=14, pady=(12, 2))
        v_c = tk.StringVar()
        mkentry(top, v_c, 56).pack(padx=14, pady=2)
        mklabel(top, "Address (ends with /storydesk/)", dim=True).pack(anchor="w", padx=14, pady=(8, 0))
        mkentry(top, v_u, 56).pack(padx=14)
        mklabel(top, "Key", dim=True).pack(anchor="w", padx=14, pady=(8, 0))
        mkentry(top, v_k, 56).pack(padx=14)

        def ok():
            c = sync_code_parse(v_c.get())
            url, key = (c["url"], c["key"]) if c else (v_u.get().strip(), v_k.get().strip())
            if not re.match(r"^https?://\S+$", url) or len(key) < 8:
                messagebox.showinfo(APP_TITLE, "Give a web address (https://...) and a key of at least 8 characters.", parent=top)
                return
            self.hub.set_server(url, key)
            top.destroy()
            self.fill()
        row = tk.Frame(top, bg=T["bg"])
        row.pack(pady=14)
        mkbtn(row, "OK", ok, 10).pack(side="left", padx=4)
        mkbtn(row, "Cancel", top.destroy, 10).pack(side="left", padx=4)
        finish_dialog(top, self.top)
        self.top.wait_window(top)

    def copy_code(self):
        if not self.hub.configured():
            self.msg("Set the server first (Use relay.json or Server...).")
            return
        self.top.clipboard_clear()
        self.top.clipboard_append(self.hub.code())
        self.msg("The code is on the clipboard. In the phone app: Settings > Paste code. It holds your key - send it only to your own phone.")

    # ---- books -----------------------------------------------------------------------------------------------------------------
    def share(self):
        p = self.sel()
        if not p:
            self.msg("Pick a book in the list first.")
            return
        if not self.hub.configured():
            self.msg("Set the server first (Use relay.json or Server...).")
            return
        if self.app.book is not None and os.path.samefile(p, self.app.book.folder):
            self.app.book.save_live()
        self.hub.share(p)
        self.fill()
        self.msg("Shared. The first sync sends the whole book.")
        self.ctl.start(manual=True)

    def unshare(self):
        p = self.sel()
        if p and self.hub.bid_of_folder(p):
            if messagebox.askyesno(APP_TITLE, "Stop sharing this book?\n\nThe book stays on this PC and on the server - nothing is "
                                   "deleted. The phone keeps its copy but gets no more changes.", parent=self.top):
                self.hub.unshare(p)
                self.fill()

    def get_book(self):
        bid = self.sel2()
        if not bid:
            self.msg("Pick a book under 'On the server' first.")
            return
        self.top.configure(cursor="watch")
        self.top.update()
        try:
            folder = self.hub.download(bid)
        except Exception as ex:
            self.msg("Could not get the book: %s" % ex)
            return
        finally:
            self.top.configure(cursor="")
        self.app.refresh_books_menu()
        self.fill()
        self.msg("The book is in your library now (Book menu or the list above).")

    def look_again(self):
        self.msg("Asking the server ...")
        if not self.ctl.start(manual=True):
            self.msg("A sync is already running, or nothing is shared yet - the list updates by itself.")

    def sync_now(self):
        if not self.hub.configured():
            self.msg("Set the server first (Use relay.json or Server...).")
            return
        self.msg("Syncing ...")
        self.ctl.start(manual=True)

    def auto_changed(self):
        self.hub.cfg["auto"] = bool(self.v_auto.get())
        self.hub.save_cfg()


# *************** DEL 50 - THE APPLICATION WINDOW ******************************

class App(object):
    TABS = ("Plan", "Write", "Notes", "Names", "Words", "Time", "Places")

    def __init__(self, root):
        self.root = root
        self.S = load_settings()
        self.book = None
        self.cur_ch = None
        self.edits = 0
        self.live_job = None
        self.playertext = None
        self.note_popups = {}                  # note id -> NotePopup
        self.chapter_popups = {}               # chapter id -> ChapterPopup
        self.folders = {}                      # menu label -> book folder
        root.title(APP_TITLE)
        root.configure(bg=T["bg"])
        setup_styles(root)
        self._open_first_book()
        self.psync = PhoneSyncController(self)     # DEL 60 / 61: phone sync
        self._build_ui()
        self.psync.start_loop()
        self.root.after(60000, self._tick)

    # ---- choosing the first book ------------------------------------------------------
    def _open_first_book(self):
        folder = self.S.get("last_book")
        if not (folder and os.path.isfile(os.path.join(folder, "book.json"))):
            books = list_books()
            folder = books[0][0] if books else None
        if folder:
            try:
                self._attach(folder)
                return
            except Exception as ex:
                messagebox.showerror(APP_TITLE, "Could not open the book:\n%s"
                                     % ex)
        r = book_dialog(self.root, "Your first book") or dict(
            title="My first book", author="", language="sv")
        b = Book(unique_folder(r["title"]))
        b.create(r["title"], r["author"], r["language"])
        self._attach(b.folder)

    def _attach(self, folder):
        b = Book(folder).load()
        b.prime_snapshot_hash()
        self.book = b
        chs = b.chapters()
        self.cur_ch = chs[0]["id"] if chs else None
        self.S["last_book"] = folder
        save_settings(self.S)
        self.edits = 0
        # a snapshot every time a book is opened (skipped when unchanged)
        try:
            b.snapshot("open")
        except Exception:
            pass

    # ---- building the window ---------------------------------------------------------------
    def _build_ui(self):
        root = self.root
        self._build_menu()
        top = tk.Frame(root, bg=T["bg"])
        top.pack(fill="x", padx=10, pady=(8, 0))
        mklabel(top, "Book:", dim=True).pack(side="left")
        self.v_book = tk.StringVar()
        self.om_book = mkoption(top, self.v_book, ["-"], None, 30)
        self.om_book.pack(side="left", padx=6)
        mkbtn(top, "Library...", lambda: LibraryDialog(self), 10).pack(
            side="left", padx=2)
        mkbtn(top, "Save  (Ctrl+S)", self.save_important, 14).pack(
            side="left", padx=2)
        mkbtn(top, "Export...", lambda: export_dialog(self), 9).pack(
            side="left", padx=2)
        self.lbl_status = mklabel(top, "", width=52, anchor="e", dim=True)
        self.lbl_status.pack(side="right")
        self.psync.build_bar(root)                 # the bar at the bottom (packed before the notebook)
        self.nb = ttk.Notebook(root)
        self.nb.pack(fill="both", expand=True, padx=4, pady=(6, 4))
        self.plan = PlanTab(self, self.nb)
        self.write = WriteTab(self, self.nb)
        self.notes = NotesTab(self, self.nb)
        self.names = NamesTab(self, self.nb)
        self.words = WordsTab(self, self.nb)
        self.timeline = TimelineTab(self, self.nb)
        self.places = PlacesTab(self, self.nb)
        self.tabs = dict(zip(self.TABS, (self.plan, self.write, self.notes,
                                         self.names, self.words,
                                         self.timeline, self.places)))
        for name in self.TABS:
            self.nb.add(self.tabs[name], text=name)
        self.nb.bind("<<NotebookTabChanged>>", lambda e: self.refresh_current())
        root.bind("<Control-s>", lambda e: self.save_important())
        root.bind("<F1>", lambda e: self.show_help())
        self.refresh_books_menu()
        self.refresh_current()

    def _build_menu(self):
        m = tk.Menu(self.root)
        bm = tk.Menu(m, tearoff=0)
        bm.add_command(label="Library...", command=lambda: LibraryDialog(self))
        bm.add_command(label="New book...", command=self.new_book)
        bm.add_command(label="Book settings...", command=self.book_settings)
        bm.add_separator()
        bm.add_command(label="Save (important snapshot)    Ctrl+S",
                       command=self.save_important)
        bm.add_command(label="Export...",
                       command=lambda: export_dialog(self))
        bm.add_command(label="Show book folder",
                       command=lambda: open_path(self.book.folder))
        bm.add_separator()
        bm.add_command(label="Quit", command=self.on_close)
        m.add_cascade(label="Book", menu=bm)
        tm = tk.Menu(m, tearoff=0)
        tm.add_command(label="Snapshots...",
                       command=lambda: SnapshotDialog(self))
        tm.add_command(label="Trash...", command=lambda: TrashDialog(self))
        tm.add_command(label="My places...",
                       command=lambda: places_dialog(self))
        tm.add_command(label="Autosave settings...",
                       command=lambda: autosave_dialog(self))
        tm.add_command(label="Phone sync...",
                       command=lambda: PhoneSyncDialog(self))
        tm.add_command(label="Note as popup",
                       command=lambda: self.open_note_popup())
        tm.add_separator()
        tm.add_command(label="Scratchpad (own texts)",
                       command=self.open_scratchpad)
        m.add_cascade(label="Tools", menu=tm)
        hm = tk.Menu(m, tearoff=0)
        hm.add_command(label="Help    F1", command=self.show_help)
        hm.add_command(label="About", command=self.show_about_box)
        m.add_cascade(label="Help", menu=hm)
        self.root.configure(menu=m)

    # ---- tabs --------------------------------------------------------------------------------
    def current_tab(self):
        return self.TABS[self.nb.index(self.nb.select())]

    def refresh_current(self):
        self.tabs[self.current_tab()].refresh()

    def show_tab(self, name):
        if self.current_tab() == name:
            self.refresh_current()
        else:
            self.nb.select(self.TABS.index(name))

    def select_chapter(self, cid, source=None):
        self.cur_ch = cid
        if source is not self.plan:
            self.plan.select(cid)

    def chapters_changed(self, source=None):
        pass                 # the other tabs rebuild when they are shown

    def open_note_popup(self, nid=None):
        """Show a note in its own window beside the main one.  Without an id:
        the note selected in the Notes tab, else one tied to the current
        chapter, else the first note, else a new one."""
        b = self.book
        if nid is None:
            nid = self.notes.nid
        if nid is None or not any(n["id"] == nid for n in b.d["notes"]):
            mine = [n for n in b.d["notes"]
                    if self.cur_ch and n.get("chapter") == self.cur_ch]
            pool = mine or b.d["notes"]
            nid = pool[0]["id"] if pool else b.add_note(
                chapter=self.cur_ch or 0, kind="Note",
                title="New note")["id"]
            self.touch()
        old = self.note_popups.get(nid)
        if old is not None:
            try:
                old.top.deiconify()
                old.top.lift()
                old.txt.focus_set()
                return old
            except Exception:
                self.note_popups.pop(nid, None)
        pop = NotePopup(self, nid)
        self.note_popups[nid] = pop
        return pop

    def close_note_popups(self):
        for p in list(self.note_popups.values()):
            p.close()

    def open_chapter_popup(self, cid=None):
        """Show a chapter (default: the one in the Write tab) in its own
        window.  Already open = bring that window forward."""
        cid = cid or self.cur_ch
        if not cid or self.book.chapter(cid) is None:
            self.status("No chapter to pop out")
            return None
        old = self.chapter_popups.get(cid)
        if old is not None:
            try:
                old.top.deiconify()
                old.top.lift()
                return old
            except Exception:
                self.chapter_popups.pop(cid, None)
        pop = ChapterPopup(self, cid)
        self.chapter_popups[cid] = pop
        return pop

    def close_chapter_popups(self):
        for p in list(self.chapter_popups.values()):
            p.close()

    def refresh_note_popups(self):
        for p in list(self.note_popups.values()):
            p.refresh()

    def open_note(self, nid):
        self.notes.nid = nid
        self.show_tab("Notes")

    # ---- books -------------------------------------------------------------------------------
    def refresh_books_menu(self):
        books = list_books()
        titles = [t for _, t in books]
        self.folders = {}
        labels = []
        for p, t in books:
            lab = t if titles.count(t) == 1 else "%s  [%s]" % (
                t, os.path.basename(p))
            self.folders[lab] = p
            labels.append(lab)
        cur = None
        for lab, p in self.folders.items():
            if os.path.samefile(p, self.book.folder):
                cur = lab
        reset_option(self.om_book, self.v_book, labels or ["-"],
                     self._book_picked)
        self.v_book.set(cur or self.book.title)

    def _book_picked(self, label):
        p = self.folders.get(label)
        if p and not os.path.samefile(p, self.book.folder):
            self.open_book(p)

    def open_book(self, folder):
        self.close_note_popups()
        self.close_chapter_popups()
        self._finish_book("close")
        try:
            self._attach(folder)
        except Exception as ex:
            messagebox.showerror(APP_TITLE, "Could not open the book:\n%s" % ex)
            self._attach(self.S.get("last_book") or folder)
        self.refresh_books_menu()
        self.refresh_current()
        self.status("Opened \"%s\"" % self.book.title)
        self.psync.book_opened()

    def new_book(self):
        r = book_dialog(self.root, "New book")
        if not r:
            self.refresh_books_menu()
            return
        b = Book(unique_folder(r["title"]))
        b.create(r["title"], r["author"], r["language"])
        self.open_book(b.folder)

    def book_settings(self):
        r = book_dialog(self.root, "Book settings", self.book.title,
                        self.book.d.get("author", ""),
                        self.book.d.get("language", "sv"))
        if r:
            self.book.d.update(r)
            self.touch()
            self.refresh_books_menu()
            self.refresh_current()

    # ---- saving: live file + snapshots ----------------------------------------------------
    def status(self, text):
        self.lbl_status.configure(text=text)

    def touch(self):
        self.book.touch()
        self.psync.kick()
        self.edits += 1
        if self.live_job:
            self.root.after_cancel(self.live_job)
        self.live_job = self.root.after(1500, self._live_save)
        if (self.edits >= int(self.S["snap_every_edits"])
                and time.time() - self.book.last_snap_time
                >= 60 * int(self.S["snap_min_minutes"])):
            self.snapshot("auto")

    def _live_save(self):
        self.live_job = None
        try:
            self.book.save_live()
            self.status("Saved %s" % time.strftime("%H:%M:%S"))
        except Exception as ex:
            self.status("COULD NOT SAVE: %s" % ex)

    def snapshot(self, kind, important=False, force=False):
        try:
            self.book.save_live()
            p = self.book.snapshot(kind, important, force)
        except Exception as ex:
            self.status("COULD NOT SNAPSHOT: %s" % ex)
            return None
        self.edits = 0
        if p:
            self.status("Snapshot %s%s" % (time.strftime("%H:%M:%S"),
                                           "  ★" if important else ""))
        return p

    def save_important(self):
        """The Save button: a snapshot that is marked important."""
        self.snapshot("save", important=True)
        self.status("Saved %s  ★  (important snapshot)"
                    % time.strftime("%H:%M:%S"))

    def restore_snapshot(self, path):
        self.book.restore_snapshot(path)
        chs = self.book.chapters()
        if self.book.chapter(self.cur_ch) is None:
            self.cur_ch = chs[0]["id"] if chs else None
        self.refresh_books_menu()
        self.refresh_current()
        self.refresh_note_popups()
        self.status("Restored an earlier state")

    def _finish_book(self, kind):
        if self.live_job:
            self.root.after_cancel(self.live_job)
            self.live_job = None
        try:
            self.book.save_live()
            if self.book.changed_since_snap:
                self.book.snapshot(kind)
        except Exception:
            pass

    def _tick(self):
        """Once a minute: a snapshot if there are unsaved-in-history changes
        and the last snapshot is more than 10 minutes old."""
        try:
            if (self.book.changed_since_snap
                    and time.time() - self.book.last_snap_time >= 600):
                self.snapshot("auto")
        except Exception:
            pass
        self.root.after(60000, self._tick)

    # ---- tools ---------------------------------------------------------------------------------
    def open_scratchpad(self):
        if self.playertext is not None:
            try:
                if self.playertext.top.winfo_exists():
                    self.playertext.top.lift()
                    return
            except Exception:
                pass
        self.S["show_playertext"] = True
        self.playertext = PlayerTextPopup(
            self.root, self.S,
            ("show_playertext", "playertext_pos", "playertext_zoom",
             "playertext_sel"),
            lambda: save_settings(self.S), T, "Scratchpad - own texts",
            PROGRAM_HF_DIR, lambda: {"hint": "Your own text - saved by itself "
                                     "as Playertext-<name>.txt in the "
                                     "program's Helpfiles folder."})

    def show_help(self):
        info_box(self.root, "Help - " + APP_TITLE, HELP_TEXT, 700, 640)

    def show_about_box(self):
        show_about(self.root, APP_TITLE,
                   "A writing desk for authors: plan, chapters, notes, "
                   "names and word watch", "\U0001F4D6")

    # ---- closing ----------------------------------------------------------------------------------
    def on_close(self):
        self.close_note_popups()
        self.close_chapter_popups()
        try:
            if self.playertext is not None:
                self.playertext.save_now()
        except Exception:
            pass
        self._finish_book("close")
        try:
            self.S["geometry"] = self.root.geometry()
            save_settings(self.S)
        except Exception:
            pass
        self.root.destroy()


# *************** DEL 99 - MAIN ***********************************************
# ToDo (nothing missing, but ideas for later):
#  - a Swedish interface file (Lang\sv.txt) made by HTTP-Claude from the
#    English strings, if wanted (the book text itself is already any language)
#  - word-form grouping for Swedish (bil / bilen / bilar counted as one word)
#  - a chapter-by-chapter word-count chart
#  - dates (2026-10-22, DEL 14 / DEL 36): "Takes place" from/to per chapter,
#    dates found in the text, Time tab.  Not done yet: relative time ("three
#    weeks later", "next morning"), a per-chapter "flashback" mark so that a
#    planned jump back is not flagged, spelled-out years, weekday checks
#    ("Monday 12 May 1985" against the calendar).
#  - places (DEL 15 / DEL 37): built-in list of ~400 names, My places, main
#    place per chapter, Places tab.  Not done yet: a map/distance check
#    ("Stockholm to Kiruna in one hour"), more cities (add them to
#    _PLACES_DATA), places that are not capitalised.

def main():
    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    app = App(root)
    geo = app.S.get("geometry") or ""
    root.geometry(geo if re.match(r"^\d+x\d+[+-]-?\d+[+-]-?\d+$", geo)
                  else "1380x860+60+40")
    root.minsize(1100, 640)
    root.protocol("WM_DELETE_WINDOW", app.on_close)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()


if __name__ == "__main__":
    main()

